cuelo 0.10.13 → 0.10.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +7 -7
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/_not-found.html +1 -1
  18. package/.next/server/app/_not-found.rsc +2 -2
  19. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  20. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  21. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  22. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  24. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  25. package/.next/server/app/api/updates/route.js +1 -1
  26. package/.next/server/app/index.html +1 -1
  27. package/.next/server/app/index.rsc +4 -4
  28. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  29. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  30. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  31. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  32. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  33. package/.next/server/app/office/page_client-reference-manifest.js +1 -1
  34. package/.next/server/app/office-preview/page_client-reference-manifest.js +1 -1
  35. package/.next/server/app/office-preview.html +1 -1
  36. package/.next/server/app/office-preview.rsc +2 -2
  37. package/.next/server/app/office-preview.segments/_full.segment.rsc +2 -2
  38. package/.next/server/app/office-preview.segments/_head.segment.rsc +1 -1
  39. package/.next/server/app/office-preview.segments/_index.segment.rsc +2 -2
  40. package/.next/server/app/office-preview.segments/_tree.segment.rsc +1 -1
  41. package/.next/server/app/office-preview.segments/office-preview/__PAGE__.segment.rsc +1 -1
  42. package/.next/server/app/office-preview.segments/office-preview.segment.rsc +1 -1
  43. package/.next/server/app/office.html +1 -1
  44. package/.next/server/app/office.rsc +4 -4
  45. package/.next/server/app/office.segments/_full.segment.rsc +4 -4
  46. package/.next/server/app/office.segments/_head.segment.rsc +1 -1
  47. package/.next/server/app/office.segments/_index.segment.rsc +2 -2
  48. package/.next/server/app/office.segments/_tree.segment.rsc +1 -1
  49. package/.next/server/app/office.segments/office/__PAGE__.segment.rsc +3 -3
  50. package/.next/server/app/office.segments/office.segment.rsc +1 -1
  51. package/.next/server/app/page_client-reference-manifest.js +1 -1
  52. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  53. package/.next/server/app/recover.html +1 -1
  54. package/.next/server/app/recover.rsc +2 -2
  55. package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
  56. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  57. package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
  58. package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
  59. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  60. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  61. package/.next/server/app-paths-manifest.json +7 -7
  62. package/.next/server/chunks/5489.js +2 -2
  63. package/.next/server/middleware-build-manifest.js +1 -1
  64. package/.next/server/pages/404.html +1 -1
  65. package/.next/server/pages/500.html +1 -1
  66. package/.next/server/server-reference-manifest.json +1 -1
  67. package/.next/static/chunks/{9575-f75f250a07112d4d.js → 9575-25a582fa4fa508a9.js} +2 -2
  68. package/.next/static/chunks/app/{layout-4c592bc979a40fac.js → layout-bbd6ea2d6385b3a7.js} +1 -1
  69. package/.next/trace +108 -108
  70. package/.next/trace-build +1 -1
  71. package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
  72. package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +347 -0
  73. package/package.json +1 -1
  74. /package/.next/static/{B90WNxaFZ8Tg4XO_DiNPQ → cG1jGEwRHRT_Sz9zPk_S5}/_buildManifest.js +0 -0
  75. /package/.next/static/{B90WNxaFZ8Tg4XO_DiNPQ → cG1jGEwRHRT_Sz9zPk_S5}/_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,n)=>{"use strict";n.d(t,{C1:()=>s,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let r=[],i=["read","bash","edit","write"],s=["read","bash","edit","write","grep","glob"],a=Object.fromEntries(s.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===a[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...s].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...s]:[...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"}},40220:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>po});var r=n(95155),i=n(12115),s=n(73321),a=n(16871),l=n(81886),o=n(68890),d=n(66919);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}),m=Object.fromEntries(c.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":return{activeView:f(t.view),transientLayer:null};case"open-layer":return{activeView:f(e.activeView),transientLayer:t.layer};case"toggle-layer":return{activeView:f(e.activeView),transientLayer:e.transientLayer===t.layer?null:t.layer};case"close-layer":return{activeView:f(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 n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=N(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function T(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(N(e.key),e.order);let r=[...e],i=new Set(e.map(N));for(let e of t){let t=N(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(N(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&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[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var R=n(92176);let E=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let A=L("(max-width: 640px)"),z=L(E);function W(){return!1}function P(){return(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,W)}var F=n(47650);async function _(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function D(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function H(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function O({onCancel:e,onSelect:t,busy:n=!1,error:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!1),[f,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),n=t.path??e??"/";c(n),p(t.parentPath??null),m(!0===t.upToDrives),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),C()},[C]);let N=f.trim()!==d,I=!!d&&!N&&!n,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(d);return l?(0,F.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,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,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:a("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void 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,r.jsx)(H,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void 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,r.jsx)(D,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noSubdirectories")}),(w||s)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??s})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!I,title:a(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:a(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),l):null}var B=n(21443),U=n.n(B);async function q(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function K({onCancel:e,onSelect:t,busy:n=!1,error:s}){let{t:a}=(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),[m,f]=(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",A=n||S,z=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await q("/api/github/projects");h(e),e.connected&&f((await q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function W(){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 P(e){if(e.preventDefault(),v.trim()&&!A){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),z()},[z]),(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,n=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await z();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[L,c,z]),!o)return null;if(c)return(0,r.jsx)(O,{onCancel:()=>u(!1),onSelect:t,busy:n,error:s});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??s??p?.device?.error;return(0,F.createPortal)((0,r.jsx)("dialog",{ref:l,className:U().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),A||e()},children:(0,r.jsxs)("form",{onSubmit:P,className:U().form,children:[(0,r.jsxs)("header",{className:U().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:a("cloudProjects.title")}),(0,r.jsx)("p",{children:a("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:U().sources,children:[(0,r.jsx)("span",{className:U().activeSource,children:a("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:A,children:a("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:U().body,children:[(0,r.jsxs)("section",{className:U().account,"aria-label":a("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:a("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?a("cloudProjects.connected"):a("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:y||A,children:a("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void W(),disabled:y||k||L||A,children:k||L?a("cloudProjects.waiting"):a("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:U().login,role:"status",children:[(0,r.jsx)("p",{children:a("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:U().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(a("cloudProjects.copyFailure")))},children:T?a("cloudProjects.copied"):a("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:a("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:a("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:a("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:U().repositories,"aria-label":a("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:a("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:a("cloudProjects.searchPlaceholder"),type:"search",disabled:A}),y?(0,r.jsx)("p",{role:"status",children:a("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:U().list,children:_.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:U().repo,"aria-pressed":v===e.fullName,disabled:A,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:U().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?a("cloudProjects.private"):a("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,r.jsx)("p",{children:a("cloudProjects.empty")}),_.length>$&&(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:a("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:U().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:a("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:A,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:a("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:U().error,role:"alert",children:[(0,r.jsx)("strong",{children:a("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:A,children:a("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:U().progress,children:a("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:U().footer,children:[(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:A,children:a("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:U().primary,disabled:A||!v.trim(),children:A?a("cloudProjects.opening"):a("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:s}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.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,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...s},children:e})]})}var J=n(17028);let G="omp-web:unread-session-ids",Y="omp-web:pinned-session-ids",Z="omp-web:removed-projects";function X(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 Q(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function ee({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function et({open:e,children:t,style:n}){let[s,a]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(a(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>a(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),s)?(0,r.jsx)("div",{style:{...n,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 en="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function er(){let[e,t]=(0,i.useState)(!1),[n,s]=(0,i.useState)(!1),a=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),s=(0,i.useRef)(null),a=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);a.current=0;let n=4*e.length,i=()=>{a.current+=1;let t=Math.floor(a.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:en[Math.floor(Math.random()*en.length)]).join("")),a.current<n?s.current=requestAnimationFrame(i):r(e)};return s.current=requestAnimationFrame(i),()=>{s.current&&cancelAnimationFrame(s.current)}},[e,t]),n}(e?"0.10.13/18.10.4":"CUELO",n),o=(0,i.useCallback)(e=>{t(e),s(!0),setTimeout(()=>s(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{a.current&&clearTimeout(a.current);let t=!e;o(t),t&&(a.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]),(0,r.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,r.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function ei(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 es({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:s,initialSessionId:a,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,loungePanel:m,loungeActive:f=!1,onLoungeActiveChange:g}){let x,{lt:v}=(0,J.H)(),{t:b,locale:y}=(0,R.s)(),w=P(),[M,$]=(0,i.useState)([]),E=t&&!M.some(e=>e.id===t.id)?[t,...M]:M,[L,A]=(0,i.useState)(!0),[z,W]=(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)(""),[en,el]=(0,i.useState)("projects"),[eu,ep]=(0,i.useState)(()=>new Set),[em,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),[eA,ez]=(0,i.useState)(null),[eW,eP]=(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,tn]=(0,i.useState)(()=>new Set),[tr,ti]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(G);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}})()),[ts,ta]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ta(function(){try{let e=window.localStorage.getItem(Y);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(Z)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await ei(n.map(e=>({key:N(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(Z)}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 ei(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&&A(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();$(r.sessions),to.current||tn(new Set(r.runningSessionIds??[])),W(null),e||(te(!0),td.current&&clearTimeout(td.current),td.current=setTimeout(()=>te(!1),2e3))}catch(e){W(String(e))}finally{e&&A(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),ta(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),c?.(e),tp()},[tp,c]),[tm,tf]=(0,i.useState)(null),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useState)(null),ty=(0,i.useCallback)(()=>{tg||(tf(null),tb(null))},[tg]),tw=(0,i.useCallback)(async e=>{tx(!0),tb(null);let t=[],n=[],r=[];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){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(to.current=!0,tn(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(ti(n),ta(n),t))c?.(e)}(await tp(),tx(!1),r.length>0)?tb(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tf(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{el(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=>{el(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==en)return;let e=()=>{"visible"===document.visibilityState&&tp(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tp,en]),(0,i.useEffect)(()=>{try{0===tr.size?window.localStorage.removeItem(G):window.localStorage.setItem(G,JSON.stringify([...tr]))}catch{}},[tr]),(0,i.useEffect)(()=>{try{0===ts.size?window.localStorage.removeItem(Y):window.localStorage.setItem(Y,JSON.stringify([...ts]))}catch{}},[ts]);let tI=(0,i.useCallback)(e=>{ta(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;to.current=!0,tn(new Set(r.runningSessionIds??[]))}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[]),(0,i.useEffect)(()=>{let t=tl.current,n=[...t].filter(t=>!tt.has(t)&&t!==e),r=[...tt].filter(e=>!t.has(e));(n.length>0||r.length>0)&&ti(e=>{let t=new Set(e);return tt.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!M.some(t=>t.id===e));(n.length>0||i)&&tp(!1,!0),n.length>0&&h?.(),tl.current=tt},[tt,e,M,tp,h]),(0,i.useEffect)(()=>{e&&ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[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(a&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===a);if(e){_(e.cwd),n(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,a,l,n,o,ey,ek]);let tA=(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})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eH(n.error??b("workspace.unable"));let r=n.cwd??t,i=N(r),s=ey.projects.find(e=>e.key===i);if(s?.hidden===!0)try{await tu([{key:i,path:r,hidden:!1}])}catch{}_(r),e_(!1)}catch{eH(b("workspace.unable"))}finally{eB(!1)}}},[tu,eO,ey.projects,b]),tz=(0,i.useCallback)(()=>{e_(!0),eH(null)},[]),tW=(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})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eQ(n.error??`HTTP ${t.status}`);eG(!1),eZ(""),eV(!1),eq(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),_(n.path),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eY,e0,eU]),tP=(0,i.useCallback)(async(e,t)=>{if(eU&&!e0){e1(!0),eQ(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e4(e);eQ(r.error??`HTTP ${n.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),eP(""),ex(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tF=(0,i.useCallback)(e=>{e.cwd&&_(e.cwd),n(e)},[n]),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),s?.(t,e)},[F,s]),[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 n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),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),eP("")},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);ez(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{ez(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let n=tZ.indexOf(e),r=n+t;if(n<0||r<0||r>=tZ.length)return;let i=new Set(tZ),s=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),a=[...tY],l=s[n],o=s[r];[a[l],a[o]]=[a[o],a[l]],tQ();try{await tu(a.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 n=N(t),r=t4.get(n);r?r.push(e):t4.set(n,[e])}let t5=(0,i.useMemo)(()=>{let e=new Map;for(let t of E){let n=t.projectRoot??t.cwd;if(!n)continue;let r=N(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),tt.has(t.id)&&i.running++,tr.has(t.id)&&i.unread++}return e},[E,tt,tr]),t8=q.trim().toLowerCase(),t6=q.length>0,t3=tZ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=N(e),r=tJ.get(n),i=r?.alias??t,s=(t4.get(n)??[]).slice().sort((e,t)=>{let n=Number(ts.has(t.id))-Number(ts.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t8)return[{project:e,key:n,name:i,sessions:s,hidden:r?.hidden===!0}];let a=i.toLowerCase().includes(t8)||t.toLowerCase().includes(t8),l=s.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t8));return a||0!==l.length?[{project:e,key:n,name:i,sessions:a?s:l,hidden:r?.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 ne={running:0,unread:0};for(let e of t9){let t=t5.get(e.key);t&&(ne.running+=t.running,ne.unread+=t.unread)}let nt=t6||eN,nn=[...t7.map(e=>({kind:"project",group:e})),...t9.length>0?[{kind:"temporary"}]:[],...nt?t9.map(e=>({kind:"project",group:e})):[]],nr=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nn.flatMap(e=>"project"===e.kind?[e.group.name]:[])),ni=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",s=new Set,a="Pinned"){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),o=l.filter(e=>s.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(s.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(u>=10)continue;u+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=c.get(r);i?i.push(e):c.set(r,[e])}let p=[];for(let e of(o.length>0&&p.push({key:"pinned",label:a,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,n){let[r,i,s]=e.split("-").map(Number),a=new Date(r,i-1,s),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(a.getFullYear(),a.getMonth(),a.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(a):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(a)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ts,b("sidebar.pinned")),[y,ts,tt,E,b]),ns=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),na=eU?.worktrees.find(e=>e.path===F)??eU?.worktrees.find(e=>e.isMain),nl=(eU?.worktrees.length??0)>=8,no=nl&&eW.trim()?(eU?.worktrees??[]).filter(e=>(e.branch??Q(e.path,D)).toLowerCase().includes(eW.trim().toLowerCase())):eU?.worktrees??[],nd=(()=>{if(!tm)return[];let e="project"===tm.kind?t4.get(N(tm.project))??[]:ni.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nc=nd.filter(e=>!tt.has(e.id)),nu=e=>{let t=new Set;for(let n of e)n.transient||tt.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},np=void 0!==m&&f;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eF&&(0,r.jsx)(B?K:O,{busy:eO,error:eD,onCancel:()=>{e_(!1),eH(null)},onSelect:e=>void tA(e)}),tm&&(0,r.jsx)(ea,{scope:tm,eligible:nc.length,runningExcluded:nd.length-nc.length,busy:tg,error:tv,onCancel:ty,onConfirm:()=>void tw(nc)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(er,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.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,r.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,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.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,r.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,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.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,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),B&&!np&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tz,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,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.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"),n=!np&&en===e;return(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tN(e),np&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("lounge.tab")}),"aria-pressed":np,"aria-controls":"navigator-lounge-panel","data-navigator-mode":"lounge",onClick:()=>g?.(!np),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:np?"var(--bg-selected)":"transparent",color:np?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:np?600:500,whiteSpace:"nowrap"},children:v("lounge.tab")})]}),!np&&"projects"===en&&(0,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"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,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eS&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!np&&"projects"===en&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tz,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,r.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,r.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,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),np&&m,!np&&"projects"===en&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.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,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.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}})]}),!np&&"projects"===en&&(0,r.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,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),eA&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eA}),!L&&ek&&!z&&0===t3.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t8?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&ek&&!z&&nn.map(t=>{let n,i,s;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":nt,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,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:nt?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:t9.length}),eh(ne,b)]})},"navigator-temporary-projects");let{project:a,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=nr.has(o.toLowerCase())&&Q((i=Math.max((n=a.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),D)||null,h=!em.has(a)&&!t8,m=eu.has(a),f=eT===a,g=tZ.indexOf(a),x=eE||t6||g<=0,v=eE||t6||g>=tZ.length-1,y=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?d:d.slice(0,5)),k=d.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ev===a?e5:void 0,onMouseEnter:()=>ex(a),onMouseLeave:()=>ex(e=>e===a&&ev!==a?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,r.jsx)("button",{type:"button",onClick:()=>tq(a),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,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.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,r.jsx)("input",{ref:e6,value:e$,onChange:e=>eR(e.target.value),onBlur:()=>void t1(a),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,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(a),title:a,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,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.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,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),null===p?null:(0,r.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}),eh(t5.get(l),b)]}),(0,r.jsx)("button",{type:"button",onClick:()=>t_(a),title:b("sidebar.newSessionTitle",{path:a}),"aria-label":b("sidebar.newSessionTitle",{path:a}),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===a?1:0,pointerEvents:w||eg===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(a),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,r.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,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eb(ev===a?null:a),eV(!1),eG(!1),eQ(null),u||_(a)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===a?"var(--bg-selected)":"transparent",color:u&&na&&!na.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===a||ev===a?1:0,pointerEvents:w||eg===a||ev===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(a),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(et,{open:ev===a,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:[ns&&eU&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:na?b("sidebar.switchWorktreeTitle",{path:na.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,r.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,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(et,{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:[nl&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eW,onChange:e=>eP(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eP(""),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,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[no.map(e=>{let t=e.path===F||e.isMain&&!eU.worktrees.some(e=>e.path===F);return e2===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tP(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,r.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,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{_(e.path),eV(!1),eQ(null),eP("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(ee,{text:e.branch??Q(e.path,D),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tP(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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nl&&0===no.length&&eW.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eJ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:e8,value:eY,onChange:e=>{eZ(e.target.value),eQ(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tW()),"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,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tW(),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,r.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,r.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,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:b("sidebar.newWorktree")})]}),eX&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eX})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>{let e;return e=tJ.get(N(a))?.alias??"",void(e3.current=!1,ez(null),eR(e),eM(a),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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),b(tJ.get(N(a))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(a,-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,r.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,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(a,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,r.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,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>void t0(a,!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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"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,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(s=0===nu(t4.get(l)??[])||tg,(0,r.jsxs)("button",{type:"button",disabled:s,onClick:()=>{tQ(),tb(null),tf({kind:"project",project:a,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:s?"default":"pointer",textAlign:"left",fontSize:11,opacity:s?.55:1},children:[(0,r.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,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(ec,{node:t,selectedSessionId:e,runningSessionIds:tt,unreadSessionIds:tr,pinnedSessionIds:ts,onSelectSession:tF,onTogglePinnedSession:tI,onRenamed:tp,onSessionDeleted:th,onSessionArchived:tS,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ep(e=>{let t=new Set(e);return t.has(a)?t.delete(a):t.add(a),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:m?b("sidebar.showLess"):b("sidebar.showMore")})]},a)})]}),!np&&(0,r.jsx)(ed,{refreshKey:tk,selectedSessionId:e,onSelectSession:tF,onRestored:tS}),!np&&"priority"===en&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[L&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),!L&&!z&&(x=nu(ni.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:tD,onClick:()=>void tU(),title:b("sidebar.newScratchSessionTitle"),style:X(tD,w),children:b("sidebar.newScratchSession")}),ni.length>0&&(0,r.jsx)("button",{type:"button",disabled:0===x||tg,onClick:()=>{tb(null),tf({kind:"priority"})},style:X(0===x||tg,w),children:b("sidebar.clearPriorityList")})]})),tO&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tO}),!L&&!z&&0===ni.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!z&&ni.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"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,r.jsx)(eo,{session:t,selected:t.id===e,running:tt.has(t.id),unread:tr.has(t.id),pinned:ts.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function ea({scope:e,eligible:t,runningExcluded:n,busy:s,error:a,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=s||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(s);h.current=s;let m=(0,i.useRef)(l);return m.current=l,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=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),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{s||e.target!==e.currentTarget||l()},children:(0,r.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,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,r.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}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:a})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:l,disabled:s,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":s,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(s?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function el({filled:e=!1}){return(0,r.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,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function eo({session:e,selected:t,running:n,unread:i,pinned:s,onSelect:a,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,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>a(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,n)=>{"use strict";n.d(t,{C1:()=>s,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let r=[],i=["read","bash","edit","write"],s=["read","bash","edit","write","grep","glob"],a=Object.fromEntries(s.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===a[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...s].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...s]:[...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"}},40220:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>po});var r=n(95155),i=n(12115),s=n(73321),a=n(16871),l=n(81886),o=n(68890),d=n(66919);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}),m=Object.fromEntries(c.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":return{activeView:f(t.view),transientLayer:null};case"open-layer":return{activeView:f(e.activeView),transientLayer:t.layer};case"toggle-layer":return{activeView:f(e.activeView),transientLayer:e.transientLayer===t.layer?null:t.layer};case"close-layer":return{activeView:f(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 n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=N(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function T(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(N(e.key),e.order);let r=[...e],i=new Set(e.map(N));for(let e of t){let t=N(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(N(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&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[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var R=n(92176);let E=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let A=L("(max-width: 640px)"),z=L(E);function W(){return!1}function P(){return(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,W)}var F=n(47650);async function _(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function D(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function H(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function O({onCancel:e,onSelect:t,busy:n=!1,error:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!1),[f,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),n=t.path??e??"/";c(n),p(t.parentPath??null),m(!0===t.upToDrives),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),C()},[C]);let N=f.trim()!==d,I=!!d&&!N&&!n,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(d);return l?(0,F.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,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,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:a("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void 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,r.jsx)(H,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void 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,r.jsx)(D,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noSubdirectories")}),(w||s)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??s})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!I,title:a(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:a(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),l):null}var B=n(21443),U=n.n(B);async function q(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function K({onCancel:e,onSelect:t,busy:n=!1,error:s}){let{t:a}=(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),[m,f]=(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",A=n||S,z=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await q("/api/github/projects");h(e),e.connected&&f((await q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function W(){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 P(e){if(e.preventDefault(),v.trim()&&!A){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),z()},[z]),(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,n=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await z();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[L,c,z]),!o)return null;if(c)return(0,r.jsx)(O,{onCancel:()=>u(!1),onSelect:t,busy:n,error:s});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??s??p?.device?.error;return(0,F.createPortal)((0,r.jsx)("dialog",{ref:l,className:U().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),A||e()},children:(0,r.jsxs)("form",{onSubmit:P,className:U().form,children:[(0,r.jsxs)("header",{className:U().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:a("cloudProjects.title")}),(0,r.jsx)("p",{children:a("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:U().sources,children:[(0,r.jsx)("span",{className:U().activeSource,children:a("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:A,children:a("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:U().body,children:[(0,r.jsxs)("section",{className:U().account,"aria-label":a("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:a("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?a("cloudProjects.connected"):a("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:y||A,children:a("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void W(),disabled:y||k||L||A,children:k||L?a("cloudProjects.waiting"):a("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:U().login,role:"status",children:[(0,r.jsx)("p",{children:a("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:U().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(a("cloudProjects.copyFailure")))},children:T?a("cloudProjects.copied"):a("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:a("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:a("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:a("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:U().repositories,"aria-label":a("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:a("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:a("cloudProjects.searchPlaceholder"),type:"search",disabled:A}),y?(0,r.jsx)("p",{role:"status",children:a("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:U().list,children:_.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:U().repo,"aria-pressed":v===e.fullName,disabled:A,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:U().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?a("cloudProjects.private"):a("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,r.jsx)("p",{children:a("cloudProjects.empty")}),_.length>$&&(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:a("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:U().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:a("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:A,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:a("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:U().error,role:"alert",children:[(0,r.jsx)("strong",{children:a("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:A,children:a("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:U().progress,children:a("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:U().footer,children:[(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:A,children:a("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:U().primary,disabled:A||!v.trim(),children:A?a("cloudProjects.opening"):a("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:s}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.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,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...s},children:e})]})}var J=n(17028);let G="omp-web:unread-session-ids",Y="omp-web:pinned-session-ids",Z="omp-web:removed-projects";function X(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 Q(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function ee({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function et({open:e,children:t,style:n}){let[s,a]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(a(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>a(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),s)?(0,r.jsx)("div",{style:{...n,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 en="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function er(){let[e,t]=(0,i.useState)(!1),[n,s]=(0,i.useState)(!1),a=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),s=(0,i.useRef)(null),a=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);a.current=0;let n=4*e.length,i=()=>{a.current+=1;let t=Math.floor(a.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:en[Math.floor(Math.random()*en.length)]).join("")),a.current<n?s.current=requestAnimationFrame(i):r(e)};return s.current=requestAnimationFrame(i),()=>{s.current&&cancelAnimationFrame(s.current)}},[e,t]),n}(e?"0.10.14/18.10.4":"CUELO",n),o=(0,i.useCallback)(e=>{t(e),s(!0),setTimeout(()=>s(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{a.current&&clearTimeout(a.current);let t=!e;o(t),t&&(a.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]),(0,r.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,r.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function ei(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 es({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:s,initialSessionId:a,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,loungePanel:m,loungeActive:f=!1,onLoungeActiveChange:g}){let x,{lt:v}=(0,J.H)(),{t:b,locale:y}=(0,R.s)(),w=P(),[M,$]=(0,i.useState)([]),E=t&&!M.some(e=>e.id===t.id)?[t,...M]:M,[L,A]=(0,i.useState)(!0),[z,W]=(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)(""),[en,el]=(0,i.useState)("projects"),[eu,ep]=(0,i.useState)(()=>new Set),[em,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),[eA,ez]=(0,i.useState)(null),[eW,eP]=(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,tn]=(0,i.useState)(()=>new Set),[tr,ti]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(G);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}})()),[ts,ta]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ta(function(){try{let e=window.localStorage.getItem(Y);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(Z)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await ei(n.map(e=>({key:N(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(Z)}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 ei(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&&A(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();$(r.sessions),to.current||tn(new Set(r.runningSessionIds??[])),W(null),e||(te(!0),td.current&&clearTimeout(td.current),td.current=setTimeout(()=>te(!1),2e3))}catch(e){W(String(e))}finally{e&&A(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),ta(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),c?.(e),tp()},[tp,c]),[tm,tf]=(0,i.useState)(null),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useState)(null),ty=(0,i.useCallback)(()=>{tg||(tf(null),tb(null))},[tg]),tw=(0,i.useCallback)(async e=>{tx(!0),tb(null);let t=[],n=[],r=[];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){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(to.current=!0,tn(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(ti(n),ta(n),t))c?.(e)}(await tp(),tx(!1),r.length>0)?tb(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tf(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{el(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=>{el(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==en)return;let e=()=>{"visible"===document.visibilityState&&tp(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tp,en]),(0,i.useEffect)(()=>{try{0===tr.size?window.localStorage.removeItem(G):window.localStorage.setItem(G,JSON.stringify([...tr]))}catch{}},[tr]),(0,i.useEffect)(()=>{try{0===ts.size?window.localStorage.removeItem(Y):window.localStorage.setItem(Y,JSON.stringify([...ts]))}catch{}},[ts]);let tI=(0,i.useCallback)(e=>{ta(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;to.current=!0,tn(new Set(r.runningSessionIds??[]))}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[]),(0,i.useEffect)(()=>{let t=tl.current,n=[...t].filter(t=>!tt.has(t)&&t!==e),r=[...tt].filter(e=>!t.has(e));(n.length>0||r.length>0)&&ti(e=>{let t=new Set(e);return tt.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!M.some(t=>t.id===e));(n.length>0||i)&&tp(!1,!0),n.length>0&&h?.(),tl.current=tt},[tt,e,M,tp,h]),(0,i.useEffect)(()=>{e&&ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[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(a&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===a);if(e){_(e.cwd),n(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,a,l,n,o,ey,ek]);let tA=(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})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eH(n.error??b("workspace.unable"));let r=n.cwd??t,i=N(r),s=ey.projects.find(e=>e.key===i);if(s?.hidden===!0)try{await tu([{key:i,path:r,hidden:!1}])}catch{}_(r),e_(!1)}catch{eH(b("workspace.unable"))}finally{eB(!1)}}},[tu,eO,ey.projects,b]),tz=(0,i.useCallback)(()=>{e_(!0),eH(null)},[]),tW=(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})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eQ(n.error??`HTTP ${t.status}`);eG(!1),eZ(""),eV(!1),eq(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),_(n.path),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eY,e0,eU]),tP=(0,i.useCallback)(async(e,t)=>{if(eU&&!e0){e1(!0),eQ(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e4(e);eQ(r.error??`HTTP ${n.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),eP(""),ex(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tF=(0,i.useCallback)(e=>{e.cwd&&_(e.cwd),n(e)},[n]),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),s?.(t,e)},[F,s]),[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 n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),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),eP("")},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);ez(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{ez(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let n=tZ.indexOf(e),r=n+t;if(n<0||r<0||r>=tZ.length)return;let i=new Set(tZ),s=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),a=[...tY],l=s[n],o=s[r];[a[l],a[o]]=[a[o],a[l]],tQ();try{await tu(a.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 n=N(t),r=t4.get(n);r?r.push(e):t4.set(n,[e])}let t5=(0,i.useMemo)(()=>{let e=new Map;for(let t of E){let n=t.projectRoot??t.cwd;if(!n)continue;let r=N(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),tt.has(t.id)&&i.running++,tr.has(t.id)&&i.unread++}return e},[E,tt,tr]),t8=q.trim().toLowerCase(),t6=q.length>0,t3=tZ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=N(e),r=tJ.get(n),i=r?.alias??t,s=(t4.get(n)??[]).slice().sort((e,t)=>{let n=Number(ts.has(t.id))-Number(ts.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t8)return[{project:e,key:n,name:i,sessions:s,hidden:r?.hidden===!0}];let a=i.toLowerCase().includes(t8)||t.toLowerCase().includes(t8),l=s.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t8));return a||0!==l.length?[{project:e,key:n,name:i,sessions:a?s:l,hidden:r?.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 ne={running:0,unread:0};for(let e of t9){let t=t5.get(e.key);t&&(ne.running+=t.running,ne.unread+=t.unread)}let nt=t6||eN,nn=[...t7.map(e=>({kind:"project",group:e})),...t9.length>0?[{kind:"temporary"}]:[],...nt?t9.map(e=>({kind:"project",group:e})):[]],nr=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nn.flatMap(e=>"project"===e.kind?[e.group.name]:[])),ni=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",s=new Set,a="Pinned"){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),o=l.filter(e=>s.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(s.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(u>=10)continue;u+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=c.get(r);i?i.push(e):c.set(r,[e])}let p=[];for(let e of(o.length>0&&p.push({key:"pinned",label:a,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,n){let[r,i,s]=e.split("-").map(Number),a=new Date(r,i-1,s),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(a.getFullYear(),a.getMonth(),a.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(a):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(a)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ts,b("sidebar.pinned")),[y,ts,tt,E,b]),ns=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),na=eU?.worktrees.find(e=>e.path===F)??eU?.worktrees.find(e=>e.isMain),nl=(eU?.worktrees.length??0)>=8,no=nl&&eW.trim()?(eU?.worktrees??[]).filter(e=>(e.branch??Q(e.path,D)).toLowerCase().includes(eW.trim().toLowerCase())):eU?.worktrees??[],nd=(()=>{if(!tm)return[];let e="project"===tm.kind?t4.get(N(tm.project))??[]:ni.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nc=nd.filter(e=>!tt.has(e.id)),nu=e=>{let t=new Set;for(let n of e)n.transient||tt.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},np=void 0!==m&&f;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eF&&(0,r.jsx)(B?K:O,{busy:eO,error:eD,onCancel:()=>{e_(!1),eH(null)},onSelect:e=>void tA(e)}),tm&&(0,r.jsx)(ea,{scope:tm,eligible:nc.length,runningExcluded:nd.length-nc.length,busy:tg,error:tv,onCancel:ty,onConfirm:()=>void tw(nc)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(er,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.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,r.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,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.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,r.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,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.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,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),B&&!np&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tz,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,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.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"),n=!np&&en===e;return(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tN(e),np&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("lounge.tab")}),"aria-pressed":np,"aria-controls":"navigator-lounge-panel","data-navigator-mode":"lounge",onClick:()=>g?.(!np),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:np?"var(--bg-selected)":"transparent",color:np?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:np?600:500,whiteSpace:"nowrap"},children:v("lounge.tab")})]}),!np&&"projects"===en&&(0,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"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,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eS&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!np&&"projects"===en&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tz,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,r.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,r.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,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),np&&m,!np&&"projects"===en&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.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,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.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}})]}),!np&&"projects"===en&&(0,r.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,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),eA&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eA}),!L&&ek&&!z&&0===t3.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t8?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&ek&&!z&&nn.map(t=>{let n,i,s;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":nt,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,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:nt?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:t9.length}),eh(ne,b)]})},"navigator-temporary-projects");let{project:a,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=nr.has(o.toLowerCase())&&Q((i=Math.max((n=a.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),D)||null,h=!em.has(a)&&!t8,m=eu.has(a),f=eT===a,g=tZ.indexOf(a),x=eE||t6||g<=0,v=eE||t6||g>=tZ.length-1,y=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?d:d.slice(0,5)),k=d.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ev===a?e5:void 0,onMouseEnter:()=>ex(a),onMouseLeave:()=>ex(e=>e===a&&ev!==a?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,r.jsx)("button",{type:"button",onClick:()=>tq(a),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,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.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,r.jsx)("input",{ref:e6,value:e$,onChange:e=>eR(e.target.value),onBlur:()=>void t1(a),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,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(a),title:a,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,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.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,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),null===p?null:(0,r.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}),eh(t5.get(l),b)]}),(0,r.jsx)("button",{type:"button",onClick:()=>t_(a),title:b("sidebar.newSessionTitle",{path:a}),"aria-label":b("sidebar.newSessionTitle",{path:a}),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===a?1:0,pointerEvents:w||eg===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(a),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,r.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,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eb(ev===a?null:a),eV(!1),eG(!1),eQ(null),u||_(a)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===a?"var(--bg-selected)":"transparent",color:u&&na&&!na.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===a||ev===a?1:0,pointerEvents:w||eg===a||ev===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(a),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(et,{open:ev===a,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:[ns&&eU&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:na?b("sidebar.switchWorktreeTitle",{path:na.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,r.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,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(et,{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:[nl&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eW,onChange:e=>eP(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eP(""),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,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[no.map(e=>{let t=e.path===F||e.isMain&&!eU.worktrees.some(e=>e.path===F);return e2===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tP(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,r.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,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{_(e.path),eV(!1),eQ(null),eP("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(ee,{text:e.branch??Q(e.path,D),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tP(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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nl&&0===no.length&&eW.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eJ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:e8,value:eY,onChange:e=>{eZ(e.target.value),eQ(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tW()),"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,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tW(),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,r.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,r.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,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:b("sidebar.newWorktree")})]}),eX&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eX})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>{let e;return e=tJ.get(N(a))?.alias??"",void(e3.current=!1,ez(null),eR(e),eM(a),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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),b(tJ.get(N(a))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(a,-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,r.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,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(a,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,r.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,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>void t0(a,!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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"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,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(s=0===nu(t4.get(l)??[])||tg,(0,r.jsxs)("button",{type:"button",disabled:s,onClick:()=>{tQ(),tb(null),tf({kind:"project",project:a,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:s?"default":"pointer",textAlign:"left",fontSize:11,opacity:s?.55:1},children:[(0,r.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,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(ec,{node:t,selectedSessionId:e,runningSessionIds:tt,unreadSessionIds:tr,pinnedSessionIds:ts,onSelectSession:tF,onTogglePinnedSession:tI,onRenamed:tp,onSessionDeleted:th,onSessionArchived:tS,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ep(e=>{let t=new Set(e);return t.has(a)?t.delete(a):t.add(a),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:m?b("sidebar.showLess"):b("sidebar.showMore")})]},a)})]}),!np&&(0,r.jsx)(ed,{refreshKey:tk,selectedSessionId:e,onSelectSession:tF,onRestored:tS}),!np&&"priority"===en&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[L&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),!L&&!z&&(x=nu(ni.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:tD,onClick:()=>void tU(),title:b("sidebar.newScratchSessionTitle"),style:X(tD,w),children:b("sidebar.newScratchSession")}),ni.length>0&&(0,r.jsx)("button",{type:"button",disabled:0===x||tg,onClick:()=>{tb(null),tf({kind:"priority"})},style:X(0===x||tg,w),children:b("sidebar.clearPriorityList")})]})),tO&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tO}),!L&&!z&&0===ni.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!z&&ni.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"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,r.jsx)(eo,{session:t,selected:t.id===e,running:tt.has(t.id),unread:tr.has(t.id),pinned:ts.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function ea({scope:e,eligible:t,runningExcluded:n,busy:s,error:a,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=s||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(s);h.current=s;let m=(0,i.useRef)(l);return m.current=l,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=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),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{s||e.target!==e.currentTarget||l()},children:(0,r.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,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,r.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}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:a})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:l,disabled:s,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":s,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(s?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function el({filled:e=!1}){return(0,r.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,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function eo({session:e,selected:t,running:n,unread:i,pinned:s,onSelect:a,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,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>a(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,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.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}),n&&(0,r.jsx)(eu,{}),!n&&i&&(0,r.jsx)(ep,{})]}),(0,r.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,r.jsx)("button",{type:"button","aria-pressed":s,"aria-label":o(s?"sidebar.unpin":"sidebar.pin"),title:o(s?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:s?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(el,{filled:s})})]})}function ed({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:s}){let{t:a}=(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 n=await t.json();e||c(n.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})}),s(t)}catch{}},[s]);return 0!==d.length||l?(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.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,r.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,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),a("sidebar.archived")," (",d.length,")"]}),l&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===d.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:a("sidebar.noArchivedSessions")}),d.map(e=>{let i=$(e.firstMessage)??e.firstMessage,s=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(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,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:a("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:a("sidebar.restore")})]},e.id)})]})]}):null}function ec({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:l,onRenamed:o,onSessionDeleted:d,onTogglePinnedSession:c,onSessionArchived:u,depth:p}){let[h,m]=(0,i.useState)(!1),f=e.children.length>0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(em,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:s.has(e.session.id),isPinned:a.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:f,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),f&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ec,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:l,onTogglePinnedSession:c,onRenamed:o,onSessionDeleted:d,onSessionArchived:u,depth:p+1},e.session.id))})]})}function eu(){let{t:e}=(0,R.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function ep(){let{t:e}=(0,R.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function eh(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.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,r.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,r.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,r.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,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function em({session:e,isSelected:t,isRunning:n,isUnread:s,isPinned:a,onClick:l,onTogglePin:o,onRenamed:d,onDeleted:c,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:f}){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]),A=(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]),z=(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]),W=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?A():S(!0)},[A]),P=(0,i.useCallback)(e=>{e.stopPropagation(),A()},[A]),F=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),_=(0,i.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({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,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${s?" 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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:P,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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,r.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,r.jsxs)(r.Fragment,{children:[p>0&&(0,r.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,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.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,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(eu,{}),!n&&s&&(0,r.jsx)(ep,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"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:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),o?.()},title:g(a?"sidebar.unpin":"sidebar.pin"),"aria-label":g(a?"sidebar.unpin":"sidebar.pin"),"aria-pressed":a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:a?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||a?1:0,pointerEvents:x||a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(el,{filled:a})}),(0,r.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,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:z,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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{onClick:W,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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let ef=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eg=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,ex=/\x1B\[([0-9;]*)m/g,ev=/\x1B_pi:c\x07/g,eb=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],ey=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function ew(e){return e.replace(ev,"").replace(ef,"")}function ek(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eg);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function ej(e,t){let n=ek(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eS(e){return ek(e)[0]?.char}function eC(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(ev,""),i=ew(e).trimEnd();if(t.test(i))continue;let s=e,a=eS(s);("│"===a||"┃"===a)&&" "===eS(s=ej(s,0))&&(s=ej(s,0));let l=function(e){let t=ek(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),o=l>=0?ek(s)[l]?.char:void 0;("│"===o||"┃"===o)&&(s=ej(s,l)),n.push(function(e){let t=e;for(;;){let e=ek(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===ew(n[0]).trim();)n.shift();for(;n.length>0&&""===ew(n[n.length-1]).trim();)n.pop();return n.length?n:e}function eN(e){let t,n=[],r={},i=0;for(ex.lastIndex=0;null!==(t=ex.exec(e));)t.index>i&&n.push({text:e.slice(i,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=eb[r-30];else if(r>=90&&r<=97)n.color=ey[r-90];else if(r>=40&&r<=47)n.backgroundColor=eb[r-40];else if(r>=100&&r<=107)n.backgroundColor=ey[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,s,a]=[t[e+2],t[e+3],t[e+4]];[i,s,a].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${s}, ${a})`:n.backgroundColor=`rgb(${i}, ${s}, ${a})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return eb[e];if(e>=8&&e<16)return ey[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(n)}, ${i(r)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===r?n.color=i:n.backgroundColor=i),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&n.push({text:e.slice(i),style:r}),n}let eI={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:""},eT={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eM={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"},e$={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 eR(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eE(e){return null!==(eM[eR(e)]??null)}function eL(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eA(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 ez(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eW(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eA(e,t))}(e,t)){let e="image"===r.type||"text"===r.type&&r.text.trim().length>0?"answer":"process",t=n[n.length-1];t?.kind===e?t.blocks.push(r):n.push({kind:e,blocks:[r]})}return n}function eP(e){return e.filter(e=>"toolCall"===e.type).length}function eF(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}function e_(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let s of i)"toolCall"===s.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};return"generate_image"===e.toolName||("write"===e.toolName?"xd://generate_image"===n.path:"read"===e.toolName&&"string"==typeof n.path&&eE(n.path))}(s,t.get(s.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:s.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let eD=new Map,eH=new Map,eO="command",eB="autolearn-saved";function eU(e){return"custom"===e.role&&(e.customType===eO||e.customType===eB&&!1!==e.display)}let eq="local-command:";function eK(e){return e?.startsWith(eq)===!0}function eV(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],s=[];for(let n=0;n<e.length;n++){let a=n<t.length;!(r.has(e[n])||a&&eK(t[n]))&&(i.push(e[n]),a&&s.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=s.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=s.length&&s.splice(t,0,e.entryId)}return{messages:i,entryIds:s}}function eJ(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let eG={create:!0,update:!0};function eY(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function eZ(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let n of e)n&&"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&"string"==typeof n.text&&t.push(n.text);return t.join("\n")}function eX(e,t){if(0===e.length)return -1;if(!t)return 0;let n=-1;for(let r=0;r<e.length;r++){let i=e[r];if(i.item===t.item){if(i.k===t.k)return r;n=r}}return -1===n?0:n}function eQ(e){try{return decodeURIComponent(e)}catch{return e}}function e0(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e1(e){let t=e0(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){s.length>0&&".."!==s[s.length-1]?s.pop():i||n||r||s.push(e);continue}s.push(e)}let a=s.join("/");return n?a:r?`//${a}`:i?`/${a}`:a}function e2(e,t,n=t){let r,i,s,a,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=eQ(o),p=u.startsWith("\\\\"),h=e0(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=eQ(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(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=`${e0(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let f=e1(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=e1(f).replace(/\/+$/,""),i=e1(n).replace(/\/+$/,""),a=(s=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(a===(l=s?i.toLowerCase():i)||a.startsWith(`${l}/`)))?null:f}function e4(e,t,n){let r=new Set,i=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,n;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(n=e.toLowerCase())||n.startsWith("edit_")||n.endsWith(".edit")||n.endsWith("_edit")||n.includes("str_replace")||n.includes("replace_editor")}(s.toolName))continue;let e=t?.get(s.toolCallId);if(!e||e.isError)continue;let a=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(s.input);if(!a||!/^[a-zA-Z]:[\\/]/.test(a)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(a))continue;let l=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),a=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(s),o=s.startsWith("//");if(l||o)n=s;else if(s.startsWith("/")){let e=a?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??a?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!a)return null;n=`${a}/${s}`}return e1(n)}(a,n);l&&(r.has(l)||(r.add(l),i.push({filePath:l})))}return i}function e5(e,t){var n;let r;if(t){let e=t.details,n=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(n))return{kind:"unknown"};let{phases:r,malformed:i}=function(e){let t=[];for(let n of e){if(!n||"object"!=typeof n||!("name"in n)||!("tasks"in n))return{phases:t,malformed:!0};let{name:e,tasks:r}=n;if("string"!=typeof e||!Array.isArray(r))return{phases:t,malformed:!0};let i=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;return"string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n?[]:[{content:t,status:n,blocker:"blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0}]}):[];if(i.length!==r.length)return{phases:t,malformed:!0};i.length>0&&t.push({name:e,tasks:i})}return{phases:t,malformed:!1}}(n);return i?{kind:"unknown"}:{kind:"authoritative",phases:r}}let i=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}function e8(e,t,n=null,r=null){return n||(function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if("assistant"!==r.role)continue;let i=r.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let n=i[e];if("toolCall"!==n.type||!function(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}(n.toolName))continue;let r=e5(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function e6(e){let t=0,n=0,r=null,i=null,s=null;for(let a of e)for(let e of a.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:a,task:e}):"blocked"===e.status?s||(s={phase:a,task:e}):i||(i={phase:a,task:e}))}let a=r??i??s,l=t+n;return{currentPhase:a?.phase??null,activeTask:a?.task??null,remaining:n,completed:t,total:l,percent:l>0?Math.round(t/l*100):null}}var e3=n(65063),e7=n(7644),e9=n(32316);function te(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tt(e){return te(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tn(e){let t=te(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tr(e,t){if(!t)return e;let n=te(e),r=te(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var ti=n(88374),ts=n(63280),ta=n(94764),tl=n(63835),to=n(54152),td=n(84678),tc=n(98164);let tu={...ta.j,attributes:{...ta.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...ta.j.strip||[],"iframe","object","style","form"]};function tp(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,a=null,l=new Map;for(let e=0;e<n.length;e++){var o;let t=n[e];if(a){r.push(t),RegExp(`</${a}\\s*>`,"i").test(t)&&(a=null);continue}let d=t.match(/^ {0,3}(`{3,}|~{3,})/);if(d){let e=d[1][0],n=d[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let c=t.match(/<(code|pre|script|style)\b/i);if(c){let e=c[1].toLowerCase(),n=t.slice((c.index??0)+c[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(a=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.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 n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>tm(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){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],i=m[2].trimEnd();if(i&&!i.includes("$$")){let s=th(n,e+1,t,l);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(tm(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],i=th(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(tm(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.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 r.join(t)}function th(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,a,l,o;let t=e[i];if(s=t,""===(a=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(a)&&/^\$\$\s*$/.test(s.slice(a.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 r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function tm(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let tf={singleTilde:!1},tg=[[to.A,["yaml"]],[td.A,tf],tc.A],tx=[[to.A,["yaml"]],[td.A,tf],tc.A],tv=[ts.A,[tl.A,tu],[ti.A,{throwOnError:!1,strict:!1}]],tb=[ts.A,[tl.A,tu],[ti.A,{throwOnError:!1,strict:!1}]],ty="pi-theme",tw=["light","dark","auto"],tk={preference:"auto",theme:"light"},tj="omp-theme",tS=null,tC=0,tN=new Set,tI=null,tT=!1;function tM(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function t$(e){return"auto"===e?tM():e}let tR="--omp-md-";function tE(e){let t=document.documentElement,n=tS?.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 n=t.style.item(e);n.startsWith("--")&&!n.startsWith(tR)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(tR)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tj,e)}catch{}}function tL(){if(tI)return tI;let e=function(){try{let e=localStorage.getItem(ty);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tj);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=t$(e);return tE(t),tI={preference:e,theme:t}}function tA(e,t,n){if(tE(t),n)try{localStorage.setItem(ty,e)}catch{}tI={preference:e,theme:t},tN.forEach(e=>e())}function tz(){let e=tL();if("auto"!==e.preference)return;let t=tM();t!==e.theme&&tA("auto",t,!1)}function tW(e){return tN.add(e),tL(),tT||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tz),window.addEventListener("focus",tz),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tz()}),tT=!0),tz(),()=>{tN.delete(e)}}function tP(){return tL()}function tF(){return tk}async function t_(e){let t=++tC,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/theme${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Theme request failed (${r.status})`);let i=await r.json();if(t===tC){tS=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(tS))}catch{}tE(tL().theme)}}function tD(e){let t=(0,i.useSyncExternalStore)(tW,tP,tF);(0,i.useEffect)(()=>{e?.syncWithOmp&&t_(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=t$(e),r=()=>{tA(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,a=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(a,window.innerHeight-a));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${a}px)`,`circle(${l}px at ${s}px ${a}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=tL().preference,r=tw.indexOf(t),tw[(r+1)%tw.length]),e)},[n]),s=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:s,isDark:"dark"===t.theme}}function tH(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 tO={...e7.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...e7.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function tB({code:e,isStreaming:t,defaultPreview:s=!1}){let{isDark:a}=tD(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(s),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),m=`${a?"dark":"light"}
4
4
  ${e}`,f=o&&!t;(0,i.useEffect)(()=>{if(!f)return;let t=!1;return u({key:m,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328)),i=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${i}`,e),await document.fonts.ready,t)return;if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:a?"dark":"default",fontFamily:i}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let s="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,l=await r.render(s,e);t||u({key:m,status:"ready",svg:l.svg})})().catch(()=>{t||u({key:m,status:"error"})}),()=>{t=!0}},[e,m,a,f]);let g=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?l("i18n.previewAfterStreaming"):f?l("i18n.showMermaidSource"):l("i18n.previewMermaid"),className:["markdown-code-action",f?"is-active":""].filter(Boolean).join(" "),children:f?l("i18n.source"):l("i18n.preview")}),[t,f,l]);if(!f)return(0,r.jsx)(tq,{code:e,lang:"mermaid",headerAction:g,isStreaming:t});let x=c?.key===m&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:l("i18n.invalidMermaid")}):c?.key!==m||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":l("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!p&&(0,r.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,r.jsx)(tU,{svg:c.svg,onClose:()=>h(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),g]}),x]})}function tU({svg:e,onClose:t}){let{t:n}=(0,R.s)(),s=(0,i.useRef)(null),[a,l]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:s,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.max(.5,e-.25)),disabled:a<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*a),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:a>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>l(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*a}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tq=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:s}){let{isDark:a}=tD(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{tH(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:l(o?"i18n.copied":"i18n.copy")})]})]}),s?(0,r.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,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(e3.A,{language:t||"text",style:a?e7.xJ:tO,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 tK({children:e,className:t,isStreaming:n,cwd:s,onOpenFile:a}){let l=(0,i.useMemo)(()=>tp(e),[e]),o=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let s=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===s?(0,r.jsx)(tB,{code:a.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(tq,{code:a.replace(/\n$/,""),lang:s,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=a?e2(e,s):null;return i&&a?(0,r.jsx)("a",{href:e,...n,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(),a(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?e2(e,s):null,a=i?`/api/files/${tt(i)}?type=read`:e;return(0,r.jsx)("img",{src:a,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[s,n,a]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(e9.oz,{remarkPlugins:tg,rehypePlugins:tv,components:o,children:l})})}let tV=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,tJ=/(?:\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 tG(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let tY={hideThinkingBlock:!1},tZ=new Set,tX=tY,tQ=0;function t0(e){return tZ.add(e),()=>{tZ.delete(e)}}function t1(){return tX}function t2(){return tY}async function t4(e){let t=++tQ,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/display-settings${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Display settings request failed (${r.status})`);let i=await r.json();t!==tQ||i.hideThinkingBlock!==tX.hideThinkingBlock&&(tX={hideThinkingBlock:!0===i.hideThinkingBlock},tZ.forEach(e=>e()))}function t5(){return(0,i.useSyncExternalStore)(t0,t1,t2)}var t8=n(64178);let t6={faces:new Map,pins:new Map},t3=[],t7=t6,t9=null,ne=new Map,nt=new Set;function nn(e){return nt.add(e),()=>{nt.delete(e)}}function nr(e){t7=e,nt.forEach(e=>e())}function ni(e){return Number.isSafeInteger(e)&&e>0}function ns(e,t){return`${e}:${t}`}function na(e,t,n){if(!t)return null;if(ni(n)){let e=t7.faces.get(ns(t,n));if(e)return e}let r=e?t7.pins.get(e):void 0;if(r&&r.provider===t){let e=t7.faces.get(ns(t,r.credentialId));if(e)return e}return(0,t8.e$)(t)}async function nl(e,t,n){if(!t||ni(n)||(0,t8.e$)(t))return na(e,t,n);try{let{data:n}=await (0,t8.ST)(e);if(n?.state==="resolved"&&n.provider===t&&ni(n.credentialId)){let r=new Map(t7.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),nr({faces:t7.faces,pins:r})}}catch{}return na(e,t,void 0)}function no(e,t,n){let r=!!t&&!ni(n)&&!!e;return(0,i.useEffect)(()=>{r&&e&&t&&function(e,t){let n=Date.now(),r=t7.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,s=ne.get(i);void 0!==s&&n-s<3e4||(ne.set(i,n),(0,t8.ST)(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!ni(i))return;let s=new Map(t7.pins);s.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),nr({faces:t7.faces,pins:s})}).catch(()=>{}))}(e,t)},[r,e,t]),(0,i.useSyncExternalStore)(nn,()=>na(e,t,n),()=>null)}var nd=n(2730);let nc={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 nu(){let{locale:e}=(0,R.s)();return{st:(0,i.useCallback)((t,n)=>(0,nd.u0)(e,t,nc,n),[e]),locale:e}}function np({seed:e,size:t,provider:n}){let[s,a]=(0,i.useState)(!1),[l,o]=(0,i.useState)(!1);return s?(0,r.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,t8.xl)(e).slice(0,1)}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),o(!0)},"aria-label":(0,t8.xl)(e),children:(0,r.jsx)("img",{className:"account-avatar",src:(0,t8.uk)(e),width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>a(!0)})}),l&&(0,r.jsx)(nh,{seed:e,provider:n,onClose:()=>o(!1)})]})}function nh({seed:e,provider:t,onClose:n}){let{t:s}=(0,R.s)(),a=(0,i.useRef)(null);(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()}},[]);let l=(0,t8.xl)(e);return(0,F.createPortal)((0,r.jsxs)("dialog",{ref:a,className:"account-avatar-dialog","aria-label":l,onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&n()},children:[(0,r.jsx)("img",{className:"account-avatar-full",src:(0,t8.uk)(e),width:256,height:256,alt:l,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:l}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:(0,t8.bN)(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:s("i18n.close")})]}),document.body)}function nm(e){let t,n=[],r=null,i=0,s=0,a=0,l=0,o=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){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(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}o=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(a>0||l>0)){if(c.startsWith("--- ")){u(),t=nf(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:nf(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),s=Number(e[3]),a=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:s++,text:h,type:"context"}}),a>0&&a--,l>0&&l--):"-"===p?(o.push({lineNo:i++,text:h}),a>0&&a--):"+"===p?(d.push({lineNo:s++,text:h}),l>0&&l--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function nf(e){return e.split(" ")[0].trim()}function ng({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,s="blocked"===e.status;return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":n?"is-abandoned":s?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":s?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,s&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let nx="/icons/catppuccin";function nv({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${nx}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${nx}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function nb({size:e=14,open:t=!1}){return(0,r.jsx)(nv,{name:t?"_folder_open":"_folder",size:e})}function ny({size:e=14}){return(0,r.jsx)(nv,{name:"_file",size:e})}let nw={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 nk(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(nv,{name:i,size:t});let s=nw[n.split(".").pop()??""];return s?(0,r.jsx)(nv,{name:s,size:t}):(0,r.jsx)(ny,{size:t})}function nj({files:e,onOpenFile:t}){let{t:n}=(0,R.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=tn(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("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:[nk(i,12),(0,r.jsx)("span",{children:i})]},e)})})}var nS=n(59959);let nC={verdicts:new Map,runs:new Map,latestByAgent:new Map};function nN(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function nI(e){return"string"==typeof e&&e.trim()?e:null}function nT(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 nM(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function n$(e,t){if(t?.isError)return null;let n=nN(e.input.tasks),r=nN(t?.details?.progress),i=Math.max(n.length,r.length),s=[];for(let a=0;a<i;a++){let i=r.find(e=>e.index===a)??r[a],l=n[a],o=nI(i?.id)??nI(l?.name);o&&s.push({key:`${e.toolCallId}#${a}`,toolCallId:e.toolCallId,index:a,agentId:o,agent:nI(i?.agent)??nI(l?.agent),task:nI(i?.task)??nI(l?.task)??"",spawned:!!t})}return s}let nR=/<task-result\b([^>]*)>/g,nE=/(\w+)="([^"]*)"/g;function nL(e,t,n){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&n.latestByAgent.get(e.agentId)===e.key)}function nA(e,t,n){let r,i=nL(e,t,n),s=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}},a=(0,nS.$V)(s),l=n.runs.get(e.key),o=null;i&&"unknown"!==i.status?(r=i.status,o="live"):l&&"unknown"!==l.status?(r=l.status,o="record"):r=e.spawned?"unobserved":"dispatching";let d=n.verdicts.get(e.key);return{member:e,title:a.title,explicitTitle:a.explicitTitle,stage:i?a.stage:null,model:i?(0,nS.A7)(s):null,run:r,runSource:o,verdict:d&&d.length>0?d[d.length-1]:null}}function nz(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function nW(e,t,n){let r=-1;n.forEach((e,t)=>{"user"===e.role&&(r=t)});let i=n.slice(0,r+1).flatMap(nz),s=n.slice(r+1).flatMap(nz),a=t.findIndex(e=>"user"===e.role),l=0===s.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===a||e.idx<a));return -1===l?{continuing:null,atCompaction:[...i,...s]}:{continuing:{position:l,calls:s},atCompaction:i}}let nP={dispatching:"running",pending:"running",running:"running",completed:"awaiting",failed:"awaiting",aborted:"awaiting",unobserved:null},nF=(0,i.createContext)({ledger:nC,subagents:[],toolResults:new Map});function n_(e,t){if(0===e.length)return null;let n=[...e].sort((e,t)=>e-t),r=(n.length-1)*t,i=Math.floor(r),s=Math.ceil(r);return n[i]+(n[s]-n[i])*(r-i)}let nD=["investigate","implement","verify","report"],nH={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},nO={bash:!0,eval:!0};function nB(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}var nU=n(75514);function nq(e){let[t,n]=(0,i.useState)(()=>Date.now());return(0,i.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}function nK({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:s=!0}){let a=(0,i.useMemo)(()=>t.filter(e=>(0,nU.Ch)(e.status)),[t]),l=r&&!!e&&a.length>0,o=(0,i.useMemo)(()=>a.map(e=>({key:e.id,liveId:e.id,status:e.status})),[a]),d=(0,nU._Z)(o,{sessionId:e??"",client:n,enabled:l&&s}),[c,u]=(0,i.useState)(null),p=a.map(e=>e.id).sort().join("\n");return(0,i.useEffect)(()=>{let t;if(!l||!e)return;let n=new AbortController,r=p.split("\n"),i=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,s=!0,a=0;async function o(){try{let t=await fetch(i,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(15e3)])}),a=t.ok?await t.json():null;!n.signal.aborted&&a&&a.sessionId===e&&a.histories&&"object"==typeof a.histories&&(u(a),s=r.some(e=>!a.histories[e]))}catch{}finally{if(!n.signal.aborted){let e=s&&a<3;e&&(a+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{n.abort(),window.clearTimeout(t)}},[p,l,e]),(0,i.useMemo)(()=>{let t=new Map;if(!l)return t;let n=c&&c.sessionId===e?c.histories:void 0;for(let e of a){let r=(s?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",n=!1;for(let r of e){if("assistant"!==r.role)continue;let e=r.content;if(Array.isArray(e))for(let r of e){if("toolCall"!==r.type)continue;let e=(r.toolName??"").toLowerCase().split(/[.:/]/).pop()??"";nH[e]?(n=!0,t="implement"):nO[e]?t=n?"verify":"investigate":"yield"===e&&(t="report",n=!1)}}return t}(r),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=e8([...e],t);if(!n)return null;let r=e6(n);return 0===r.total||null===r.percent?null:{completed:r.completed,total:r.total,percent:r.percent,activeTask:r.activeTask?.content??null}}(r),history:n?.[e.id]??null})}return t},[a,c,l,d,e,s])}function nV(e,t){let n=nB(t);return n?0===n.hours?e("duration.minutes",{minutes:n.minutes}):0===n.minutes?e("duration.hours",{hours:n.hours}):e("duration.hoursMinutes",{hours:n.hours,minutes:n.minutes}):e("duration.underMinute")}function nJ(e,t){let n=Math.floor(t/1e3);return n<60?e("duration.seconds",{seconds:n}):n<3600?e("duration.minutesSeconds",{minutes:Math.floor(n/60),seconds:n%60}):nV(e,t)}function nG({phase:e}){let{st:t}=nu();return(0,r.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,r.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,r.jsx)("span",{"aria-hidden":"true",children:nD.map((n,i)=>(0,r.jsxs)("span",{children:[i>0&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,r.jsx)("span",{"data-current":n===e?"":void 0,style:n===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${n}`)})]},n))})]})}function nY(e,t){let n=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${n} \xb7 ${t.activeTask}`:n}function nZ({snapshot:e,view:t,id:n}){var i,s,a;let l,o,d,{st:c}=nu(),u=nq(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 n=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(n.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:n.length};let r=n_(n,.5)??0;return{kind:"remaining",p25Ms:n_(n,.25)??0,medianMs:r,p75Ms:n_(n,.75)??0,samples:n.length,percent:Math.round(t/(t+r)*100)}}(t.history,p),m=(i=t.todo,!i||null===p||0===i.completed||i.completed>=i.total?null:p*(i.total-i.completed)/i.completed),f={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,r.jsxs)("span",{id:n,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,r.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:c("eta.elapsed",{duration:nJ(c,p)})}),g?.rework&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:c("eta.reworkHint"),children:null!==x&&x>=0?c("eta.rework",{attempt:g.attempt,duration:nJ(c,x)}):c("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{title:c("eta.hint"),children:c("eta.remaining",{range:(s=h.p25Ms,a=h.p75Ms,o=nB(s),d=nB(a),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:nV(c,s),high:nV(c,a)})),samples:h.samples})})," \xb7 ",(0,r.jsx)("span",{style:f,children:c("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:{color:"var(--warning)"},title:c("eta.hint"),children:0===h.longerRuns?c("eta.overrun",{longest:nV(c,h.longestMs)}):c("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==m&&t.todo&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:c("eta.byTodoHint"),children:m<6e4?c("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):c("eta.byTodo",{duration:nV(c,m),completed:t.todo.completed,total:t.todo.total})})]})]})}let nX={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},nQ={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function n0({maker:e,st:t}){let n=e.verdict?.verdict??"none",i=e.verdict?.attempt;return(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(nX[e.run])}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":n,children:[t(nQ[n]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function n1({calls:e}){let{ledger:t,subagents:n,toolResults:s,onOpenPanel:a,focusedDispatch:l,sessionId:o}=(0,i.useContext)(nF),{st:d}=nu(),[c,u]=(0,i.useState)(!1),p=(0,i.useId)(),h=(0,i.useMemo)(()=>(0,nS.Et)(),[]),m=(0,i.useMemo)(()=>e.flatMap(e=>n$(e,s.get(e.toolCallId))??[]).map(e=>nA(e,n,t)),[e,s,n,t]),f=(0,i.useMemo)(()=>m.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=nL(e.member,n,t);return r?[r]:[]}),[m,n,t]),g=nK({sessionId:o,snapshots:f,client:h,enabled:!0,transcripts:c});if(0===m.length)return null;let x=0,v=0,b=0;for(let e of m)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(x+=1),"completed"===e.run&&(v+=1),e.verdict?.verdict==="accepted"&&(b+=1);return(0,r.jsxs)("section",{className:l&&m.some(e=>e.member.key===l)?"answer-dispatch answer-dispatch-flash":"answer-dispatch","aria-label":d("dispatch.title",{count:m.length}),children:[(0,r.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,r.jsx)("span",{className:"answer-dispatch-heading",children:d("dispatch.title",{count:m.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:d("dispatch.tally",{running:x,done:v,accepted:b})}),(0,r.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,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,r.jsx)("ul",{className:"answer-dispatch-list",id:p,children:m.map(e=>{let t="pending"===e.run||"running"===e.run,n=t?f.find(t=>t.id===e.member.agentId):void 0,i=n?g.get(n.id):void 0;return(0,r.jsxs)("li",{className:"answer-dispatch-row","data-focused":e.member.key===l?"":void 0,children:[(0,r.jsxs)("div",{className:"answer-dispatch-line",children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,r.jsx)(n0,{maker:e,st:d})]}),n&&i&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[i.phase&&(0,r.jsx)(nG,{phase:i.phase}),i.phase&&i.todo?` \xb7 ${nY(d,i.todo)}`:null,i.phase?" \xb7 ":null,(0,r.jsx)(nZ,{snapshot:n,view:i})]}),c&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[t&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:d("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??d("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:d("detail.model")}),(0,r.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,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:d("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.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,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:d("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),c&&a&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>a("subagents"),children:d("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>a("process"),children:d("detail.openProcess")})]})]})}function n2({summary:e,onOpenFile:t}){let{ledger:n,subagents:s,toolResults:a}=(0,i.useContext)(nF),{st:l}=nu(),[o,d]=(0,i.useState)(!1),c=(0,i.useId)(),u=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>n$(e,a.get(e.toolCallId))??[]).map(e=>nA(e,s,n)),[e.dispatchCalls,a,s,n]),p=e.checks.filter(e=>"failed"===e.state),h=e.checks.filter(e=>"passed"!==e.state),m=u.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted"),f=h.length+m.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})),f>0&&g.push(l("summary.unverified",{count:f})),(0,r.jsxs)("div",{className:"answer-summary",children:[(0,r.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,r.jsx)("span",{className:"answer-summary-text","data-unverified":f>0?"":void 0,children:g.join(" \xb7 ")}),(0,r.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,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),o&&(0,r.jsxs)("div",{className:"answer-summary-body",id:c,children:[e.files.length>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.files")}),(0,r.jsx)(nj,{files:e.files,onOpenFile:t})]}),e.checks.length>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.checks")}),(0,r.jsx)("ul",{className:"answer-summary-list",children:e.checks.map(e=>(0,r.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,r.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,r.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))})]}),f>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.unverified")}),(0,r.jsxs)("ul",{className:"answer-summary-list",children:[h.map(e=>(0,r.jsx)("li",{children:l("failed"===e.state?"summary.u.checkFailed":"summary.u.checkUnobserved",{command:e.command})},`check-${e.toolCallId}`)),m.map(e=>(0,r.jsxs)("li",{className:"answer-summary-maker",children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,r.jsx)(n0,{maker:e,st:l})]},`maker-${e.member.key}`))]})]})]})]})}let n4=/^att_[0-9a-f]{32}$/,n5=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function n8(e){return"string"==typeof e&&n4.test(e)}function n6(e){return"string"==typeof e&&n5.test(e)}class n3 extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let n7={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},n9={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},re={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function rt(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let n=t.lastIndexOf(".");if(n>0&&n9[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&re[r]?"text":null}let rn={".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 rr(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?rn[t.slice(n)]:void 0;if(r)return r;let i=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return i?.startsWith("audio/")?i:null}function ri(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function rs(e){if(!Array.isArray(e))return[];let t=[],n=0,r=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;!(n+i.size>0x1000000)&&(r+i.text.length>24e4||(t.push({name:i.name,mimeType:i.mimeType,size:i.size,text:i.text,...n8(i.attachmentId)?{attachmentId:i.attachmentId}:{}}),n+=i.size,r+=i.text.length))}}return t}async function ra(e){let t,n=rt(e);if(!n)throw new n3("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new n3("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await rg(e);else{try{t=await e.text()}catch(e){throw new n3("read_failed",e instanceof Error?e.message:String(e))}rx(t)}return{name:e.name,mimeType:n7[n],size:e.size,text:t}}function rl(e,t){let n=rs(t);if(0===n.length)return e;let r={userMessageLength:e.length,documents:n.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,textLength:r.length}))},i=`${rv}${JSON.stringify(r)}${rb}
@@ -16,7 +16,7 @@ Attached: ${n}`:`Attached: ${n}`}(g)).then(()=>{f(!0),setTimeout(()=>f(!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!==s)return;let n=!0;return(function(e,t){let n=`${e}
17
17
  ${t}`,r=eD.get(n);if(void 0!==r)return Promise.resolve(r);let i=eH.get(n);if(i)return i;let s=fetch(eF(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),r=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return eD.set(n,r),r}).catch(()=>0).finally(()=>eH.delete(n));return eH.set(n,s),s})(e,t).then(e=>{n&&a(e)}),()=>{n=!1}},[s,e,t]),!s)return null;let u=Array.from({length:s},(e,t)=>t).filter(e=>!d.has(e));return 0===u.length?null:(0,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(i=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>o(i),children:(0,r.jsx)("img",{src:eF(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>c(e=>new Set(e).add(i))})},i)),null!==l&&(0,r.jsx)(rF,{src:eF(e,t,l),onClose:()=>o(null)})]})}function rF({src:e,onClose:t}){let{t:n}=(0,R.s)(),s=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,F.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"tool-image-dialog",onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:[(0,r.jsx)("img",{className:"tool-image-full",src:e,alt:"",draggable:!1}),(0,r.jsx)("button",{type:"button",className:"tool-image-close",onClick:t,children:n("i18n.close")})]}),document.body)}function r_({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(rI,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rD({block:e,duration:t,sessionId:n,entryId:s,blockIndex:a}){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 n&&s?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=rN.get(r);if(i)return rN.delete(r),rN.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw rN.delete(r),e});if(rN.set(r,s),rN.size>100){let e=rN.keys().next().value;e&&rN.delete(e)}return s})(n,s,a).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,a,s,n,l]);let m=e.deferred?o:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":l("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:c?(0,r.jsx)("span",{className:"markdown-thinking-status",children:l("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,r.jsx)(tK,{className:"markdown-thinking-body",children:m}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:l("chat.thinking")})}),void 0!==t&&f&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function rH({block:e,result:t,duration:n}){let s,a=e.toolName.toLowerCase(),l="edit"===a||a.startsWith("edit_")||a.endsWith(".edit")||a.endsWith("_edit")||a.includes("str_replace")||a.includes("replace_editor"),[o,d]=(0,i.useState)(l),c=JSON.stringify(e.input,null,2),u="todo"===a||a.endsWith(".todo")||a.endsWith("_todo"),p="bash"===a||a.startsWith("bash ")||a.endsWith(".bash")||a.endsWith("_bash"),h=t&&!t.isError?function(e){let t=e.details;if(!rQ(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(t):null,m=u?"unknown"===(s=e5(e,t)).kind||0===s.phases.length?null:s.phases:null,f=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,r.jsx)(rV,{command:rQ(e.input)&&"string"==typeof e.input.command?e.input.command:"",output:g??"",pending:!t,isError:v,duration:n,local:a.includes("(local)")});if(u&&m)return(0,r.jsx)(rK,{phases:m});let b=!!(m||h),y=function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.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 n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(0,120);if("file_path"in n)return String(n.file_path).slice(0,120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let s=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==s)return String(s).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,m);return(0,r.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,r.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,r.jsx)(rU,{toolName:e.toolName,isError:v}),(0,r.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,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:y}),f&&(0,r.jsxs)("span",{title:`${f.added} lines added, ${f.removed} lines removed`,"aria-label":`${f.added} lines added, ${f.removed} lines removed`,style:{display:"inline-flex",alignItems:"center",gap:6,flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",f.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",f.removed]})]}),void 0!==n&&(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[n,"s"]}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:o?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),h&&(0,r.jsx)("div",{style:{maxHeight:o?560:260,overflowY:"auto",overflowX:"hidden",borderTop:"1px solid var(--success-line)"},children:(0,r.jsx)(rJ,{diff:h})}),t&&v&&(0,r.jsx)(r0,{text:g??"",isEmpty:x,isError:!0}),o&&!b&&(0,r.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,r.jsx)(r0,{text:g??"",isEmpty:x,isError:!1})]})}let rO={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 rB(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function rU({toolName:e,isError:t}){let n,i=(n=e.trim().toLowerCase()).includes("str_replace")||n.includes("replace_editor")||rB(n,"edit")?"edit":rB(n,"read")||rB(n,"cat")?"read":rB(n,"write")||rB(n,"save")?"write":rB(n,"glob")||rB(n,"find")?"glob":rB(n,"grep")||rB(n,"search")?"grep":rB(n,"bash")||rB(n,"shell")||rB(n,"exec")?"bash":rB(n,"todo")?"todo":rB(n,"eval")?"eval":rB(n,"task")||rB(n,"agent")?"task":rB(n,"browser")||rB(n,"web_search")||rB(n,"fetch")?"browser":rB(n,"image")||rB(n,"inspect_image")?"image":"generic",s=t?"var(--danger)":rO[i];return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:s},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)(rq,{kind:i})})})}function rq({kind:e}){switch(e){case"read":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.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,r.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,r.jsxs)(r.Fragment,{children:[(0,r.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,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,r.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,r.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.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,r.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,r.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,r.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,r.jsx)(r.Fragment,{children:(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,r.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,r.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,r.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,r.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function rK({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),n=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,r.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,r.jsxs)("div",{className:"todo-checklist-header",children:[(0,r.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,r.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,r.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,r.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),n>0&&n<t&&(0,r.jsxs)("span",{className:"todo-checklist-progress",children:[n,"/",t]})]}),(0,r.jsx)("div",{className:"todo-checklist-body",children:e.map((t,n)=>(0,r.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,r.jsx)(ng,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function rV({command:e,output:t,pending:n,isError:i,duration:s,local:a}){let{isDark:l}=tD(),{t:o}=(0,R.s)(),d=eC(t.split(/\r?\n/)),c=1===d.length&&""===d[0]?[]:d,u=n?o("chat.runningCommand"):i?"failed":"";return(0,r.jsxs)("div",{className:`shell-output-preview${i?" is-error":""}`,children:[(0,r.jsxs)("div",{className:"shell-command-line",children:[(0,r.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,r.jsx)(e3.A,{className:"shell-command-code",language:"bash",style:l?e7.xJ:e7.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||" "}),a&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsxs)("div",{className:"shell-output-divider",children:[(0,r.jsx)("span",{className:"shell-output-label",children:"Output"}),u&&(0,r.jsx)("span",{className:`shell-output-status${i?" is-error":n?" is-pending":""}`,children:u})]}),(0,r.jsxs)("div",{className:"shell-output-body","aria-live":n?"polite":void 0,children:[0===c.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:o("i18n.noOutput")}),c.map((e,t)=>{let n=ew(e).trimStart(),s=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${s}`.trim(),children:[eN(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},t):(0,r.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)}),n&&(0,r.jsx)("span",{className:"shell-output-pending","aria-label":o("chat.runningCommand"),children:"▋"})]})]}),void 0!==s&&(0,r.jsxs)("div",{className:"shell-output-footer",children:[s,"s"]})]})}function rJ({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(rG,{text:e.text})})}function rG({text:e}){let{t}=(0,R.s)(),n=(0,i.useMemo)(()=>nm(e),[e]);if(!n)return(0,r.jsx)(rX,{text:e});let s=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[s&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(rY,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(rY,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(rZ,{cell:e.left,side:"left"}),(0,r.jsx)(rZ,{cell:e.right,side:"right"})]},t))})]},n))})}function rY({title:e,side:t}){return(0,r.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 rZ({cell:e,side:t}){let n="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?"-":" ",s="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:s,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.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 rX({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"var(--success-soft)":"removed"===n?"var(--danger-soft)":"hunk"===n?"var(--accent-soft)":"transparent",borderLeft:"added"===n?"3px solid var(--success)":"removed"===n?"3px solid var(--danger)":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"var(--success)":"removed"===n?"var(--danger)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function rQ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r0({text:e,isEmpty:t,isError:n}){let{t:i}=(0,R.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--danger-line)":"var(--success-line)"}`,background:n?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"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 r1({message:e}){let{t}=(0,R.s)(),n=r8(e.content),s=(0,i.useMemo)(()=>{let e,t,r,i,s;return e=[],t=[],r=n.match(tJ),i=r?.[1]??"",s=r?.index===void 0?n:n.slice(0,r.index),i.replace(tV,(n,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):t.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:t}},[n]),a=rR(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,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==l&&(0,r.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:tG(l)})}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),s.body?(0,r.jsx)(tK,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(r2,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function r2({readFiles:e,modifiedFiles:t}){let{t:n}=(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,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(r4,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(r4,{title:n("i18n.readFiles"),files:e})]})}function r4({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function r5({message:e,cwd:t,onOpenFile:n}){var s;let a,{t:l}=(0,R.s)(),o=!1===e.display,[d,c]=(0,i.useState)(!o),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=r8(e.content),g="string"==typeof(s=e.content)?[]:s.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=rR(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:o?"var(--bg-subtle)":"var(--bg)",opacity:o&&!d?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),d?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=r6(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,r.jsx)(tK,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>c(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(a=f.replace(/\s+/g," ").trim())?a.length>140?`${a.slice(0,140)}...`:a:"Show extension message":l("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,r.jsx)("button",{onClick:()=>{tH(f||v).then(()=>{m(!0),setTimeout(()=>m(!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,r.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,r.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 r8(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function r6(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 r3({message:e,sessionId:t}){let[n,s]=(0,i.useState)(null),[a,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===n,m=n??e.output;async function f(){if(p){l(!0),d(null);try{let e=await fetch(p),t=await e.json();t.success?s(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:m?[{type:"text",text:m}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rH,{block:x,result:v}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:f,disabled:a,style:{background:"none",border:"none",color:"var(--accent)",cursor:a?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:a?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),o&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",o,")"]})]})]})}function r7({summary:e,onJump:t,onOpenPanel:n}){let{st:i}=nu();if(!e)return null;let{target:s}=e,a=s.position;if(null===a&&!n)return null;let l=i(null!==a?"dock.jump":"dock.openPanel",{title:s.maker.title});return(0,r.jsxs)("button",{type:"button",className:"run-status-line answer-dock-line","data-tone":"accent",title:l,onClick:()=>{null!==a?t(a,s.maker.member.key):n?.()},children:[(0,r.jsx)("span",{className:"run-status-label",children:i("dock.label")}),(0,r.jsxs)("span",{className:"answer-dock-counts",children:[e.running>0&&(0,r.jsx)("span",{className:"answer-dock-count","data-phase":"running",children:i("dock.running",{count:e.running})}),e.awaiting>0&&(0,r.jsx)("span",{className:"answer-dock-count","data-phase":"awaiting",children:i("dock.awaiting",{count:e.awaiting})})]}),(0,r.jsx)("span",{className:"answer-dock-title",children:s.maker.title}),(0,r.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,r.jsx)("polyline",{points:"18 15 12 9 6 15"})})]})}n(21340);let r9=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,ie="cuelo-chat-search",it="cuelo-chat-search-active";function ir(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 ii({open:e,onClose:t,containerRef:n,index:s,renderedStart:a,renderedEnd:l,contentKey:o,onReveal:d,onProgrammaticScroll:c,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[m,f]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)({index:-1,total:0}),y=(0,i.useDeferredValue)(m),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)(()=>()=>{ir(ie,[]),ir(it,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){ir(ie,[]),ir(it,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),i=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let s=(e.textContent??"").toLowerCase(),a=n.get(i);a||(a=[],n.set(i,a));for(let n=s.indexOf(t);-1!==n;n=s.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),a.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,i){let s=[];if(!t)return s;for(let a=0;a<e.length;a++){let l=a>=r&&a<i?n.get(a)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[a],t);for(let e=0;e<l;e++)s.push({item:a,k:e})}return s}(s,w,n,a,l);j.current=r;let i=eX(r,k.current);b(e=>e.index===i&&e.total===r.length?e:{index:i,total:r.length});let o=[];for(let t of e.values())for(let e of t)o.push(e);if(ir(ie,o),i<0){ir(it,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=a&&u.item<l,m=S.current,f=m.needle!==w||m.key?.item!==u.item||m.key?.k!==u.k||!m.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){ir(it,[]),f&&d(u.item);return}let g=e.get(u.item)?.[u.k];if(ir(it,g?[g]:[]),f)if(c(),g){let e,n;e=g.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,s,a,l,o,g,n,d,c]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=eX(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,r.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsx)("input",{ref:h,type:"search",value:m,onChange:e=>f(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,r.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,r.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}function is({questions:e,containerRef:t,layoutKey:n,onJump:s,label:a}){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 n=t.current;if(!n||!p)return;let r=0,i=null,s=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,s=0,a=i.length-1,l=i.length-1;for(;s<=a;){let e=s+a>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(l=e,a=e-1):s=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)},a=()=>{r||(r=requestAnimationFrame(s))};return r=requestAnimationFrame(s),n.addEventListener("scroll",a,{passive:!0}),()=>{n.removeEventListener("scroll",a),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,i.useEffect)(()=>{let e=l.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let n=t.offsetTop-e.scrollTop;(n<0||n+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[o]);let h=e.length,m=(0,i.useCallback)((e,t)=>{let n="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===n)return;e.preventDefault();let r=Math.max(0,Math.min(h-1,n));l.current?.querySelectorAll("button")[r]?.focus()},[h]);if(!p)return null;let f=e.some(e=>e.item===o)?o:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":a,children:(0,r.jsx)("div",{ref:l,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(ia,{question:e,position:t,count:h,active:e.item===o,focusable:e.item===f,onJump:s,onMoveFocus:m},e.item))})})}let ia=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:s,onJump:a,onMoveFocus:l}){let o=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,r.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:s?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${o}`,title:o,onClick:()=>a(e.item),onKeyDown:e=>l(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function il({label:e,tone:t,children:n}){return(0,r.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"run-status-label",children:e}),(0,r.jsx)("span",{className:"run-status-text",children:n})]})}let io={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function id({compaction:e,t}){let[n,s]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;s(Date.now());let t=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let a=Math.max(0,Math.floor((n-e.startedAt)/1e3)),l=e.reason&&!0===io[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(il,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:a}),l?` \xb7 ${l}`:""]})}function ic({onDismiss:e,t}){return(0,r.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,r.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,r.jsxs)("span",{className:"interrupted-run-text",children:[(0,r.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,r.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,r.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}var iu=n(39092),ip=n.n(iu);let ih=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],im={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},ig=["approval","choice","done","failed","blocked","working"],ix={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},iv={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function ib(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function iy(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(ix,e)?e:null}function iw(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:s,ko:a}=i;if("string"!=typeof e||""===e)continue;let l=iy(s);if(null===l)continue;let o=t+e.replace(/^\/+/,""),d=n.get(l);d?d.push(o):n.set(l,[o]),"string"==typeof a&&""!==a.trim()&&r.set(o,a.trim())}return{files:n,lines:r}}function ik(e,t,n){let r=t&&Object.hasOwn(im,t)?im[t]:null;return r?e.get(r)?.get(n)??null:null}async function ij(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:n}=e;if(!Array.isArray(n))return t;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:r,stickers:i,captions:s}=e;if("string"!=typeof n||""===n)continue;let a=iw(r,"/audio/completion/"),l=iw(i,"/stickers/"),o=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if("object"!=typeof n||null===n)continue;let{tag:e,ko:r}=n;if("string"!=typeof r||""===r.trim())continue;let i=iy(e);if(null===i)continue;let s=t.get(i);s?s.push(r.trim()):t.set(i,[r.trim()])}return t}(s),d=new Map;for(let e of ig){let t=a.files.get(e)??[],n=new Map;for(let e of t){let t=a.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:n,captions:o.get(e)??[]})}t.set(n,d)}return t}(await t.json())}catch{return new Map}}function iS(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,s=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&s>=r?s+1:s]}function iC(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let n of e.content)if("text"===n.type)t.push(n.text.trim());else if("toolCall"===n.type){let e="id"in n&&"string"==typeof n.id?n.id:"";t.push(`toolCall:${n.toolCallId||e}`)}}let n="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,n,t.filter(Boolean)])}let iN=["01","02","03"];function iI(e,t,n){if(!e||"streaming"===t||!ih.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),s=iS(iN.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>(function(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),0x1000193);return(t>>>0)/0x100000000})(n));return s?{src:s,alt:ix[r]}:null}let iT=new Map,iM=(0,i.createContext)(iT);function i$({utterances:e,children:t}){return(0,r.jsx)(iM.Provider,{value:e,children:t})}function iR({turnIndex:e,turnEntryId:t,sessionId:n,cwd:s,onOpenFile:a}){let l=(0,i.useContext)(iM).get(e);return l&&0!==l.length?(0,r.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:l.map(e=>(0,r.jsx)(iE,{utterance:e,sessionId:n,cwd:s,onOpenFile:a},e.key))}):null}function iE({utterance:e,sessionId:t,cwd:n,onOpenFile:s}){let a=no(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(),m=a?.alias??h??(0,t8.bN)(e.provider),f=a?.alias.split("(",1)[0]?.trim(),g=a&&h&&h!==a.alias&&h!==f?`작업 \xb7 ${h}`:null,x=iI(a?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...a?{minHeight:40}:null},children:[a&&(0,r.jsx)(np,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...l?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(tK,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:s,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(d||l)&&(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.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,r.jsx)(ip(),{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 iL=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function iA(e,t,n,r){if("string"!=typeof n)return[];let i=iL.exec(n),s=i?.[1],a=i?.[2];return s&&a?[{toolCallId:e,...t?{name:t}:{},alias:s,model:a,batchSize:r}]:[]}function iz(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[]){if("toolCall"!==n.type||"task"!==n.toolName)continue;let e=n.input,r=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...iA(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let i of e.tasks)!i||"object"!=typeof i||Array.isArray(i)||t.push(...iA(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function iW(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[])"toolCall"===n.type&&"task"===n.toolName&&t.push(n.toolCallId);return t}let iP=/^agent:\/\/([^/?#]+)\/?$/i;function iF(e,t){if(!e||"assistant"!==e.role)return[];let n=[];for(let r of e.content??[]){if("toolCall"!==r.type||"write"!==r.toolName)continue;let e=r.input,i="string"==typeof e.path?iP.exec(e.path):null,s=i?.[1],a=e.content;if(!s||"string"!=typeof a)continue;let l=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:s,message:a,...l?.from?{from:l.from}:{},...l?.receipts?{receipts:l.receipts}:{}})}return n}let i_=["greeting","utterance","message","text"],iD=function(e){let t=(0,i.useMemo)(()=>(0,nS.Et)(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let s of n.subagents){if(t.has(s.name))continue;let n=[...i].reverse().find(e=>e.name===s.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},s="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,a="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==s||void 0!==a)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==s?{resolvedModel:s,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==a?{retryFailure:{attempt:0,errorMessage:a}}:{}}),i}(s,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),s="string"==typeof t.task?iL.exec(t.task):null,a=s?.[1],l=s?.[2],o=i.find(e=>e.name===t.id)??(a&&l?r.requests.find(e=>e.alias===a&&e.model===l):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.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:r.turnIndex,summon:o,sends:d}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),s=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=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:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),a=(0,nU._Z)(s,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&s.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:s}=e,a="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",l="failed"===a,o=s?.model.split("/",1)[0]?.trim()||void 0,d=l&&o?o:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=r.indexOf("/");if(i>0)return r.slice(0,i);let s=t?.model.trim()??"",a=s.indexOf("/");return a>0?s.slice(0,a):n?.trim()||void 0}(i,s,n),c=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,n)=>{var r;let f;if("irc"in t){let{from:n,message:r,truncated:s}=t.irc;if(s||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let s=e.sends[t];if(s.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(s.send,i.id)&&s.send.from===n){h=s.turnIndex,m=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=((f=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let n of e.content??[]){if("toolCall"!==n.type||"yield"!==n.toolName)continue;let e=n.input.data,r="";if("string"==typeof e)r=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...i_]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let i=r.trim();i.length>0&&(t=i)}return t}(r))||(l?t.message.errorMessage?.trim()??"":"");0!==x.length&&p.push({key:`${i.id}:${n}`,turnIndex:h,speakerId:u,provider:g,credentialId:t.message.credentialId,accountSessionId:null,label:l&&s?s.alias:c,text:x,status:a})}),0===p.length&&"settled"!==a&&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&&s?s.alias:c,text:e||"",status:a})}return p})(t,a.get(t.snapshot.id),e.sessionProvider)),[r,a,e.sessionProvider])},iH="web6",iO=[],iB=[],iU=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let s=`${t}?sessionId=${encodeURIComponent(i)}`,a=await e(s,{signal:r});if(!a.ok)throw Error(`HTTP ${a.status}`);let l=await a.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 n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:s,text:a,error:l}=e;return{sessionId:t,startedAt:n,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof s&&""!==s?s:void 0,text:"string"==typeof a&&""!==a?a:void 0,error:"string"==typeof l&&""!==l?l:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(iB),s=(0,i.useRef)(""),a=e.sessionId??"",l=a.length>0;return(0,i.useEffect)(()=>{if(!l){s.current="",r(iB);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(a,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===s.current)return;s.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,l,a]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return iO;let r=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if("user"!==r.role)continue;let i=r.timestamp;"number"==typeof i&&Number.isFinite(i)&&t.push({index:n,openedAt:i})}return t}(t);if(0===r.length)return iO;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let s=t.error??"";0!==s.trim().length&&i.push({key:`${iH}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${iH}:${t.conversationId??"unknown"}`,text:s,status:"failed"})}return i.length>0?i:iO})(n,e.messages,a),[n,e.messages,a])},iq={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function iK(e){return e.trim()}function iV(e){return iK(e.text)||(e.images>0?"[Image]":"")}function iJ(e){let t=e.filter(e=>!iq[e.stage]);if(t.length<=4)return e;let n=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!n.has(e.id))}function iG(e,t){switch(t.type){case"submit":return iJ([...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 iJ(e.map(e=>e.id===t.id&&iq[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,i=(e,t)=>{let n=`${e}\u0000${iK(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)i("steer",e);for(let e of n)i("followUp",e);let s=!1,a=e.map(e=>{if(!iq[e.stage])return e;let t=`${e.kind}\u0000${iV(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-1),e.inQueue&&"accepted"===e.stage)?e:(s=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(s=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return s?a:e}(e,t.steering,t.followUp);case"user-message":{let n=iK(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(iq[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&iK(e.text)===n&&e.images===t.images);if(!r)return e;return iJ(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>iq[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=iK(t.text),i=e.find(e=>n(e)&&e.kind===t.kind&&(iK(e.text)===r||iV(e)===r));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 iY={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},iZ={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function iX({rows:e,removeLabel:t,onRemove:n}){let s,{st:a}=nu(),[l,o]=(0,i.useState)(!1),{rows:d,hidden:c}=(s=Math.max(0,e.length-4),l||0===s?{rows:e,hidden:s}:{rows:e.slice(s),hidden:s}),u=e.length>4;return(0,i.useEffect)(()=>{u||o(!1)},[u]),(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":l,onClick:()=>o(e=>!e),children:l?a("delivery.showRecent",{count:4}):a("delivery.showOlder",{count:c})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:d.map(e=>{let i=ro(e.text),s=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?a("delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,r.jsx)("span",{className:"answer-delivery-kind",children:a(iY[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:s,children:s}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:a(iZ[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${s}`,onClick:()=>n(e.kind,e.text),children:(0,r.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,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}let iQ=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),i0=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function i1({soundEnabled:e,onToggle:t}){let n=e?"완료음 끄기":"완료음 켜기";return(0,r.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:n,"aria-label":n,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?iQ:i0})})})}let i2=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u");class i4{#e;#t;#n;#r;#i;#s;constructor(e=()=>new AudioContext){this.#t=null,this.#n=0,this.#r=0,this.#i=null,this.#s=new Set,this.#e=e}unlock(){let e=this.#a();e?.state==="suspended"&&e.resume().catch(()=>{})}get speaking(){return this.#s.size>0}push(e,t){if(e<this.#n)return;e>this.#n&&this.reset(e);let n=this.#a();if(!n)return;let r=function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(t);if(null!==this.#i){let e=new Uint8Array(r.length+1);e[0]=this.#i,e.set(r,1),r=e,this.#i=null}r.length%2==1&&(this.#i=r[r.length-1],r=r.subarray(0,r.length-1));let i=r.length/2;if(0===i)return;let s=n.createBuffer(1,i,24e3),a=s.getChannelData(0),l=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let e=0;e<i;e+=1)a[e]=l.getInt16(2*e,!0)/32768;let o=n.createBufferSource();o.buffer=s,o.connect(n.destination);let d=Math.max(n.currentTime+.05,this.#r);o.onended=()=>{this.#s.delete(o)},this.#s.add(o),o.start(d),this.#r=d+s.duration}reset(e){for(let t of(this.#n=Math.max(this.#n,e),this.#r=0,this.#i=null,this.#s)){t.onended=null;try{t.stop()}catch{}}this.#s.clear()}close(){this.reset(this.#n);let e=this.#t;this.#t=null,e&&e.close().catch(()=>{})}#a(){if(this.#t&&"closed"!==this.#t.state)return this.#t;try{this.#t=this.#e()}catch{this.#t=null}return this.#t}}function i5(e){return e&&"object"==typeof e&&"mode"in e?"character"===e.mode&&"string"==typeof e.alias&&("accepted"===e.tuning||"provisional"===e.tuning)?{mode:"character",alias:e.alias,tuning:e.tuning}:"native"===e.mode&&("no-key"===e.reason||"character-unknown"===e.reason||"voice-not-ready"===e.reason)?{mode:"native",alias:"string"==typeof e.alias?e.alias:null,reason:e.reason}:null:null}let i8={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0},i6={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",voice:"chat.liveVoiceFailed",failed:"chat.liveFailed"},i3=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),i7=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function i9({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:s}=(0,R.s)(),a=function(e,t,n){let{locale:r}=(0,R.s)(),[s,a]=(0,i.useState)("idle"),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(null),j=(0,i.useRef)(null),S=(0,i.useRef)(null),C=(0,i.useRef)(null),N=(0,i.useRef)(0);(0,i.useEffect)(()=>{g("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let I=(0,i.useCallback)(e=>{N.current+=1;let t=j.current;for(let e of(j.current=null,k.current?.close(),k.current=null,b.current?.close(),b.current=null,y.current?.getTracks()??[]))e.stop();y.current=null;let n=w.current;w.current=null,n&&(n.srcObject=null,n.remove()),S.current?.close(),S.current=null,C.current=null,t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),a(e),p(null),m(null),v(!1)},[]),T=(0,i.useCallback)((e,t)=>{o(e),c(t??null),I("error")},[I]),M=(0,i.useCallback)(async()=>{let i,s=N.current+1;N.current=s,o(null),c(null),v(!0),a("connecting"),S.current?.close();let l=new i4;l.unlock(),S.current=l;let d=e;if(!d&&t){try{d=await t()}catch{d=void 0}if(N.current!==s)return}if(!d){N.current===s&&(v(!1),T("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";N.current===s&&(v(!1),T("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(N.current!==s){for(let e of i.getTracks())e.stop();return}y.current=i;try{let e,t,l=new RTCPeerConnection;for(let e of(b.current=l,i.getTracks()))l.addTrack(e,i);let o=document.createElement("audio");if(o.autoplay=!0,w.current=o,l.ontrack=e=>{let[t]=e.streams;t&&C.current?.mode!=="character"&&(o.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await function(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(s),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},s=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}(l),N.current!==s)return;let c=l.localDescription?.sdp;if(!c)throw Error("The browser produced no offer SDP.");let f=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:d,sdp:c,locale:r})}),g=await f.json().catch(()=>({})),x="",y="";if(g&&"object"==typeof g&&("error"in g&&(e=g.error),"message"in g&&"string"==typeof g.message&&(t=g.message),"callId"in g&&"string"==typeof g.callId&&(x=g.callId),"sdp"in g&&"string"==typeof g.sdp&&(y=g.sdp),"voice"in g&&N.current===s&&(C.current=i5(g.voice))),!f.ok||!x||!y){if(N.current===s){var u,h;v(!1),T((u=f.status,h=e,401===u||"live-auth"===h?"auth":502===u||"live-upstream"===h?"upstream":"failed"),t)}return}if(N.current!==s)return void fetch(`/api/live/call/${encodeURIComponent(x)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:y}),N.current!==s){l.close(),fetch(`/api/live/call/${encodeURIComponent(x)}`,{method:"DELETE"}).catch(()=>{});return}j.current=x,m(C.current);let M=new EventSource(`/api/live/events?callId=${encodeURIComponent(x)}`);k.current=M,M.onmessage=e=>{let t;if(N.current===s){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;if("string"!=typeof t.state||(r=t.state,!0!==i8[r]))return;"closed"===t.state?I("closed"):a(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&&n&&Promise.resolve().then(()=>n(d)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&i2.test(e)&&I("idle")}return}if("voice"===t.type&&"voice"in t){let e=i5(t.voice);e&&e.mode===C.current?.mode&&(C.current=e,m(e));return}if("speech"===t.type&&"epoch"in t&&"audio"in t){"number"==typeof t.epoch&&"string"==typeof t.audio&&S.current?.push(t.epoch,t.audio);return}if("speech-reset"===t.type&&"epoch"in t){"number"==typeof t.epoch&&S.current?.reset(t.epoch);return}if("speech-error"===t.type&&"message"in t&&"string"==typeof t.message)return void T("voice",t.message);"error"===t.type&&"message"in t&&"string"==typeof t.message&&T("upstream",t.message)}}},M.onerror=()=>{N.current===s&&j.current&&T("failed")},a("live")}catch(e){N.current===s&&T("failed",e instanceof Error?e.message:String(e))}finally{N.current===s&&v(!1)}},[e,t,n,r,T,I]),$=(0,i.useCallback)(()=>{if("idle"===s||"closed"===s||"error"===s){x||M();return}I("idle")},[x,s,M,I]);return(0,i.useEffect)(()=>()=>I("closed"),[I]),{state:s,failure:l,detail:d,transcript:u,voice:h,supported:f,toggle:$}}(e,t,n),l="connecting"===a.state||"live"===a.state||"working"===a.state,o="connecting"===a.state?"chat.liveConnecting":"working"===a.state?"chat.liveWorking":"live"===a.state?"chat.liveOn":null,d=s(l?"chat.liveStop":"chat.liveStart"),c=!1===a.supported?i6.unsupported:a.failure?i6[a.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession",h=l?function(e,t){if(!e)return null;if("character"===e.mode){let n=t("chat.liveVoiceCharacter",{name:e.alias});return"provisional"===e.tuning?`${n} \xb7 ${t("chat.liveVoiceProvisional")}`:n}return"voice-not-ready"===e.reason&&e.alias?t("chat.liveVoiceNativeNotReady",{name:e.alias}):"character-unknown"===e.reason?t("chat.liveVoiceNativeUnknown"):null}(a.voice,s):null;return(0,r.jsxs)("div",{role:"group","aria-label":s("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[c&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a.detail??void 0,children:s(c)}),o&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s(o)}),h&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",maxWidth:200,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:h,children:h}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${l?" is-active":""}`,onClick:a.toggle,disabled:!a.supported||!u,"aria-pressed":l,title:p?s(p):d,"aria-label":p?s(p):d,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:l?i7:i3})})]})}let se={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 st({sessionId:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void s(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let a=Array.isArray(i.handles)?i.handles:[],l=a.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==l,s(l)}catch{}},a=async()=>{await i(),t||(n=window.setTimeout(()=>void a(),r?5e3:3e4))};return a(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:se,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}function sn(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let sr=new Map,si="ompweb-drafts-for-reload-v1",ss=!1,sa=new Map,sl=new Map,so="\0stale",sd=new Map,sc=0,su=new Map,sp=new Map,sh=new Map,sm=new Map,sf=new Map,sg=(e,t,n)=>rf(e,t,n.length?{sentAttachmentIds:n}:{}),sx=null,sv=!1;function sb(){if(ss||"u"<typeof sessionStorage)return;ss=!0;let e=sessionStorage.getItem(si);if(e){sessionStorage.removeItem(si);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)&&(sr.set(e[0],sw(t)),"string"==typeof t.draftId&&t.draftId&&(sa.set(e[0],t.draftId),sl.set(t.draftId,so)),s$(e[0]))}}catch{}}}function sy(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(si,JSON.stringify([...sr.entries()].map(([e,t])=>{let n=sa.get(e);return[e,n?{...sw(t),draftId:n}:sw(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function sw(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function sk(e){return!e.value&&0===e.images.length&&0===e.documents.length}function sj(e){sb();let t=sr.get(e);return t?sw(t):null}function sS(e,t){sb(),sk(t)?sr.delete(e):sr.set(e,sw(t)),s$(e)}function sC(e){sr.delete(e),s$(e)}function sN(e,t,n,r,i,s=[]){let a=[...t??[],...r].filter(sn).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=rs([...i??[],...s]);return{value:e.trim()?n.trim()?`${e}
18
18
 
19
- ${n}`:e:n,images:a,documents:l}}function sI(e,t,n){if(e===t)return n?sw(n):sj(t);let r=sj(e),i=n&&!sk(n)?sw(n):r??(n?sw(n):null),s=sj(t),a=sa.get(e);if(sa.delete(e),a&&!sa.has(t)&&sa.set(t,a),sC(e),!i)return s;let l=s?sN(s.value,s.images,i.value,i.images,s.documents,i.documents):i;return sS(t,l),sw(l)}function sT(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function sM(e){sb();let t=sa.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 n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),sa.set(e,t)),t}function s$(e){let t=sT(sr.get(e)?.documents),n=t.length?sM(e):sa.get(e);for(let[e,n]of sp){for(let e of t)n.delete(e);0===n.size&&sp.delete(e)}let r=`${n??""}|${t.join(",")}`;sm.get(e)!==r&&(0!==t.length||n?sm.set(e,r):sm.delete(e),sP())}async function sR(e){let t=sM(e);su.set(t,(su.get(t)??0)+1),await sf.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(su.get(t)??1)-1;if(r>0?su.set(t,r):su.delete(t),e){let n=sp.get(t)??new Set;n.add(e),sp.set(t,n)}sl.set(t,so),sP()}}}function sE(e,t){let n=sh.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&sh.delete(e),[...n].sort()}async function sL(){if(!sg)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of sa)t(n,sT(sr.get(e)?.documents));for(let{draftId:e,ids:n}of sd.values())t(e,n);for(let[e,n]of sp)t(e,n);for(let e of sl.keys())t(e,[]);for(let e of sh.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(su.has(e))return!1;let n=sl.get(e);return sE(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=su.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=sE(r,i),s=sg(r,i,e).then(()=>{0===i.length?sl.delete(r):sl.set(r,i.join(","));let t=sh.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&sh.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});sf.set(r,s),await s,sf.get(r)===s&&sf.delete(r)}n?function(){if(sW)return;sW=!0;let e=setTimeout(()=>{sW=!1,sP()},sz);"object"==typeof e&&"unref"in e&&e.unref(),sz=Math.min(2*sz,6e4)}():sz=sA}let sA=5e3,sz=5e3,sW=!1;function sP(){if(sg){if(sx){sv=!0;return}sx=Promise.resolve().then(sL).finally(()=>{sx=null,sv&&(sv=!1,sP())})}}let sF=Math.floor(Number.MAX_SAFE_INTEGER/1048576),s_=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function sD(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=sF}async function sH(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!sD(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:sD((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:s_.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:s_.autoCleanupEnabled,orphanGraceDays:7}}async function sO(e={}){return sH(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function sB(e){return sH(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function sU(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function sq(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function sK(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}let sV="omp-web:model-picks";function sJ(){try{let e=JSON.parse(window.localStorage.getItem(sV)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function sG(e,t,n,r,i={}){let s=i.gap??8,a=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,n-2*a)),d=Math.max(0,e-s-a),c=Math.max(0,n-t-s-a),u="above"===l?d:c,p="above"===l?c:d,h=u>=r||u>=p;return{side:h?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(r,h?u:p))}}function sY(e,t,n){return Math.min(e*t,n)}function sZ(e,t,n){let{viewportFraction:r,cap:s,gap:a,margin:l,minHeight:o,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:s}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=sG(i.top,i.bottom,n,sY(n,r,s),{gap:a,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,s,a,l,o,d,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.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 sX=n(14755);async function sQ(e,t,n,r,i,s,a){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await a?.()??[],d=[...ar,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(s&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await n?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&r(c.prompt),!0}if(d&&"builtin"!==d.source)return r(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 s0(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let s1=["off","default","full"],s2={off:"none",default:"default",full:"full"},s4=sX.IN.join(" \xb7 "),s5=sX.C1.filter(e=>!sX.IN.includes(e)).join(" \xb7 ");function s8(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let s6=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),s3=0,s7={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function s9(e,t){return s6.compare(e.name||e.modelId,t.name||t.modelId)||s6.compare(e.provider,t.provider)||s6.compare(e.modelId,t.modelId)}let ae=["auto","off","minimal","low","medium","high","xhigh","max"],at=["low","medium","high","xhigh"],an={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},ar=[{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"}],ai=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],as={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},aa={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function al(e,t,n){let r=e.name.toLowerCase(),i=ao(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function ao(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function ad(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function ac(e){return{data:e.data,mimeType:e.mimeType}}function au(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function ap(e){return(e??[]).filter(sn).slice(0,10).map(au)}let ah=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,am="\n\nTranscript of the audio ";function af(e){return rs(e).map(e=>{let t=rp(e),n="audio"===t&&e.attachmentId&&!e.text.includes(am)?ah.exec(e.text):null;return{...e,id:++s3,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function ag({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function ax(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.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 av extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let ab="composer:unkeyed";async function ay(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new av("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function aw(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function ak({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function aj({error:e}){return e?(0,r.jsx)(ak,{tone:"error",title:"Model error",body:e}):null}function aS({warnings:e}){return e&&0!==e.length?(0,r.jsx)(ak,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let aC=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:s,isStreaming:l,model:o,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,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:A=null,fastModeBusy:z=!1,onFastModeToggle:W,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},en){let er,ei,es,ea,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:em}=nu(),ef=_.some(e=>e.removable),eg=P(),[ex,ev]=(0,i.useState)(()=>Z?sj(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(sJ())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,eA]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(null),[eP,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?ap(sj(Z)?.images):[]),[eH,eO]=(0,i.useState)(()=>Z?af(sj(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||s0(e)),eV=eH.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(am))),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,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(!1),[ts,ta]=(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),tm=(0,i.useRef)(null),tf=(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)(en,()=>({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,n,r=tc.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.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"),ro(t)?.message??t),s=ap("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return sn(r)?[r]:[]})),a=af((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ro(n)?.documents??[]));t$.current=i,tR.current=s,tL.current=a,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(aw),s)),eO(a),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tM.current!==e)return void sI(e,t);let n={value:t$.current,images:tR.current.map(ac),documents:tL.current.filter(e=>"ready"===e.status).map(ag)},r=sI(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tM.current=t,i)return;let s=ap(r.images),a=ax(af(r.documents),tL.current),l=r.value;t$.current=l,tR.current=s,tL.current=a,ev(l),eD(e=>(e.forEach(aw),s)),eO(a),e2(null),e7(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tM.current,s=r??i,a=s===i,l=!a&&s?sj(s):null,o=sN(e,t,a?t$.current:l?.value??"",a?tR.current.map(ac):l?.images??[],n,a?tL.current.filter(e=>"ready"===e.status).map(ag):l?.documents??[]);if(s&&sS(s,o),!a)return;let d=t?.length?[...ap(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=ax(af(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 n=Math.max(0,10-e.length),r=ap(t).slice(0,n),i=r.length>0?[...r,...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 n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),s=t.value.slice(r),a=i.length>0&&!i.endsWith(" ")?" ":"",l=i+a+e+s;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let r=n+a.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tY(e)}}));let tA=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tR.current.length-tE.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eU(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:rd(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.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,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eD(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(aw);let r=[...t,...n];return tR.current=r,r})}finally{tE.current-=i.length}}},[eh]),tz=(0,i.useCallback)(async e=>{for(let t of e){let e=rt(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:rd(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:rd(0x1000000)}));continue}let n={id:++s3,name:t.name,mimeType:n7[e],size:t.size,text:"",status:"extracting"},r=[...tL.current,n];tL.current=r,eO(r);try{let e=await ra(t);if(tL.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new n3("text_too_large","Total extracted text exceeds 240000 characters");let r=tL.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tL.current=r,eO(r)}catch(i){let e=tL.current.some(e=>e.id===n.id),r=tL.current.filter(e=>e.id!==n.id);if(tL.current=r,eO(r),!e)continue;i instanceof n3?"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]),tW=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.id===e))return!1;let n=t?tL.current.map(n=>n.id===e?t:n):tL.current.filter(t=>t.id!==e);return tL.current=n,eO(n),!0},[]),tP=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.attachmentId===e))return!1;let n=tL.current.map(n=>n.attachmentId===e?t(n):n);return tL.current=n,eO(n),!0},[]),tF=(0,i.useCallback)((e,t,n)=>{if(!e||e===tM.current)return;let r=sj(e);r?.documents.some(e=>e.attachmentId===t)&&sS(e,{...r,documents:af(r.documents).map(e=>e.attachmentId===t?n(e):e).map(ag)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tH=(0,i.useRef)(new Set),tO=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=rh({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tB=(0,i.useCallback)(e=>e instanceof av&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof av&&"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 n=tM.current,r=tL.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;tD.current.get(e)?.abort();let s=new AbortController;tD.current.set(e,s),tP(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await ay(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:s.signal}));if("string"!=typeof r.transcript)throw new av("Invalid transcription result",null,null,null);let i=r.transcript;tP(e,e=>tO(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(n,e,e=>tO(e,i,[])??e)}catch(n){if(s.signal.aborted)return void tP(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof av&&"confirmation_required"===n.code)return void tq.current?.(e);let t=tB(n);tP(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{tD.current.get(e)===s&&tD.current.delete(e)}},[eh,tB,tP,tF,tO]),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(async e=>{let t;tD.current.get(e)?.abort();let n=new AbortController;tD.current.set(e,n),tP(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 av("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await ay(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tP(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tB(t);tP(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{tD.current.get(e)===n&&tD.current.delete(e)}t.requiresConfirmation?tP(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tU(e,!1)},[tU,tB,tP]);tq.current=tK;let tV=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tP(e,e=>({...e,transcription:{state:"skipped"}}))},[tP]),tJ=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++s3,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},s=[...tL.current,i];tL.current=s,eO(s);let a=(e,t)=>{let n=tL.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?ri("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?ri("utf-16be",t.subarray(2)):t.includes(0)?null:ri("utf-8",t)??ri("euc-kr",t)},()=>null);if(null!==e&&a(e.length,r.size)){tW(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await sO().catch(()=>s_)).uploadLimitMb),r.size>n){tW(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:r.name,limit:rd(n)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tW(i.id,l))continue;let o=tM.current??ab,d=await sR(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tH.current.has(i.id))continue;let e=await rm(r,{sessionId:Q,draftId:d.draftId,signal:u.signal}),n=tL.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),s=rh({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(s).byteLength;if(!a(s.length,p)){tW(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:rd(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:s,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tW(i.id,h))c=e.id;else if(!tH.current.has(i.id)&&o!==tM.current){let t=sj(o)??{value:"",images:[],documents:[]};sS(o,{...t,documents:[...t.documents,ag(h)]}),c=e.id}}catch(e){if(u.signal.aborted)continue;tW(i.id,null)&&eU(eh("chat.attachUploadFailed",{name:r.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)}},[tW,tK,Q,eh]),tY=(0,i.useCallback)(async e=>{eU(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let s of e)s.type.startsWith("image/")?t.push(s):null!==rt(s)?n.push(s):rr(s)?r.push(s):i.push(s);return{images:t,documents:n,audio:r,files:i}}(e),s=n.filter(e=>e.size>8388608);await Promise.all([tA(t),tz(n.filter(e=>e.size<=8388608)),tJ(r,"audio"),tJ([...i,...s],"file")])},[tz,tJ,tA]),tZ=(0,i.useCallback)(e=>{eD(t=>{let n=[...t],[r]=n.splice(e,1);return r&&aw(r),tR.current=n,n})},[]),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 n=t.attachmentId;for(let[e,t]of sp)t.delete(n)&&(0===t.size&&sp.delete(e),sP())}let r=tL.current.filter(t=>t.id!==e);tL.current=r,eO(r)},[]),tQ=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(aw),[]))},[]),t0=(0,i.useCallback)(()=>{tL.current=[],eO([])},[]),t1=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&sC(Z),tM.current&&tM.current!==Z&&sC(tM.current),tQ(),t0(),eU(null),tc.current&&(tc.current.style.height="auto")},[t0,tQ,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&sS(Z,{value:ex,images:e_.map(ac),documents:eq.map(ag)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&sS(e,{value:t$.current,images:tR.current.map(ac),documents:tL.current.filter(e=>"ready"===e.status).map(ag)});let t=Z?sj(Z):null;tM.current=Z;let n=t?.value??"",r=ap(t?.images),i=af(t?.documents);t$.current=n,tR.current=r,tL.current=i,ev(n),e2(null),e7(!1),eD(e=>(e.forEach(aw),r)),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(aw)},[]);let t2=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=sT(t);if(0===n.length)return()=>{};let r=++sc;return sd.set(r,{draftId:sM(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=sd.get(r);if(t){if(sd.delete(r),"accepted"===e){let e=sh.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);sh.set(t.draftId,e)}sP()}}}(tM.current??ab,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t4=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eJ.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!e_.length&&!eq.length||l||eK)return;G?.();let i=e_.length?e_:void 0,s=eq.length?eq:void 0;if(r.startsWith("/")){await sQ(r,B,K,t=>t2(s,()=>e(t,i,s)),eU,!!(i||s),q)&&t1();return}t1(),t2(s,()=>e(r,i,s))},[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,t6=(()=>{if(null===t5)return[];let e=[...l?[]:ar,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=ao(e,eh).toLowerCase();return t.includes(t5)||n.includes(t5)}).sort((e,t)=>{let n=al(e,t5,eh)-al(t,t5,eh);return 0!==n?n:aa[e.source]-aa[t.source]||s6.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t3,groups:t7}=(er=0,{commands:(ei=ai.map(e=>{let t=t6.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!ad(e,td)),...t.filter(e=>ad(e,td))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),t9=1===t6.length?eh(t5?"chat.match":"chat.command"):eh(t5?"chat.matches":"chat.commands",{count:t6.length}),ne=!!ex.trim(),nt=!eK&&(ne||e_.length>0||eq.length>0),nn=(0,i.useCallback)((e,t)=>{if(!X)return void e2(null);let n=t??e.length;e2(sU(e.slice(0,n)))},[X]),nr=e1?.query??null,ni=i.useMemo(()=>null!==nr&&tt&&tt.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:sK(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:sK(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||sq(e.entry.path)-sq(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tt.entries,nr):[],[nr,tt,X]),ns=!!(nr&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!ns||!X||!nr)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(nr)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ta({cwd:X,query:nr,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ns,nr,X]);let na=ns&&null!==ts&&ts.cwd===X&&ts.query===nr,nl=na?ts.matches:ni,no=null===e1?null:`${e1.start}:${+!!e1.quoted}:${e1.query}`;(0,i.useEffect)(()=>{if(null===no){e5(!1),e6(0);return}e5(!0),e6(0)},[no]);let nd=null!==e1,nc=sZ(tb,e3,{viewportFraction:.44,cap:360}),np=sZ(tb,eZ,{viewportFraction:.56,cap:460}),nh=sZ(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!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=>{tn({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>sq(e.path)-sq(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tI.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tI.current=null}).finally(()=>{tT.current=null,ti(!1)}))},[nd,X]);let nm=(0,i.useCallback)(e=>{if(!e1)return;let t=tc.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e1.start),i=ex.slice(n);e1.quoted&&i.startsWith('"')&&(i=i.slice(1));let s=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,e1.quoted),a=r+s.text+i,l=r.length+s.cursorOffset;ev(a),e2(sU(a.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>=nl.length&&e6(Math.max(0,nl.length-1))},[nl.length,e8]),(0,i.useEffect)(()=>{tC.current.length=nl.length},[nl.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 nf=(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`)})},[]),ng=(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`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eJ.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,a=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!a)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await sQ(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(a.documents,()=>Y(e,l,a.images,a.documents))},eU,!!(a.images?.length||a.documents?.length),q)&&t1();return}t1(),"steer"===e&&n?t2(a.documents,()=>n(a.message,a.images,a.documents)):"followup"===e&&s&&t2(a.documents,()=>s(a.message,a.images,a.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,n,s,t1,G,t2]),nv=(0,i.useCallback)(e=>{let t=t3.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 n=tS.current[eQ];if(!n)return"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eQ)continue;let t=tS.current[n];if(!t)continue;let r=t.getBoundingClientRect(),o=r.top+r.height/2-s;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(a=n,l=d)}return a>=0?a:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t3.length,eQ]),ny=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tk.current<100,a=tw.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(a||i)){i&&e.preventDefault();return}if(e3&&!a){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(),nf(D[e9]);return}}if(eZ&&null!==t5){if("ArrowDown"===e.key){e.preventDefault(),e0(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(nv("left"));return}if("Escape"===e.key){e.preventDefault(),eX(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t3[eQ]){e.preventDefault(),ng(t3[eQ]);return}}if(e4&&null!==e1&&!a){if("ArrowDown"===e.key){e.preventDefault(),e6(e=>Math.min(Math.max(0,nl.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)&&nl[e8]){e.preventDefault(),nm(nl[e8]);return}}if("ArrowUp"===e.key&&!a&&!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&&!a&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(n||s)?nx(n?"steer":"followup"):t4())},[l,n,s,t,eZ,t5,t3,eQ,ng,nx,t4,nv,e4,e1,nl,e8,nm,e3,D,e9,nf,ex]),nw=(0,i.useCallback)(()=>{let e=tc.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nj=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tY(t))},[tY]);(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 n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;to({cwd:X,values:n})}).catch(()=>{e||to({cwd:X,values:{}})}),()=>{e=!0}},[eZ,X]),(0,i.useEffect)(()=>{eQ>=t3.length&&e0(Math.max(0,t3.length-1))},[t3.length,eQ]),(0,i.useEffect)(()=>{tS.current.length=t3.length},[t3.length]),(0,i.useEffect)(()=>{eZ&&tS.current[eQ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eQ,eZ]);let nS=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(s9):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(s9),nC=g??null,nN=t8.bo.find(e=>e.alias===nC)?.provider??null,nI=nN?nS.filter(e=>e.provider===nN):nS,nT=(es=ej.trim().toLocaleLowerCase())?nI.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(es)):nI,nM=nI.length>8,n$=[];for(let e of nT){let t=n$.find(t=>t.provider===e.provider);t?t.options.push(e):n$.push({provider:e.provider,options:[e]})}let nR=nN?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nE=o?nR.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nL=ej.trim()?[]:nI.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??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})),nA=(e,t,n)=>{let i=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ey(!1),eS(""),!i||d){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(sJ(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(sV,JSON.stringify(r))}catch{}eN(r),m?.(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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nz=o?nS.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nW=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nP=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${tG(S.tokensBefore)} -> ${tG(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:tG(nW)})})`:null,nF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},n_="auto"===(ea=I??"auto")?M?`auto ≤ ${nF(M)??M}`:"auto":L?L[ea]??ea:ea,nD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,nH=$&&nD?eh("chat.currentReasoning",{level:nD}):null,nO=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...at.filter(nO).map(e=>({level:"auto",ceiling:e})),...ae.filter(e=>"auto"!==e&&nO(e)).map(e=>({level:e,ceiling:null}))],nU=Object.entries(s2).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)&&tm.current&&!tm.current.contains(e.target)&&eT(!1),tf.current&&!tf.current.contains(e.target)&&eE(!1),tg.current&&!tg.current.contains(e.target)&&eA(!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 nq=(0,r.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,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),nK=f&&t8.bo.length>0?(0,r.jsxs)("div",{ref:th,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.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,r.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:n}=sG(eM.top,eM.bottom,e,sY(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,r.jsx)("div",{ref:tm,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eT(!1),th.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:t8.bo.map(e=>{let t=e.alias===nC;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),f((0,t8.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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:(0,t8.uk)(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:e.alias}),(0,r.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,nV=$?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eW({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(!1),eA(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},title:eh("chat.changeReasoning",{level:n_}),"aria-label":eh("chat.changeReasoning",{level:n_}),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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:n_})]}),eL&&ez&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=sG(ez.top,ez.bottom,e,sY(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ez.top+6}:{top:ez.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ez.left,width:"max-content",minWidth:Math.max(180,ez.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,s="auto"===e&&null===t?null:nF(i),a=t?`auto ≤ ${s??t}`:s??e,l=t?eh("chat.thinkingAutoCapped",{level:s??t}):eh(an[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eA(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[a,null!==s&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,nJ=W?(el=z?eh("chat.fastModeBusy"):null===A?eh("chat.fastModeUnknown"):A.active?eh("chat.fastModeActive"):A.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eo=z||l||b,ed=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:W,disabled:eo,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":z||void 0,title:el,"aria-label":el,style:{flexShrink:0,opacity:l?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:ed?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:ed&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,nG=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nx("steer"),disabled:!nt,title:eK?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nt?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nt?"var(--warning)":"var(--text-dim)",cursor:nt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),s&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!nt,title:eK?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nt?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nt?"var(--accent-hover)":"var(--text-dim)",cursor:nt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nY=void 0!==J?(0,r.jsx)(i1,{soundEnabled:V??!0,onToggle:J}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:ty,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tY(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(aj,{error:p}),(0,r.jsx)(aS,{warnings:h}),_.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:em("delivery.title",{count:_.length})}),H&&ef&&(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(iX,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:O?(e,t)=>O("steer"===e?"steering":"followUp",t):void 0})]}),F&&(0,r.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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:F.attempt,max:F.maxAttempts}),F.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",F.errorMessage]})]}),nP&&(0,r.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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nP]}),j&&(0,r.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,r.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,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eB}),(0,r.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,r.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,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(e_.length>0||eH.length>0)&&(0,r.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,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.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,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tZ(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eH.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||s0(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,r.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"}}):nk(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):s7[e.mimeType]," \xb7 ",rd(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,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.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,r.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,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eV.length>0&&(0,r.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,n,i,s,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"):(n=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),s=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${s}`:`${i}:${s}`),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,r.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,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:o?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),c&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:c}),o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[o.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:o.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(a.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tb,style:{position:"relative",minWidth:0},children:[e3&&D.length>0&&(0,r.jsxs)("div",{ref:tv,style:{position:"absolute",left:0,right:0,...s8(nc.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nc.maxHeight},children:[(0,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nc.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===e9;return(0,r.jsxs)("button",{ref:e=>{tN.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>te(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eZ&&null!==t5&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...s8(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:U?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:t9})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:10},children:U||0!==t6.length?t7.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(as[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===eQ,i=ad(e,td);return(0,r.jsxs)("button",{ref:e=>{tS.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ng(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 ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),ao(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:ao(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e4&&null!==e1&&(ec=tr&&(!tt||tt.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=tt?.truncated&&!na?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...s8(nh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nh.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ec?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nh.maxHeight-34),overflowY:"auto",padding:4},children:ec||0!==nl.length?nl.map((e,t)=>{let n=t===e8,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tC.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>e6(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(nb,{size:14}):nk(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ns&&!na?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.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&&(n||s)?"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,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tc,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),e7(!1),nn(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nn(t.value,t.selectionStart)},onKeyDown:ny,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;nn(t.value,t.selectionStart)},onInput:nw,onPaste:nj,placeholder:l&&(n||s)?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,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nG}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t4,disabled:!nt,"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:nt?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nt?"var(--accent-hover)":"var(--text-dim)",cursor:nt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eG&&(0,r.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,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.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)&&nq,!eg&&nK,!(eg&&l)&&(nS.length>0||nz||p)&&m&&(0,r.jsxs)("div",{ref:tu,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.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":nS.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nz??(nS.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=sG(ew.top,ew.bottom,e,sY(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nL.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),nL.map(({option:e,count:t})=>nA(e,"frequent",t))]}),nR.length>0&&!ej.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nL.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.modelRoles")}),nR.map(e=>{let t=nE?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ey(!1),eS(""),v(e.role)},title:e.selector??n,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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{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,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,r.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===n$.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):n$.map((e,t)=>(0,r.jsxs)("div",{children:[n$.length>1&&(0,r.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=>nA(e,"all"))]},e.provider))]})]})})()]}),eg&&l&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nG}),!eg&&nV,!eg&&nJ,!eg&&nH&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nH}),(0,r.jsx)(st,{sessionId:Q})]}),(0,r.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,r.jsx)("button",{type:"button",className:`composer-icon-button${eP?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eP,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eP?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eP,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eP?"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,r.jsxs)(r.Fragment,{children:[l&&nq,nK,nV,nJ]}),!l&&N&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eR?" is-active":""}`,onClick:()=>!l&&eE(e=>!e),disabled:l,title:eh("chat.changeToolPreset")+`: ${nU}`,"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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nU})]}),eR&&(0,r.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:s1.map(e=>{let t=s2[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:s4}):eh("chat.allBuiltInTools",{tools:`${s4} + ${s5}`});return(0,r.jsxs)("button",{onClick:()=>{eE(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&y&&(0,r.jsx)("div",{children:(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nY,eP&&(0,r.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),eA(!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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),l&&(0,r.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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(i9,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nY]})]})]})]})});function aN({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(" "),n=ew(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eN(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function aI({phases:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(!1),[a,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=e6(e);if(0===p)return null;let m=0===c;return(0,r.jsxs)("div",{className:`todo-strip${m?" is-done":""}`,children:[(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":n,onClick:()=>s(e=>!e),children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:m?"✓":"›"}),o&&(0,r.jsx)("span",{className:"todo-strip-phase",children:o.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:m?t("todo.allDone",{count:u}):d?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:m?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),n&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,n)=>{let i=t.tasks.filter(e=>a||"completed"!==e.status);return 0===i.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,r.jsx)(ng,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":a,onClick:()=>l(e=>!e),children:t(a?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function aT(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function aM(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 a$(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}var aR=n(62503);class aE extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function aL(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new aE(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let aA="ompweb-update-client-id",az="ompweb-update-resume-intent-v2",aW="ompweb-update-return-v1",aP="cuelo-restart-return-v1",aF="ompweb-update-failure-return-v1",a_="ompweb:update-wake";function aD(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function aH(){let e=sessionStorage.getItem(aA);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(aA,t),t}function aO(){sessionStorage.removeItem(az)}function aB(){let e=sessionStorage.getItem(aW);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 aU(e){let t=aB();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(aW,JSON.stringify(n))}catch{}return n}async function aq(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:aH(),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 aK(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 n=await t.json().catch(()=>null);!function(e){let t=aB();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(aW,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),aO();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(a_,{detail:{sessionId:e.sessionId}}))}async function aV(e){let t=function(e){let t=sessionStorage.getItem(aF);if(!t)return null;sessionStorage.removeItem(aF);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(aO(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(a_,{detail:{sessionId:e.sessionId}})),"failed"):(await aK(e),"resumed")}function aJ(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.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}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function aG(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 aY(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function aZ(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function aX(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function aQ(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function a0(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function a1(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!eK(r??void 0))return{message:e[n],entryId:r}}return null}let a2=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class a4 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 a5(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function a8(e){return new Promise(t=>setTimeout(t,e))}function a6(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function a3(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:a6(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:a6(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=a6(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function a7(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 a9(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(a7).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function le(e){return"user"===e.role?`user:${a9(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 lt(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 lr(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let li=!1,ls={width:0,height:0},la=new Set,ll=null;function lo(){let e=window.visualViewport,t=lr();ls.width!==window.innerWidth?ls={width:window.innerWidth,height:window.innerHeight}:t||(ls.height=Math.max(ls.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:ls.height});if(n!==li)for(let e of(li=n,la))e()}function ld(e){if(la.add(e),!ll){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,lo()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),lo(),ll=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{la.delete(e),0===la.size&&ll&&(ll(),ll=null)}}function lc(){return(0,i.useSyncExternalStore)(ld,()=>li,()=>!1)}let lu={count:50,end:null};function lp(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),s=r-i;return{startIndex:s,endIndex:r,hasMore:s>0,hasLater:r<n}}function lh(e,t,n){let{startIndex:r,endIndex:i}=lp(e,n);if(t>=r&&t<i)return n;let s=Math.max(0,t-10),a=Math.max(t+1,s+50);return a>=e?{count:e-s,end:null}:{count:a-s,end:a}}function lm({sticker:e,text:t,tag:n,followRef:s}){let a=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!s||s.current)&&a.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:a,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:ix[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(ip(),{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 lf(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"),n=(ro(t)?.message??t).trim();return n.length>0?n:null}function lg(e){return`omp-cues:${e}`}function lx(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(lg(e),JSON.stringify(n.slice(-200)))}catch{}}let lv=[];function lb(e){return`omp-web:interrupted-dismissed:${e}`}let ly=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:s,messageCwd:a,onOpenFile:l,sessionBusy:o,isNew:d,isStreaming:c,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,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:n,modelNames:s,cwd:a,sessionId:f})},[N,x,e,t,n,s,a,f]);let M=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let s=new Map,a=new Map;for(let e of t){let t=a.get(e.anchorIdx);for(let l of(t||(t=new Set,a.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let a=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=eY(i.action);if(!0===eG[e]){let t={kind:"skill",action:e,name:eY(i.name)};n(JSON.stringify(t),t)}continue}let s=eY(i.memory),a=i.skill,l=a?{action:eY(a.action),name:eY(a.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:s,skill:l}),{kind:"lesson",memory:s.length>160?`${s.slice(0,160)}…`:s,...l?{skill:l}:{}})}}(l.blocks??e.content??[],r,(e,t)=>{if(o.has(e))return;o.add(e);let n=s.get(a);n?n.push(t):s.set(a,[t])})}}return s}(g,x,e,n)){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(r,{role:"custom",customType:eB,content:[C("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,C]),$=(0,i.useMemo)(()=>{let t=null;if(o)for(let n of g)"message"===n.kind&&e[n.idx]?.role==="user"&&(t=n.idx);let r=new Map;for(let[i,s]of function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx),s=new Map;for(let[a,l]of(e.forEach((e,t)=>{"answer"===e.kind&&s.set(e.anchorIdx,t)}),s)){if(a===n)continue;let e=i.find(e=>e>a);r.set(l,{from:a+1,to:e??t.length})}return r}(g,e,t))r.set(i,function(e,t,n){let r=[],i=[];for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){i.push(n);continue}if("bash"!==n.toolName)continue;let e="string"==typeof n.input.command?n.input.command.trim():"";if(!e||!r9.test(e))continue;let s=t.get(n.toolCallId),a=s?function(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}(s):null,l=null===a?s?.isError?"failed":"unobserved":0===a?"passed":"failed";r.push({toolCallId:n.toolCallId,command:e,state:l,exitCode:a})}return{checks:r,dispatchCalls:i,files:e4(e,t,n)}}(function(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}(e,s.from,s.to),n,a));return r},[g,e,n,a,o]),R=y>0,E=w<g.length,L=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&eK(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 n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(rE,{message:x,toolResults:n,modelNames:s,cwd:a,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:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${y}-view-${i}`)},A=(t,n)=>{let i=g[t],s="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":s?"":void 0,className:S===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[R&&(0,r.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((s,o)=>{let d=y+o,c=b?.position===d?(0,r.jsx)(n1,{calls:b.calls}):null,u="message"===s.kind?s.anchorIdx??s.idx:s.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=s.idx&&r<m}).map(e=>(0,r.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,r.jsx)(rE,{message:k,cwd:a,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,r.jsx)(iR,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:a,onOpenFile:l}):null;if("message"===s.kind)return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(s.idx)),j,S,x]},`message-${s.idx}`);let C=e4(s.precedingBlocks,n,a);return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(s.idx,{keyPrefix:`answer-${s.runIndex}`,messageOverride:eL(e[s.idx],s.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${s.idx}-${s.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,r.jsx)(n1,{calls:b.calls}),E&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadLater",{count:g.length-w})})]})});function lw({session:e,newSessionCwd:t,initialSessionData:s,transitioning:a=!1,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,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:A,jumpRequest:z=null,onJumpHandled:W}){var _,D;let H,O,B,{t:U}=(0,R.s)(),q=lc(),K=P(),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),en=(0,i.useRef)([]),er=(0,i.useRef)([]),ei=(0,i.useRef)(null),es=(0,i.useRef)(0),ea=(0,i.useRef)(-1),el=(0,i.useRef)(-1),eo=(0,i.useCallback)(()=>{let e=ei.current?.current;return e?{sessionId:e,turn:es.current}:null},[]),ed=(0,i.useCallback)(e=>ei.current?.current===e.sessionId&&es.current===e.turn,[]),ec=(0,i.useCallback)((e,t,n,r)=>{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:n.sessionId},s="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};Q(e=>{let t=[...e,s];return null!==s.anchorEntryId&&lx(n.sessionId,t),t})},[]),eu=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ed(n)&&("working"!==t||el.current!==n.turn);i()&&G.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&ec(e,t,n,r)}).catch(()=>{})},[ed,ec]),ep=(0,i.useCallback)(async(e,t,n)=>{let r=(await nl(e,t,n))?.alias??null;return r&&Z.current?.(r),r},[]),eh=(0,i.useCallback)((e,t,n,r)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=iC(e[n]),s=0;for(let t=r;t<=n;t++)iC(e[t])===i&&(s+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:s}}}(en.current,er.current);ep(t.sessionId,n,r).then(n=>{eu(n,e,t,i)})},[eu,ep]),[em,ef]=(0,i.useState)(0),eg=(0,i.useRef)([]),ex=(0,i.useCallback)(e=>{if(es.current+=1,null!==ib(e.outcome)){let t=e.sessionId;eg.current.push({completion:e,trigger:t?{sessionId:t,turn:es.current}:null}),ef(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eg.current.splice(0)){let n=ib(e.outcome),r="neutral"===n?null:n;t?eh(r,t,e.provider,e.credentialId):G.current(null,r).catch(()=>{})}},[em,eh]);let ev=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ey,messages:ek,entryIds:ej,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eI,modelNames:eT,modelList:eM,modelError:e$,modelScopeWarnings:eR,modelThinkingLevels:eE,modelThinkingLevelMaps:eA,modelRoles:eF,toolPreset:eD,thinkingLevel:eH,effectiveThinkingLevel:eB,thinkingCeiling:eG,fastMode:eY,fastModeBusy:eX,handleFastModeToggle:eQ,retryInfo:e0,contextUsage:e1,forkingEntryId:e2,isCompacting:e4,compaction:e5,compactError:e6,compactResult:e3,displayModel:e7,modelSwitching:e9,sessionStats:te,runStateKnown:tt,compactedWork:tn,slashCommands:tr,slashCommandsLoading:ti,deliveryRows:ts,subagents:ta,todoPhases:tl,notices:to,extensionDialog:td,extensionResponse:tc,extensionCustomUi:tu,extensionStatuses:tp,extensionWidgets:th,respondToExtensionUi:tm,sendExtensionCustomInput:tf,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:tA,handleSteer:tz,handleFollowUp:tW,handlePromptWithStreamingBehavior:tP,handleAbortCompaction:tF,handleRecallQueue:t_,handleRemoveQueuedMessage:tD,handleBuiltinSlashCommand:tH,handleToolPresetChange:tO,handleThinkingLevelChange:tB,loadSlashCommands:tU,ensureNewSession:tq,refreshLiveTranscript:tK}=function(e){let{session:t,newSessionCwd:r,initialData:s,onAgentEnd:a,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=s&&s.sessionId===t?.id?s:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[N,I]=(0,i.useState)(f?.context.entryIds??[]),[T,M]=(0,i.useState)(f?.context.compactedWork??null),[$,R]=(0,i.useReducer)(aG,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)(!1),[W,P]=(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),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)("default"),[ea,el]=(0,i.useState)(()=>{let e=f?.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),[em,ef]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[eb,ey]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(f?.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),[eA,ez]=(0,i.useState)(!1),[eW,eP]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eH]=(0,i.useState)(null),eB=(0,i.useRef)(null),[eU,eJ]=(0,i.useState)(!1),[eG,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(a3,{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),[tn,tr]=(0,i.useState)([]),[ti,ts]=(0,i.useState)([]),[ta,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(iG,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ta.steering,followUp:ta.followUp})},[ta]),(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 n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iV(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let s=`${e}\u0000${iK(t)}`,a=n.get(s)??0;a>0?n.set(s,a-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(tc,ta),[tc,ta]),[tm,tf]=(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)(f?.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),tA=(0,i.useRef)(null),tz=(0,i.useRef)(0),tW=(0,i.useRef)(!1),tP=(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 ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),ns=(0,i.useRef)(Promise.resolve()),na=e.setToolPreset??es,nl=eT??g?.context.model??e$??null,no=m?X??en:nl,nd=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,s=0,a=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(s+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;a+=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,n+=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:r,assistantMessages:i,toolCalls:a,toolResults:s,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ek?{contextUsage:ek}:{}}},[S,e4,ek,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nc=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nc.current+=1,tf(n=>n?.sid===e&&aQ(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nc.current===n&&Array.isArray(t)&&tf(n=>n?.sid===e&&aQ(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nm=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),nf=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let s=r??null;if(!s){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);s=await r.json()}if(tj.current!==e)return null;x(s),j(s.leafId),tS.current=s.leafId??null;let a=eV(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(a.messages),nm(a.entryIds),M(s.context.compactedWork??null),ej(s.contextUsage??null),eM(e=>ni.current?e:null),w(null);let l=!n&&t8.current===e;if(l||(el(s.context.configuredThinkingLevel??s.context.thinkingLevel??"off"),ed(s.context.thinkingLevel)),eu(s.context.thinkingCeiling??null),i=!0,t&&b(!1),!n){if(l)try{let t=t6.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t6.current===t&&(r.state?.thinkingLevel!==void 0?(el(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(t8.current=null,el(s.context.configuredThinkingLevel??s.context.thinkingLevel??"off"),ed(s.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nc.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ej(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&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ts(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(aY(i.queuedMessages)),void 0!==i.subagents&&td(e=>aJ(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[np,nm,nh]),ng=(0,i.useCallback)(e=>{let t=ns.current.then(async()=>{tj.current===e&&await nf(e)});return ns.current=t.catch(()=>{}),t},[nf]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,s=await fetch(i);if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let l=eV(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(l.messages),nm(l.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nm,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await aL(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));na(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[na]),nb=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;m&&r&&n&&!t1.current&&(t1.current=!0,o?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,o]),ny=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t5.current,i=t4.current;e&&eR(e);let s={cwd:r,type:"ensure_session",toolNames:(0,sX.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},a=JSON.stringify(s),l=t0.current,o=l?.body===a?l.createRequestId:a5();t0.current={body:a,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...s,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||er(c.model)),c.thinkingLevel&&t5.current===n&&(el(c.configuredThinkingLevel??c.thinkingLevel),ed(c.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await aL(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}},[m,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await ny();if(!e)return eX([]),[];e0(!0);try{let t=await aL(e,{type:"get_commands"}),n=t?.commands??[];return eX(n),n}catch(e){return console.error("Failed to load slash commands:",e),eX([]),[]}finally{e0(!1)}},[ny]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tF.current?.(n):"agent_start"===n.type&&t_.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(s),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},s=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)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nI=(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 n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new a4(n.status)},[nN]),nT=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await aL(r,{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)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await aL(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),n$=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({type:"add",notice:{id:e.id??a5(),message:t,type:e.type??"info"}})},[]),nR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eO,content:ew(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),s=null;for(let e=i.length-1;e>=0;e--)if(!eK(i[e])){s=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eq}${n.seq}`,baseEntryId:s,message:t}),nh(e=>[...e,t])},[nh]),nE=(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(aM(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":n$({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ts(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});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)}},[n$,l,e.chatInputRef]),nL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eY(null),ey(null),R({type:"end"}),e},[]),nA=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=a1(tC.current,tN.current);tA.current=e?{entryId:e.entryId,key:le(e.message)}:null,tz.current+=1},[]),nz=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let n=a1(tC.current,tN.current),r=n?.message,i=tA.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:le(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=a0(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nW=(0,i.useCallback)(e=>{let t=nz();if("unknown"!==t.outcome||!e)return void a?.(t);let n=tz.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tz.current===n;a?.(e?nz():t)})},[a,nz]),nP=(0,i.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,nW(t),!0),[nW]),nF=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nc.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let a=s.state;if(td(e=>aJ(e,a?.subagents??[])),np(e,a?.todoPhases,r),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!a?.isStreaming,t$.current=!!a?.isPromptRunning,tT.current=!0,L(!0),eY(a?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(s.running&&a?.isCompacting){ez(!0),eH(aX(a)),ty.current=setTimeout(()=>void n(),600);return}if(s.running&&(a?.subagents?.length??0)>0){ty.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,ty.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void n(),600)}};ty.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),n_=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nf(e)}finally{if(nt.current!==t)return;let n=t$.current,r=tM.current;t$.current=!1,tM.current=!1,nr.current=null;let i=nL();n?nP(t):r&&i&&nW(),e&&nF(e)}},[nf,nW,nP,nF,nL]),nD=(0,i.useCallback)(async(e,t)=>{await a8(800);let n=Date.now();for(;tT.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await n_(e,t)}}catch{}await a8(600)}},[n_]),nH=(0,i.useCallback)(async e=>{let t=tP.current+1;for(tP.current=t;tW.current&&tP.current===t&&tj.current===e;){await a8(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nf(e),tP.current!==t||tj.current!==e)return;tW.current=!1,z(!1),P(null);return}catch{}}},[nf]),nO=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=nt.current;try{let n=nc.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let s=i.state;if(ez(s?.isCompacting??!1),eH(aX(s)),tl(aY(s?.queuedMessages)),s?.contextUsage!==void 0&&ej(s.contextUsage??null),td(e=>aJ(e,s?.subagents??[])),np(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting||s.isHandoffRunning)||!tT.current)return;s&&(void 0!==s.systemPrompt&&eC(s.systemPrompt??null),void 0!==s.extensionStatuses&&tr(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&ts(s.extensionWidgets??[])),await n_(e,t)}catch{}},[np,n_]),nB=(0,i.useCallback)(async e=>{let t=await nf(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tT.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,t$.current=!!n.isPromptRunning,tT.current=!0,L(!0),eY(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nD(e),!0)},[nN,nf,nD]),nU=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ej(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eA){eB.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eB.current})},[eA]),(0,i.useEffect)(()=>{if(!E&&!eA)return;let e=()=>{let e=tj.current;e&&nU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,eA,nU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&nO(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[E,nO]),(0,i.useEffect)(()=>{if(E)return;let e=()=>{let e=tj.current;e&&!tT.current&&nB(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tT.current&&nB(t).then(e=>{e||tj.current!==t||tT.current||nf(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(a_,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(a_,n)}},[E,nB,nf]),t_.current=e=>{if(tj.current!==e||tT.current||tg.current||tD.current)return;let t=nB(e).then(async t=>{t||tj.current!==e||tT.current||await nf(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,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let s=e.context.messages,a=new Map;for(let e of s){let t=le(e);a.set(t,(a.get(t)??0)+1)}let l=Math.min(r.length,i.length);for(let e of r.slice(0,l)){let t=le(e),n=a.get(t)??0;n>0&&a.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=le(e),n=a.get(t)??0;return 0===n||(a.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...s,...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 n=eV(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);nh(n.messages),nm(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;nk(),e&&nA(),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){nf(tj.current);let e=nc.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ej(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ts(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>aJ(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(aY(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,n=nL();ez(!1);let r=t?nf(t):void 0;t&&nF(t),n&&nW(r);break}case"prompt_done":{let e=nt.current,t=t$.current;t$.current=!1,nr.current=null;let n=tR.current!==e;if(!t&&!n)break;let r=tj.current;nP(e,r?nf(r):void 0),!tM.current&&(nL(),r&&nF(r))}break;case"prompt_error":tE.current="failed",n$({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tE.current="failed",n$({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,aR.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=a0(t)),t&&"user"===t.role){let e=(0,aR.B)(t),n=a9(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&a9(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||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&&nh(e=>[...e,(0,aR.B)(t)]);let n=tj.current;n&&nU(n),R({type:"reset"}),eY({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t8.current=t,t6.current+=1,el(e.configured??n),ed(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eY(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eY(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"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(n=>{let r=n.find(e=>e.id===t.id);return aJ(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={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=>aJ(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};td(e=>aJ(e,[r]));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){eB.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}ez(!0),eP(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(ez(!1),e.errorMessage)eP(e.errorMessage),e_(null);else if(!e.aborted){e_(lt(e.result,e.reason??"auto"));let t=tj.current;t&&(nf(t),nU(t))}break;case"extension_ui_request":nE(e)}},[n$,nu,np,nk,nE,nf,nW,nP,nU,nA,nF,nL,nm,nh]);let nq=(0,i.useCallback)(async(n,i,s)=>{let a=n.trim();if(!a&&!i?.length&&!s?.length)return"returned";if(tT.current||tW.current||ni.current)return"unknown";let l=rl(n,s??[]),o=!i?.length&&!s?.length&&a.startsWith("/");if(!i?.length&&!s?.length&&a.startsWith("!")){let e=a.startsWith("!!"),t=(e?a.slice(2):a.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}nA();let d=nt.current+1;nk(),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()};nh(e=>[...e,u]),nr.current=a9(u),nt.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,f=!1,g="unknown";try{if(m&&r){let e=tj.current??await tQ.current,t=await ny();t&&(h=t,X&&(eR(X),e&&await aL(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),f=!0,await aL(t,{type:"prompt",message:l,...p?.length?{images:p}:{}}),nb(1,n),g="accepted")}else t&&(h=t.id,await nI(t.id),f=!0,await aL(t.id,{type:"prompt",message:l,...p?.length?{images:p}:{}}),g="accepted");return o&&h&&nD(h,d),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof aE&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof aE&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&h)return nD(h,d),"unknown";t$.current=!1,tT.current=!1,nj();let a=nr.current;return a&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&a9(t)===a?e.slice(0,-1):e}),n$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,ln(i),s,t?.id??h??void 0),nr.current=null,L(!1),eY(null),R({type:"end"}),"returned"}},[m,r,X,t,ny,nI,nb,nD,n$,nk,nj,e.chatInputRef,nA,nh]);tV.current=(0,i.useCallback)(async(n,r)=>{if(tT.current||tW.current)return;let i=`${r?"!!":"!"}${n}`;tW.current=!0,tY.current(!0),P({command:n,excludeFromContext:r}),z(!0);try{let e=tj.current??t?.id??await ny();if(!e)throw Error("Unable to create a session for the shell command");await aL(e,{type:"bash",command:n,excludeFromContext:r}),await nf(e),nb(1,i)}catch(t){console.error("Failed to execute shell command:",t),n$({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tW.current=!1,P(null),z(!1)}},[n$,ny,nf,e.chatInputRef,nb,t]);let nK=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tW.current){try{await aL(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await aL(e,{type:"abort"}),tE.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nV=(0,i.useCallback)(async e=>{if(tW.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:n,newSessionId:r}=await aL(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return d?.(r),{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]),nJ=(0,i.useCallback)(async e=>{if(tW.current)return;let t=tj.current;t&&(aL(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nG=(0,i.useCallback)(async e=>{if(tW.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&aL(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nY=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t4.current=null,et(null)),Q(n),eR(n);let i=tj.current??await tQ.current;if(!i)return;try{await aL(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await aL(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nf(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eT),n$({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nf(n)}finally{ni.current=!1,eL(!1)}}},[n$,eT,m,nf,Q]),nZ=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(ni.current)return!1;ni.current=!0,eL(!0);let e=t2.current,s=t4.current,a=t5.current;try{t2.current=t,t4.current=n??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await aL(e,r),Q(t),et(n??null),eR(t),el("auto"),ed(void 0),e&&await nf(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t4.current=s,t5.current=a,n$({type:"error",message:i(n)});let t=tj.current;return t&&await nf(t),!1}finally{ni.current=!1,eL(!1)}}let s=tj.current;if(!s||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await aL(s,r),await nf(s),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),n$({type:"error",message:i(e)}),await nf(s),!1}finally{ni.current=!1,eL(!1)}},[n$,eT,eo,m,nf,Q,ea]),nX=(0,i.useCallback)(async e=>{let t=Y.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t5.current=t??null,el(t??"auto"),ed(void 0),t2.current=e,t4.current=null,et(null),Q(e),eR(e)}let r=tj.current??(m?await tQ.current:null);if(r)try{await aL(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Y,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eA){eB.current="manual",ez(!0),eP(null),e_(null);try{let t=await aL(e,{type:"compact"});e_(lt(t,"manual")),await nf(e,!0)}catch(e){eP(e instanceof Error?e.message:String(e)),e_(null)}finally{ez(!1)}}},[eA,nf]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",s=await fetch(i,e?{signal:e}:void 0);if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();_(a.models),B(a.modelError??null),q(a.modelScopeWarnings??[]),V(a.thinkingLevels??{}),G(a.thinkingLevelMaps??{}),Z(a.roles??[]);let l=a.modelList??[];if(H(l),m&&!tj.current){let e=(a.defaultModel?l.find(e=>e.id===a.defaultModel?.modelId&&e.provider===a.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&a.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[m,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=await ny(),a=e=>(e.handled&&(e.error?n$({type:"error",message:e.error}):"openSessionStats"!==e.action&&n$({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||eA)return a({handled:!0,error:"No active session to compact"});eB.current="manual",ez(!0),eP(null),e_(null);let e=await aL(s,{type:"compact",...i?{customInstructions:i}:{}});return e_(lt(e,"manual")),await nf(s,!0)&&nb(),a({handled:!0,message:"Compacted context"})}case"reload":if(!s)return a({handled:!0,error:"No active session to reload"});return await aL(s,{type:"reload"}),await Promise.all([nf(s,!1,!0),nv(s),nw(),n0()]),a({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return a({handled:!0,error:"No active session to name"});if(!i)return a({handled:!0,error:"Usage: /name <name>"});return await aL(s,{type:"set_session_name",name:i}),await nf(s)&&nb(),a({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return a({handled:!0,error:"No active session"});let e=await aL(s,{type:"get_session_stats"});return e&&e5(e),h?.(),a({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return a({handled:!0,error:"No active session"});let e=await aL(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return a({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),a({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!s)return a({handled:!0,error:"No active session to fork"});let e=await nV();if(!e.forked)return a({handled:!0,error:e.error??"Fork failed"});return a({handled:!0,message:"Forked a new session"})}case"goal":{if(!s)return a({handled:!0,error:"No active session"});let e=await aL(s,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return a({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nR(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&n$({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return a({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!s)return a({handled:!0,error:"No active session"});if(tT.current||tW.current)return a({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eY({kind:"running_command"});try{await nI(s);let e=await aL(s,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return a({handled:!0,error:"Handoff cancelled"});return await nf(s,!0)&&nb(),a({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eY(null),tj.current===s&&nF(s)}default:{if(!s)return a({handled:!0,error:"No active session"});let t=await aL(s,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nR(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return a({handled:!0,message:"Command completed"})}}}catch(e){return a({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&ez(!1)}},[n$,nR,nI,ny,nV,eA,n0,nf,nw,nv,nb,h,nF]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r),"returned";let s=rl(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:s,images:a?.length??0});try{return await aL(i,{type:"steer",message:s,...a?.length?{images:a}:{}}),tu({type:"ack",id:l}),"accepted"}catch(s){return tu({type:"fail",id:l}),console.error("Failed to steer:",s),n$({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r,i),"returned"}},[n$,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r,i)=>{let s=tj.current;if(!s)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),i),"returned";let a=rl(t,i??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:n,text:a,images:l?.length??0});try{return await aL(s,{type:"prompt",message:a,streamingBehavior:n,...l?.length?{images:l}:{}}),tu({type:"ack",id:o}),"accepted"}catch(n){return tu({type:"fail",id:o}),console.error("Failed to queue prompt:",n),n$({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),i,s),"returned"}},[n$,e.chatInputRef]),n5=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r),"returned";let s=rl(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:s,images:a?.length??0});try{return await aL(i,{type:"follow_up",message:s,...a?.length?{images:a}:{}}),tu({type:"ack",id:l}),"accepted"}catch(s){return tu({type:"fail",id:l}),console.error("Failed to follow up:",s),n$({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r,i),"returned"}},[n$,e.chatInputRef]),n8=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await aL(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await aL(t,{type:"clear_queue"});tu({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.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),n$({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,n$]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await aL(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),n$({type:"error",message:"Failed to remove queued message"})}},[n$]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ec;el(e),eu(n),m&&(!tj.current||t7.current===tj.current)&&(t5.current=e,t3.current=n),ed(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await ny():r&&await aL(i,{type:"set_thinking_ceiling",ceiling:n}),await aL(i,{type:"set_thinking_level",level:e}),await nf(i)}catch(e){console.error("Failed to set thinking level:",e),n$({type:"error",message:"Failed to set thinking level"}),await nf(i)}},[m,nf,n$,ec,ny]);ev.current=no?`${no.provider}/${no.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?aZ(t.state):void 0)??null})}).catch(()=>{})},[rt,E,eE]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await ny(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};ef(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=aZ(await aL(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let s=await aL(e,{type:"set_fast_mode",enabled:!n});i({enabled:s?.enabled===!0,active:s?.active===!0})}catch(t){if(!r())return;n$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(aZ(await aL(e,{type:"get_state"}))??null)}catch{i(null)}}finally{ef(!1)}},[ny,ep,n$]),ri=(0,i.useCallback)(async e=>{let t=(0,sX.xG)(e);na(e);let n=tj.current??await tQ.current;if(n)try{await aL(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[na]),rs=(0,i.useCallback)(e=>{tO.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=rs;let ra=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tJ.current=0,rs(!0),ra("smooth")},[ra,rs]),rd=(0,i.useCallback)(()=>{tJ.current=0,rs(!1)},[rs]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!a2.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[]),ru=(0,i.useCallback)(()=>{if(!tT.current&&!tW.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?rs(!0):t&&rs(!1))},[rs]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&nf(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(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"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nD(t.id)),e.state?.isBashRunning&&(tW.current=!0,z(!0),nH(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&ez(n.isCompacting),eH(aX(n)),void 0!==n.contextUsage&&ej(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t8.current=t.id,el(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ts(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(aY(n.queuedMessages)),void 0!==n.subagents&&td(e=>aJ(e,n.subagents??[])),void 0!==n.goal&&tK(n.goal??null)),e&&eJ(!0)}),()=>{tP.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nG)},[g?.tree,k,nG,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rc),()=>{window.removeEventListener("keydown",rc)}),[rc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rc,{passive:!0}),e.addEventListener("wheel",rc,{passive:!0}),e.addEventListener("touchstart",rc,{passive:!0}),e.addEventListener("scroll",ru,{passive:!0}),()=>{e.removeEventListener("pointerdown",rc),e.removeEventListener("wheel",rc),e.removeEventListener("touchstart",rc),e.removeEventListener("scroll",ru)}},[S.length,v,ru,rc]),(0,i.useEffect)(()=>{if(t9.current||!E&&!A||!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,A,S.length,$.streamingMessage,eG,W,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,ra("instant");return}if(!t9.current&&tO.current){let e=Date.now()-ne.current<1500;ra(tT.current||tW.current||e?"instant":"smooth")}}},[S.length,E,A,ra,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,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,ek?.tokens,ek?.percent,ek?.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:ea,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:eA,compaction:eD,compactError:eW,compactResult:eF,currentModel:nl,displayModel:no,modelSwitching:eE,sessionStats:nd,runStateKnown:eU,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ta,deliveryRows:th,subagents:to,todoPhases:tm&&tm.sid===tj.current?tm.phases:null,compactedWork:T,notices:e1.visible,extensionDialog:e8,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nT,sendExtensionCustomInput:nM,isAutoModelSelection:m&&null===X,agentPhase:eG,isNew:m,autoFollowPaused:tB,resumeAutoFollow:ro,pauseAutoFollow:rd,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tZ,scrollContainerRef:tX,handleSend:nq,handleAbort:nK,handleFork:nV,handleNavigate:nJ,handleModelChange:nY,handleRoleModelChange:nX,handleMainPresetChange:nZ,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n5,handlePromptWithStreamingBehavior:n4,handleAbortCompaction:n8,handleRecallQueue:n6,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:em,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:ny,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:A,pendingBash:W,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:s,transitioning:a,onAgentEnd:ex,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tV=no(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:t8.bo.find(e=>e.alias===tV?.alias)?.oauthPosition;return t8.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;en.current=ek,er.current=ej,ei.current=tj;let t6=(0,i.useRef)(!0);t6.current=!tb;let t3=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t3.current&&(es.current+=1),t3.current=eC},[eC]),(0,i.useEffect)(()=>()=>{es.current+=1},[]),(0,i.useEffect)(()=>{Q(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(lg(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 n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let s=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let s=0;for(let a=i;a<r;a++)if(iC(t[a])===e.identity&&(s+=1)===e.occurrence)return{kind:"entry",entryId:n[a]};return null}(i.intent,ek,ej);if(null===s){r.push(i);continue}n=!0,"drop"!==s.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===s.entryId)||r.push({id:i.id,anchorEntryId:s.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(lx(e,r),r):t})},[ek,ej,tj]);let t7=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tj.current,t=t7.current;if(t7.current=e?{sessionId:e,entryIds:ej}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let s=e.length;s<i;s++){let e=n[s];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&r.push(t[s])}return r}(t.entryIds,ej,ek),r=eo();if(0===n.length||!r)return;let i=na(e,"web6",void 0)?.alias??null;for(let e of n)ee.current.some(t=>t.anchorEntryId===e)||eu(i,"done",r,{kind:"entry",entryId:e})},[ej,ek,tj,eo,eu]);let t9=eC&&tx?.kind==="running_tools"&&tx.tools.length>0&&tx.tools.every(e=>"wait"===e.name),ne=eb||a,{hideThinkingBlock:nt}=(_=t??e?.cwd??null,H=t5(),(0,i.useEffect)(()=>{t4(_).catch(()=>{})},[_]),H),nn=(0,i.useMemo)(()=>({hideThinking:nt}),[nt]);(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:nr,process:ni}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],s=-1,a=null,l=(e,t,n)=>{if(0===t.length)return;let s=(a&&a.anchorIdx===e||(a={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(a)),a),l=r.length-1;for(let e of t)s.entries.push({...e,afterMainIndex:l});s.messageCount+=t.length,s.toolCallCount+=n},o=e_(e),d=new Map,c=(e,t)=>{let n=d.get(e)??0;d.set(e,n+1),r.push({kind:"answer",anchorIdx:s,idx:e,runIndex:n,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){r.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(),s=i.idx,r.push(i);continue}if(eU(t)){r.push(void 0!==i.anchorIdx||s<0?i:{...i,anchorIdx:s});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(s,[{idx:i.idx}],0);continue}let a=eW(t,n),d=!1;for(let e of a){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(s,[{idx:i.idx,blocks:e.blocks}],eP(e.blocks)),o.collect(i.idx,e.blocks)}!d&&ez(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(ek,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(eJ(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!eJ(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let s=i,a=s+1;for(;a<e.length&&!eJ(e[a]);)a+=1;if((t.sessionBusy||t.isStreaming)&&a===e.length&&s===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,s+1,a)){for(let e=s;e<a;e++)r.push({kind:"message",idx:e});i=a;continue}for(let n of(r.push({kind:"message",idx:s}),function(e,t,n,r){let i=[],s=[],a=0,l=[],o=0,d=0,c=e_(e.slice(t+1,n)),u=()=>{0!==s.length&&(i.push({kind:"process",anchorIdx:t,idx:s[0].idx,groupIndex:d++,entries:s,messageCount:s.length,toolCallCount:a,turnHasAnswer:!1}),s=[],a=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:c.attach(n),precedingBlocks:l}),l=[]};for(let o=t+1;o<n;o++){let n=e[o];if("assistant"!==n.role){if(eU(n)){u(),i.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&s.push({idx:o});continue}let d=eW(n,r),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(s.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),a+=eP(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&ez(n,r)&&p(o,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:o++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,s,a,{hideThinking:t.hideThinking})))r.push(n);i=a}return r}(ek,{sessionBusy:t1,isStreaming:eS.isStreaming,hideThinking:nn.hideThinking}),nn),[ek,t1,eS.isStreaming,nn]),ns=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let s=-1,a=-1;t.forEach((e,t)=>{let n=nz(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===s||e.item.anchorIdx===a),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=r.get(o.position);e?e.calls.push(...n):r.set(o.position,{calls:[...n],placement:l?"after":"before"})}}"user"===e.role&&(s=t),eJ(e)&&(a=t)});let{continuing:l}=nW(e,t,n);if(l){let e=r.get(l.position);e?e.calls.unshift(...l.calls):r.set(l.position,{calls:l.calls,placement:"before"})}return r})(nr,ek,tn?.messages),[nr,ek,tn]),nd=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=nW(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let s=e.findIndex(e=>e.idx>i),a=-1===s?e.length:s;return{position:a,jumpTo:a<e.length?a:e.length>0?e.length-1:null,calls:r}})(nr,ek,tn?.messages),[nr,ek,tn]),[nc,nu]=(0,i.useState)(lu),{startIndex:np,endIndex:nh,hasLater:nm}=lp(nr.length,nc),nf=null!==nc.end&&nm,ng=(0,i.useRef)(nr.length);ng.current=nr.length;let nx=(0,i.useRef)(null),nv=(0,i.useRef)(null),nb=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nc.end&&nc.end>=nr.length&&nu(e=>({count:e.count,end:null}))},[nc.end,nr.length]),(0,i.useEffect)(()=>{let e=nx.current,t=tC.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nb.current=t.scrollHeight-t.scrollTop,nu(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nc,nr.length,tC]),(0,i.useEffect)(()=>{if(null==nb.current)return;let e=tC.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nb.current),nb.current=null}},[nc.count,tC]),(0,i.useEffect)(()=>{let e=nv.current,t=tC.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nu(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=lp(e,t),s=i+n;return s>=e?{count:e-r,end:null}:{count:s-r,end:s}})(ng.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nc,nr.length,tC]);let[ny,nw]=(0,i.useState)(null),[nk,nj]=(0,i.useState)(null),[nS,nC]=(0,i.useState)(0),nL=(0,i.useRef)(null),n_=(0,i.useCallback)((e,t=null)=>{tw(),nL.current={item:e,dispatchKey:t},nw(null),nj(null),nu(t=>lh(ng.current,e,t)),nC(e=>e+1)},[tw]);(0,i.useLayoutEffect)(()=>{let e,t=nL.current,n=tC.current;if(null===t||!n)return;let r=n.querySelector(`[data-chat-item="${t.item}"]`);if(!r)return;nL.current=null;let i=t.dispatchKey?r.querySelector(".answer-dispatch"):null;if(i)e=i.getBoundingClientRect().top;else{let t=document.createRange();t.selectNodeContents(r),e=t.getBoundingClientRect().top}n.scrollTop+=e-n.getBoundingClientRect().top-24,i&&t.dispatchKey?nj(t.dispatchKey):nw(t.item)},[nS,nc,nr,tC]),(0,i.useEffect)(()=>{if(null===ny)return;let e=setTimeout(()=>nw(null),1800);return()=>clearTimeout(e)},[ny]),(0,i.useEffect)(()=>{if(null===nk)return;let e=setTimeout(()=>nj(null),1800);return()=>clearTimeout(e)},[nk]);let nD=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>nu(lu));let e=tC.current;e&&(e.scrollTop=e.scrollHeight)},[tC]),nH=(0,i.useCallback)(()=>{nf&&nD(),ty()},[nf,nD,ty]),nO=(0,i.useRef)(null),[nB,nU]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!z||nO.current===z.id||z.sessionId!==e?.id||eb||0===ek.length)return;nO.current=z.id,W?.(z.id);let t=ej.indexOf(z.entryId);if(t<0)return void nU(!0);let n=0;for(let e=0;e<nr.length;e++){let r=nr[e].idx;if(r>t||(n=e,r===t))break}n_(n)},[z,e?.id,eb,ek.length,ej,nr,n_,W]),(0,i.useEffect)(()=>{if(!nB)return;let e=setTimeout(()=>nU(!1),6e3);return()=>clearTimeout(e)},[nB]);let[nq,nK]=(0,i.useState)(!1),[nV,nJ]=(0,i.useState)(0),nG=(0,i.useMemo)(()=>nq?nr.map(e=>(function(e,t){if("answer"===e.kind)return eZ(e.blocks);let n=t[e.idx];return n&&"content"in n?eZ(n.content):""})(e,ek).toLowerCase()):lv,[nq,nr,ek]),nY=(0,i.useCallback)(e=>{tw(),nu(t=>lh(ng.current,e,t))},[tw]),nZ=(0,i.useCallback)(()=>nK(!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 n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nK(!0),nJ(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tC]);let nX=(0,i.useMemo)(()=>{let e=[];return nr.forEach((t,n)=>{if("message"!==t.kind)return;let r=lf(ek[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nr,ek]),nQ=`${np}:${nh}`,n0=ej.length>0?ej[ej.length-1]:null,[n1,n2]=(0,i.useState)(null),n4=(0,i.useRef)(!1);(0,i.useEffect)(()=>{n4.current||!tt||eb||!e?.id||(n4.current=!0,t1||!n0||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(ek)||function(e){try{return window.localStorage.getItem(lb(e))}catch{return null}}(e.id)!==n0&&n2(n0))},[tt,eb,e?.id,t1,n0,ek]);let n5=(0,i.useCallback)(()=>{e?.id&&n1&&function(e,t){try{window.localStorage.setItem(lb(e),t)}catch{}}(e.id,n1),n2(null)},[e?.id,n1]),n8=null!==n1&&n1===n0&&!t1&&!nf,n6=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,n3=(0,i.useRef)(te);n3.current=te,(0,i.useEffect)(()=>{f?.(n3.current)},[n6,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let n7=e1?`${e1.percent??"null"}|${e1.contextWindow}|${e1.tokens??"null"}`:null,n9=(0,i.useRef)(e1);n9.current=e1,(0,i.useEffect)(()=>{x?.(n9.current)},[n7,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(ta)},[b,ta]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:re,handleDragEnter:rt,handleDragOver:rn,handleDragLeave:rr,handleDrop:ri}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:a,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t1||p?.current?.addAttachments(e)},[t1,p])),rs=(0,i.useMemo)(()=>{var e;return e=tn?.messages,e&&e.length>0?[...e,...ek]:ek},[tn,ek]),ra=(0,i.useMemo)(()=>{let e=new Map;for(let t of rs)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rs]),ro=(0,i.useMemo)(()=>{let e,t,n,r;return e=new Map,t=new Map,n=new Map,r=(e,r,i)=>{let s=n.get(e);s&&r&&t.set(s,{status:r,order:i})},rs.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=ra.get(e.toolCallId);if(t)for(let r of n$(e,t)??[])n.set(r.agentId,r.key)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(nM(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=nI(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let s=i[i.length-1],a=i.slice(1,-1).join("#");return/^\d+$/.test(s)&&a?{key:`${a}#${s}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:nI(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i}),e.set(n.key,r);return}if("wait"===t.toolName)for(let e of nN(t.details?.jobs)){if("task"!==e.type)continue;let t=nI(e.id);t&&r(t,nT(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of nM(t.content).matchAll(nR)){let t=Object.fromEntries([...e[1].matchAll(nE)].map(e=>[e[1],e[2]]));t.id&&r(t.id,nT(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:n}},[rs,ra]),rd=(0,i.useMemo)(()=>({ledger:ro,subagents:ta,toolResults:ra,onOpenPanel:w,focusedDispatch:nk,sessionId:e?.id??null}),[ro,ta,ra,w,nk,e?.id]),rc=(0,i.useMemo)(()=>(function(e,t,n,r,i,s,a=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of n)for(let n of t.calls)o.set(n.toolCallId,e);if(a?.jumpTo!=null)for(let e of a.calls)o.set(e.toolCallId,a.jumpTo);let d=[];if(e.forEach((e,n)=>{if("assistant"!==e.role)return;let a=n>l;for(let n of e.content??[])if("toolCall"===n.type&&"task"===n.toolName)for(let e of n$(n,t.get(n.toolCallId))??[]){let t=nA(e,r,i),l=nP[t.run],c=null;"running"===l&&("live"===t.runSource||a&&s)?c="running":"awaiting"===l&&a&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(n.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]}})(rs,ra,ns,ta,ro,t1,nd),[rs,ra,ns,ta,ro,t1,nd]),ru=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),rp=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ek.length-1;n>=0;n-=1){let r=lf(ek[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ek]),rh=(0,i.useMemo)(()=>e8(ek,ra,tl,tn?.todoPhases??null),[ek,ra,tl,tn]),rm=(0,i.useMemo)(()=>iW(eS.streamingMessage).join("|"),[eS.streamingMessage]),rf=(0,i.useMemo)(()=>JSON.stringify(iz(eS.streamingMessage)),[eS.streamingMessage]),rg=(0,i.useMemo)(()=>JSON.stringify(iF(eS.streamingMessage)),[eS.streamingMessage]),rx=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let s=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.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(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),a=[],l=new Map,o=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){o=n;continue}let i=iW(r),d=iF(r,s);if(0===i.length&&0===d.length||o<0)continue;let c=iz(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),a.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let s=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){s=t;break}if(s>=0){let e=l.get(s);e||(e={index:s,entryId:t[s],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(s,e),a.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!o.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.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 a.sort((e,t)=>e.index-t.index)})(ek,ej,rm.length>0?rm.split("|"):[],JSON.parse(rf),JSON.parse(rg)),[ek,ej,rm,rf,rg]),rv=e?.id??tj.current??void 0,rb=(O=iD(D=(0,i.useMemo)(()=>({sessionId:rv,sessionProvider:e7?.provider,turns:rx,messages:ek,subagents:ta}),[rv,e7?.provider,rx,ek,ta])),B=iU(D),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...O,...B])),[O,B])),ry=tv&&0===ek.length&&!eS.isStreaming&&!t1,rw=e?.cwd??t??void 0,rk=e7?eE[`${e7.provider}:${e7.modelId}`]??null:null,rj=e7?eA[`${e7.provider}:${e7.modelId}`]??null:null,rS=(0,i.useRef)(null),rC=(0,i.useRef)(null),rN=(0,i.useCallback)(()=>{rS.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(C?.(rN),()=>C?.(null)),[rN,C]),(0,i.useLayoutEffect)(()=>{let e=rC.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tC.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tC.current;if(!i)return;let s=n-i.clientHeight;n=i.clientHeight,s<=0||i.scrollHeight-i.scrollTop-i.clientHeight-s<=1&&(i.scrollTop+=s)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[eb,tC]);let rI=(0,i.useCallback)((...e)=>(null!==nc.end&&nD(),tN(...e)),[tN,nc.end,nD]),rT=(0,r.jsx)("div",{ref:rS,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(aC,{ref:p,sessionId:e?.id??tj.current??void 0,onEnsureSession:tv&&t?tq:void 0,onLiveTranscriptPersisted:tK,onSend:rI,onAbort:tI,onSteer:eC?tz:void 0,onFollowUp:eC?tW:void 0,onPromptWithStreamingBehavior:eC?tP: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:eF,onRoleModelChange:tR,modelSwitching:e9,onCompact:e||tv?tA:void 0,onAbortCompaction:tF,isCompacting:e4,compactError:e6,compactResult:e3,toolPreset:eD,onToolPresetChange:e||tv?tO:void 0,thinkingLevel:eH,effectiveThinkingLevel:eB,thinkingCeiling:eG,onThinkingLevelChange:e||tv?tB:void 0,fastMode:eY,fastModeBusy:eX,onFastModeToggle:e||tv?eQ:void 0,availableThinkingLevels:rk,thinkingLevelMap:rj,retryInfo:e0,deliveryRows:ts,inputHistory:rp,onRecallQueue:t_,onRemoveQueuedMessage:tD,slashCommands:tr,slashCommandsLoading:ti,onLoadSlashCommands:tU,onBuiltinCommand:tH,soundEnabled:M,onSoundToggle:$,onAudioUnlock:A,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rM=eS.streamingMessage,r$=(0,i.useMemo)(()=>rM?eW(rM,{isStreaming:!0}):[],[rM]),rR=(0,i.useMemo)(()=>r$.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[r$]),rL=(0,i.useMemo)(()=>r$.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[r$]),rA=rM?.role==="assistant"?rM:null,rz=eC&&(tx?.kind==="running_tools"||(rA?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rW=rA?.provider??e7?.provider,rP=rA?.credentialId;(0,i.useEffect)(()=>{if(!rz)return;let e=eo();e&&ea.current!==e.turn&&el.current!==e.turn&&(ea.current=e.turn,eh("working",e,rW,rP))},[rz,rW,rP,eo,eh]);let[rF,r_]=(0,i.useState)(null),rD=(0,i.useCallback)(e=>{r_(e)},[]),rH=(0,i.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),rO=(0,i.useMemo)(()=>{let e=[eC&&!rM&&tx?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.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,rM,tx,eN,eI,U]);(0,i.useEffect)(()=>{if(!rF)return void k?.(null);let e=[],t=[],n=0;if(rM&&rL.length>0){let r=rF.messages.length+e.length;for(let i of(e.push(rM),rL))t.push({idx:r,blocks:i}),n+=eP(i)}if(rH&&(t.push({idx:rF.messages.length+e.length}),e.push(rH)),0===t.length)return void k?.(rO?{...rF,status:rO}:rF);let r=-1;for(let e=rF.messages.length-1;e>=0;e--)if(eJ(rF.messages[e])){r=e;break}let i=rF.groups.slice(),s=i.length>0?i[i.length-1]:void 0;s&&s.anchorIdx===r?i[i.length-1]={...s,entries:[...s.entries,...t],messageCount:s.messageCount+t.length,toolCallCount:s.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),k?.({...rF,groups:i,messages:[...rF.messages,...e],status:rO})},[rF,rL,rM,rH,rO,k]),(0,i.useEffect)(()=>()=>k?.(null),[k]);let rB=th.filter(e=>"belowEditor"!==e.placement),rU=th.filter(e=>"belowEditor"===e.placement);return ey?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ey}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":ne,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:rt,onDragOver:rn,onDragLeave:rr,onDrop:ri,children:[ne?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.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,re&&!t1&&(0,r.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,r.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,r.jsx)(lI,{request:tu,onInput:tf}),ry&&!S?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,r.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,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(V,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.13"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.10.4"]})]})]})]}),(0,r.jsx)(lS,{notices:to,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[S&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:S}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!S,style:{display:S?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(ii,{open:nq,onClose:nZ,containerRef:tC,index:nG,renderedStart:np,renderedEnd:nh,contentKey:ek,onReveal:nY,onProgrammaticScroll:tw,focusRequest:nV,t:U}),nB&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:U("chat.jumpMissing")}),(0,r.jsx)(lS,{notices:to,floating:!0,align:"right"})]})}),(0,r.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,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(lj,{widgets:rB}),(0,r.jsx)(nF.Provider,{value:rd,children:(0,r.jsx)(i$,{utterances:rb,children:(0,r.jsx)(ly,{messages:ek,entryIds:ej,toolResultsMap:ra,modelNames:eT,messageCwd:rw,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:nr,dispatchSlots:ns,compactedDispatch:nd,process:ni,startIndex:np,endIndex:nh,sentinelRef:nx,laterSentinelRef:nv,flashItem:ny,t:U,cues:X,cueFollowRef:t6,onProcessLogChange:rD})})}),!nf&&eS.isStreaming&&eS.streamingMessage&&rR.length>0&&(0,r.jsx)(rE,{message:eL(eS.streamingMessage,rR),sessionId:e?.id??tj.current??void 0,isStreaming:!0,modelNames:eT,cwd:rw,onOpenFile:j}),n8&&(0,r.jsx)(ic,{onDismiss:n5,t:U}),(0,r.jsx)("div",{ref:tS})]})})}),(0,r.jsx)(is,{questions:nX,containerRef:tC,layoutKey:nQ,onJump:n_,label:U("chat.questionRail")}),(t1&&tb||nf)&&(0,r.jsxs)("button",{type:"button",onClick:nH,"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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),U("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rC,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[td&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(lN,{request:td,onRespond:tm,onActivity:e=>void tf(e,"activity"),delivery:tc})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(id,{compaction:e5,t:U}),(0,r.jsx)(lk,{goal:tk,t:U}),!J&&(0,r.jsx)(r7,{summary:rc,onJump:n_,onOpenPanel:ru}),(0,r.jsx)(lj,{widgets:rU}),rh&&!J&&(0,r.jsx)(aI,{phases:rh})]})}),rT,(0,r.jsx)(aN,{statuses:tp})]})]})}function lk({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tG(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tG(e.tokensUsed)});return(0,r.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:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function lj({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.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,r.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 lS({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let s="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.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:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function lC({focusKey:e,label:t,labelledBy:n,maxBlockSize:s="min(56dvh, 620px)",onCancel:a,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 n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:a?e=>{"Escape"===e.key&&(e.stopPropagation(),a())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:s},children:[l?(0,r.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 lN({request:e,onRespond:t,onActivity:n,delivery:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,m]=(0,i.useState)(""),f=(0,i.useRef)(0),g=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-f.current<1e3||(f.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{if(o("editor"===e.method?e.prefill??"":""),m(""),p({}),"ask"!==e.method)return void c({});let t={};for(let n of e.questions)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];c(t)},[e]);let x=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:l})};if("ask"===e.method){let n=e.questions.every(e=>(d[e.id]?.length??0)>0||(u[e.id]?.trim().length??0)>0),i=()=>{n&&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,r.jsx)(lC,{focusKey:e.id,label:a("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:a("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let s=d[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=s.includes(n),l=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{var e,r;return e=t.id,r=t.multi??!1,void(g(),c(t=>{let i=t[e]??[],s=r?i.includes(n)?i.filter(e=>e!==n):[...i,n]:[n];return{...t,[e]:s}}))},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,r.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,r.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,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.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,r.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,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:u[t.id]??"",onChange:e=>{g(),p(n=>({...n,[t.id]:e.target.value}))},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:a("chat.customAnswer"),"aria-label":a("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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.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:a("chat.cancel")}),(0,r.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:a("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||s?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&s?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&s?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&s?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:s?.status==="sending"?a("chat.responseSending"):a("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(lC,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.planApproval")}),(0,r.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,r.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,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(tK,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:h,onChange:e=>m(e.target.value),placeholder:a("chat.planFeedback"),"aria-label":a("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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.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:a("chat.refinePlan")}),(0,r.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:a("chat.approvePlan")})]})]})]})}):(0,r.jsx)(lC,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:a("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.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,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),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:n},n))}),"input"===e.method&&(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.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:a("chat.cancel")}),"confirm"===e.method?(0,r.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:a("chat.confirm")}):"select"!==e.method?(0,r.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:a("chat.submit")}):null]})]})})}function lI({request:e,onInput:t}){let{t:n}=(0,R.s)(),s=(0,i.useRef)(null),a=(0,i.useRef)(!1),l=eC(e.lines);return(0,i.useEffect)(()=>{s.current?.focus()},[e.id]),(0,r.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,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||s.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,r.jsx)("textarea",{ref:s,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=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=eT[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":" ":eI[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:n=>{a.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.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:n("chat.close")})]}),(0,r.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,n)=>{var s;return(0,r.jsxs)(i.Fragment,{children:[(s=`line-${t}`,eN(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function lT({onPick:e,t}){let[n,s]=(0,i.useState)(""),[a,l]=(0,i.useState)({kind:"idle"}),o=(0,i.useRef)(null),d=n.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"===a.kind?a.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>s(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 n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),d.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===a.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===a.kind&&t("palette.searching"),"error"===a.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,r.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((n,i)=>{let s=u.sessions[n.sessionId],a=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!s,onClick:()=>s&&e(s,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),c(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:s?s.name?.trim()||s.firstMessage?.trim()||s.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,a)}),n.snippet.slice(a)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var lM=n(50640),l$=n(73620);let lR=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lE(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let lL=["tags","categories","keywords","tag","category"];function lA({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=lL.find(t=>Array.isArray(e[t])),a=s?e[s].map(lE).filter(Boolean):[],l=n.filter(([e])=>e!==s&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),a.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:a.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=lE(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}let lz={source:"Source",preview:"Preview",diff:"Diff"},lW={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},lP={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 lF(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function l_(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function lD(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=l_(n.startContainer),i=l_(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),a=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(a))return null;if(s<a){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((i=e).dataset.lineNumber))}}}return s>a?null:{startLine:s,endLine:a}}function lH({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,s)=>{let a=e.children??[],l=a[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?a[0]:null,c=o?a.slice(1):a;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":s+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,lM.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${s}`}),(0,r.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,r)=>(0,lM.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${s}-${r}`}))})]},`source-line-${s}`)})}function lO(e,t,n,r={}){let i=tt(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function lB({filePath:e,sourceSessionId:t}){let{t:n}=(0,R.s)();return(0,r.jsx)("a",{href:lO(e,"download",t),download:tn(e),title:n("i18n.downloadFile"),"aria-label":n("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function lU(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lq({patch:e}){let t,{t:n}=(0,R.s)(),i=(t=nm(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,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let s=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),a=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)a.add(t);let l=[],o=0;for(;o<i.length;)if(a.has(o)){let e=[];for(;o<i.length&&a.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!a.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lW},children:l.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:lP,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function lK({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=tn(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lO(e,"watch",n));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,n]);let v=lO(e,"read",n,o?{v:o}:void 0),b=null!=c?lU(c):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,r.jsx)("span",{children:b}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(lB,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:m?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:m}):(0,r.jsx)("img",{src:v,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>f("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function lV({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=tn(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lO(e,"watch",n));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),f(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,n]);let v=lO(e,"read",n,o?{v:o}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"audio"}),null!=p&&(0,r.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}(p)}),null!=c&&(0,r.jsx)("span",{children:lU(c)}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(lB,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[m&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:m}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:v,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>f("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function lJ({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eR(e),g="pdf"===f,x=g?lO(e,"read",n,o?{v:o}:void 0):lO(e,"preview",n,o?{v:o}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),l(!1),m.current&&(m.current.close(),m.current=null),fetch(lO(e,"meta",n)).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(lO(e,"watch",n));return m.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(),m.current=null}},[e,g,n]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===f?"docx preview":"pdf"}),null!=c&&(0,r.jsx)("span",{children:lU(c)}),(0,r.jsx)(lB,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:tn(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function lG({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o}){let d;return eE(e)?(0,r.jsx)(lK,{filePath:e,cwd:t,sourceSessionId:n}):null!==(e$[eR(e)]??null)?(0,r.jsx)(lV,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(d=eR(e))||"docx"===d?d:null)?(0,r.jsx)(lJ,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(lY,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o})}function lY({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:s,onMentionLines:a,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d}){let c,u,{isDark:p}=tD(),{t:h}=(0,R.s)(),[m,f]=(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),[A,z]=(0,i.useState)(null),W=(0,i.useCallback)(e=>fetch(lO(e,"read",n)).then(e=>e.json()).then(e=>e.error?(j(e.error),null):(j(null),f(e),e)).catch(e=>(j(String(e)),null)),[n]),P=(0,i.useCallback)(async e=>{let n=++E.current;if(b(!0),!t){x(null),b(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(n!==E.current)return;x(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{n===E.current&&x(null)}finally{n===E.current&&b(!1)}},[t]);(0,i.useEffect)(()=>{w(!0),j(null),f(null),x(null),C("source"),I(!1),M(!1),$.current&&($.current.close(),$.current=null),W(e).finally(()=>w(!1));let t=new EventSource(lO(e,"watch",n));return $.current=t,t.addEventListener("connected",()=>{M(!0)}),t.addEventListener("change",()=>{W(e),P(e)}),t.addEventListener("error",()=>{M(!1)}),t.onerror=()=>{M(!1)},()=>{t.close(),$.current=null}},[e,W,P,n]),(0,i.useEffect)(()=>{P(e)},[P,e,o]),(0,i.useEffect)(()=>{(m?.language==="markdown"||m?.language==="html")&&"diff"!==d&&C("preview")},[m?.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)(()=>m?.language==="markdown"?tp(m.content):"",[m]),O=(0,i.useMemo)(()=>m?.language==="markdown"?function(e){let t=function(e){let t=lR.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,l$.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(m.content):null,[m]);(0,i.useEffect)(()=>{let e=()=>{let e=L.current;z(a&&"source"===S&&e?lD(e,window.getSelection()):null)};if(e(),a&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,S,a]);let B=(0,i.useCallback)(n=>{a&&n&&a(tr(e,t),n.startLine,n.endLine)},[t,e,a]);if((0,i.useEffect)(()=>{if(!a||"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 n=L.current,r=n?lD(n,window.getSelection()):null;r&&(e.preventDefault(),B(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,B,a]),y||"diff"===d&&v&&!m)return(0,r.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,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:k});if(!m&&!_)return null;let U=m?.language??"text",q=m?.content??"",K="html"===U,V="markdown"===U,J=(u=(c=te(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 ${lU(m.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:X,children:X}),!_&&(0,r.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,r.jsxs)("div",{className:"file-viewer-controls",children:[Z.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":h("i18n.fileViewMode"),children:Z.map(e=>{let t=Y===e;return(0,r.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:lz[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(l||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{A&&a?B(A):l?.(tr(e,t),!1)},title:A&&a?`${h("i18n.mentionSelectedLines")} (L${A.startLine}${A.startLine!==A.endLine?`-L${A.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!l&&!a,className:"file-viewer-icon-button",children:(0,r.jsx)(lF,{})}),"source"===Y&&(0,r.jsx)(r.Fragment,{children:(0,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!_&&(0,r.jsx)(lB,{filePath:e,sourceSessionId:n})]})]}),(0,r.jsx)("div",{ref:L,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===Y&&F?(0,r.jsx)(lq,{patch:g.patch}):K&&"preview"===Y?(0,r.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,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[O?.data&&(0,r.jsx)(lA,{data:O.data}),(0,r.jsx)(e9.oz,{remarkPlugins:tx,rehypePlugins:tb,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,r.jsx)(tB,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tq,{code:s.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let a=s?e2(e,J,t??J):null;return a&&s?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),s(a))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...s}){delete s.node;let a="string"==typeof e?e2(e,J,t??J):null,l=a?lO(a,"read",n):e;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...s})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:H})]}):(0,r.jsx)(e3.A,{className:N?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?e7.xJ:e7.vs,showLineNumbers:!0,lineNumberStyle:{...lP},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,r.jsx)(lH,{...e,wrapLines:N}),wrapLongLines:N,children:q})})]})}function lZ({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:s}){let{t:a,locale:l}=(0,R.s)(),[o,d]=(0,i.useState)(null);return(0,r.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,r.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(),s(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,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(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,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:nk(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),s(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background: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:a("i18n.close"),"aria-label":`${a("i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let lX=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],lQ=new Set(lX);function l0(e){return void 0!==e&&lQ.has(e)}function l1(e){if(!e)return[...lX];let t=new Set(e);return lX.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function l2(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return l0(n)?n:"inherit"}function l4(e,t){let n=e.lastIndexOf(":"),r=l0(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var l5=n(98795),l8=n.n(l5);function l6(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function l3({value:e,options:t,onChange:n,disabled:s=!1,placeholder:a="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),m=(0,i.useRef)(null),f=(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=l6(v.trim());return e?t.filter(t=>l6(`${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(()=>m.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&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=sZ(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),I=e=>{e.disabled||(n(e.value),x(!1))},T=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${l8().root}${c?` ${c}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:l8().trigger,disabled:s,"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,r.jsx)("span",{className:j?l8().value:l8().placeholder,children:j?.label??(e||a)}),(0,r.jsx)("svg",{className:l8().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:l8().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,r.jsxs)("div",{className:l8().searchWrap,children:[(0,r.jsxs)("svg",{className:l8().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:l8().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,r.jsx)("div",{id:k,className:l8().options,role:"listbox","aria-label":d,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:l8().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>I(t),children:[(0,r.jsxs)("span",{className:l8().optionCopy,children:[(0,r.jsx)("span",{className:l8().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:l8().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:l8().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:l8().empty,children:o})})]})]})}let l7=["global","project"],l9=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function oe(e){return`${e.provider}/${e.id}`}function ot({cwd:e,onRolesChanged:t}){let{t:n}=(0,R.s)(),[s,a]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){a([]),o([]),c({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let s=await r.json();if(s.error)throw Error(s.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();a(s.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[e]);(0,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);a(s.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>s.filter(e=>!e.hidden),[s]),k=w.some(e=>l9.includes(e.role)&&!e.selector);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")}),!h&&k&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:n("roles.harnessNote")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:l7.map(e=>(0,r.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?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:l4(e.selector??"","inherit"),i=l2(e.selector),s=l1(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),a=l9.includes(e.role);return(0,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,r.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,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),a&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:n(`roles.harness.${e.role}`)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:a&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(l3,{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 n=l.find(e=>oe(e)===t),r=n?d[`${n.provider}:${n.id}`]:void 0,i=l2(e.selector),s=l1(r).includes(i)?i:"inherit";y(e.role,l4(t,s))},options:[{value:"",label:n("roles.unset")},...l.map(e=>({value:oe(e),label:`${e.name} — ${e.provider}`,searchText:oe(e)})),...t&&!l.some(e=>oe(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:s.map(s=>{let a=i===s;return(0,r.jsx)("button",{type:"button","aria-pressed":a,disabled:x===e.role,title:"inherit"===s?n("roles.thinkingInherit"):s,onClick:()=>{a||y(e.role,l4(t,s))},style:{padding:"3px 7px",border:`1px solid ${a?"var(--accent)":"var(--border)"}`,borderRadius:4,background:a?"var(--bg-selected)":"transparent",color:a?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:a?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:s},s)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function on(e){window.open(e,"_blank","noopener,noreferrer")}var or=n(67381),oi=n(64433),os=n(70350),oa=n(88195),ol=n(9312),oo=n(87275),od=n(22008),oc=n(95476),ou=n(35029),op=n(14489),oh=n(78728),om=n(19872),of=n(7751),og=n(92526),ox=n(48238),ov=n(57794),ob=n(41098),oy=n(84604),ow=n(15315),ok=n(74278),oj=n(55457),oS=n(71437),oC=n(29167),oN=n(97283),oI=n(34166),oT=n(33889),oM=n(85486),o$=n(74068),oR=n(83546),oE=n(83709);let oL={anthropic:{Icon:or.A,hasColor:!1},openai:{Icon:oi.A,hasColor:!1},"openai-codex":{Icon:oi.A,hasColor:!1},google:{Icon:os.A,hasColor:!0},"google-vertex":{Icon:os.A,hasColor:!0},"ant-ling":{Icon:oT.A,hasColor:!0},deepseek:{Icon:oa.A,hasColor:!0},groq:{Icon:ol.A,hasColor:!1},mistral:{Icon:oo.A,hasColor:!0},moonshotai:{Icon:od.A,hasColor:!1},"moonshotai-cn":{Icon:od.A,hasColor:!1},moonshot:{Icon:od.A,hasColor:!1},minimax:{Icon:oc.A,hasColor:!0},"minimax-cn":{Icon:oc.A,hasColor:!0},fireworks:{Icon:ou.A,hasColor:!0},huggingface:{Icon:op.A,hasColor:!0},cerebras:{Icon:oh.A,hasColor:!0},openrouter:{Icon:om.A,hasColor:!1},xai:{Icon:of.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:og.A,hasColor:!0},"cloudflare-workers-ai":{Icon:og.A,hasColor:!0},"vercel-ai-gateway":{Icon:ox.A,hasColor:!1},"github-copilot":{Icon:ov.A,hasColor:!1},"amazon-bedrock":{Icon:ob.A,hasColor:!0},"azure-openai-responses":{Icon:oy.A,hasColor:!0},"kimi-coding":{Icon:ow.A,hasColor:!0},nvidia:{Icon:oM.A,hasColor:!0},opencode:{Icon:o$.A,hasColor:!1},"opencode-go":{Icon:o$.A,hasColor:!1},qwen:{Icon:ok.A,hasColor:!0},xiaomi:{Icon:oR.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oR.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oR.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oR.A,hasColor:!1},zai:{Icon:oE.A,hasColor:!1},"zai-coding-cn":{Icon:oE.A,hasColor:!1},zhipu:{Icon:oj.A,hasColor:!0},cohere:{Icon:oS.A,hasColor:!0},perplexity:{Icon:oC.A,hasColor:!0},together:{Icon:oN.A,hasColor:!0},grok:{Icon:oI.A,hasColor:!1}},oA=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function oz({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.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 oP({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...oW,fontFamily:i?"var(--font-mono)":"inherit"}})}function oF({value:e,onChange:t,placeholder:n,mono:s,onKeyDown:a,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,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:a,placeholder:n,style:{...oW,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:o}),(0,r.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,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function o_({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:oW})}function oD({value:e,onChange:t,options:n,required:i}){let{t:s}=(0,R.s)();return(0,r.jsx)(l3,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${s("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function oH({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function oO({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function oB({name:e,provider:t,onChange:n,onRename:s,onDelete:a,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=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 r.json();if(n!==x.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==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=f.filter(e=>!w.has(e)).length,T=N.length>0&&N.every(e=>f.includes(e)),M=!T&&N.some(e=>f.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:o("i18n.provider")}),(0,r.jsx)("button",{onClick:a,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,r.jsxs)(oz,{label:o("i18n.providerName"),children:[(0,r.jsx)(oP,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>s(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,r.jsx)(oz,{label:"Base URL",children:(0,r.jsx)(oP,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(oz,{label:"API Key",children:[(0,r.jsx)(oF,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(oz,{label:"API",children:(0,r.jsx)(oD,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:oA,required:!0})}),(0,r.jsxs)(oz,{label:"Headers",children:[(0,r.jsx)(oJ,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.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,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:o("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":o("models.discoveryFilter"),style:{...oW,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.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,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:o("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:o("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.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,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),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 oU=["off","minimal","low","medium","high","xhigh","max"],oq={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oK({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:oU.map(e=>{let t=n[e],s=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=oq[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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===s?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===s?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===s?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...o,..."omit"===s?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===s?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===s?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,a||e),style:{...o,..."string"===s?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:a,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==s&&i(e,a||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===s?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===s?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oV={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oJ({headers:e,onChange:t}){let[n,s]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),a=(0,i.useRef)(n.length),l=e=>{s(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},o=(e,t)=>{l(n.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.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,r.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,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void l(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>s(e=>[...e,{id:a.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 oG({providerName:e,provider:t,model:n,onChange:s,onDelete:a}){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),m=(e,t)=>s({...n,[e]:t}),f=(()=>{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,n.id,n.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==l.phase){o({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.json();if(!r.ok||!i.ok)return void o({phase:"error",message:i.error??`HTTP ${r.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)})}}},[n,t,e,l.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===c.phase)return;let i=++p.current;u({phase:"loading"});try{let a=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&a.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${a}`),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 n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s=!0,r+=1);s&&(n.cost=i)}return{model:n,appliedCount:r}}(n,o.recommendation.preset);d.appliedCount>0&&(h.current=n,s(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,n,s,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:n}=c,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \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`${r} \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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:d("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,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:f}),(0,r.jsxs)("button",{onClick:g,disabled:!n.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":n.id.trim()&&"testing"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?d("i18n.checking"):"success"===l.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)("button",{onClick:a,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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(oz,{label:"ID *",children:(0,r.jsx)(oP,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(oz,{label:"Name",children:(0,r.jsx)(oP,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,s(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,r.jsx)(oz,{label:"API override",children:(0,r.jsx)(oD,{value:n.api??"",onChange:e=>m("api",e||void 0),options:oA})}),(0,r.jsxs)(oz,{label:"Headers",children:[(0,r.jsx)(oJ,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(oH,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(oH,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oH,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oV}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(oH,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>s({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(oO,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("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,r.jsx)(oK,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(oz,{label:"Context window (tokens)",children:(0,r.jsx)(o_,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(oz,{label:"Max output tokens",children:(0,r.jsx)(o_,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(oO,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(oz,{label:e,children:(0,r.jsx)(o_,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void s({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let oY={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function oZ({provider:e,onRefresh:t,relogin:n}){let s=n?.onLoginSucceeded,[a,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),m=(0,i.useRef)(null),f=void 0!==n;(0,i.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,i.useEffect)(()=>{("auth"===a.phase||"prompt"===a.phase)&&setTimeout(()=>h.current?.focus(),50)},[a.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(),s?.())},[t,s]),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 n=JSON.parse(e.data);"auth"===n.type?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),on(n.url)):"device_code"===n.type?(l({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),on(n.verificationUri)):"prompt_request"===n.type?l({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?l({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?l({phase:"progress",message:n.message}):"success"===n.type?g():"error"===n.type?(t.close(),l({phase:"error",message:n.message})):"cancelled"===n.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,n,r)=>{l({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})}),i=await r.json().catch(()=>({}));if(!r.ok)return void l({phase:"error",message:i.error??`Server error ${r.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"===a.phase||"progress"===a.phase||"auth"===a.phase||"device_code"===a.phase||"prompt"===a.phase||"select"===a.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:o("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:o(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),n&&(0,r.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,r.jsx)(np,{seed:n.target.seed,size:32,provider:n.target.provider}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:o("relogin.title")}),(0,r.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[n.target.alias,n.target.masked&&(0,r.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:n.target.masked})]}),n.target.reason&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:n.target.reason})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n?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"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("i18n.openingBrowser")}),"select"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(a.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"===a.phase||"prompt"===a.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===a.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.":a.message}),"auth"===a.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:h,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&y(a.token,d)},placeholder:"auth"===a.phase?"Paste the redirect URL or code":a.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,r.jsx)("button",{onClick:()=>y(a.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"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:a.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:a.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:a.verificationUri}),a.expiresInSeconds?` Expires in ${Math.ceil(a.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a.message}),"success"===a.phase&&(n?(0,r.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("relogin.done")}),n.outcome&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===n.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===n.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:o(oY[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:o("i18n.connectedSuccessfully")})),"error"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:a.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:m,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&&!n&&(0,r.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 oX({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)(""),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,R.s)();(0,i.useEffect)(()=>{s(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){l(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(s(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{l(!1)}}},[n,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.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,r.jsx)(oz,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(oF,{value:n,onChange:s,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:a||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:a||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":a?"i18n.saving":"i18n.save")]})]})}),c&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,r.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:m(o?"i18n.removing":"i18n.disconnect")})]})}function oQ({id:e,size:t}){let n=oL[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.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:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}function o0({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:s,onAddCustom:a,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))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+m.length+ +!!f,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,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref: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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{a(),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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(oQ,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.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"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(oQ,{id:e.id,size:28})]},e.id))]})})]})})}function o1({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:s,relogin:a}){let l=P(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)({providers:{}}),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(a?{type:"oauth",providerId:a.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(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),L=(0,i.useCallback)((e,t)=>{c(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),y(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),A=(0,i.useCallback)(e=>{c(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),c(e=>{let t=Object.keys(e.providers??{});return y(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),z=(0,i.useCallback)(e=>{c(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),c(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return y({type:"model",providerName:e,index:n}),t})},[]),W=(0,i.useCallback)((e,t)=>{c(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],s=new Set(i.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),F=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),_=(0,i.useCallback)((e,t)=>{c(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),y({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{m(!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),s?.(),setTimeout(()=>v(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[d,s]),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,r.jsx)(ot,{cwd:e??null,onRolesChanged:s});if("oauth"===b.type){let e=w.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oZ,{provider:e,onRefresh:M,relogin:a?.target.provider===e.id?a:void 0},e.id):null}if("apikey"===b.type){let e=j.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oX,{provider:e,onRefresh:M},e.id):null}if("provider"===b.type){let e=d.providers?.[b.name];return e?(0,r.jsx)(oB,{name:b.name,provider:e,onChange:e=>E(b.name,e),onRename:e=>L(b.name,e),onDelete:()=>A(b.name),onAddModels:e=>W(b.name,e)},b.name):null}let t=d.providers?.[b.providerName],n=t?.models?.[b.index];return n?(0,r.jsx)(oG,{providerName:b.providerName,provider:t,model:n,onChange:e=>F(b.providerName,b.index,e),onDelete:()=>_(b.providerName,b.index)},`${b.providerName}-${b.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},...n?{}:{role:"dialog","aria-modal":!0,"aria-label":o("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,r.jsxs)("div",{style:{width:n?"100%":l?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":l?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.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,r.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,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:o("roles.title")})]}),(0,r.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,r.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,r.jsx)(oQ,{id:e.id,size:16}),(0,r.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,r.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,r.jsx)(oQ,{id:e.id,size:16}),(0,r.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,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):H.map(([e,t])=>{let n=b?.type==="provider"&&b.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>y({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{let i=b?.type==="model"&&b.providerName===e&&b.index===n;return(0,r.jsxs)("div",{onClick:()=>y({type:"model",providerName:e,index:n}),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,r.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,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)("div",{onClick:t=>{t.stopPropagation(),z(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,r.jsxs)("span",{style:{fontSize:11},children:["+ ",o("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:U??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[f&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:f}),(0,r.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,r.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,r.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,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:x?o("i18n.saved"):h?o("i18n.saving"):o("i18n.save")})]})]})]})}),C&&(0,r.jsx)(o0,{oauthProviders:w,apiKeyProviders:j,onSelectOAuth:e=>y({type:"oauth",providerId:e}),onSelectApiKey:e=>y({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>N(!1)})]})}function o2(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function o4(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function o5(e){let t=o4(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function o8(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function o6(e){return e?e.slice(0,8):"unknown"}function o3({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,R.s)();return(0,r.jsx)("button",{onClick:n,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,r.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 o7({skill:e,cwd:t,onToggle:n,toggling:i,saveError:s,updateStatus:a,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=o4(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.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,r.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 n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return o2(e)}(e.filePath)}),(0,r.jsx)(o3,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:s})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.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,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:o6(a?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.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")}),a?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:o6(a.latestVersion)}),(l||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":a?.state==="up-to-date"?"#16a34a":a?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):a?.state==="up-to-date"?p("i18n.upToDate"):a?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):a?.message||p("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.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,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function o9({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,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),m(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);c(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),s()}catch(e){v(String(e))}finally{g(null)}},[s,w,e]),N="global"===w?"~/.claude/skills/":`${o2(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:a("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(l)},placeholder:a("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,r.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?a("i18n.searching"):a("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:a("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"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||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=f===e.package,s=e.package.indexOf("@"),l=s>-1?e.package.slice(0,s):e.package,o=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:o??l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${a("i18n.installed")}`:i?a("i18n.installing"):a("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.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 de({cwd:e,onClose:t,embedded:n=!1}){let s=P(),{t:a}=(0,R.s)(),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,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),[A,z]=(0,i.useState)({}),W=(0,i.useCallback)(async()=>{c(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(o(r),L(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&z(t=>({...t,[o5(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{c(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),$(null),W()},[e]);let F=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(o8).filter(e=>!!e);if(0!==n.length){$(null),S(e=>new Set([...e,...n])),t||N(!0);try{let n=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})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.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 n)t.delete(e);return t}),t||N(!1)}}},[e,l]),_=(0,i.useCallback)(async t=>{if(!t.install)return;let n=o8(t);T(n),$(null);try{let r=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 r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await W();let s=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,W]),D=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);o(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&z(t=>({...t,[o5(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),H=l.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":s?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":s?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o2(e)})]}),(0,r.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,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:a("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:s?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:s?"100%":210,maxHeight:s?"40vh":void 0,borderRight:s?"none":"1px solid var(--border)",borderBottom:s?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:a("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===o4(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===o4(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===o4(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===o4(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===o4(e)}]){let r=l.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(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,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:s?"var(--border)":"var(--accent)",boxShadow:s?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:s?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=o8(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),s=n.filter(e=>e.disableModelInvocation),l=A[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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),s.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>z(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,r.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),a("i18n.dormant")," (",s.length,")"]}),l&&s.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),a("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(o9,{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:()=>{W()}}):d?null:H?(0,r.jsx)(o7,{skill:H,cwd:e,onToggle:D,toggling:f.has(H.filePath),saveError:x,updateStatus:o8(H)?w[o8(H)]:void 0,checkingUpdate:!!o8(H)&&j.has(o8(H)),updating:I===o8(H),updateError:M,onCheckUpdate:()=>void F(H),onUpdate:()=>void _(H)},H.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,r.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?a("i18n.checking"):a("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.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?a("i18n.update"):a("i18n.updates")]})]}),(0,r.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:a("i18n.close")})]})]})})}let dt="global";function dn(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function dr(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function di(e){return`${e.scope}\0${e.source}`}function ds(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function da(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function dl(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function dd({pkg:e}){let{t}=(0,R.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function dc({scope:e}){return(0,r.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 du(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 dp({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,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,r.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 dh({installDir:e,source:t,busy:n,actionError:s,onSourceChange:a,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("i18n.addPlugin")}),(0,r.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,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:d,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=dr(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(dr(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()&&!n&&l()}})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,r.jsx)("button",{type:"button",onClick:l,disabled:n||!t.trim(),style:{...du(n||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:o(n?"i18n.installing":"i18n.install")})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>a(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))})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:s})]})}function dm({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:s,sessionId:a,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=di(e),u=n?.endsWith(c)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(dp,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(dc,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:d("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>l("update",e),disabled:u||p,style:du(u||p),children:d(n===`update:${c}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:o,disabled:!a||p||u,style:du(!a||p||u),title:d(a?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:du(u||p,!0),children:d(n===`remove:${c}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.status")}),(0,r.jsx)("div",{style:{color:dl(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:da(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:ds(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.installedPath")}),(0,r.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,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("i18n.resolvedResources")}),(0,r.jsx)(dd,{pkg:e})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function df({cwd:e,sessionId:t,onClose:n,onReloaded:s,embedded:a=!1}){let l=P(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[f,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=>di(e)===f)??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),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);c(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>di(t)===e)?e:n.packages[0]?di(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let L=(0,i.useCallback)(async(t,n)=>{let r=di(n);k(`${t}:${r}`),S(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);if(c(i),"remove"===t)g(i.packages[0]?di(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]),A=(0,i.useCallback)(async()=>{let t=dr(b).trim();if(!t)return;y(t);let n=`${dt}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:dt,cwd:e})}),l=await a.json();if(!a.ok||l.error)throw Error(l.error??`HTTP ${a.status}`);c(l);let d=(r=l.packages,s=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===dt&&e.source===i)??r.find(e=>e.scope===dt&&e.source===`npm:${s}`)??r.find(e=>e.scope===dt&&e.source.endsWith(i)));g(d?di(d):n),v(!1),y(""),N(o("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,o]),z=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await aL(t,{type:"reload"}),s?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,s,t,o]),W=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:a?"relative":"fixed",inset:a?void 0:0,width:"100%",height:"100%",zIndex:a?void 0:1e3,background:a?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{a||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:a?"100%":l?"calc(100vw - 16px)":860,maxWidth:a?"none":"calc(100vw - 16px)",height:a?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:a?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:a?"none":"1px solid var(--border)",borderRadius:8*!a,display:"flex",flexDirection:"column",boxShadow:a?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:dn(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===I.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):$.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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=di(e),n=!x&&f===t;return(0,r.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:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:dl(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.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,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:da(e,o)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),o("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(dh,{installDir:d?.installDir,source:b,busy:W,actionError:j,onSourceChange:y,onInstall:A}):u?null:T?(0,r.jsx)(dm,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:z},di(T)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,r.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,r.jsx)("span",{children:d?`${d.totals.extensions} ext \xb7 ${d.totals.skills} skills \xb7 ${d.totals.prompts} prompts \xb7 ${d.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:du(u||null!==w),children:o("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:du(!1),children:o("i18n.close")})]})]})})}var dg=n(13004),dx=n.n(dg);function dv(){let[e,t]=(0,i.useState)(null),[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,f]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),l(null),d(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.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!==m)return void l("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),f(""),d(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[m,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,r.jsx)("div",{className:dx().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:dx().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.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,r.jsxs)("div",{className:dx().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),o&&(0,r.jsx)("div",{className:dx().reloadNotice,children:(0,r.jsx)("span",{children:o})})]}),(0,r.jsxs)("div",{className:dx().settingsBody,children:[(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:dx().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,r.jsx)("div",{className:dx().settingDescription,children:"Set a password below before turning this on."}),a&&(0,r.jsx)("div",{className:dx().error,children:a})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("button",{type:"button",className:dx().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,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:dx().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{className:dx().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:dx().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{className:dx().textInput,type:"password",autoComplete:"new-password",value:m,disabled:c||w,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,r.jsxs)("div",{className:dx().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:dx().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:dx().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:dx().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.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,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("a",{className:dx().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:dx().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,r.jsx)("div",{className:dx().settingControl})]})]})]})]})}let db="/api/live/character-voice",dy={ready:"chat.liveVoiceStateReady","not-prepared":"chat.liveVoiceStateNotPrepared",preparing:"chat.liveVoiceStatePreparing","needs-check":"chat.liveVoiceStateNeedsCheck",failed:"chat.liveVoiceStateFailed","missing-asset":"chat.liveVoiceStateMissingAsset"},dw={failed:!0,"needs-check":!0,"missing-asset":!0};async function dk(e){let t=await e.json().catch(()=>({}));if(!e.ok||!t||"object"!=typeof t||!("characters"in t))throw Error(t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message?t.message:`HTTP ${e.status}`);return t}function dj(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=(0,i.useCallback)(async()=>{try{a(await dk(await fetch(db,{cache:"no-store"})))}catch(t){o(t instanceof Error?t.message:e("chat.liveVoiceLoadFailed"))}},[e]);(0,i.useEffect)(()=>{f()},[f]);let g=s?.preparing===!0;(0,i.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>void f(),2e3);return()=>clearTimeout(e)},[g,s,f]);let x=(0,i.useCallback)(async e=>{m(!0),o(null);try{return a(await dk(await fetch(db,e))),!0}catch(e){return o(e instanceof Error?e.message:String(e)),!1}finally{m(!1)}},[]),v=async()=>{let e=d.trim();e&&await x({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})})&&c("")};if(!s)return(0,r.jsx)("div",{className:dx().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"});let b=s.configured,y=l??s.lastError??null;return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:dx().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsxs)("div",{className:dx().settingsBody,children:[(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e("chat.liveVoiceKeyLabel")}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:t,className:dx().settingLabel,style:{display:"block"},children:e("chat.liveVoiceKeyLabel")}),(0,r.jsx)("div",{className:dx().settingDescription,children:e("chat.liveVoiceKeyHelp")}),b&&s.keyHint&&(0,r.jsx)("div",{className:dx().saveState,style:{overflowWrap:"anywhere"},children:e("chat.liveVoiceKeySaved",{hint:s.keyHint})})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{id:t,className:dx().textInput,type:"password",autoComplete:"off",spellCheck:!1,value:d,disabled:h,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&v()},placeholder:"sk_car_…"})})]}),(0,r.jsxs)("div",{className:dx().editorActions,children:[(0,r.jsx)("div",{}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8},children:[b&&(0,r.jsx)("button",{type:"button",className:dx().dangerButton,disabled:h||g,onClick:()=>void x({method:"DELETE"}),children:e("chat.liveVoiceKeyRemove")}),(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:h||!d.trim(),onClick:()=>void v(),children:e("chat.liveVoiceKeySave")})]})]})]}),(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e("chat.liveVoicePrepare")}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",minWidth:0},children:[(0,r.jsx)("input",{id:n,type:"checkbox",checked:u,onChange:e=>p(e.target.checked),style:{marginTop:3,flex:"none"}}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:n,className:dx().settingDescription,style:{display:"block",color:"var(--text)"},children:e("chat.liveVoiceConsent")}),(0,r.jsxs)("div",{className:dx().settingDescription,style:{marginTop:4},children:[e("chat.liveVoicePlanNote")," ",(0,r.jsx)("a",{href:"/audio/live/ACML-1.0.txt",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:e("chat.liveVoiceLicense")})]})]})]}),(0,r.jsx)("div",{className:dx().settingControl,style:{alignItems:"center"},children:(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:h||g||!b||!u,onClick:()=>void x({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prepare:!0,acknowledged:!0})}),"aria-busy":g,children:g?e("chat.liveVoicePreparing"):e("chat.liveVoicePrepare")})})]}),y&&(0,r.jsx)("div",{className:dx().error,role:"alert",style:{overflowWrap:"anywhere"},children:y})]}),(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e("chat.liveVoiceCharacters")}),(0,r.jsx)("ul",{"aria-live":"polite",style:{listStyle:"none",margin:0,padding:0},children:s.characters.map(t=>(0,r.jsxs)("li",{className:dx().settingRow,style:{minHeight:44},title:t.error,children:[(0,r.jsxs)("div",{className:dx().settingLabel,style:{marginBottom:0},children:[t.alias,"provisional"===t.tuning&&(0,r.jsxs)("span",{className:dx().settingDescription,style:{fontWeight:400},children:[" \xb7 ",e("chat.liveVoiceProvisional")]})]}),(0,r.jsx)("div",{className:dx().settingControl,style:{fontSize:12,color:dw[t.state]?"var(--danger)":"ready"===t.state?"var(--text)":"var(--text-muted)"},children:e(dy[t.state])})]},t.id))})]})]})]})}function dS(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return sO({signal:e.signal}).then(e=>{a(e),o(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let f=(0,i.useCallback)(async e=>{p(!0),c(null),m(!1);try{let t=await sB(e);a(t),o(String(t.uploadLimitMb)),m(!0)}catch(e){c(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return s?(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:dx().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:dx().settingsBody,children:(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:dx().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:dx().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{id:t,className:dx().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(s.uploadLimitMb))return;let n=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n<1){m(!1),c(e("chat.attachmentUploadLimitInvalid"));return}f({uploadLimitMb:n})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:dx().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:dx().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:s.orphanGraceDays})})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("button",{type:"button",className:dx().switch,"data-on":s.autoCleanupEnabled,"aria-pressed":s.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!s.autoCleanupEnabled})})})]}),d&&(0,r.jsx)("div",{className:dx().error,role:"alert",style:{overflowWrap:"anywhere"},children:d}),h&&!d&&(0,r.jsx)("div",{className:dx().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:dx().empty,children:d?`${e("chat.attachmentSettingsLoadFailed")}: ${d}`:"…"})}function dC({cwd:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[m,f]=(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,n,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 n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let i=e?`?include=${encodeURIComponent(e)}`:"",a=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),o=await a.json();if(n!==b.current||r.signal.aborted)return;if(!a.ok||!o.projects)throw Error(o.error??`HTTP ${a.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,s(o.projects),l(null),d&&f({cwd:d.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;l(e instanceof Error?e.message:String(e))}finally{y.current===r&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=n?.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},n=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",n),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[c,o,n,S,j]);let C=(0,i.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),d(null),x(e),f(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),i=await r.json();if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);let a=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=a,s(a),"cancel"===n?f({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(n=>({...n,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!n)return(0,r.jsxs)("div",{className:dx().empty,children:[a?t("trust.loadFailed",{error:a}):"…",a&&(0,r.jsx)("button",{type:"button",className:dx().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:dx().contentDescription,children:t("trust.settingsDescription")}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,r.jsx)("button",{type:"button",className:dx().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),a&&(0,r.jsx)("div",{className:dx().error,role:"alert",children:t("trust.loadFailed",{error:a})})]})]}),(0,r.jsx)("div",{className:dx().settingsBody,children:(0,r.jsxs)("section",{className:dx().group,children:[0===n.length&&(0,r.jsx)("div",{className:dx().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=c===e.cwd,s=o?.cwd===e.cwd?o:null,a=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,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:dx().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:dx().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,r.jsx)("span",{children:(n=e.cwd).split(/[\\/]/).filter(Boolean).pop()??n}),(0,r.jsx)("span",{className:dx().settingDescription,style:{fontWeight:600},children:a})]}),(0,r.jsx)("code",{className:dx().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:dx().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,r.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,r.jsx)("div",{className:dx().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:dx().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),s&&(0,r.jsx)("div",{className:dx().settingDescription,style:{color:"var(--text)"},children:"revoke"===s.action?t("trust.confirmRevoke"):s.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:dx().saveState,children:m.text})]}),l&&(0,r.jsx)("div",{className:dx().error,role:"alert",children:l})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:dx().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:s?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:dx().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{d(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===s.action?dx().dangerButton:dx().primaryButton,disabled:N,onClick:()=>void C(e.cwd,s.action),children:"revoke"===s.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:dx().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,r.jsx)("button",{type:"button",className:dx().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,r.jsx)("button",{type:"button",className:dx().dangerButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let dN=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이다"}}}'),dI=[{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"}],dT={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),attachments:(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.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,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.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,r.jsx)(r.Fragment,{children:(0,r.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,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function dM({kind:e}){return(0,r.jsx)("svg",{className:dx().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:dT[e]??dT.tools})}function d$({field:e,busy:t,onSave:n}){let[s,a]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{a("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:dx().textInput,type:"secret"===e.type?"password":"text",value:s,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>a(e.target.value),onBlur:()=>{s!==l&&("secret"!==e.type||s.length>0)&&n(s)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function dR({field:e,busy:t,onSave:n}){let s=JSON.stringify(e.value??{},null,2),[a,l]=(0,i.useState)(s),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(s),d(null)},[s]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:dx().jsonEditor,style:{minHeight:92},value:a,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(a!==s)try{n(JSON.parse(a)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,r.jsx)("div",{className:dx().error,children:o})]})}function dE({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],s=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let s=[...i];[s[e],s[r]]=[s[r],s[e]],n(s)};return(0,r.jsx)("div",{className:dx().multiSelect,children:e.options?.map(a=>{let l=i.indexOf(a.value);return(0,r.jsxs)("span",{className:dx().choice,"data-selected":l>=0,title:a.description,children:[(0,r.jsx)("button",{type:"button",className:dx().choiceToggle,disabled:t,onClick:()=>{let e;return e=a.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:a.label}),e.ordered&&l>=0&&(0,r.jsxs)("span",{className:dx().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>s(l,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>s(l,1),children:"→"})]})]},a.value)})})}function dL({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:dx().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(l3,{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=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(dE,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(dR,{field:e,busy:t,onSave:n}):(0,r.jsx)(d$,{field:e,busy:t,onSave:n})}function dA({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:e.label}),(0,r.jsx)("div",{className:dx().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:dx().error,children:n})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)(dL,{field:e,busy:t,onSave:i})})]})}function dz({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:dx().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:dx().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:dx().themePreviewPanel,children:[(0,r.jsx)("div",{className:dx().themePreviewLine}),(0,r.jsx)("div",{className:dx().themePreviewLine})]})]})}let dW='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',dP=new Set(["hideThinkingBlock"]);function dF({cwd:e,sessionId:t,initialSection:n="models",onClose:s,onModelsChanged:a,onReloaded:l}){let[o,d]=(0,i.useState)(n),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,f]=(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}=tD(),{locale:T,t:M}=(0,R.s)(),$=(0,i.useRef)(null),E=e=>"ko"===T?dN.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(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(dW)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(dW)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let A=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await t_(e),await L()):dP.has(t.path)?await t4(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,L]),z=(0,i.useMemo)(()=>new Map(c?.fields.map(e=>[e.path,e.value])??[]),[c?.fields]),W=(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,z))??[],[c?.fields,z]),P=o.startsWith("settings:")?o.slice(9):null,F=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?W.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):P?W.filter(e=>e.tab===P&&("appearance"!==P||"Theme"!==e.group)):[]},[P,g,W]),_=(0,i.useCallback)(()=>{a?.(),s()},[s,a]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await aL(t,{type:"reload"}),j(!1),l?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),H=c?.tabs.find(e=>e.id===P),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 n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:t}),n.map(e=>(0,r.jsx)(dA,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void A(e,t)},e.path))]},t):null}),U=()=>p?(0,r.jsx)("div",{className:dx().empty,children:E("Loading omp settings…")}):m||!c?(0,r.jsx)("div",{className:dx().empty,children:m??E("Settings unavailable")}):(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:O}),(0,r.jsx)("p",{className:dx().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,r.jsxs)("div",{className:dx().reloadNotice,children:[(0,r.jsx)("span",{children:E("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:E(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:dx().settingsBody,children:F.length?B(F,H?.groups??[]):(0,r.jsx)("div",{className:dx().empty,children:E("No settings match this search.")})})]});return(0,r.jsx)("div",{className:dx().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&_()},children:(0,r.jsxs)("div",{ref:$,tabIndex:-1,className:dx().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,r.jsxs)("aside",{className:dx().sidebar,children:[(0,r.jsxs)("div",{className:dx().brand,children:[(0,r.jsx)("div",{className:dx().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:dx().title,children:E("Settings")}),(0,r.jsx)("code",{className:dx().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,r.jsxs)("div",{className:dx().searchWrap,children:[(0,r.jsxs)("svg",{className:dx().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:dx().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:dx().nav,children:[(0,r.jsx)("div",{className:dx().navLabel,children:E("Configuration")}),dI.map(t=>{let n=t.labelKey?M(t.labelKey):E(t.label);return(0,r.jsxs)("button",{type:"button",className:dx().navButton,"data-active":!g&&o===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${E("requires a project")}`:n,onClick:()=>{x(""),d(t.id)},children:[(0,r.jsx)(dM,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:dx().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:dx().navButton,"data-active":!g&&P===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,r.jsx)(dM,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:dx().closeRail,children:(0,r.jsxs)("button",{type:"button",className:dx().closeButton,onClick:_,children:[(0,r.jsx)("span",{children:E("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:dx().content,children:g.trim()?U():"models"===o?(0,r.jsx)(o1,{cwd:e,embedded:!0,onClose:_,onModelsChanged:a}):"themes"===o?c?(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:E("Themes")}),(0,r.jsxs)("p",{className:dx().contentDescription,children:[E("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),E(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:dx().settingsBody,children:[(0,r.jsx)("div",{className:dx().themeGrid,children:["dark","light"].map(e=>{let t=c.fields.find(t=>t.path===`theme.${e}`),n=c.theme.palettes[e];return(0,r.jsxs)("div",{className:dx().themeCard,children:[(0,r.jsx)(dz,{mode:e,palette:n}),(0,r.jsxs)("div",{className:dx().themeCardBody,children:[(0,r.jsxs)("div",{className:dx().themeCardHeader,children:[(0,r.jsxs)("span",{className:dx().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,r.jsx)("span",{className:dx().themeActive,children:E("Active on web")})]}),(0,r.jsx)(l3,{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 A(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:dx().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,r.jsx)("div",{className:dx().empty,children:p?E("Loading themes…"):m??E("Themes unavailable")}):"skills"===o&&e?(0,r.jsx)(de,{cwd:e,embedded:!0,onClose:_}):"plugins"===o&&e?(0,r.jsx)(df,{cwd:e,sessionId:t,embedded:!0,onClose:_,onReloaded:l}):"mcp"===o?(0,r.jsx)(d_,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,r.jsx)(dv,{}):"trust"===o?(0,r.jsx)(dC,{cwd:e}):"live-voice"===o?(0,r.jsx)(dj,{}):"attachments"===o?(0,r.jsx)(dS,{}):U()})]})})}function d_({cwd:e,sessionId:t,onReloaded:n}){let[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[f,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)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);a(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=s?"user"===l?s.user:s.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{a(t=>{if(!t)return t;let n={..."user"===l?t.user:t.project,servers:e};return"user"===l?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(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}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,servers:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${l}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",s=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:r.name,enabled:!r.enabled})}),a=await s.json();if(!s.ok||a.error)throw Error(a.error??`HTTP ${s.status}`);await w(),t&&(await aL(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:dx().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,r.jsx)("div",{className:dx().settingsBody,children:s?(0,r.jsxs)("div",{className:dx().mcpLayout,children:[(0,r.jsxs)("aside",{className:dx().mcpList,children:[(0,r.jsxs)("div",{className:dx().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:dx().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",s.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:dx().scopeButton,"data-active":"project"===l,disabled:!s.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",s.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:dx().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:dx().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${l}:${e.name}`;return(0,r.jsxs)("div",{className:dx().serverRow,"data-active":d===t,children:[(0,r.jsxs)("button",{type:"button",className:dx().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,r.jsx)("span",{className:dx().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:dx().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:dx().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:dx().serverToggle,"data-on":e.enabled,disabled:b===n,"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===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:dx().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:dx().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 n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),c(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:dx().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:dx().editorHeader,children:[(0,r.jsx)("input",{className:dx().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:dx().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,r.jsxs)("div",{className:dx().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:dx().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:dx().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:dx().error,children:f}),(0,r.jsx)("div",{className:dx().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:dx().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:dx().empty,children:f??"Loading MCP configuration…"})})]})}let dD="cuelo-notification-prompt-dismissed";function dH({variant:e,locale:t,permission:n,dismissed:i,request:s,dismiss:a}){let l="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||i?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":l?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:l?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,children:l?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,r.jsx)(d.k.Item,{disabled:"denied"===n,onClick:"default"===n?s:void 0,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:"default"===n?l?"알림 켜기":"Enable notifications":l?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(d.k.ItemDescription,{children:l?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function dO({cwd:e,busy:t,scheduled:n,error:s,onCancel:a,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:5,cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.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||a()},children:(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:d(n?"trust.scheduledTitle":"trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:d(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.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}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:s})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.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,r.jsx)("button",{ref:c,type:"button",onClick:a,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d(n?"trust.close":"trust.cancel")}),!n&&(0,r.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 dB=n(55681),dU=n(54265);let dq={kind:"loading"};function dK(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,nU.Ch)(e.status)?"var(--accent)":"var(--success)"}function dV(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let dJ={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function dG(e){return e.lastUpdate||e.progress?.durationMs||0}function dY(){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 dZ({sessionId:e,sessionCwd:t,record:n,client:s,visible:a,onBack:l}){let o=(0,i.useMemo)(()=>[{key:n.key,liveId:n.live?.id,status:n.live?.status,archiveName:n.archive?.name}],[n.key,n.live?.id,n.live?.status,n.archive?.name]),d=(0,i.useRef)(null),c=(0,nU._Z)(o,{sessionId:e,client:s,enabled:a}).get(n.key)?.state??dq;(0,i.useEffect)(()=>{if(!a||"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,a]);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=n.live?.id||n.archive?.name||"Subagent";return(0,r.jsxs)("div",{role:"dialog","aria-label":`${h} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:l,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:dY(),children:(0,r.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,r.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:h}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:dV(n)})]}),n.live&&(0,r.jsx)("span",{style:{color:dK(n.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:n.live.status})]}),(0,r.jsxs)("div",{ref:d,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===c.kind&&(0,r.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,n)=>{if(!("message"in e))return[];let i=c.entries[n-1];return[(0,r.jsx)(rE,{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,r.jsxs)(r.Fragment,{children:[c.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:c.note}),c.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),c.entries.map((e,t)=>(0,r.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,r.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,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[c.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:c.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===c.kind&&(0,r.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,r.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 dX({record:e,view:t,onSelect:n}){let{st:s}=nu(),a=(0,i.useId)(),l=e.live,o=e.archive,d=(0,nS.$V)(e),c=!!(l&&(0,nU.Ch)(l.status)),u=c?d.stage:null,p=c&&t?t:null,h=p?.phase?s("phase.current",{phase:s(`phase.${p.phase}`)}):"",m=p?.todo?nY(s,p.todo):"",f=l?.id||o?.name||"Subagent",g=dV(e),x=(0,nS.wX)(e),v=(0,nS.A7)(e),b=v.modelShort??"모델 미확인",y=v.effort??"추론 미확인",w="known"===x.kind?x.label:"역할 미확인";return(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:n,"data-identity":e.identity,title:`${f}
19
+ ${n}`:e:n,images:a,documents:l}}function sI(e,t,n){if(e===t)return n?sw(n):sj(t);let r=sj(e),i=n&&!sk(n)?sw(n):r??(n?sw(n):null),s=sj(t),a=sa.get(e);if(sa.delete(e),a&&!sa.has(t)&&sa.set(t,a),sC(e),!i)return s;let l=s?sN(s.value,s.images,i.value,i.images,s.documents,i.documents):i;return sS(t,l),sw(l)}function sT(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function sM(e){sb();let t=sa.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 n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),sa.set(e,t)),t}function s$(e){let t=sT(sr.get(e)?.documents),n=t.length?sM(e):sa.get(e);for(let[e,n]of sp){for(let e of t)n.delete(e);0===n.size&&sp.delete(e)}let r=`${n??""}|${t.join(",")}`;sm.get(e)!==r&&(0!==t.length||n?sm.set(e,r):sm.delete(e),sP())}async function sR(e){let t=sM(e);su.set(t,(su.get(t)??0)+1),await sf.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(su.get(t)??1)-1;if(r>0?su.set(t,r):su.delete(t),e){let n=sp.get(t)??new Set;n.add(e),sp.set(t,n)}sl.set(t,so),sP()}}}function sE(e,t){let n=sh.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&sh.delete(e),[...n].sort()}async function sL(){if(!sg)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of sa)t(n,sT(sr.get(e)?.documents));for(let{draftId:e,ids:n}of sd.values())t(e,n);for(let[e,n]of sp)t(e,n);for(let e of sl.keys())t(e,[]);for(let e of sh.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(su.has(e))return!1;let n=sl.get(e);return sE(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=su.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=sE(r,i),s=sg(r,i,e).then(()=>{0===i.length?sl.delete(r):sl.set(r,i.join(","));let t=sh.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&sh.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});sf.set(r,s),await s,sf.get(r)===s&&sf.delete(r)}n?function(){if(sW)return;sW=!0;let e=setTimeout(()=>{sW=!1,sP()},sz);"object"==typeof e&&"unref"in e&&e.unref(),sz=Math.min(2*sz,6e4)}():sz=sA}let sA=5e3,sz=5e3,sW=!1;function sP(){if(sg){if(sx){sv=!0;return}sx=Promise.resolve().then(sL).finally(()=>{sx=null,sv&&(sv=!1,sP())})}}let sF=Math.floor(Number.MAX_SAFE_INTEGER/1048576),s_=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function sD(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=sF}async function sH(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!sD(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:sD((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:s_.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:s_.autoCleanupEnabled,orphanGraceDays:7}}async function sO(e={}){return sH(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function sB(e){return sH(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function sU(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function sq(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function sK(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}let sV="omp-web:model-picks";function sJ(){try{let e=JSON.parse(window.localStorage.getItem(sV)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function sG(e,t,n,r,i={}){let s=i.gap??8,a=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,n-2*a)),d=Math.max(0,e-s-a),c=Math.max(0,n-t-s-a),u="above"===l?d:c,p="above"===l?c:d,h=u>=r||u>=p;return{side:h?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(r,h?u:p))}}function sY(e,t,n){return Math.min(e*t,n)}function sZ(e,t,n){let{viewportFraction:r,cap:s,gap:a,margin:l,minHeight:o,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:s}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=sG(i.top,i.bottom,n,sY(n,r,s),{gap:a,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,s,a,l,o,d,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.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 sX=n(14755);async function sQ(e,t,n,r,i,s,a){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await a?.()??[],d=[...ar,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(s&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await n?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&r(c.prompt),!0}if(d&&"builtin"!==d.source)return r(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 s0(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let s1=["off","default","full"],s2={off:"none",default:"default",full:"full"},s4=sX.IN.join(" \xb7 "),s5=sX.C1.filter(e=>!sX.IN.includes(e)).join(" \xb7 ");function s8(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let s6=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),s3=0,s7={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function s9(e,t){return s6.compare(e.name||e.modelId,t.name||t.modelId)||s6.compare(e.provider,t.provider)||s6.compare(e.modelId,t.modelId)}let ae=["auto","off","minimal","low","medium","high","xhigh","max"],at=["low","medium","high","xhigh"],an={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},ar=[{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"}],ai=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],as={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},aa={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function al(e,t,n){let r=e.name.toLowerCase(),i=ao(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function ao(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function ad(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function ac(e){return{data:e.data,mimeType:e.mimeType}}function au(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function ap(e){return(e??[]).filter(sn).slice(0,10).map(au)}let ah=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,am="\n\nTranscript of the audio ";function af(e){return rs(e).map(e=>{let t=rp(e),n="audio"===t&&e.attachmentId&&!e.text.includes(am)?ah.exec(e.text):null;return{...e,id:++s3,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function ag({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function ax(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.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 av extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let ab="composer:unkeyed";async function ay(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new av("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function aw(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function ak({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function aj({error:e}){return e?(0,r.jsx)(ak,{tone:"error",title:"Model error",body:e}):null}function aS({warnings:e}){return e&&0!==e.length?(0,r.jsx)(ak,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let aC=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:s,isStreaming:l,model:o,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,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:A=null,fastModeBusy:z=!1,onFastModeToggle:W,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},en){let er,ei,es,ea,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:em}=nu(),ef=_.some(e=>e.removable),eg=P(),[ex,ev]=(0,i.useState)(()=>Z?sj(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(sJ())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,eA]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(null),[eP,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?ap(sj(Z)?.images):[]),[eH,eO]=(0,i.useState)(()=>Z?af(sj(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||s0(e)),eV=eH.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(am))),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,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(!1),[ts,ta]=(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),tm=(0,i.useRef)(null),tf=(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)(en,()=>({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,n,r=tc.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.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"),ro(t)?.message??t),s=ap("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return sn(r)?[r]:[]})),a=af((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ro(n)?.documents??[]));t$.current=i,tR.current=s,tL.current=a,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(aw),s)),eO(a),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tM.current!==e)return void sI(e,t);let n={value:t$.current,images:tR.current.map(ac),documents:tL.current.filter(e=>"ready"===e.status).map(ag)},r=sI(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tM.current=t,i)return;let s=ap(r.images),a=ax(af(r.documents),tL.current),l=r.value;t$.current=l,tR.current=s,tL.current=a,ev(l),eD(e=>(e.forEach(aw),s)),eO(a),e2(null),e7(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tM.current,s=r??i,a=s===i,l=!a&&s?sj(s):null,o=sN(e,t,a?t$.current:l?.value??"",a?tR.current.map(ac):l?.images??[],n,a?tL.current.filter(e=>"ready"===e.status).map(ag):l?.documents??[]);if(s&&sS(s,o),!a)return;let d=t?.length?[...ap(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=ax(af(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 n=Math.max(0,10-e.length),r=ap(t).slice(0,n),i=r.length>0?[...r,...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 n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),s=t.value.slice(r),a=i.length>0&&!i.endsWith(" ")?" ":"",l=i+a+e+s;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let r=n+a.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tY(e)}}));let tA=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tR.current.length-tE.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eU(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:rd(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.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,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eD(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(aw);let r=[...t,...n];return tR.current=r,r})}finally{tE.current-=i.length}}},[eh]),tz=(0,i.useCallback)(async e=>{for(let t of e){let e=rt(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:rd(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:rd(0x1000000)}));continue}let n={id:++s3,name:t.name,mimeType:n7[e],size:t.size,text:"",status:"extracting"},r=[...tL.current,n];tL.current=r,eO(r);try{let e=await ra(t);if(tL.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new n3("text_too_large","Total extracted text exceeds 240000 characters");let r=tL.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tL.current=r,eO(r)}catch(i){let e=tL.current.some(e=>e.id===n.id),r=tL.current.filter(e=>e.id!==n.id);if(tL.current=r,eO(r),!e)continue;i instanceof n3?"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]),tW=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.id===e))return!1;let n=t?tL.current.map(n=>n.id===e?t:n):tL.current.filter(t=>t.id!==e);return tL.current=n,eO(n),!0},[]),tP=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.attachmentId===e))return!1;let n=tL.current.map(n=>n.attachmentId===e?t(n):n);return tL.current=n,eO(n),!0},[]),tF=(0,i.useCallback)((e,t,n)=>{if(!e||e===tM.current)return;let r=sj(e);r?.documents.some(e=>e.attachmentId===t)&&sS(e,{...r,documents:af(r.documents).map(e=>e.attachmentId===t?n(e):e).map(ag)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tH=(0,i.useRef)(new Set),tO=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=rh({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tB=(0,i.useCallback)(e=>e instanceof av&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof av&&"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 n=tM.current,r=tL.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;tD.current.get(e)?.abort();let s=new AbortController;tD.current.set(e,s),tP(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await ay(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:s.signal}));if("string"!=typeof r.transcript)throw new av("Invalid transcription result",null,null,null);let i=r.transcript;tP(e,e=>tO(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(n,e,e=>tO(e,i,[])??e)}catch(n){if(s.signal.aborted)return void tP(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof av&&"confirmation_required"===n.code)return void tq.current?.(e);let t=tB(n);tP(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{tD.current.get(e)===s&&tD.current.delete(e)}},[eh,tB,tP,tF,tO]),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(async e=>{let t;tD.current.get(e)?.abort();let n=new AbortController;tD.current.set(e,n),tP(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 av("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await ay(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tP(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tB(t);tP(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{tD.current.get(e)===n&&tD.current.delete(e)}t.requiresConfirmation?tP(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tU(e,!1)},[tU,tB,tP]);tq.current=tK;let tV=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tP(e,e=>({...e,transcription:{state:"skipped"}}))},[tP]),tJ=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++s3,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},s=[...tL.current,i];tL.current=s,eO(s);let a=(e,t)=>{let n=tL.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?ri("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?ri("utf-16be",t.subarray(2)):t.includes(0)?null:ri("utf-8",t)??ri("euc-kr",t)},()=>null);if(null!==e&&a(e.length,r.size)){tW(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await sO().catch(()=>s_)).uploadLimitMb),r.size>n){tW(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:r.name,limit:rd(n)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tW(i.id,l))continue;let o=tM.current??ab,d=await sR(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tH.current.has(i.id))continue;let e=await rm(r,{sessionId:Q,draftId:d.draftId,signal:u.signal}),n=tL.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),s=rh({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(s).byteLength;if(!a(s.length,p)){tW(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:rd(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:s,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tW(i.id,h))c=e.id;else if(!tH.current.has(i.id)&&o!==tM.current){let t=sj(o)??{value:"",images:[],documents:[]};sS(o,{...t,documents:[...t.documents,ag(h)]}),c=e.id}}catch(e){if(u.signal.aborted)continue;tW(i.id,null)&&eU(eh("chat.attachUploadFailed",{name:r.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)}},[tW,tK,Q,eh]),tY=(0,i.useCallback)(async e=>{eU(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let s of e)s.type.startsWith("image/")?t.push(s):null!==rt(s)?n.push(s):rr(s)?r.push(s):i.push(s);return{images:t,documents:n,audio:r,files:i}}(e),s=n.filter(e=>e.size>8388608);await Promise.all([tA(t),tz(n.filter(e=>e.size<=8388608)),tJ(r,"audio"),tJ([...i,...s],"file")])},[tz,tJ,tA]),tZ=(0,i.useCallback)(e=>{eD(t=>{let n=[...t],[r]=n.splice(e,1);return r&&aw(r),tR.current=n,n})},[]),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 n=t.attachmentId;for(let[e,t]of sp)t.delete(n)&&(0===t.size&&sp.delete(e),sP())}let r=tL.current.filter(t=>t.id!==e);tL.current=r,eO(r)},[]),tQ=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(aw),[]))},[]),t0=(0,i.useCallback)(()=>{tL.current=[],eO([])},[]),t1=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&sC(Z),tM.current&&tM.current!==Z&&sC(tM.current),tQ(),t0(),eU(null),tc.current&&(tc.current.style.height="auto")},[t0,tQ,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&sS(Z,{value:ex,images:e_.map(ac),documents:eq.map(ag)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&sS(e,{value:t$.current,images:tR.current.map(ac),documents:tL.current.filter(e=>"ready"===e.status).map(ag)});let t=Z?sj(Z):null;tM.current=Z;let n=t?.value??"",r=ap(t?.images),i=af(t?.documents);t$.current=n,tR.current=r,tL.current=i,ev(n),e2(null),e7(!1),eD(e=>(e.forEach(aw),r)),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(aw)},[]);let t2=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=sT(t);if(0===n.length)return()=>{};let r=++sc;return sd.set(r,{draftId:sM(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=sd.get(r);if(t){if(sd.delete(r),"accepted"===e){let e=sh.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);sh.set(t.draftId,e)}sP()}}}(tM.current??ab,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t4=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eJ.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!e_.length&&!eq.length||l||eK)return;G?.();let i=e_.length?e_:void 0,s=eq.length?eq:void 0;if(r.startsWith("/")){await sQ(r,B,K,t=>t2(s,()=>e(t,i,s)),eU,!!(i||s),q)&&t1();return}t1(),t2(s,()=>e(r,i,s))},[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,t6=(()=>{if(null===t5)return[];let e=[...l?[]:ar,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=ao(e,eh).toLowerCase();return t.includes(t5)||n.includes(t5)}).sort((e,t)=>{let n=al(e,t5,eh)-al(t,t5,eh);return 0!==n?n:aa[e.source]-aa[t.source]||s6.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t3,groups:t7}=(er=0,{commands:(ei=ai.map(e=>{let t=t6.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!ad(e,td)),...t.filter(e=>ad(e,td))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),t9=1===t6.length?eh(t5?"chat.match":"chat.command"):eh(t5?"chat.matches":"chat.commands",{count:t6.length}),ne=!!ex.trim(),nt=!eK&&(ne||e_.length>0||eq.length>0),nn=(0,i.useCallback)((e,t)=>{if(!X)return void e2(null);let n=t??e.length;e2(sU(e.slice(0,n)))},[X]),nr=e1?.query??null,ni=i.useMemo(()=>null!==nr&&tt&&tt.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:sK(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:sK(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||sq(e.entry.path)-sq(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tt.entries,nr):[],[nr,tt,X]),ns=!!(nr&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!ns||!X||!nr)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(nr)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ta({cwd:X,query:nr,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ns,nr,X]);let na=ns&&null!==ts&&ts.cwd===X&&ts.query===nr,nl=na?ts.matches:ni,no=null===e1?null:`${e1.start}:${+!!e1.quoted}:${e1.query}`;(0,i.useEffect)(()=>{if(null===no){e5(!1),e6(0);return}e5(!0),e6(0)},[no]);let nd=null!==e1,nc=sZ(tb,e3,{viewportFraction:.44,cap:360}),np=sZ(tb,eZ,{viewportFraction:.56,cap:460}),nh=sZ(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!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=>{tn({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>sq(e.path)-sq(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tI.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tI.current=null}).finally(()=>{tT.current=null,ti(!1)}))},[nd,X]);let nm=(0,i.useCallback)(e=>{if(!e1)return;let t=tc.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e1.start),i=ex.slice(n);e1.quoted&&i.startsWith('"')&&(i=i.slice(1));let s=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,e1.quoted),a=r+s.text+i,l=r.length+s.cursorOffset;ev(a),e2(sU(a.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>=nl.length&&e6(Math.max(0,nl.length-1))},[nl.length,e8]),(0,i.useEffect)(()=>{tC.current.length=nl.length},[nl.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 nf=(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`)})},[]),ng=(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`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eJ.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,a=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!a)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await sQ(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(a.documents,()=>Y(e,l,a.images,a.documents))},eU,!!(a.images?.length||a.documents?.length),q)&&t1();return}t1(),"steer"===e&&n?t2(a.documents,()=>n(a.message,a.images,a.documents)):"followup"===e&&s&&t2(a.documents,()=>s(a.message,a.images,a.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,n,s,t1,G,t2]),nv=(0,i.useCallback)(e=>{let t=t3.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 n=tS.current[eQ];if(!n)return"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eQ)continue;let t=tS.current[n];if(!t)continue;let r=t.getBoundingClientRect(),o=r.top+r.height/2-s;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(a=n,l=d)}return a>=0?a:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t3.length,eQ]),ny=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tk.current<100,a=tw.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(a||i)){i&&e.preventDefault();return}if(e3&&!a){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(),nf(D[e9]);return}}if(eZ&&null!==t5){if("ArrowDown"===e.key){e.preventDefault(),e0(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(nv("left"));return}if("Escape"===e.key){e.preventDefault(),eX(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t3[eQ]){e.preventDefault(),ng(t3[eQ]);return}}if(e4&&null!==e1&&!a){if("ArrowDown"===e.key){e.preventDefault(),e6(e=>Math.min(Math.max(0,nl.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)&&nl[e8]){e.preventDefault(),nm(nl[e8]);return}}if("ArrowUp"===e.key&&!a&&!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&&!a&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(n||s)?nx(n?"steer":"followup"):t4())},[l,n,s,t,eZ,t5,t3,eQ,ng,nx,t4,nv,e4,e1,nl,e8,nm,e3,D,e9,nf,ex]),nw=(0,i.useCallback)(()=>{let e=tc.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nj=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tY(t))},[tY]);(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 n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;to({cwd:X,values:n})}).catch(()=>{e||to({cwd:X,values:{}})}),()=>{e=!0}},[eZ,X]),(0,i.useEffect)(()=>{eQ>=t3.length&&e0(Math.max(0,t3.length-1))},[t3.length,eQ]),(0,i.useEffect)(()=>{tS.current.length=t3.length},[t3.length]),(0,i.useEffect)(()=>{eZ&&tS.current[eQ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eQ,eZ]);let nS=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(s9):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(s9),nC=g??null,nN=t8.bo.find(e=>e.alias===nC)?.provider??null,nI=nN?nS.filter(e=>e.provider===nN):nS,nT=(es=ej.trim().toLocaleLowerCase())?nI.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(es)):nI,nM=nI.length>8,n$=[];for(let e of nT){let t=n$.find(t=>t.provider===e.provider);t?t.options.push(e):n$.push({provider:e.provider,options:[e]})}let nR=nN?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nE=o?nR.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nL=ej.trim()?[]:nI.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??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})),nA=(e,t,n)=>{let i=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ey(!1),eS(""),!i||d){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(sJ(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(sV,JSON.stringify(r))}catch{}eN(r),m?.(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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nz=o?nS.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nW=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nP=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${tG(S.tokensBefore)} -> ${tG(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:tG(nW)})})`:null,nF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},n_="auto"===(ea=I??"auto")?M?`auto ≤ ${nF(M)??M}`:"auto":L?L[ea]??ea:ea,nD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,nH=$&&nD?eh("chat.currentReasoning",{level:nD}):null,nO=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...at.filter(nO).map(e=>({level:"auto",ceiling:e})),...ae.filter(e=>"auto"!==e&&nO(e)).map(e=>({level:e,ceiling:null}))],nU=Object.entries(s2).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)&&tm.current&&!tm.current.contains(e.target)&&eT(!1),tf.current&&!tf.current.contains(e.target)&&eE(!1),tg.current&&!tg.current.contains(e.target)&&eA(!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 nq=(0,r.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,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),nK=f&&t8.bo.length>0?(0,r.jsxs)("div",{ref:th,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.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,r.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:n}=sG(eM.top,eM.bottom,e,sY(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,r.jsx)("div",{ref:tm,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eT(!1),th.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:t8.bo.map(e=>{let t=e.alias===nC;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),f((0,t8.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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:(0,t8.uk)(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:e.alias}),(0,r.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,nV=$?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eW({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(!1),eA(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},title:eh("chat.changeReasoning",{level:n_}),"aria-label":eh("chat.changeReasoning",{level:n_}),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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:n_})]}),eL&&ez&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=sG(ez.top,ez.bottom,e,sY(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ez.top+6}:{top:ez.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ez.left,width:"max-content",minWidth:Math.max(180,ez.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,s="auto"===e&&null===t?null:nF(i),a=t?`auto ≤ ${s??t}`:s??e,l=t?eh("chat.thinkingAutoCapped",{level:s??t}):eh(an[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eA(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[a,null!==s&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,nJ=W?(el=z?eh("chat.fastModeBusy"):null===A?eh("chat.fastModeUnknown"):A.active?eh("chat.fastModeActive"):A.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eo=z||l||b,ed=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:W,disabled:eo,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":z||void 0,title:el,"aria-label":el,style:{flexShrink:0,opacity:l?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:ed?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:ed&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,nG=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nx("steer"),disabled:!nt,title:eK?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nt?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nt?"var(--warning)":"var(--text-dim)",cursor:nt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),s&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!nt,title:eK?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nt?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nt?"var(--accent-hover)":"var(--text-dim)",cursor:nt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nY=void 0!==J?(0,r.jsx)(i1,{soundEnabled:V??!0,onToggle:J}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:ty,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tY(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(aj,{error:p}),(0,r.jsx)(aS,{warnings:h}),_.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:em("delivery.title",{count:_.length})}),H&&ef&&(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(iX,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:O?(e,t)=>O("steer"===e?"steering":"followUp",t):void 0})]}),F&&(0,r.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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:F.attempt,max:F.maxAttempts}),F.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",F.errorMessage]})]}),nP&&(0,r.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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nP]}),j&&(0,r.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,r.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,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eB}),(0,r.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,r.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,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(e_.length>0||eH.length>0)&&(0,r.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,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.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,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tZ(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eH.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||s0(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,r.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"}}):nk(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):s7[e.mimeType]," \xb7 ",rd(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,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.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,r.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,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eV.length>0&&(0,r.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,n,i,s,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"):(n=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),s=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${s}`:`${i}:${s}`),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,r.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,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:o?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),c&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:c}),o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[o.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:o.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(a.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tb,style:{position:"relative",minWidth:0},children:[e3&&D.length>0&&(0,r.jsxs)("div",{ref:tv,style:{position:"absolute",left:0,right:0,...s8(nc.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nc.maxHeight},children:[(0,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nc.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===e9;return(0,r.jsxs)("button",{ref:e=>{tN.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>te(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eZ&&null!==t5&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...s8(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:U?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:t9})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:10},children:U||0!==t6.length?t7.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(as[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===eQ,i=ad(e,td);return(0,r.jsxs)("button",{ref:e=>{tS.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ng(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 ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),ao(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:ao(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e4&&null!==e1&&(ec=tr&&(!tt||tt.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=tt?.truncated&&!na?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...s8(nh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nh.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ec?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nh.maxHeight-34),overflowY:"auto",padding:4},children:ec||0!==nl.length?nl.map((e,t)=>{let n=t===e8,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tC.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>e6(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(nb,{size:14}):nk(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ns&&!na?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.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&&(n||s)?"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,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tc,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),e7(!1),nn(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nn(t.value,t.selectionStart)},onKeyDown:ny,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;nn(t.value,t.selectionStart)},onInput:nw,onPaste:nj,placeholder:l&&(n||s)?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,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nG}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t4,disabled:!nt,"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:nt?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nt?"var(--accent-hover)":"var(--text-dim)",cursor:nt?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eG&&(0,r.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,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.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)&&nq,!eg&&nK,!(eg&&l)&&(nS.length>0||nz||p)&&m&&(0,r.jsxs)("div",{ref:tu,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.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":nS.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nz??(nS.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=sG(ew.top,ew.bottom,e,sY(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},s=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nL.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),nL.map(({option:e,count:t})=>nA(e,"frequent",t))]}),nR.length>0&&!ej.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nL.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.modelRoles")}),nR.map(e=>{let t=nE?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ey(!1),eS(""),v(e.role)},title:e.selector??n,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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{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,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,r.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===n$.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):n$.map((e,t)=>(0,r.jsxs)("div",{children:[n$.length>1&&(0,r.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=>nA(e,"all"))]},e.provider))]})]})})()]}),eg&&l&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nG}),!eg&&nV,!eg&&nJ,!eg&&nH&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nH}),(0,r.jsx)(st,{sessionId:Q})]}),(0,r.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,r.jsx)("button",{type:"button",className:`composer-icon-button${eP?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eP,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eP?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eP,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eP?"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,r.jsxs)(r.Fragment,{children:[l&&nq,nK,nV,nJ]}),!l&&N&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eR?" is-active":""}`,onClick:()=>!l&&eE(e=>!e),disabled:l,title:eh("chat.changeToolPreset")+`: ${nU}`,"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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nU})]}),eR&&(0,r.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:s1.map(e=>{let t=s2[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:s4}):eh("chat.allBuiltInTools",{tools:`${s4} + ${s5}`});return(0,r.jsxs)("button",{onClick:()=>{eE(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&y&&(0,r.jsx)("div",{children:(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nY,eP&&(0,r.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),eA(!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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),l&&(0,r.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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(i9,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nY]})]})]})]})});function aN({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(" "),n=ew(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eN(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function aI({phases:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(!1),[a,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=e6(e);if(0===p)return null;let m=0===c;return(0,r.jsxs)("div",{className:`todo-strip${m?" is-done":""}`,children:[(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":n,onClick:()=>s(e=>!e),children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:m?"✓":"›"}),o&&(0,r.jsx)("span",{className:"todo-strip-phase",children:o.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:m?t("todo.allDone",{count:u}):d?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:m?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),n&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,n)=>{let i=t.tasks.filter(e=>a||"completed"!==e.status);return 0===i.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,r.jsx)(ng,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":a,onClick:()=>l(e=>!e),children:t(a?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function aT(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function aM(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 a$(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}var aR=n(62503);class aE extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function aL(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new aE(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let aA="ompweb-update-client-id",az="ompweb-update-resume-intent-v2",aW="ompweb-update-return-v1",aP="cuelo-restart-return-v1",aF="ompweb-update-failure-return-v1",a_="ompweb:update-wake";function aD(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function aH(){let e=sessionStorage.getItem(aA);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(aA,t),t}function aO(){sessionStorage.removeItem(az)}function aB(){let e=sessionStorage.getItem(aW);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 aU(e){let t=aB();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(aW,JSON.stringify(n))}catch{}return n}async function aq(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:aH(),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 aK(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 n=await t.json().catch(()=>null);!function(e){let t=aB();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(aW,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),aO();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(a_,{detail:{sessionId:e.sessionId}}))}async function aV(e){let t=function(e){let t=sessionStorage.getItem(aF);if(!t)return null;sessionStorage.removeItem(aF);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(aO(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(a_,{detail:{sessionId:e.sessionId}})),"failed"):(await aK(e),"resumed")}function aJ(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.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}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function aG(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 aY(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function aZ(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function aX(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function aQ(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function a0(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function a1(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!eK(r??void 0))return{message:e[n],entryId:r}}return null}let a2=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class a4 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 a5(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function a8(e){return new Promise(t=>setTimeout(t,e))}function a6(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function a3(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:a6(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:a6(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=a6(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function a7(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 a9(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(a7).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function le(e){return"user"===e.role?`user:${a9(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 lt(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 lr(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let li=!1,ls={width:0,height:0},la=new Set,ll=null;function lo(){let e=window.visualViewport,t=lr();ls.width!==window.innerWidth?ls={width:window.innerWidth,height:window.innerHeight}:t||(ls.height=Math.max(ls.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:ls.height});if(n!==li)for(let e of(li=n,la))e()}function ld(e){if(la.add(e),!ll){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,lo()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),lo(),ll=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{la.delete(e),0===la.size&&ll&&(ll(),ll=null)}}function lc(){return(0,i.useSyncExternalStore)(ld,()=>li,()=>!1)}let lu={count:50,end:null};function lp(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),s=r-i;return{startIndex:s,endIndex:r,hasMore:s>0,hasLater:r<n}}function lh(e,t,n){let{startIndex:r,endIndex:i}=lp(e,n);if(t>=r&&t<i)return n;let s=Math.max(0,t-10),a=Math.max(t+1,s+50);return a>=e?{count:e-s,end:null}:{count:a-s,end:a}}function lm({sticker:e,text:t,tag:n,followRef:s}){let a=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!s||s.current)&&a.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:a,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:ix[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(ip(),{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 lf(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"),n=(ro(t)?.message??t).trim();return n.length>0?n:null}function lg(e){return`omp-cues:${e}`}function lx(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(lg(e),JSON.stringify(n.slice(-200)))}catch{}}let lv=[];function lb(e){return`omp-web:interrupted-dismissed:${e}`}let ly=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:s,messageCwd:a,onOpenFile:l,sessionBusy:o,isNew:d,isStreaming:c,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,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:n,modelNames:s,cwd:a,sessionId:f})},[N,x,e,t,n,s,a,f]);let M=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let s=new Map,a=new Map;for(let e of t){let t=a.get(e.anchorIdx);for(let l of(t||(t=new Set,a.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let a=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=eY(i.action);if(!0===eG[e]){let t={kind:"skill",action:e,name:eY(i.name)};n(JSON.stringify(t),t)}continue}let s=eY(i.memory),a=i.skill,l=a?{action:eY(a.action),name:eY(a.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:s,skill:l}),{kind:"lesson",memory:s.length>160?`${s.slice(0,160)}…`:s,...l?{skill:l}:{}})}}(l.blocks??e.content??[],r,(e,t)=>{if(o.has(e))return;o.add(e);let n=s.get(a);n?n.push(t):s.set(a,[t])})}}return s}(g,x,e,n)){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(r,{role:"custom",customType:eB,content:[C("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,C]),$=(0,i.useMemo)(()=>{let t=null;if(o)for(let n of g)"message"===n.kind&&e[n.idx]?.role==="user"&&(t=n.idx);let r=new Map;for(let[i,s]of function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx),s=new Map;for(let[a,l]of(e.forEach((e,t)=>{"answer"===e.kind&&s.set(e.anchorIdx,t)}),s)){if(a===n)continue;let e=i.find(e=>e>a);r.set(l,{from:a+1,to:e??t.length})}return r}(g,e,t))r.set(i,function(e,t,n){let r=[],i=[];for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){i.push(n);continue}if("bash"!==n.toolName)continue;let e="string"==typeof n.input.command?n.input.command.trim():"";if(!e||!r9.test(e))continue;let s=t.get(n.toolCallId),a=s?function(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}(s):null,l=null===a?s?.isError?"failed":"unobserved":0===a?"passed":"failed";r.push({toolCallId:n.toolCallId,command:e,state:l,exitCode:a})}return{checks:r,dispatchCalls:i,files:e4(e,t,n)}}(function(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}(e,s.from,s.to),n,a));return r},[g,e,n,a,o]),R=y>0,E=w<g.length,L=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&eK(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 n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(rE,{message:x,toolResults:n,modelNames:s,cwd:a,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:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${y}-view-${i}`)},A=(t,n)=>{let i=g[t],s="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":s?"":void 0,className:S===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[R&&(0,r.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((s,o)=>{let d=y+o,c=b?.position===d?(0,r.jsx)(n1,{calls:b.calls}):null,u="message"===s.kind?s.anchorIdx??s.idx:s.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=s.idx&&r<m}).map(e=>(0,r.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,r.jsx)(rE,{message:k,cwd:a,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,r.jsx)(iR,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:a,onOpenFile:l}):null;if("message"===s.kind)return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(s.idx)),j,S,x]},`message-${s.idx}`);let C=e4(s.precedingBlocks,n,a);return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(s.idx,{keyPrefix:`answer-${s.runIndex}`,messageOverride:eL(e[s.idx],s.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${s.idx}-${s.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,r.jsx)(n1,{calls:b.calls}),E&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadLater",{count:g.length-w})})]})});function lw({session:e,newSessionCwd:t,initialSessionData:s,transitioning:a=!1,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,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:A,jumpRequest:z=null,onJumpHandled:W}){var _,D;let H,O,B,{t:U}=(0,R.s)(),q=lc(),K=P(),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),en=(0,i.useRef)([]),er=(0,i.useRef)([]),ei=(0,i.useRef)(null),es=(0,i.useRef)(0),ea=(0,i.useRef)(-1),el=(0,i.useRef)(-1),eo=(0,i.useCallback)(()=>{let e=ei.current?.current;return e?{sessionId:e,turn:es.current}:null},[]),ed=(0,i.useCallback)(e=>ei.current?.current===e.sessionId&&es.current===e.turn,[]),ec=(0,i.useCallback)((e,t,n,r)=>{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:n.sessionId},s="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};Q(e=>{let t=[...e,s];return null!==s.anchorEntryId&&lx(n.sessionId,t),t})},[]),eu=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ed(n)&&("working"!==t||el.current!==n.turn);i()&&G.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&ec(e,t,n,r)}).catch(()=>{})},[ed,ec]),ep=(0,i.useCallback)(async(e,t,n)=>{let r=(await nl(e,t,n))?.alias??null;return r&&Z.current?.(r),r},[]),eh=(0,i.useCallback)((e,t,n,r)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=iC(e[n]),s=0;for(let t=r;t<=n;t++)iC(e[t])===i&&(s+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:s}}}(en.current,er.current);ep(t.sessionId,n,r).then(n=>{eu(n,e,t,i)})},[eu,ep]),[em,ef]=(0,i.useState)(0),eg=(0,i.useRef)([]),ex=(0,i.useCallback)(e=>{if(es.current+=1,null!==ib(e.outcome)){let t=e.sessionId;eg.current.push({completion:e,trigger:t?{sessionId:t,turn:es.current}:null}),ef(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eg.current.splice(0)){let n=ib(e.outcome),r="neutral"===n?null:n;t?eh(r,t,e.provider,e.credentialId):G.current(null,r).catch(()=>{})}},[em,eh]);let ev=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ey,messages:ek,entryIds:ej,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eI,modelNames:eT,modelList:eM,modelError:e$,modelScopeWarnings:eR,modelThinkingLevels:eE,modelThinkingLevelMaps:eA,modelRoles:eF,toolPreset:eD,thinkingLevel:eH,effectiveThinkingLevel:eB,thinkingCeiling:eG,fastMode:eY,fastModeBusy:eX,handleFastModeToggle:eQ,retryInfo:e0,contextUsage:e1,forkingEntryId:e2,isCompacting:e4,compaction:e5,compactError:e6,compactResult:e3,displayModel:e7,modelSwitching:e9,sessionStats:te,runStateKnown:tt,compactedWork:tn,slashCommands:tr,slashCommandsLoading:ti,deliveryRows:ts,subagents:ta,todoPhases:tl,notices:to,extensionDialog:td,extensionResponse:tc,extensionCustomUi:tu,extensionStatuses:tp,extensionWidgets:th,respondToExtensionUi:tm,sendExtensionCustomInput:tf,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:tA,handleSteer:tz,handleFollowUp:tW,handlePromptWithStreamingBehavior:tP,handleAbortCompaction:tF,handleRecallQueue:t_,handleRemoveQueuedMessage:tD,handleBuiltinSlashCommand:tH,handleToolPresetChange:tO,handleThinkingLevelChange:tB,loadSlashCommands:tU,ensureNewSession:tq,refreshLiveTranscript:tK}=function(e){let{session:t,newSessionCwd:r,initialData:s,onAgentEnd:a,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=s&&s.sessionId===t?.id?s:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[N,I]=(0,i.useState)(f?.context.entryIds??[]),[T,M]=(0,i.useState)(f?.context.compactedWork??null),[$,R]=(0,i.useReducer)(aG,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)(!1),[W,P]=(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),[en,er]=(0,i.useState)(null),[ei,es]=(0,i.useState)("default"),[ea,el]=(0,i.useState)(()=>{let e=f?.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),[em,ef]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[eb,ey]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(f?.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),[eA,ez]=(0,i.useState)(!1),[eW,eP]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eH]=(0,i.useState)(null),eB=(0,i.useRef)(null),[eU,eJ]=(0,i.useState)(!1),[eG,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(a3,{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),[tn,tr]=(0,i.useState)([]),[ti,ts]=(0,i.useState)([]),[ta,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(iG,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ta.steering,followUp:ta.followUp})},[ta]),(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 n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iV(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let s=`${e}\u0000${iK(t)}`,a=n.get(s)??0;a>0?n.set(s,a-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(tc,ta),[tc,ta]),[tm,tf]=(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)(f?.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),tA=(0,i.useRef)(null),tz=(0,i.useRef)(0),tW=(0,i.useRef)(!1),tP=(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 ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),ns=(0,i.useRef)(Promise.resolve()),na=e.setToolPreset??es,nl=eT??g?.context.model??e$??null,no=m?X??en:nl,nd=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,s=0,a=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(s+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;a+=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,n+=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:r,assistantMessages:i,toolCalls:a,toolResults:s,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ek?{contextUsage:ek}:{}}},[S,e4,ek,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nc=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nc.current+=1,tf(n=>n?.sid===e&&aQ(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nc.current===n&&Array.isArray(t)&&tf(n=>n?.sid===e&&aQ(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nm=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),nf=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let s=r??null;if(!s){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);s=await r.json()}if(tj.current!==e)return null;x(s),j(s.leafId),tS.current=s.leafId??null;let a=eV(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(a.messages),nm(a.entryIds),M(s.context.compactedWork??null),ej(s.contextUsage??null),eM(e=>ni.current?e:null),w(null);let l=!n&&t8.current===e;if(l||(el(s.context.configuredThinkingLevel??s.context.thinkingLevel??"off"),ed(s.context.thinkingLevel)),eu(s.context.thinkingCeiling??null),i=!0,t&&b(!1),!n){if(l)try{let t=t6.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t6.current===t&&(r.state?.thinkingLevel!==void 0?(el(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(t8.current=null,el(s.context.configuredThinkingLevel??s.context.thinkingLevel??"off"),ed(s.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nc.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ej(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&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ts(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(aY(i.queuedMessages)),void 0!==i.subagents&&td(e=>aJ(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[np,nm,nh]),ng=(0,i.useCallback)(e=>{let t=ns.current.then(async()=>{tj.current===e&&await nf(e)});return ns.current=t.catch(()=>{}),t},[nf]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,s=await fetch(i);if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let l=eV(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(l.messages),nm(l.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nm,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await aL(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));na(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[na]),nb=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;m&&r&&n&&!t1.current&&(t1.current=!0,o?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,o]),ny=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t5.current,i=t4.current;e&&eR(e);let s={cwd:r,type:"ensure_session",toolNames:(0,sX.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},a=JSON.stringify(s),l=t0.current,o=l?.body===a?l.createRequestId:a5();t0.current={body:a,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...s,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||er(c.model)),c.thinkingLevel&&t5.current===n&&(el(c.configuredThinkingLevel??c.thinkingLevel),ed(c.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await aL(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}},[m,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await ny();if(!e)return eX([]),[];e0(!0);try{let t=await aL(e,{type:"get_commands"}),n=t?.commands??[];return eX(n),n}catch(e){return console.error("Failed to load slash commands:",e),eX([]),[]}finally{e0(!1)}},[ny]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tF.current?.(n):"agent_start"===n.type&&t_.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(s),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},s=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)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nI=(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 n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new a4(n.status)},[nN]),nT=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await aL(r,{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)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await aL(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),n$=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({type:"add",notice:{id:e.id??a5(),message:t,type:e.type??"info"}})},[]),nR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eO,content:ew(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),s=null;for(let e=i.length-1;e>=0;e--)if(!eK(i[e])){s=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eq}${n.seq}`,baseEntryId:s,message:t}),nh(e=>[...e,t])},[nh]),nE=(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(aM(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":n$({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ts(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});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)}},[n$,l,e.chatInputRef]),nL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eY(null),ey(null),R({type:"end"}),e},[]),nA=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=a1(tC.current,tN.current);tA.current=e?{entryId:e.entryId,key:le(e.message)}:null,tz.current+=1},[]),nz=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let n=a1(tC.current,tN.current),r=n?.message,i=tA.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:le(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=a0(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nW=(0,i.useCallback)(e=>{let t=nz();if("unknown"!==t.outcome||!e)return void a?.(t);let n=tz.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tz.current===n;a?.(e?nz():t)})},[a,nz]),nP=(0,i.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,nW(t),!0),[nW]),nF=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nc.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let a=s.state;if(td(e=>aJ(e,a?.subagents??[])),np(e,a?.todoPhases,r),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!a?.isStreaming,t$.current=!!a?.isPromptRunning,tT.current=!0,L(!0),eY(a?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(s.running&&a?.isCompacting){ez(!0),eH(aX(a)),ty.current=setTimeout(()=>void n(),600);return}if(s.running&&(a?.subagents?.length??0)>0){ty.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,ty.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void n(),600)}};ty.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),n_=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nf(e)}finally{if(nt.current!==t)return;let n=t$.current,r=tM.current;t$.current=!1,tM.current=!1,nr.current=null;let i=nL();n?nP(t):r&&i&&nW(),e&&nF(e)}},[nf,nW,nP,nF,nL]),nD=(0,i.useCallback)(async(e,t)=>{await a8(800);let n=Date.now();for(;tT.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await n_(e,t)}}catch{}await a8(600)}},[n_]),nH=(0,i.useCallback)(async e=>{let t=tP.current+1;for(tP.current=t;tW.current&&tP.current===t&&tj.current===e;){await a8(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nf(e),tP.current!==t||tj.current!==e)return;tW.current=!1,z(!1),P(null);return}catch{}}},[nf]),nO=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=nt.current;try{let n=nc.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let s=i.state;if(ez(s?.isCompacting??!1),eH(aX(s)),tl(aY(s?.queuedMessages)),s?.contextUsage!==void 0&&ej(s.contextUsage??null),td(e=>aJ(e,s?.subagents??[])),np(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting||s.isHandoffRunning)||!tT.current)return;s&&(void 0!==s.systemPrompt&&eC(s.systemPrompt??null),void 0!==s.extensionStatuses&&tr(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&ts(s.extensionWidgets??[])),await n_(e,t)}catch{}},[np,n_]),nB=(0,i.useCallback)(async e=>{let t=await nf(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tT.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,t$.current=!!n.isPromptRunning,tT.current=!0,L(!0),eY(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nD(e),!0)},[nN,nf,nD]),nU=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ej(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eA){eB.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eB.current})},[eA]),(0,i.useEffect)(()=>{if(!E&&!eA)return;let e=()=>{let e=tj.current;e&&nU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,eA,nU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&nO(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[E,nO]),(0,i.useEffect)(()=>{if(E)return;let e=()=>{let e=tj.current;e&&!tT.current&&nB(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tT.current&&nB(t).then(e=>{e||tj.current!==t||tT.current||nf(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(a_,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(a_,n)}},[E,nB,nf]),t_.current=e=>{if(tj.current!==e||tT.current||tg.current||tD.current)return;let t=nB(e).then(async t=>{t||tj.current!==e||tT.current||await nf(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,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let s=e.context.messages,a=new Map;for(let e of s){let t=le(e);a.set(t,(a.get(t)??0)+1)}let l=Math.min(r.length,i.length);for(let e of r.slice(0,l)){let t=le(e),n=a.get(t)??0;n>0&&a.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=le(e),n=a.get(t)??0;return 0===n||(a.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...s,...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 n=eV(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);nh(n.messages),nm(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;nk(),e&&nA(),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){nf(tj.current);let e=nc.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ej(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ts(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>aJ(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(aY(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,n=nL();ez(!1);let r=t?nf(t):void 0;t&&nF(t),n&&nW(r);break}case"prompt_done":{let e=nt.current,t=t$.current;t$.current=!1,nr.current=null;let n=tR.current!==e;if(!t&&!n)break;let r=tj.current;nP(e,r?nf(r):void 0),!tM.current&&(nL(),r&&nF(r))}break;case"prompt_error":tE.current="failed",n$({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tE.current="failed",n$({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,aR.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=a0(t)),t&&"user"===t.role){let e=(0,aR.B)(t),n=a9(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&a9(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||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&&nh(e=>[...e,(0,aR.B)(t)]);let n=tj.current;n&&nU(n),R({type:"reset"}),eY({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t8.current=t,t6.current+=1,el(e.configured??n),ed(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eY(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eY(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"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(n=>{let r=n.find(e=>e.id===t.id);return aJ(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={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=>aJ(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};td(e=>aJ(e,[r]));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){eB.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}ez(!0),eP(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(ez(!1),e.errorMessage)eP(e.errorMessage),e_(null);else if(!e.aborted){e_(lt(e.result,e.reason??"auto"));let t=tj.current;t&&(nf(t),nU(t))}break;case"extension_ui_request":nE(e)}},[n$,nu,np,nk,nE,nf,nW,nP,nU,nA,nF,nL,nm,nh]);let nq=(0,i.useCallback)(async(n,i,s)=>{let a=n.trim();if(!a&&!i?.length&&!s?.length)return"returned";if(tT.current||tW.current||ni.current)return"unknown";let l=rl(n,s??[]),o=!i?.length&&!s?.length&&a.startsWith("/");if(!i?.length&&!s?.length&&a.startsWith("!")){let e=a.startsWith("!!"),t=(e?a.slice(2):a.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}nA();let d=nt.current+1;nk(),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()};nh(e=>[...e,u]),nr.current=a9(u),nt.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,f=!1,g="unknown";try{if(m&&r){let e=tj.current??await tQ.current,t=await ny();t&&(h=t,X&&(eR(X),e&&await aL(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),f=!0,await aL(t,{type:"prompt",message:l,...p?.length?{images:p}:{}}),nb(1,n),g="accepted")}else t&&(h=t.id,await nI(t.id),f=!0,await aL(t.id,{type:"prompt",message:l,...p?.length?{images:p}:{}}),g="accepted");return o&&h&&nD(h,d),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof aE&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof aE&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&h)return nD(h,d),"unknown";t$.current=!1,tT.current=!1,nj();let a=nr.current;return a&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&a9(t)===a?e.slice(0,-1):e}),n$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,ln(i),s,t?.id??h??void 0),nr.current=null,L(!1),eY(null),R({type:"end"}),"returned"}},[m,r,X,t,ny,nI,nb,nD,n$,nk,nj,e.chatInputRef,nA,nh]);tV.current=(0,i.useCallback)(async(n,r)=>{if(tT.current||tW.current)return;let i=`${r?"!!":"!"}${n}`;tW.current=!0,tY.current(!0),P({command:n,excludeFromContext:r}),z(!0);try{let e=tj.current??t?.id??await ny();if(!e)throw Error("Unable to create a session for the shell command");await aL(e,{type:"bash",command:n,excludeFromContext:r}),await nf(e),nb(1,i)}catch(t){console.error("Failed to execute shell command:",t),n$({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tW.current=!1,P(null),z(!1)}},[n$,ny,nf,e.chatInputRef,nb,t]);let nK=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tW.current){try{await aL(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await aL(e,{type:"abort"}),tE.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nV=(0,i.useCallback)(async e=>{if(tW.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:n,newSessionId:r}=await aL(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return d?.(r),{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]),nJ=(0,i.useCallback)(async e=>{if(tW.current)return;let t=tj.current;t&&(aL(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nG=(0,i.useCallback)(async e=>{if(tW.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&aL(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nY=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t4.current=null,et(null)),Q(n),eR(n);let i=tj.current??await tQ.current;if(!i)return;try{await aL(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await aL(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nf(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eT),n$({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nf(n)}finally{ni.current=!1,eL(!1)}}},[n$,eT,m,nf,Q]),nZ=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(ni.current)return!1;ni.current=!0,eL(!0);let e=t2.current,s=t4.current,a=t5.current;try{t2.current=t,t4.current=n??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await aL(e,r),Q(t),et(n??null),eR(t),el("auto"),ed(void 0),e&&await nf(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t4.current=s,t5.current=a,n$({type:"error",message:i(n)});let t=tj.current;return t&&await nf(t),!1}finally{ni.current=!1,eL(!1)}}let s=tj.current;if(!s||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await aL(s,r),await nf(s),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),n$({type:"error",message:i(e)}),await nf(s),!1}finally{ni.current=!1,eL(!1)}},[n$,eT,eo,m,nf,Q,ea]),nX=(0,i.useCallback)(async e=>{let t=Y.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t5.current=t??null,el(t??"auto"),ed(void 0),t2.current=e,t4.current=null,et(null),Q(e),eR(e)}let r=tj.current??(m?await tQ.current:null);if(r)try{await aL(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Y,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eA){eB.current="manual",ez(!0),eP(null),e_(null);try{let t=await aL(e,{type:"compact"});e_(lt(t,"manual")),await nf(e,!0)}catch(e){eP(e instanceof Error?e.message:String(e)),e_(null)}finally{ez(!1)}}},[eA,nf]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",s=await fetch(i,e?{signal:e}:void 0);if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();_(a.models),B(a.modelError??null),q(a.modelScopeWarnings??[]),V(a.thinkingLevels??{}),G(a.thinkingLevelMaps??{}),Z(a.roles??[]);let l=a.modelList??[];if(H(l),m&&!tj.current){let e=(a.defaultModel?l.find(e=>e.id===a.defaultModel?.modelId&&e.provider===a.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&a.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[m,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=await ny(),a=e=>(e.handled&&(e.error?n$({type:"error",message:e.error}):"openSessionStats"!==e.action&&n$({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||eA)return a({handled:!0,error:"No active session to compact"});eB.current="manual",ez(!0),eP(null),e_(null);let e=await aL(s,{type:"compact",...i?{customInstructions:i}:{}});return e_(lt(e,"manual")),await nf(s,!0)&&nb(),a({handled:!0,message:"Compacted context"})}case"reload":if(!s)return a({handled:!0,error:"No active session to reload"});return await aL(s,{type:"reload"}),await Promise.all([nf(s,!1,!0),nv(s),nw(),n0()]),a({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return a({handled:!0,error:"No active session to name"});if(!i)return a({handled:!0,error:"Usage: /name <name>"});return await aL(s,{type:"set_session_name",name:i}),await nf(s)&&nb(),a({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return a({handled:!0,error:"No active session"});let e=await aL(s,{type:"get_session_stats"});return e&&e5(e),h?.(),a({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return a({handled:!0,error:"No active session"});let e=await aL(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return a({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),a({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!s)return a({handled:!0,error:"No active session to fork"});let e=await nV();if(!e.forked)return a({handled:!0,error:e.error??"Fork failed"});return a({handled:!0,message:"Forked a new session"})}case"goal":{if(!s)return a({handled:!0,error:"No active session"});let e=await aL(s,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return a({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nR(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&n$({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return a({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!s)return a({handled:!0,error:"No active session"});if(tT.current||tW.current)return a({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eY({kind:"running_command"});try{await nI(s);let e=await aL(s,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return a({handled:!0,error:"Handoff cancelled"});return await nf(s,!0)&&nb(),a({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eY(null),tj.current===s&&nF(s)}default:{if(!s)return a({handled:!0,error:"No active session"});let t=await aL(s,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nR(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return a({handled:!0,message:"Command completed"})}}}catch(e){return a({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&ez(!1)}},[n$,nR,nI,ny,nV,eA,n0,nf,nw,nv,nb,h,nF]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r),"returned";let s=rl(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:s,images:a?.length??0});try{return await aL(i,{type:"steer",message:s,...a?.length?{images:a}:{}}),tu({type:"ack",id:l}),"accepted"}catch(s){return tu({type:"fail",id:l}),console.error("Failed to steer:",s),n$({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r,i),"returned"}},[n$,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r,i)=>{let s=tj.current;if(!s)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),i),"returned";let a=rl(t,i??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:n,text:a,images:l?.length??0});try{return await aL(s,{type:"prompt",message:a,streamingBehavior:n,...l?.length?{images:l}:{}}),tu({type:"ack",id:o}),"accepted"}catch(n){return tu({type:"fail",id:o}),console.error("Failed to queue prompt:",n),n$({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(r),i,s),"returned"}},[n$,e.chatInputRef]),n5=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r),"returned";let s=rl(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:s,images:a?.length??0});try{return await aL(i,{type:"follow_up",message:s,...a?.length?{images:a}:{}}),tu({type:"ack",id:l}),"accepted"}catch(s){return tu({type:"fail",id:l}),console.error("Failed to follow up:",s),n$({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,ln(n),r,i),"returned"}},[n$,e.chatInputRef]),n8=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await aL(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await aL(t,{type:"clear_queue"});tu({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.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),n$({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,n$]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await aL(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),n$({type:"error",message:"Failed to remove queued message"})}},[n$]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ec;el(e),eu(n),m&&(!tj.current||t7.current===tj.current)&&(t5.current=e,t3.current=n),ed(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await ny():r&&await aL(i,{type:"set_thinking_ceiling",ceiling:n}),await aL(i,{type:"set_thinking_level",level:e}),await nf(i)}catch(e){console.error("Failed to set thinking level:",e),n$({type:"error",message:"Failed to set thinking level"}),await nf(i)}},[m,nf,n$,ec,ny]);ev.current=no?`${no.provider}/${no.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?aZ(t.state):void 0)??null})}).catch(()=>{})},[rt,E,eE]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await ny(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};ef(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=aZ(await aL(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let s=await aL(e,{type:"set_fast_mode",enabled:!n});i({enabled:s?.enabled===!0,active:s?.active===!0})}catch(t){if(!r())return;n$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(aZ(await aL(e,{type:"get_state"}))??null)}catch{i(null)}}finally{ef(!1)}},[ny,ep,n$]),ri=(0,i.useCallback)(async e=>{let t=(0,sX.xG)(e);na(e);let n=tj.current??await tQ.current;if(n)try{await aL(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[na]),rs=(0,i.useCallback)(e=>{tO.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=rs;let ra=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tJ.current=0,rs(!0),ra("smooth")},[ra,rs]),rd=(0,i.useCallback)(()=>{tJ.current=0,rs(!1)},[rs]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!a2.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[]),ru=(0,i.useCallback)(()=>{if(!tT.current&&!tW.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?rs(!0):t&&rs(!1))},[rs]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&nf(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(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"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nD(t.id)),e.state?.isBashRunning&&(tW.current=!0,z(!0),nH(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&ez(n.isCompacting),eH(aX(n)),void 0!==n.contextUsage&&ej(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t8.current=t.id,el(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ts(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(aY(n.queuedMessages)),void 0!==n.subagents&&td(e=>aJ(e,n.subagents??[])),void 0!==n.goal&&tK(n.goal??null)),e&&eJ(!0)}),()=>{tP.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nG)},[g?.tree,k,nG,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rc),()=>{window.removeEventListener("keydown",rc)}),[rc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rc,{passive:!0}),e.addEventListener("wheel",rc,{passive:!0}),e.addEventListener("touchstart",rc,{passive:!0}),e.addEventListener("scroll",ru,{passive:!0}),()=>{e.removeEventListener("pointerdown",rc),e.removeEventListener("wheel",rc),e.removeEventListener("touchstart",rc),e.removeEventListener("scroll",ru)}},[S.length,v,ru,rc]),(0,i.useEffect)(()=>{if(t9.current||!E&&!A||!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,A,S.length,$.streamingMessage,eG,W,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,ra("instant");return}if(!t9.current&&tO.current){let e=Date.now()-ne.current<1500;ra(tT.current||tW.current||e?"instant":"smooth")}}},[S.length,E,A,ra,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,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,ek?.tokens,ek?.percent,ek?.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:ea,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:eA,compaction:eD,compactError:eW,compactResult:eF,currentModel:nl,displayModel:no,modelSwitching:eE,sessionStats:nd,runStateKnown:eU,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ta,deliveryRows:th,subagents:to,todoPhases:tm&&tm.sid===tj.current?tm.phases:null,compactedWork:T,notices:e1.visible,extensionDialog:e8,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nT,sendExtensionCustomInput:nM,isAutoModelSelection:m&&null===X,agentPhase:eG,isNew:m,autoFollowPaused:tB,resumeAutoFollow:ro,pauseAutoFollow:rd,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tZ,scrollContainerRef:tX,handleSend:nq,handleAbort:nK,handleFork:nV,handleNavigate:nJ,handleModelChange:nY,handleRoleModelChange:nX,handleMainPresetChange:nZ,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n5,handlePromptWithStreamingBehavior:n4,handleAbortCompaction:n8,handleRecallQueue:n6,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:em,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:ny,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:A,pendingBash:W,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:s,transitioning:a,onAgentEnd:ex,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tV=no(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:t8.bo.find(e=>e.alias===tV?.alias)?.oauthPosition;return t8.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;en.current=ek,er.current=ej,ei.current=tj;let t6=(0,i.useRef)(!0);t6.current=!tb;let t3=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t3.current&&(es.current+=1),t3.current=eC},[eC]),(0,i.useEffect)(()=>()=>{es.current+=1},[]),(0,i.useEffect)(()=>{Q(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(lg(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 n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let s=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let s=0;for(let a=i;a<r;a++)if(iC(t[a])===e.identity&&(s+=1)===e.occurrence)return{kind:"entry",entryId:n[a]};return null}(i.intent,ek,ej);if(null===s){r.push(i);continue}n=!0,"drop"!==s.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===s.entryId)||r.push({id:i.id,anchorEntryId:s.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(lx(e,r),r):t})},[ek,ej,tj]);let t7=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tj.current,t=t7.current;if(t7.current=e?{sessionId:e,entryIds:ej}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let s=e.length;s<i;s++){let e=n[s];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&r.push(t[s])}return r}(t.entryIds,ej,ek),r=eo();if(0===n.length||!r)return;let i=na(e,"web6",void 0)?.alias??null;for(let e of n)ee.current.some(t=>t.anchorEntryId===e)||eu(i,"done",r,{kind:"entry",entryId:e})},[ej,ek,tj,eo,eu]);let t9=eC&&tx?.kind==="running_tools"&&tx.tools.length>0&&tx.tools.every(e=>"wait"===e.name),ne=eb||a,{hideThinkingBlock:nt}=(_=t??e?.cwd??null,H=t5(),(0,i.useEffect)(()=>{t4(_).catch(()=>{})},[_]),H),nn=(0,i.useMemo)(()=>({hideThinking:nt}),[nt]);(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:nr,process:ni}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],s=-1,a=null,l=(e,t,n)=>{if(0===t.length)return;let s=(a&&a.anchorIdx===e||(a={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(a)),a),l=r.length-1;for(let e of t)s.entries.push({...e,afterMainIndex:l});s.messageCount+=t.length,s.toolCallCount+=n},o=e_(e),d=new Map,c=(e,t)=>{let n=d.get(e)??0;d.set(e,n+1),r.push({kind:"answer",anchorIdx:s,idx:e,runIndex:n,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){r.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(),s=i.idx,r.push(i);continue}if(eU(t)){r.push(void 0!==i.anchorIdx||s<0?i:{...i,anchorIdx:s});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(s,[{idx:i.idx}],0);continue}let a=eW(t,n),d=!1;for(let e of a){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(s,[{idx:i.idx,blocks:e.blocks}],eP(e.blocks)),o.collect(i.idx,e.blocks)}!d&&ez(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(ek,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(eJ(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!eJ(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let s=i,a=s+1;for(;a<e.length&&!eJ(e[a]);)a+=1;if((t.sessionBusy||t.isStreaming)&&a===e.length&&s===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,s+1,a)){for(let e=s;e<a;e++)r.push({kind:"message",idx:e});i=a;continue}for(let n of(r.push({kind:"message",idx:s}),function(e,t,n,r){let i=[],s=[],a=0,l=[],o=0,d=0,c=e_(e.slice(t+1,n)),u=()=>{0!==s.length&&(i.push({kind:"process",anchorIdx:t,idx:s[0].idx,groupIndex:d++,entries:s,messageCount:s.length,toolCallCount:a,turnHasAnswer:!1}),s=[],a=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:c.attach(n),precedingBlocks:l}),l=[]};for(let o=t+1;o<n;o++){let n=e[o];if("assistant"!==n.role){if(eU(n)){u(),i.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&s.push({idx:o});continue}let d=eW(n,r),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(s.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),a+=eP(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&ez(n,r)&&p(o,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:o++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,s,a,{hideThinking:t.hideThinking})))r.push(n);i=a}return r}(ek,{sessionBusy:t1,isStreaming:eS.isStreaming,hideThinking:nn.hideThinking}),nn),[ek,t1,eS.isStreaming,nn]),ns=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let s=-1,a=-1;t.forEach((e,t)=>{let n=nz(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===s||e.item.anchorIdx===a),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=r.get(o.position);e?e.calls.push(...n):r.set(o.position,{calls:[...n],placement:l?"after":"before"})}}"user"===e.role&&(s=t),eJ(e)&&(a=t)});let{continuing:l}=nW(e,t,n);if(l){let e=r.get(l.position);e?e.calls.unshift(...l.calls):r.set(l.position,{calls:l.calls,placement:"before"})}return r})(nr,ek,tn?.messages),[nr,ek,tn]),nd=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=nW(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let s=e.findIndex(e=>e.idx>i),a=-1===s?e.length:s;return{position:a,jumpTo:a<e.length?a:e.length>0?e.length-1:null,calls:r}})(nr,ek,tn?.messages),[nr,ek,tn]),[nc,nu]=(0,i.useState)(lu),{startIndex:np,endIndex:nh,hasLater:nm}=lp(nr.length,nc),nf=null!==nc.end&&nm,ng=(0,i.useRef)(nr.length);ng.current=nr.length;let nx=(0,i.useRef)(null),nv=(0,i.useRef)(null),nb=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nc.end&&nc.end>=nr.length&&nu(e=>({count:e.count,end:null}))},[nc.end,nr.length]),(0,i.useEffect)(()=>{let e=nx.current,t=tC.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nb.current=t.scrollHeight-t.scrollTop,nu(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nc,nr.length,tC]),(0,i.useEffect)(()=>{if(null==nb.current)return;let e=tC.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nb.current),nb.current=null}},[nc.count,tC]),(0,i.useEffect)(()=>{let e=nv.current,t=tC.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nu(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=lp(e,t),s=i+n;return s>=e?{count:e-r,end:null}:{count:s-r,end:s}})(ng.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nc,nr.length,tC]);let[ny,nw]=(0,i.useState)(null),[nk,nj]=(0,i.useState)(null),[nS,nC]=(0,i.useState)(0),nL=(0,i.useRef)(null),n_=(0,i.useCallback)((e,t=null)=>{tw(),nL.current={item:e,dispatchKey:t},nw(null),nj(null),nu(t=>lh(ng.current,e,t)),nC(e=>e+1)},[tw]);(0,i.useLayoutEffect)(()=>{let e,t=nL.current,n=tC.current;if(null===t||!n)return;let r=n.querySelector(`[data-chat-item="${t.item}"]`);if(!r)return;nL.current=null;let i=t.dispatchKey?r.querySelector(".answer-dispatch"):null;if(i)e=i.getBoundingClientRect().top;else{let t=document.createRange();t.selectNodeContents(r),e=t.getBoundingClientRect().top}n.scrollTop+=e-n.getBoundingClientRect().top-24,i&&t.dispatchKey?nj(t.dispatchKey):nw(t.item)},[nS,nc,nr,tC]),(0,i.useEffect)(()=>{if(null===ny)return;let e=setTimeout(()=>nw(null),1800);return()=>clearTimeout(e)},[ny]),(0,i.useEffect)(()=>{if(null===nk)return;let e=setTimeout(()=>nj(null),1800);return()=>clearTimeout(e)},[nk]);let nD=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>nu(lu));let e=tC.current;e&&(e.scrollTop=e.scrollHeight)},[tC]),nH=(0,i.useCallback)(()=>{nf&&nD(),ty()},[nf,nD,ty]),nO=(0,i.useRef)(null),[nB,nU]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!z||nO.current===z.id||z.sessionId!==e?.id||eb||0===ek.length)return;nO.current=z.id,W?.(z.id);let t=ej.indexOf(z.entryId);if(t<0)return void nU(!0);let n=0;for(let e=0;e<nr.length;e++){let r=nr[e].idx;if(r>t||(n=e,r===t))break}n_(n)},[z,e?.id,eb,ek.length,ej,nr,n_,W]),(0,i.useEffect)(()=>{if(!nB)return;let e=setTimeout(()=>nU(!1),6e3);return()=>clearTimeout(e)},[nB]);let[nq,nK]=(0,i.useState)(!1),[nV,nJ]=(0,i.useState)(0),nG=(0,i.useMemo)(()=>nq?nr.map(e=>(function(e,t){if("answer"===e.kind)return eZ(e.blocks);let n=t[e.idx];return n&&"content"in n?eZ(n.content):""})(e,ek).toLowerCase()):lv,[nq,nr,ek]),nY=(0,i.useCallback)(e=>{tw(),nu(t=>lh(ng.current,e,t))},[tw]),nZ=(0,i.useCallback)(()=>nK(!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 n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nK(!0),nJ(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tC]);let nX=(0,i.useMemo)(()=>{let e=[];return nr.forEach((t,n)=>{if("message"!==t.kind)return;let r=lf(ek[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nr,ek]),nQ=`${np}:${nh}`,n0=ej.length>0?ej[ej.length-1]:null,[n1,n2]=(0,i.useState)(null),n4=(0,i.useRef)(!1);(0,i.useEffect)(()=>{n4.current||!tt||eb||!e?.id||(n4.current=!0,t1||!n0||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(ek)||function(e){try{return window.localStorage.getItem(lb(e))}catch{return null}}(e.id)!==n0&&n2(n0))},[tt,eb,e?.id,t1,n0,ek]);let n5=(0,i.useCallback)(()=>{e?.id&&n1&&function(e,t){try{window.localStorage.setItem(lb(e),t)}catch{}}(e.id,n1),n2(null)},[e?.id,n1]),n8=null!==n1&&n1===n0&&!t1&&!nf,n6=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,n3=(0,i.useRef)(te);n3.current=te,(0,i.useEffect)(()=>{f?.(n3.current)},[n6,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let n7=e1?`${e1.percent??"null"}|${e1.contextWindow}|${e1.tokens??"null"}`:null,n9=(0,i.useRef)(e1);n9.current=e1,(0,i.useEffect)(()=>{x?.(n9.current)},[n7,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(ta)},[b,ta]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:re,handleDragEnter:rt,handleDragOver:rn,handleDragLeave:rr,handleDrop:ri}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:a,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t1||p?.current?.addAttachments(e)},[t1,p])),rs=(0,i.useMemo)(()=>{var e;return e=tn?.messages,e&&e.length>0?[...e,...ek]:ek},[tn,ek]),ra=(0,i.useMemo)(()=>{let e=new Map;for(let t of rs)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rs]),ro=(0,i.useMemo)(()=>{let e,t,n,r;return e=new Map,t=new Map,n=new Map,r=(e,r,i)=>{let s=n.get(e);s&&r&&t.set(s,{status:r,order:i})},rs.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=ra.get(e.toolCallId);if(t)for(let r of n$(e,t)??[])n.set(r.agentId,r.key)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(nM(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=nI(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let s=i[i.length-1],a=i.slice(1,-1).join("#");return/^\d+$/.test(s)&&a?{key:`${a}#${s}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:nI(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i}),e.set(n.key,r);return}if("wait"===t.toolName)for(let e of nN(t.details?.jobs)){if("task"!==e.type)continue;let t=nI(e.id);t&&r(t,nT(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of nM(t.content).matchAll(nR)){let t=Object.fromEntries([...e[1].matchAll(nE)].map(e=>[e[1],e[2]]));t.id&&r(t.id,nT(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:n}},[rs,ra]),rd=(0,i.useMemo)(()=>({ledger:ro,subagents:ta,toolResults:ra,onOpenPanel:w,focusedDispatch:nk,sessionId:e?.id??null}),[ro,ta,ra,w,nk,e?.id]),rc=(0,i.useMemo)(()=>(function(e,t,n,r,i,s,a=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of n)for(let n of t.calls)o.set(n.toolCallId,e);if(a?.jumpTo!=null)for(let e of a.calls)o.set(e.toolCallId,a.jumpTo);let d=[];if(e.forEach((e,n)=>{if("assistant"!==e.role)return;let a=n>l;for(let n of e.content??[])if("toolCall"===n.type&&"task"===n.toolName)for(let e of n$(n,t.get(n.toolCallId))??[]){let t=nA(e,r,i),l=nP[t.run],c=null;"running"===l&&("live"===t.runSource||a&&s)?c="running":"awaiting"===l&&a&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(n.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]}})(rs,ra,ns,ta,ro,t1,nd),[rs,ra,ns,ta,ro,t1,nd]),ru=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),rp=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ek.length-1;n>=0;n-=1){let r=lf(ek[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ek]),rh=(0,i.useMemo)(()=>e8(ek,ra,tl,tn?.todoPhases??null),[ek,ra,tl,tn]),rm=(0,i.useMemo)(()=>iW(eS.streamingMessage).join("|"),[eS.streamingMessage]),rf=(0,i.useMemo)(()=>JSON.stringify(iz(eS.streamingMessage)),[eS.streamingMessage]),rg=(0,i.useMemo)(()=>JSON.stringify(iF(eS.streamingMessage)),[eS.streamingMessage]),rx=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let s=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.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(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),a=[],l=new Map,o=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){o=n;continue}let i=iW(r),d=iF(r,s);if(0===i.length&&0===d.length||o<0)continue;let c=iz(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),a.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let s=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){s=t;break}if(s>=0){let e=l.get(s);e||(e={index:s,entryId:t[s],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(s,e),a.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!o.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.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 a.sort((e,t)=>e.index-t.index)})(ek,ej,rm.length>0?rm.split("|"):[],JSON.parse(rf),JSON.parse(rg)),[ek,ej,rm,rf,rg]),rv=e?.id??tj.current??void 0,rb=(O=iD(D=(0,i.useMemo)(()=>({sessionId:rv,sessionProvider:e7?.provider,turns:rx,messages:ek,subagents:ta}),[rv,e7?.provider,rx,ek,ta])),B=iU(D),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...O,...B])),[O,B])),ry=tv&&0===ek.length&&!eS.isStreaming&&!t1,rw=e?.cwd??t??void 0,rk=e7?eE[`${e7.provider}:${e7.modelId}`]??null:null,rj=e7?eA[`${e7.provider}:${e7.modelId}`]??null:null,rS=(0,i.useRef)(null),rC=(0,i.useRef)(null),rN=(0,i.useCallback)(()=>{rS.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(C?.(rN),()=>C?.(null)),[rN,C]),(0,i.useLayoutEffect)(()=>{let e=rC.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tC.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tC.current;if(!i)return;let s=n-i.clientHeight;n=i.clientHeight,s<=0||i.scrollHeight-i.scrollTop-i.clientHeight-s<=1&&(i.scrollTop+=s)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[eb,tC]);let rI=(0,i.useCallback)((...e)=>(null!==nc.end&&nD(),tN(...e)),[tN,nc.end,nD]),rT=(0,r.jsx)("div",{ref:rS,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(aC,{ref:p,sessionId:e?.id??tj.current??void 0,onEnsureSession:tv&&t?tq:void 0,onLiveTranscriptPersisted:tK,onSend:rI,onAbort:tI,onSteer:eC?tz:void 0,onFollowUp:eC?tW:void 0,onPromptWithStreamingBehavior:eC?tP: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:eF,onRoleModelChange:tR,modelSwitching:e9,onCompact:e||tv?tA:void 0,onAbortCompaction:tF,isCompacting:e4,compactError:e6,compactResult:e3,toolPreset:eD,onToolPresetChange:e||tv?tO:void 0,thinkingLevel:eH,effectiveThinkingLevel:eB,thinkingCeiling:eG,onThinkingLevelChange:e||tv?tB:void 0,fastMode:eY,fastModeBusy:eX,onFastModeToggle:e||tv?eQ:void 0,availableThinkingLevels:rk,thinkingLevelMap:rj,retryInfo:e0,deliveryRows:ts,inputHistory:rp,onRecallQueue:t_,onRemoveQueuedMessage:tD,slashCommands:tr,slashCommandsLoading:ti,onLoadSlashCommands:tU,onBuiltinCommand:tH,soundEnabled:M,onSoundToggle:$,onAudioUnlock:A,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rM=eS.streamingMessage,r$=(0,i.useMemo)(()=>rM?eW(rM,{isStreaming:!0}):[],[rM]),rR=(0,i.useMemo)(()=>r$.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[r$]),rL=(0,i.useMemo)(()=>r$.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[r$]),rA=rM?.role==="assistant"?rM:null,rz=eC&&(tx?.kind==="running_tools"||(rA?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rW=rA?.provider??e7?.provider,rP=rA?.credentialId;(0,i.useEffect)(()=>{if(!rz)return;let e=eo();e&&ea.current!==e.turn&&el.current!==e.turn&&(ea.current=e.turn,eh("working",e,rW,rP))},[rz,rW,rP,eo,eh]);let[rF,r_]=(0,i.useState)(null),rD=(0,i.useCallback)(e=>{r_(e)},[]),rH=(0,i.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),rO=(0,i.useMemo)(()=>{let e=[eC&&!rM&&tx?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.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,rM,tx,eN,eI,U]);(0,i.useEffect)(()=>{if(!rF)return void k?.(null);let e=[],t=[],n=0;if(rM&&rL.length>0){let r=rF.messages.length+e.length;for(let i of(e.push(rM),rL))t.push({idx:r,blocks:i}),n+=eP(i)}if(rH&&(t.push({idx:rF.messages.length+e.length}),e.push(rH)),0===t.length)return void k?.(rO?{...rF,status:rO}:rF);let r=-1;for(let e=rF.messages.length-1;e>=0;e--)if(eJ(rF.messages[e])){r=e;break}let i=rF.groups.slice(),s=i.length>0?i[i.length-1]:void 0;s&&s.anchorIdx===r?i[i.length-1]={...s,entries:[...s.entries,...t],messageCount:s.messageCount+t.length,toolCallCount:s.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),k?.({...rF,groups:i,messages:[...rF.messages,...e],status:rO})},[rF,rL,rM,rH,rO,k]),(0,i.useEffect)(()=>()=>k?.(null),[k]);let rB=th.filter(e=>"belowEditor"!==e.placement),rU=th.filter(e=>"belowEditor"===e.placement);return ey?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ey}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":ne,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:rt,onDragOver:rn,onDragLeave:rr,onDrop:ri,children:[ne?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.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,re&&!t1&&(0,r.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,r.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,r.jsx)(lI,{request:tu,onInput:tf}),ry&&!S?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,r.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,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(V,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.14"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.10.4"]})]})]})]}),(0,r.jsx)(lS,{notices:to,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[S&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:S}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!S,style:{display:S?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(ii,{open:nq,onClose:nZ,containerRef:tC,index:nG,renderedStart:np,renderedEnd:nh,contentKey:ek,onReveal:nY,onProgrammaticScroll:tw,focusRequest:nV,t:U}),nB&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:U("chat.jumpMissing")}),(0,r.jsx)(lS,{notices:to,floating:!0,align:"right"})]})}),(0,r.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,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(lj,{widgets:rB}),(0,r.jsx)(nF.Provider,{value:rd,children:(0,r.jsx)(i$,{utterances:rb,children:(0,r.jsx)(ly,{messages:ek,entryIds:ej,toolResultsMap:ra,modelNames:eT,messageCwd:rw,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:nr,dispatchSlots:ns,compactedDispatch:nd,process:ni,startIndex:np,endIndex:nh,sentinelRef:nx,laterSentinelRef:nv,flashItem:ny,t:U,cues:X,cueFollowRef:t6,onProcessLogChange:rD})})}),!nf&&eS.isStreaming&&eS.streamingMessage&&rR.length>0&&(0,r.jsx)(rE,{message:eL(eS.streamingMessage,rR),sessionId:e?.id??tj.current??void 0,isStreaming:!0,modelNames:eT,cwd:rw,onOpenFile:j}),n8&&(0,r.jsx)(ic,{onDismiss:n5,t:U}),(0,r.jsx)("div",{ref:tS})]})})}),(0,r.jsx)(is,{questions:nX,containerRef:tC,layoutKey:nQ,onJump:n_,label:U("chat.questionRail")}),(t1&&tb||nf)&&(0,r.jsxs)("button",{type:"button",onClick:nH,"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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),U("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rC,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[td&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(lN,{request:td,onRespond:tm,onActivity:e=>void tf(e,"activity"),delivery:tc})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(id,{compaction:e5,t:U}),(0,r.jsx)(lk,{goal:tk,t:U}),!J&&(0,r.jsx)(r7,{summary:rc,onJump:n_,onOpenPanel:ru}),(0,r.jsx)(lj,{widgets:rU}),rh&&!J&&(0,r.jsx)(aI,{phases:rh})]})}),rT,(0,r.jsx)(aN,{statuses:tp})]})]})}function lk({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tG(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tG(e.tokensUsed)});return(0,r.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:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function lj({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.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,r.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 lS({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let s="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.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:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function lC({focusKey:e,label:t,labelledBy:n,maxBlockSize:s="min(56dvh, 620px)",onCancel:a,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 n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:a?e=>{"Escape"===e.key&&(e.stopPropagation(),a())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:s},children:[l?(0,r.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 lN({request:e,onRespond:t,onActivity:n,delivery:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,m]=(0,i.useState)(""),f=(0,i.useRef)(0),g=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-f.current<1e3||(f.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{if(o("editor"===e.method?e.prefill??"":""),m(""),p({}),"ask"!==e.method)return void c({});let t={};for(let n of e.questions)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];c(t)},[e]);let x=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:l})};if("ask"===e.method){let n=e.questions.every(e=>(d[e.id]?.length??0)>0||(u[e.id]?.trim().length??0)>0),i=()=>{n&&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,r.jsx)(lC,{focusKey:e.id,label:a("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:a("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let s=d[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=s.includes(n),l=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{var e,r;return e=t.id,r=t.multi??!1,void(g(),c(t=>{let i=t[e]??[],s=r?i.includes(n)?i.filter(e=>e!==n):[...i,n]:[n];return{...t,[e]:s}}))},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,r.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,r.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,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.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,r.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,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:u[t.id]??"",onChange:e=>{g(),p(n=>({...n,[t.id]:e.target.value}))},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:a("chat.customAnswer"),"aria-label":a("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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.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:a("chat.cancel")}),(0,r.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:a("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||s?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&s?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&s?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&s?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:s?.status==="sending"?a("chat.responseSending"):a("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(lC,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.planApproval")}),(0,r.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,r.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,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(tK,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:h,onChange:e=>m(e.target.value),placeholder:a("chat.planFeedback"),"aria-label":a("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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.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:a("chat.refinePlan")}),(0,r.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:a("chat.approvePlan")})]})]})]})}):(0,r.jsx)(lC,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:a("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.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,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),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:n},n))}),"input"===e.method&&(0,r.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,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.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:a("chat.cancel")}),"confirm"===e.method?(0,r.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:a("chat.confirm")}):"select"!==e.method?(0,r.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:a("chat.submit")}):null]})]})})}function lI({request:e,onInput:t}){let{t:n}=(0,R.s)(),s=(0,i.useRef)(null),a=(0,i.useRef)(!1),l=eC(e.lines);return(0,i.useEffect)(()=>{s.current?.focus()},[e.id]),(0,r.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,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||s.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,r.jsx)("textarea",{ref:s,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=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=eT[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":" ":eI[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:n=>{a.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.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:n("chat.close")})]}),(0,r.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,n)=>{var s;return(0,r.jsxs)(i.Fragment,{children:[(s=`line-${t}`,eN(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function lT({onPick:e,t}){let[n,s]=(0,i.useState)(""),[a,l]=(0,i.useState)({kind:"idle"}),o=(0,i.useRef)(null),d=n.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"===a.kind?a.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>s(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 n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),d.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===a.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===a.kind&&t("palette.searching"),"error"===a.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,r.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((n,i)=>{let s=u.sessions[n.sessionId],a=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!s,onClick:()=>s&&e(s,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),c(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:s?s.name?.trim()||s.firstMessage?.trim()||s.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,a)}),n.snippet.slice(a)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var lM=n(50640),l$=n(73620);let lR=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lE(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let lL=["tags","categories","keywords","tag","category"];function lA({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=lL.find(t=>Array.isArray(e[t])),a=s?e[s].map(lE).filter(Boolean):[],l=n.filter(([e])=>e!==s&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),a.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:a.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=lE(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}let lz={source:"Source",preview:"Preview",diff:"Diff"},lW={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},lP={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 lF(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function l_(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function lD(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=l_(n.startContainer),i=l_(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),a=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(a))return null;if(s<a){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((i=e).dataset.lineNumber))}}}return s>a?null:{startLine:s,endLine:a}}function lH({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,s)=>{let a=e.children??[],l=a[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?a[0]:null,c=o?a.slice(1):a;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":s+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,lM.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${s}`}),(0,r.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,r)=>(0,lM.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${s}-${r}`}))})]},`source-line-${s}`)})}function lO(e,t,n,r={}){let i=tt(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function lB({filePath:e,sourceSessionId:t}){let{t:n}=(0,R.s)();return(0,r.jsx)("a",{href:lO(e,"download",t),download:tn(e),title:n("i18n.downloadFile"),"aria-label":n("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function lU(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lq({patch:e}){let t,{t:n}=(0,R.s)(),i=(t=nm(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,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let s=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),a=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)a.add(t);let l=[],o=0;for(;o<i.length;)if(a.has(o)){let e=[];for(;o<i.length&&a.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!a.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lW},children:l.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:lP,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function lK({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=tn(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lO(e,"watch",n));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,n]);let v=lO(e,"read",n,o?{v:o}:void 0),b=null!=c?lU(c):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,r.jsx)("span",{children:b}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(lB,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:m?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:m}):(0,r.jsx)("img",{src:v,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>f("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function lV({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=tn(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),f(null),l(!1),g.current&&(g.current.close(),g.current=null);let t=new EventSource(lO(e,"watch",n));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),f(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),g.current=null}},[e,n]);let v=lO(e,"read",n,o?{v:o}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"audio"}),null!=p&&(0,r.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}(p)}),null!=c&&(0,r.jsx)("span",{children:lU(c)}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(lB,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[m&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:m}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:v,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>f("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function lJ({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,R.s)(),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eR(e),g="pdf"===f,x=g?lO(e,"read",n,o?{v:o}:void 0):lO(e,"preview",n,o?{v:o}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),l(!1),m.current&&(m.current.close(),m.current=null),fetch(lO(e,"meta",n)).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(lO(e,"watch",n));return m.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(),m.current=null}},[e,g,n]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===f?"docx preview":"pdf"}),null!=c&&(0,r.jsx)("span",{children:lU(c)}),(0,r.jsx)(lB,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:tn(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function lG({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o}){let d;return eE(e)?(0,r.jsx)(lK,{filePath:e,cwd:t,sourceSessionId:n}):null!==(e$[eR(e)]??null)?(0,r.jsx)(lV,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(d=eR(e))||"docx"===d?d:null)?(0,r.jsx)(lJ,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(lY,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:l,initialDisplayMode:o})}function lY({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:s,onMentionLines:a,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d}){let c,u,{isDark:p}=tD(),{t:h}=(0,R.s)(),[m,f]=(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),[A,z]=(0,i.useState)(null),W=(0,i.useCallback)(e=>fetch(lO(e,"read",n)).then(e=>e.json()).then(e=>e.error?(j(e.error),null):(j(null),f(e),e)).catch(e=>(j(String(e)),null)),[n]),P=(0,i.useCallback)(async e=>{let n=++E.current;if(b(!0),!t){x(null),b(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(n!==E.current)return;x(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{n===E.current&&x(null)}finally{n===E.current&&b(!1)}},[t]);(0,i.useEffect)(()=>{w(!0),j(null),f(null),x(null),C("source"),I(!1),M(!1),$.current&&($.current.close(),$.current=null),W(e).finally(()=>w(!1));let t=new EventSource(lO(e,"watch",n));return $.current=t,t.addEventListener("connected",()=>{M(!0)}),t.addEventListener("change",()=>{W(e),P(e)}),t.addEventListener("error",()=>{M(!1)}),t.onerror=()=>{M(!1)},()=>{t.close(),$.current=null}},[e,W,P,n]),(0,i.useEffect)(()=>{P(e)},[P,e,o]),(0,i.useEffect)(()=>{(m?.language==="markdown"||m?.language==="html")&&"diff"!==d&&C("preview")},[m?.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)(()=>m?.language==="markdown"?tp(m.content):"",[m]),O=(0,i.useMemo)(()=>m?.language==="markdown"?function(e){let t=function(e){let t=lR.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,l$.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(m.content):null,[m]);(0,i.useEffect)(()=>{let e=()=>{let e=L.current;z(a&&"source"===S&&e?lD(e,window.getSelection()):null)};if(e(),a&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,S,a]);let B=(0,i.useCallback)(n=>{a&&n&&a(tr(e,t),n.startLine,n.endLine)},[t,e,a]);if((0,i.useEffect)(()=>{if(!a||"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 n=L.current,r=n?lD(n,window.getSelection()):null;r&&(e.preventDefault(),B(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,B,a]),y||"diff"===d&&v&&!m)return(0,r.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,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:k});if(!m&&!_)return null;let U=m?.language??"text",q=m?.content??"",K="html"===U,V="markdown"===U,J=(u=(c=te(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 ${lU(m.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:e,children:tr(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:X,children:X}),!_&&(0,r.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,r.jsxs)("div",{className:"file-viewer-controls",children:[Z.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":h("i18n.fileViewMode"),children:Z.map(e=>{let t=Y===e;return(0,r.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:lz[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(l||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{A&&a?B(A):l?.(tr(e,t),!1)},title:A&&a?`${h("i18n.mentionSelectedLines")} (L${A.startLine}${A.startLine!==A.endLine?`-L${A.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!l&&!a,className:"file-viewer-icon-button",children:(0,r.jsx)(lF,{})}),"source"===Y&&(0,r.jsx)(r.Fragment,{children:(0,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!_&&(0,r.jsx)(lB,{filePath:e,sourceSessionId:n})]})]}),(0,r.jsx)("div",{ref:L,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},children:"diff"===Y&&F?(0,r.jsx)(lq,{patch:g.patch}):K&&"preview"===Y?(0,r.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,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[O?.data&&(0,r.jsx)(lA,{data:O.data}),(0,r.jsx)(e9.oz,{remarkPlugins:tx,rehypePlugins:tb,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,r.jsx)(tB,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tq,{code:s.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let a=s?e2(e,J,t??J):null;return a&&s?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),s(a))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...s}){delete s.node;let a="string"==typeof e?e2(e,J,t??J):null,l=a?lO(a,"read",n):e;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...s})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:H})]}):(0,r.jsx)(e3.A,{className:N?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?e7.xJ:e7.vs,showLineNumbers:!0,lineNumberStyle:{...lP},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,r.jsx)(lH,{...e,wrapLines:N}),wrapLongLines:N,children:q})})]})}function lZ({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:s}){let{t:a,locale:l}=(0,R.s)(),[o,d]=(0,i.useState)(null);return(0,r.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,r.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(),s(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,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(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,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:nk(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),s(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background: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:a("i18n.close"),"aria-label":`${a("i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let lX=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],lQ=new Set(lX);function l0(e){return void 0!==e&&lQ.has(e)}function l1(e){if(!e)return[...lX];let t=new Set(e);return lX.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function l2(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return l0(n)?n:"inherit"}function l4(e,t){let n=e.lastIndexOf(":"),r=l0(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var l5=n(98795),l8=n.n(l5);function l6(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function l3({value:e,options:t,onChange:n,disabled:s=!1,placeholder:a="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),m=(0,i.useRef)(null),f=(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=l6(v.trim());return e?t.filter(t=>l6(`${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(()=>m.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&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=sZ(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),I=e=>{e.disabled||(n(e.value),x(!1))},T=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${l8().root}${c?` ${c}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:l8().trigger,disabled:s,"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,r.jsx)("span",{className:j?l8().value:l8().placeholder,children:j?.label??(e||a)}),(0,r.jsx)("svg",{className:l8().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:l8().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,r.jsxs)("div",{className:l8().searchWrap,children:[(0,r.jsxs)("svg",{className:l8().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:l8().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,r.jsx)("div",{id:k,className:l8().options,role:"listbox","aria-label":d,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:l8().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>I(t),children:[(0,r.jsxs)("span",{className:l8().optionCopy,children:[(0,r.jsx)("span",{className:l8().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:l8().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:l8().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:l8().empty,children:o})})]})]})}let l7=["global","project"],l9=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function oe(e){return`${e.provider}/${e.id}`}function ot({cwd:e,onRolesChanged:t}){let{t:n}=(0,R.s)(),[s,a]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){a([]),o([]),c({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let s=await r.json();if(s.error)throw Error(s.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();a(s.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[e]);(0,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);a(s.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>s.filter(e=>!e.hidden),[s]),k=w.some(e=>l9.includes(e.role)&&!e.selector);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")}),!h&&k&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:n("roles.harnessNote")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:l7.map(e=>(0,r.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?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:l4(e.selector??"","inherit"),i=l2(e.selector),s=l1(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),a=l9.includes(e.role);return(0,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,r.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,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),a&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:n(`roles.harness.${e.role}`)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:a&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(l3,{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 n=l.find(e=>oe(e)===t),r=n?d[`${n.provider}:${n.id}`]:void 0,i=l2(e.selector),s=l1(r).includes(i)?i:"inherit";y(e.role,l4(t,s))},options:[{value:"",label:n("roles.unset")},...l.map(e=>({value:oe(e),label:`${e.name} — ${e.provider}`,searchText:oe(e)})),...t&&!l.some(e=>oe(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:s.map(s=>{let a=i===s;return(0,r.jsx)("button",{type:"button","aria-pressed":a,disabled:x===e.role,title:"inherit"===s?n("roles.thinkingInherit"):s,onClick:()=>{a||y(e.role,l4(t,s))},style:{padding:"3px 7px",border:`1px solid ${a?"var(--accent)":"var(--border)"}`,borderRadius:4,background:a?"var(--bg-selected)":"transparent",color:a?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:a?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:s},s)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function on(e){window.open(e,"_blank","noopener,noreferrer")}var or=n(67381),oi=n(64433),os=n(70350),oa=n(88195),ol=n(9312),oo=n(87275),od=n(22008),oc=n(95476),ou=n(35029),op=n(14489),oh=n(78728),om=n(19872),of=n(7751),og=n(92526),ox=n(48238),ov=n(57794),ob=n(41098),oy=n(84604),ow=n(15315),ok=n(74278),oj=n(55457),oS=n(71437),oC=n(29167),oN=n(97283),oI=n(34166),oT=n(33889),oM=n(85486),o$=n(74068),oR=n(83546),oE=n(83709);let oL={anthropic:{Icon:or.A,hasColor:!1},openai:{Icon:oi.A,hasColor:!1},"openai-codex":{Icon:oi.A,hasColor:!1},google:{Icon:os.A,hasColor:!0},"google-vertex":{Icon:os.A,hasColor:!0},"ant-ling":{Icon:oT.A,hasColor:!0},deepseek:{Icon:oa.A,hasColor:!0},groq:{Icon:ol.A,hasColor:!1},mistral:{Icon:oo.A,hasColor:!0},moonshotai:{Icon:od.A,hasColor:!1},"moonshotai-cn":{Icon:od.A,hasColor:!1},moonshot:{Icon:od.A,hasColor:!1},minimax:{Icon:oc.A,hasColor:!0},"minimax-cn":{Icon:oc.A,hasColor:!0},fireworks:{Icon:ou.A,hasColor:!0},huggingface:{Icon:op.A,hasColor:!0},cerebras:{Icon:oh.A,hasColor:!0},openrouter:{Icon:om.A,hasColor:!1},xai:{Icon:of.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:og.A,hasColor:!0},"cloudflare-workers-ai":{Icon:og.A,hasColor:!0},"vercel-ai-gateway":{Icon:ox.A,hasColor:!1},"github-copilot":{Icon:ov.A,hasColor:!1},"amazon-bedrock":{Icon:ob.A,hasColor:!0},"azure-openai-responses":{Icon:oy.A,hasColor:!0},"kimi-coding":{Icon:ow.A,hasColor:!0},nvidia:{Icon:oM.A,hasColor:!0},opencode:{Icon:o$.A,hasColor:!1},"opencode-go":{Icon:o$.A,hasColor:!1},qwen:{Icon:ok.A,hasColor:!0},xiaomi:{Icon:oR.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oR.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oR.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oR.A,hasColor:!1},zai:{Icon:oE.A,hasColor:!1},"zai-coding-cn":{Icon:oE.A,hasColor:!1},zhipu:{Icon:oj.A,hasColor:!0},cohere:{Icon:oS.A,hasColor:!0},perplexity:{Icon:oC.A,hasColor:!0},together:{Icon:oN.A,hasColor:!0},grok:{Icon:oI.A,hasColor:!1}},oA=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function oz({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.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 oP({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...oW,fontFamily:i?"var(--font-mono)":"inherit"}})}function oF({value:e,onChange:t,placeholder:n,mono:s,onKeyDown:a,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,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:a,placeholder:n,style:{...oW,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:o}),(0,r.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,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function o_({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:oW})}function oD({value:e,onChange:t,options:n,required:i}){let{t:s}=(0,R.s)();return(0,r.jsx)(l3,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${s("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function oH({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function oO({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function oB({name:e,provider:t,onChange:n,onRename:s,onDelete:a,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=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 r.json();if(n!==x.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==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=f.filter(e=>!w.has(e)).length,T=N.length>0&&N.every(e=>f.includes(e)),M=!T&&N.some(e=>f.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:o("i18n.provider")}),(0,r.jsx)("button",{onClick:a,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,r.jsxs)(oz,{label:o("i18n.providerName"),children:[(0,r.jsx)(oP,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>s(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,r.jsx)(oz,{label:"Base URL",children:(0,r.jsx)(oP,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(oz,{label:"API Key",children:[(0,r.jsx)(oF,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(oz,{label:"API",children:(0,r.jsx)(oD,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:oA,required:!0})}),(0,r.jsxs)(oz,{label:"Headers",children:[(0,r.jsx)(oJ,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.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,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:o("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":o("models.discoveryFilter"),style:{...oW,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.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,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:o("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:o("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.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,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),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 oU=["off","minimal","low","medium","high","xhigh","max"],oq={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oK({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:oU.map(e=>{let t=n[e],s=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",l=oq[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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===s?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===s?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===s?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...o,..."omit"===s?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===s?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===s?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,a||e),style:{...o,..."string"===s?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:a,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==s&&i(e,a||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===s?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===s?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oV={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oJ({headers:e,onChange:t}){let[n,s]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),a=(0,i.useRef)(n.length),l=e=>{s(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},o=(e,t)=>{l(n.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.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,r.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,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void l(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>s(e=>[...e,{id:a.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 oG({providerName:e,provider:t,model:n,onChange:s,onDelete:a}){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),m=(e,t)=>s({...n,[e]:t}),f=(()=>{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,n.id,n.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==l.phase){o({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.json();if(!r.ok||!i.ok)return void o({phase:"error",message:i.error??`HTTP ${r.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)})}}},[n,t,e,l.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===c.phase)return;let i=++p.current;u({phase:"loading"});try{let a=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&a.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${a}`),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 n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s=!0,r+=1);s&&(n.cost=i)}return{model:n,appliedCount:r}}(n,o.recommendation.preset);d.appliedCount>0&&(h.current=n,s(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,n,s,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:n}=c,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \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`${r} \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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:d("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,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:f}),(0,r.jsxs)("button",{onClick:g,disabled:!n.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":n.id.trim()&&"testing"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?d("i18n.checking"):"success"===l.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)("button",{onClick:a,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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(oz,{label:"ID *",children:(0,r.jsx)(oP,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(oz,{label:"Name",children:(0,r.jsx)(oP,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,s(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,r.jsx)(oz,{label:"API override",children:(0,r.jsx)(oD,{value:n.api??"",onChange:e=>m("api",e||void 0),options:oA})}),(0,r.jsxs)(oz,{label:"Headers",children:[(0,r.jsx)(oJ,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(oH,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(oH,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oH,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oV}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(oH,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>s({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(oO,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("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,r.jsx)(oK,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(oz,{label:"Context window (tokens)",children:(0,r.jsx)(o_,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(oz,{label:"Max output tokens",children:(0,r.jsx)(o_,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(oO,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(oz,{label:e,children:(0,r.jsx)(o_,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void s({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let oY={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function oZ({provider:e,onRefresh:t,relogin:n}){let s=n?.onLoginSucceeded,[a,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),m=(0,i.useRef)(null),f=void 0!==n;(0,i.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,i.useEffect)(()=>{("auth"===a.phase||"prompt"===a.phase)&&setTimeout(()=>h.current?.focus(),50)},[a.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(),s?.())},[t,s]),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 n=JSON.parse(e.data);"auth"===n.type?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),on(n.url)):"device_code"===n.type?(l({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),on(n.verificationUri)):"prompt_request"===n.type?l({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?l({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?l({phase:"progress",message:n.message}):"success"===n.type?g():"error"===n.type?(t.close(),l({phase:"error",message:n.message})):"cancelled"===n.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,n,r)=>{l({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})}),i=await r.json().catch(()=>({}));if(!r.ok)return void l({phase:"error",message:i.error??`Server error ${r.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"===a.phase||"progress"===a.phase||"auth"===a.phase||"device_code"===a.phase||"prompt"===a.phase||"select"===a.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:o("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:o(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),n&&(0,r.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,r.jsx)(np,{seed:n.target.seed,size:32,provider:n.target.provider}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:o("relogin.title")}),(0,r.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[n.target.alias,n.target.masked&&(0,r.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:n.target.masked})]}),n.target.reason&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:n.target.reason})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n?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"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("i18n.openingBrowser")}),"select"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:a.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:a.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(a.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"===a.phase||"prompt"===a.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===a.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.":a.message}),"auth"===a.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:a.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:h,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&y(a.token,d)},placeholder:"auth"===a.phase?"Paste the redirect URL or code":a.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,r.jsx)("button",{onClick:()=>y(a.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"===a.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:a.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:a.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:a.verificationUri}),a.expiresInSeconds?` Expires in ${Math.ceil(a.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a.message}),"success"===a.phase&&(n?(0,r.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("relogin.done")}),n.outcome&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===n.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===n.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:o(oY[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:o("i18n.connectedSuccessfully")})),"error"===a.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:a.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:m,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&&!n&&(0,r.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 oX({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)(""),[a,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,R.s)();(0,i.useEffect)(()=>{s(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){l(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(s(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{l(!1)}}},[n,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(oO,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.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,r.jsx)(oz,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(oF,{value:n,onChange:s,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:a||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:a||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":a?"i18n.saving":"i18n.save")]})]})}),c&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,r.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:m(o?"i18n.removing":"i18n.disconnect")})]})}function oQ({id:e,size:t}){let n=oL[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.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:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}function o0({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:s,onAddCustom:a,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))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+m.length+ +!!f,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,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref: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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{a(),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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(oQ,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.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"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(oQ,{id:e.id,size:28})]},e.id))]})})]})})}function o1({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:s,relogin:a}){let l=P(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)({providers:{}}),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(a?{type:"oauth",providerId:a.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(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),L=(0,i.useCallback)((e,t)=>{c(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),y(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),A=(0,i.useCallback)(e=>{c(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),c(e=>{let t=Object.keys(e.providers??{});return y(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),z=(0,i.useCallback)(e=>{c(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),c(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return y({type:"model",providerName:e,index:n}),t})},[]),W=(0,i.useCallback)((e,t)=>{c(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],s=new Set(i.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),F=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),_=(0,i.useCallback)((e,t)=>{c(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),y({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{m(!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),s?.(),setTimeout(()=>v(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[d,s]),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,r.jsx)(ot,{cwd:e??null,onRolesChanged:s});if("oauth"===b.type){let e=w.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oZ,{provider:e,onRefresh:M,relogin:a?.target.provider===e.id?a:void 0},e.id):null}if("apikey"===b.type){let e=j.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oX,{provider:e,onRefresh:M},e.id):null}if("provider"===b.type){let e=d.providers?.[b.name];return e?(0,r.jsx)(oB,{name:b.name,provider:e,onChange:e=>E(b.name,e),onRename:e=>L(b.name,e),onDelete:()=>A(b.name),onAddModels:e=>W(b.name,e)},b.name):null}let t=d.providers?.[b.providerName],n=t?.models?.[b.index];return n?(0,r.jsx)(oG,{providerName:b.providerName,provider:t,model:n,onChange:e=>F(b.providerName,b.index,e),onDelete:()=>_(b.providerName,b.index)},`${b.providerName}-${b.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},...n?{}:{role:"dialog","aria-modal":!0,"aria-label":o("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,r.jsxs)("div",{style:{width:n?"100%":l?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":l?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.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,r.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,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:o("roles.title")})]}),(0,r.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,r.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,r.jsx)(oQ,{id:e.id,size:16}),(0,r.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,r.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,r.jsx)(oQ,{id:e.id,size:16}),(0,r.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,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):H.map(([e,t])=>{let n=b?.type==="provider"&&b.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>y({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{let i=b?.type==="model"&&b.providerName===e&&b.index===n;return(0,r.jsxs)("div",{onClick:()=>y({type:"model",providerName:e,index:n}),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,r.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,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)("div",{onClick:t=>{t.stopPropagation(),z(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,r.jsxs)("span",{style:{fontSize:11},children:["+ ",o("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:U??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[f&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:f}),(0,r.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,r.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,r.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,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:x?o("i18n.saved"):h?o("i18n.saving"):o("i18n.save")})]})]})]})}),C&&(0,r.jsx)(o0,{oauthProviders:w,apiKeyProviders:j,onSelectOAuth:e=>y({type:"oauth",providerId:e}),onSelectApiKey:e=>y({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>N(!1)})]})}function o2(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function o4(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function o5(e){let t=o4(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function o8(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function o6(e){return e?e.slice(0,8):"unknown"}function o3({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,R.s)();return(0,r.jsx)("button",{onClick:n,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,r.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 o7({skill:e,cwd:t,onToggle:n,toggling:i,saveError:s,updateStatus:a,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=o4(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.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,r.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 n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return o2(e)}(e.filePath)}),(0,r.jsx)(o3,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:s})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.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,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:o6(a?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.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")}),a?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:o6(a.latestVersion)}),(l||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":a?.state==="up-to-date"?"#16a34a":a?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):a?.state==="up-to-date"?p("i18n.upToDate"):a?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):a?.message||p("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.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,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function o9({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:s}){let{t:a}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,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),m(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);c(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),s()}catch(e){v(String(e))}finally{g(null)}},[s,w,e]),N="global"===w?"~/.claude/skills/":`${o2(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:a("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(l)},placeholder:a("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,r.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?a("i18n.searching"):a("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:a("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"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||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=f===e.package,s=e.package.indexOf("@"),l=s>-1?e.package.slice(0,s):e.package,o=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:o??l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${a("i18n.installed")}`:i?a("i18n.installing"):a("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.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 de({cwd:e,onClose:t,embedded:n=!1}){let s=P(),{t:a}=(0,R.s)(),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,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),[A,z]=(0,i.useState)({}),W=(0,i.useCallback)(async()=>{c(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(o(r),L(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&z(t=>({...t,[o5(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{c(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),$(null),W()},[e]);let F=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(o8).filter(e=>!!e);if(0!==n.length){$(null),S(e=>new Set([...e,...n])),t||N(!0);try{let n=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})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.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 n)t.delete(e);return t}),t||N(!1)}}},[e,l]),_=(0,i.useCallback)(async t=>{if(!t.install)return;let n=o8(t);T(n),$(null);try{let r=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 r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await W();let s=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,W]),D=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);o(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&z(t=>({...t,[o5(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),H=l.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":s?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":s?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o2(e)})]}),(0,r.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,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:a("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:s?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:s?"100%":210,maxHeight:s?"40vh":void 0,borderRight:s?"none":"1px solid var(--border)",borderBottom:s?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:a("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===o4(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===o4(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===o4(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===o4(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===o4(e)}]){let r=l.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(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,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:s?"var(--border)":"var(--accent)",boxShadow:s?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:s?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=o8(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),s=n.filter(e=>e.disableModelInvocation),l=A[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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),s.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>z(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,r.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),a("i18n.dormant")," (",s.length,")"]}),l&&s.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),a("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(o9,{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:()=>{W()}}):d?null:H?(0,r.jsx)(o7,{skill:H,cwd:e,onToggle:D,toggling:f.has(H.filePath),saveError:x,updateStatus:o8(H)?w[o8(H)]:void 0,checkingUpdate:!!o8(H)&&j.has(o8(H)),updating:I===o8(H),updateError:M,onCheckUpdate:()=>void F(H),onUpdate:()=>void _(H)},H.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,r.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?a("i18n.checking"):a("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.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?a("i18n.update"):a("i18n.updates")]})]}),(0,r.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:a("i18n.close")})]})]})})}let dt="global";function dn(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function dr(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function di(e){return`${e.scope}\0${e.source}`}function ds(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function da(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function dl(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function dd({pkg:e}){let{t}=(0,R.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function dc({scope:e}){return(0,r.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 du(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 dp({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,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,r.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 dh({installDir:e,source:t,busy:n,actionError:s,onSourceChange:a,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("i18n.addPlugin")}),(0,r.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,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:d,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=dr(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(dr(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()&&!n&&l()}})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,r.jsx)("button",{type:"button",onClick:l,disabled:n||!t.trim(),style:{...du(n||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:o(n?"i18n.installing":"i18n.install")})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>a(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))})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:s})]})}function dm({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:s,sessionId:a,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=di(e),u=n?.endsWith(c)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(dp,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(dc,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:d("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>l("update",e),disabled:u||p,style:du(u||p),children:d(n===`update:${c}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:o,disabled:!a||p||u,style:du(!a||p||u),title:d(a?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:du(u||p,!0),children:d(n===`remove:${c}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.status")}),(0,r.jsx)("div",{style:{color:dl(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:da(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:ds(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.installedPath")}),(0,r.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,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dn(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("i18n.resolvedResources")}),(0,r.jsx)(dd,{pkg:e})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function df({cwd:e,sessionId:t,onClose:n,onReloaded:s,embedded:a=!1}){let l=P(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[f,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=>di(e)===f)??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),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);c(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>di(t)===e)?e:n.packages[0]?di(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let L=(0,i.useCallback)(async(t,n)=>{let r=di(n);k(`${t}:${r}`),S(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);if(c(i),"remove"===t)g(i.packages[0]?di(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]),A=(0,i.useCallback)(async()=>{let t=dr(b).trim();if(!t)return;y(t);let n=`${dt}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:dt,cwd:e})}),l=await a.json();if(!a.ok||l.error)throw Error(l.error??`HTTP ${a.status}`);c(l);let d=(r=l.packages,s=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===dt&&e.source===i)??r.find(e=>e.scope===dt&&e.source===`npm:${s}`)??r.find(e=>e.scope===dt&&e.source.endsWith(i)));g(d?di(d):n),v(!1),y(""),N(o("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,o]),z=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await aL(t,{type:"reload"}),s?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,s,t,o]),W=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:a?"relative":"fixed",inset:a?void 0:0,width:"100%",height:"100%",zIndex:a?void 0:1e3,background:a?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{a||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:a?"100%":l?"calc(100vw - 16px)":860,maxWidth:a?"none":"calc(100vw - 16px)",height:a?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:a?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:a?"none":"1px solid var(--border)",borderRadius:8*!a,display:"flex",flexDirection:"column",boxShadow:a?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:dn(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===I.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):$.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.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=di(e),n=!x&&f===t;return(0,r.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:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:dl(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.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,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:da(e,o)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),o("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(dh,{installDir:d?.installDir,source:b,busy:W,actionError:j,onSourceChange:y,onInstall:A}):u?null:T?(0,r.jsx)(dm,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:z},di(T)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,r.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,r.jsx)("span",{children:d?`${d.totals.extensions} ext \xb7 ${d.totals.skills} skills \xb7 ${d.totals.prompts} prompts \xb7 ${d.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:du(u||null!==w),children:o("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:du(!1),children:o("i18n.close")})]})]})})}var dg=n(13004),dx=n.n(dg);function dv(){let[e,t]=(0,i.useState)(null),[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,f]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),l(null),d(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.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!==m)return void l("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),f(""),d(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[m,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,r.jsx)("div",{className:dx().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:dx().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.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,r.jsxs)("div",{className:dx().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),o&&(0,r.jsx)("div",{className:dx().reloadNotice,children:(0,r.jsx)("span",{children:o})})]}),(0,r.jsxs)("div",{className:dx().settingsBody,children:[(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:dx().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,r.jsx)("div",{className:dx().settingDescription,children:"Set a password below before turning this on."}),a&&(0,r.jsx)("div",{className:dx().error,children:a})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("button",{type:"button",className:dx().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,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:dx().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{className:dx().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:dx().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{className:dx().textInput,type:"password",autoComplete:"new-password",value:m,disabled:c||w,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,r.jsxs)("div",{className:dx().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:dx().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:dx().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:dx().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.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,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("a",{className:dx().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:dx().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,r.jsx)("div",{className:dx().settingControl})]})]})]})]})}let db="/api/live/character-voice",dy={ready:"chat.liveVoiceStateReady","not-prepared":"chat.liveVoiceStateNotPrepared",preparing:"chat.liveVoiceStatePreparing","needs-check":"chat.liveVoiceStateNeedsCheck",failed:"chat.liveVoiceStateFailed","missing-asset":"chat.liveVoiceStateMissingAsset"},dw={failed:!0,"needs-check":!0,"missing-asset":!0};async function dk(e){let t=await e.json().catch(()=>({}));if(!e.ok||!t||"object"!=typeof t||!("characters"in t))throw Error(t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message?t.message:`HTTP ${e.status}`);return t}function dj(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=(0,i.useCallback)(async()=>{try{a(await dk(await fetch(db,{cache:"no-store"})))}catch(t){o(t instanceof Error?t.message:e("chat.liveVoiceLoadFailed"))}},[e]);(0,i.useEffect)(()=>{f()},[f]);let g=s?.preparing===!0;(0,i.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>void f(),2e3);return()=>clearTimeout(e)},[g,s,f]);let x=(0,i.useCallback)(async e=>{m(!0),o(null);try{return a(await dk(await fetch(db,e))),!0}catch(e){return o(e instanceof Error?e.message:String(e)),!1}finally{m(!1)}},[]),v=async()=>{let e=d.trim();e&&await x({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e})})&&c("")};if(!s)return(0,r.jsx)("div",{className:dx().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"});let b=s.configured,y=l??s.lastError??null;return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:dx().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsxs)("div",{className:dx().settingsBody,children:[(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e("chat.liveVoiceKeyLabel")}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:t,className:dx().settingLabel,style:{display:"block"},children:e("chat.liveVoiceKeyLabel")}),(0,r.jsx)("div",{className:dx().settingDescription,children:e("chat.liveVoiceKeyHelp")}),b&&s.keyHint&&(0,r.jsx)("div",{className:dx().saveState,style:{overflowWrap:"anywhere"},children:e("chat.liveVoiceKeySaved",{hint:s.keyHint})})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{id:t,className:dx().textInput,type:"password",autoComplete:"off",spellCheck:!1,value:d,disabled:h,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&v()},placeholder:"sk_car_…"})})]}),(0,r.jsxs)("div",{className:dx().editorActions,children:[(0,r.jsx)("div",{}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8},children:[b&&(0,r.jsx)("button",{type:"button",className:dx().dangerButton,disabled:h||g,onClick:()=>void x({method:"DELETE"}),children:e("chat.liveVoiceKeyRemove")}),(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:h||!d.trim(),onClick:()=>void v(),children:e("chat.liveVoiceKeySave")})]})]})]}),(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e("chat.liveVoicePrepare")}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-start",minWidth:0},children:[(0,r.jsx)("input",{id:n,type:"checkbox",checked:u,onChange:e=>p(e.target.checked),style:{marginTop:3,flex:"none"}}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:n,className:dx().settingDescription,style:{display:"block",color:"var(--text)"},children:e("chat.liveVoiceConsent")}),(0,r.jsxs)("div",{className:dx().settingDescription,style:{marginTop:4},children:[e("chat.liveVoicePlanNote")," ",(0,r.jsx)("a",{href:"/audio/live/ACML-1.0.txt",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:e("chat.liveVoiceLicense")})]})]})]}),(0,r.jsx)("div",{className:dx().settingControl,style:{alignItems:"center"},children:(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:h||g||!b||!u,onClick:()=>void x({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prepare:!0,acknowledged:!0})}),"aria-busy":g,children:g?e("chat.liveVoicePreparing"):e("chat.liveVoicePrepare")})})]}),y&&(0,r.jsx)("div",{className:dx().error,role:"alert",style:{overflowWrap:"anywhere"},children:y})]}),(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:e("chat.liveVoiceCharacters")}),(0,r.jsx)("ul",{"aria-live":"polite",style:{listStyle:"none",margin:0,padding:0},children:s.characters.map(t=>(0,r.jsxs)("li",{className:dx().settingRow,style:{minHeight:44},title:t.error,children:[(0,r.jsxs)("div",{className:dx().settingLabel,style:{marginBottom:0},children:[t.alias,"provisional"===t.tuning&&(0,r.jsxs)("span",{className:dx().settingDescription,style:{fontWeight:400},children:[" \xb7 ",e("chat.liveVoiceProvisional")]})]}),(0,r.jsx)("div",{className:dx().settingControl,style:{fontSize:12,color:dw[t.state]?"var(--danger)":"ready"===t.state?"var(--text)":"var(--text-muted)"},children:e(dy[t.state])})]},t.id))})]})]})]})}function dS(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return sO({signal:e.signal}).then(e=>{a(e),o(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let f=(0,i.useCallback)(async e=>{p(!0),c(null),m(!1);try{let t=await sB(e);a(t),o(String(t.uploadLimitMb)),m(!0)}catch(e){c(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return s?(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:dx().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:dx().settingsBody,children:(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:dx().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:dx().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("input",{id:t,className:dx().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(s.uploadLimitMb))return;let n=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n<1){m(!1),c(e("chat.attachmentUploadLimitInvalid"));return}f({uploadLimitMb:n})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:dx().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:dx().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:s.orphanGraceDays})})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)("button",{type:"button",className:dx().switch,"data-on":s.autoCleanupEnabled,"aria-pressed":s.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!s.autoCleanupEnabled})})})]}),d&&(0,r.jsx)("div",{className:dx().error,role:"alert",style:{overflowWrap:"anywhere"},children:d}),h&&!d&&(0,r.jsx)("div",{className:dx().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:dx().empty,children:d?`${e("chat.attachmentSettingsLoadFailed")}: ${d}`:"…"})}function dC({cwd:e}){let{t}=(0,R.s)(),[n,s]=(0,i.useState)(null),[a,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[m,f]=(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,n,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 n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let i=e?`?include=${encodeURIComponent(e)}`:"",a=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),o=await a.json();if(n!==b.current||r.signal.aborted)return;if(!a.ok||!o.projects)throw Error(o.error??`HTTP ${a.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,s(o.projects),l(null),d&&f({cwd:d.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;l(e instanceof Error?e.message:String(e))}finally{y.current===r&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=n?.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},n=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",n),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[c,o,n,S,j]);let C=(0,i.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),d(null),x(e),f(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),i=await r.json();if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);let a=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=a,s(a),"cancel"===n?f({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(n=>({...n,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!n)return(0,r.jsxs)("div",{className:dx().empty,children:[a?t("trust.loadFailed",{error:a}):"…",a&&(0,r.jsx)("button",{type:"button",className:dx().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:dx().contentDescription,children:t("trust.settingsDescription")}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,r.jsx)("button",{type:"button",className:dx().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),a&&(0,r.jsx)("div",{className:dx().error,role:"alert",children:t("trust.loadFailed",{error:a})})]})]}),(0,r.jsx)("div",{className:dx().settingsBody,children:(0,r.jsxs)("section",{className:dx().group,children:[0===n.length&&(0,r.jsx)("div",{className:dx().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=c===e.cwd,s=o?.cwd===e.cwd?o:null,a=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,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:dx().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:dx().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,r.jsx)("span",{children:(n=e.cwd).split(/[\\/]/).filter(Boolean).pop()??n}),(0,r.jsx)("span",{className:dx().settingDescription,style:{fontWeight:600},children:a})]}),(0,r.jsx)("code",{className:dx().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:dx().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,r.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,r.jsx)("div",{className:dx().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:dx().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),s&&(0,r.jsx)("div",{className:dx().settingDescription,style:{color:"var(--text)"},children:"revoke"===s.action?t("trust.confirmRevoke"):s.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:dx().saveState,children:m.text})]}),l&&(0,r.jsx)("div",{className:dx().error,role:"alert",children:l})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:dx().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:s?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:dx().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{d(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===s.action?dx().dangerButton:dx().primaryButton,disabled:N,onClick:()=>void C(e.cwd,s.action),children:"revoke"===s.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:dx().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,r.jsx)("button",{type:"button",className:dx().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,r.jsx)("button",{type:"button",className:dx().dangerButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let dN=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이다"}}}'),dI=[{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"}],dT={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),attachments:(0,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.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,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.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,r.jsx)(r.Fragment,{children:(0,r.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,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function dM({kind:e}){return(0,r.jsx)("svg",{className:dx().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:dT[e]??dT.tools})}function d$({field:e,busy:t,onSave:n}){let[s,a]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{a("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:dx().textInput,type:"secret"===e.type?"password":"text",value:s,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>a(e.target.value),onBlur:()=>{s!==l&&("secret"!==e.type||s.length>0)&&n(s)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function dR({field:e,busy:t,onSave:n}){let s=JSON.stringify(e.value??{},null,2),[a,l]=(0,i.useState)(s),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(s),d(null)},[s]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:dx().jsonEditor,style:{minHeight:92},value:a,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(a!==s)try{n(JSON.parse(a)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,r.jsx)("div",{className:dx().error,children:o})]})}function dE({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],s=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let s=[...i];[s[e],s[r]]=[s[r],s[e]],n(s)};return(0,r.jsx)("div",{className:dx().multiSelect,children:e.options?.map(a=>{let l=i.indexOf(a.value);return(0,r.jsxs)("span",{className:dx().choice,"data-selected":l>=0,title:a.description,children:[(0,r.jsx)("button",{type:"button",className:dx().choiceToggle,disabled:t,onClick:()=>{let e;return e=a.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:a.label}),e.ordered&&l>=0&&(0,r.jsxs)("span",{className:dx().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>s(l,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>s(l,1),children:"→"})]})]},a.value)})})}function dL({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:dx().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(l3,{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=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(dE,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(dR,{field:e,busy:t,onSave:n}):(0,r.jsx)(d$,{field:e,busy:t,onSave:n})}function dA({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:dx().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:dx().settingLabel,children:e.label}),(0,r.jsx)("div",{className:dx().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:dx().error,children:n})]}),(0,r.jsx)("div",{className:dx().settingControl,children:(0,r.jsx)(dL,{field:e,busy:t,onSave:i})})]})}function dz({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:dx().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:dx().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:dx().themePreviewPanel,children:[(0,r.jsx)("div",{className:dx().themePreviewLine}),(0,r.jsx)("div",{className:dx().themePreviewLine})]})]})}let dW='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',dP=new Set(["hideThinkingBlock"]);function dF({cwd:e,sessionId:t,initialSection:n="models",onClose:s,onModelsChanged:a,onReloaded:l}){let[o,d]=(0,i.useState)(n),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,f]=(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}=tD(),{locale:T,t:M}=(0,R.s)(),$=(0,i.useRef)(null),E=e=>"ko"===T?dN.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(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(dW)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(dW)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let A=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await t_(e),await L()):dP.has(t.path)?await t4(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,L]),z=(0,i.useMemo)(()=>new Map(c?.fields.map(e=>[e.path,e.value])??[]),[c?.fields]),W=(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,z))??[],[c?.fields,z]),P=o.startsWith("settings:")?o.slice(9):null,F=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?W.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):P?W.filter(e=>e.tab===P&&("appearance"!==P||"Theme"!==e.group)):[]},[P,g,W]),_=(0,i.useCallback)(()=>{a?.(),s()},[s,a]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await aL(t,{type:"reload"}),j(!1),l?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),H=c?.tabs.find(e=>e.id===P),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 n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:dx().group,children:[(0,r.jsx)("h3",{className:dx().groupTitle,children:t}),n.map(e=>(0,r.jsx)(dA,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void A(e,t)},e.path))]},t):null}),U=()=>p?(0,r.jsx)("div",{className:dx().empty,children:E("Loading omp settings…")}):m||!c?(0,r.jsx)("div",{className:dx().empty,children:m??E("Settings unavailable")}):(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:O}),(0,r.jsx)("p",{className:dx().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,r.jsxs)("div",{className:dx().reloadNotice,children:[(0,r.jsx)("span",{children:E("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:E(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:dx().settingsBody,children:F.length?B(F,H?.groups??[]):(0,r.jsx)("div",{className:dx().empty,children:E("No settings match this search.")})})]});return(0,r.jsx)("div",{className:dx().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&_()},children:(0,r.jsxs)("div",{ref:$,tabIndex:-1,className:dx().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,r.jsxs)("aside",{className:dx().sidebar,children:[(0,r.jsxs)("div",{className:dx().brand,children:[(0,r.jsx)("div",{className:dx().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:dx().title,children:E("Settings")}),(0,r.jsx)("code",{className:dx().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,r.jsxs)("div",{className:dx().searchWrap,children:[(0,r.jsxs)("svg",{className:dx().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:dx().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:dx().nav,children:[(0,r.jsx)("div",{className:dx().navLabel,children:E("Configuration")}),dI.map(t=>{let n=t.labelKey?M(t.labelKey):E(t.label);return(0,r.jsxs)("button",{type:"button",className:dx().navButton,"data-active":!g&&o===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${E("requires a project")}`:n,onClick:()=>{x(""),d(t.id)},children:[(0,r.jsx)(dM,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:dx().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:dx().navButton,"data-active":!g&&P===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,r.jsx)(dM,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:dx().closeRail,children:(0,r.jsxs)("button",{type:"button",className:dx().closeButton,onClick:_,children:[(0,r.jsx)("span",{children:E("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:dx().content,children:g.trim()?U():"models"===o?(0,r.jsx)(o1,{cwd:e,embedded:!0,onClose:_,onModelsChanged:a}):"themes"===o?c?(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:E("Themes")}),(0,r.jsxs)("p",{className:dx().contentDescription,children:[E("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),E(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:dx().settingsBody,children:[(0,r.jsx)("div",{className:dx().themeGrid,children:["dark","light"].map(e=>{let t=c.fields.find(t=>t.path===`theme.${e}`),n=c.theme.palettes[e];return(0,r.jsxs)("div",{className:dx().themeCard,children:[(0,r.jsx)(dz,{mode:e,palette:n}),(0,r.jsxs)("div",{className:dx().themeCardBody,children:[(0,r.jsxs)("div",{className:dx().themeCardHeader,children:[(0,r.jsxs)("span",{className:dx().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,r.jsx)("span",{className:dx().themeActive,children:E("Active on web")})]}),(0,r.jsx)(l3,{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 A(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:dx().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,r.jsx)("div",{className:dx().empty,children:p?E("Loading themes…"):m??E("Themes unavailable")}):"skills"===o&&e?(0,r.jsx)(de,{cwd:e,embedded:!0,onClose:_}):"plugins"===o&&e?(0,r.jsx)(df,{cwd:e,sessionId:t,embedded:!0,onClose:_,onReloaded:l}):"mcp"===o?(0,r.jsx)(d_,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,r.jsx)(dv,{}):"trust"===o?(0,r.jsx)(dC,{cwd:e}):"live-voice"===o?(0,r.jsx)(dj,{}):"attachments"===o?(0,r.jsx)(dS,{}):U()})]})})}function d_({cwd:e,sessionId:t,onReloaded:n}){let[s,a]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[f,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)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);a(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=s?"user"===l?s.user:s.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{a(t=>{if(!t)return t;let n={..."user"===l?t.user:t.project,servers:e};return"user"===l?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(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}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,servers:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${l}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",s=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:r.name,enabled:!r.enabled})}),a=await s.json();if(!s.ok||a.error)throw Error(a.error??`HTTP ${s.status}`);await w(),t&&(await aL(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:dx().scrollContent,children:[(0,r.jsxs)("header",{className:dx().contentHeader,children:[(0,r.jsx)("h2",{className:dx().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:dx().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,r.jsx)("div",{className:dx().settingsBody,children:s?(0,r.jsxs)("div",{className:dx().mcpLayout,children:[(0,r.jsxs)("aside",{className:dx().mcpList,children:[(0,r.jsxs)("div",{className:dx().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:dx().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",s.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:dx().scopeButton,"data-active":"project"===l,disabled:!s.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",s.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:dx().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:dx().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${l}:${e.name}`;return(0,r.jsxs)("div",{className:dx().serverRow,"data-active":d===t,children:[(0,r.jsxs)("button",{type:"button",className:dx().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,r.jsx)("span",{className:dx().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:dx().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:dx().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:dx().serverToggle,"data-on":e.enabled,disabled:b===n,"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===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:dx().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:dx().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 n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),c(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:dx().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:dx().editorHeader,children:[(0,r.jsx)("input",{className:dx().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:dx().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,r.jsxs)("div",{className:dx().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:dx().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:dx().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:dx().error,children:f}),(0,r.jsx)("div",{className:dx().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:dx().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:dx().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:dx().empty,children:f??"Loading MCP configuration…"})})]})}let dD="cuelo-notification-prompt-dismissed";function dH({variant:e,locale:t,permission:n,dismissed:i,request:s,dismiss:a}){let l="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||i?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":l?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:l?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,children:l?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,r.jsx)(d.k.Item,{disabled:"denied"===n,onClick:"default"===n?s:void 0,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:"default"===n?l?"알림 켜기":"Enable notifications":l?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(d.k.ItemDescription,{children:l?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function dO({cwd:e,busy:t,scheduled:n,error:s,onCancel:a,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:5,cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.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||a()},children:(0,r.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,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:d(n?"trust.scheduledTitle":"trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:d(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.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}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:s})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.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,r.jsx)("button",{ref:c,type:"button",onClick:a,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d(n?"trust.close":"trust.cancel")}),!n&&(0,r.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 dB=n(55681),dU=n(54265);let dq={kind:"loading"};function dK(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,nU.Ch)(e.status)?"var(--accent)":"var(--success)"}function dV(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let dJ={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function dG(e){return e.lastUpdate||e.progress?.durationMs||0}function dY(){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 dZ({sessionId:e,sessionCwd:t,record:n,client:s,visible:a,onBack:l}){let o=(0,i.useMemo)(()=>[{key:n.key,liveId:n.live?.id,status:n.live?.status,archiveName:n.archive?.name}],[n.key,n.live?.id,n.live?.status,n.archive?.name]),d=(0,i.useRef)(null),c=(0,nU._Z)(o,{sessionId:e,client:s,enabled:a}).get(n.key)?.state??dq;(0,i.useEffect)(()=>{if(!a||"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,a]);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=n.live?.id||n.archive?.name||"Subagent";return(0,r.jsxs)("div",{role:"dialog","aria-label":`${h} 기록`,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:l,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:dY(),children:(0,r.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,r.jsx)("path",{d:"m10.5 3-5 5 5 5"})})}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontWeight:700},children:h}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:dV(n)})]}),n.live&&(0,r.jsx)("span",{style:{color:dK(n.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:n.live.status})]}),(0,r.jsxs)("div",{ref:d,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===c.kind&&(0,r.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,n)=>{if(!("message"in e))return[];let i=c.entries[n-1];return[(0,r.jsx)(rE,{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,r.jsxs)(r.Fragment,{children:[c.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:c.note}),c.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),c.entries.map((e,t)=>(0,r.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,r.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,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[c.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:c.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===c.kind&&(0,r.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,r.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 dX({record:e,view:t,onSelect:n}){let{st:s}=nu(),a=(0,i.useId)(),l=e.live,o=e.archive,d=(0,nS.$V)(e),c=!!(l&&(0,nU.Ch)(l.status)),u=c?d.stage:null,p=c&&t?t:null,h=p?.phase?s("phase.current",{phase:s(`phase.${p.phase}`)}):"",m=p?.todo?nY(s,p.todo):"",f=l?.id||o?.name||"Subagent",g=dV(e),x=(0,nS.wX)(e),v=(0,nS.A7)(e),b=v.modelShort??"모델 미확인",y=v.effort??"추론 미확인",w="known"===x.kind?x.label:"역할 미확인";return(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:n,"data-identity":e.identity,title:`${f}
20
20
  ${v.model??"모델 미확인"} \xb7 ${y}
21
21
  ${d.title}${u?`
22
22
  현재 단계: ${u}`:""}${h?`