cuelo 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +9 -9
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +2 -2
  6. package/.next/required-server-files.json +2 -2
  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 +9 -9
  62. package/.next/server/chunks/1008.js +1 -1
  63. package/.next/server/chunks/5489.js +2 -2
  64. package/.next/server/chunks/6429.js +1 -1
  65. package/.next/server/middleware-build-manifest.js +1 -1
  66. package/.next/server/pages/404.html +1 -1
  67. package/.next/server/pages/500.html +1 -1
  68. package/.next/server/server-reference-manifest.json +1 -1
  69. package/.next/static/chunks/{9575-6f450839544bc6b3.js → 9575-9196474bb9e5c752.js} +2 -2
  70. package/.next/static/chunks/app/{layout-d8c1b10303bcd958.js → layout-713017c65de14601.js} +1 -1
  71. package/.next/trace +108 -108
  72. package/.next/trace-build +1 -1
  73. package/README.md +4 -1
  74. package/Tools/CUELO_Setup/files/native-runtime-patch.js +3 -3
  75. package/Tools/OMP_Global_Config/agent/RULES.md +4 -0
  76. package/Tools/OMP_Global_Config/agent/agents/maker.md +12 -6
  77. package/Tools/OMP_Global_Config/agent/extensions/character-voice.ts +3 -3
  78. package/Tools/OMP_Global_Config/agent/extensions/command-guard/index.ts +16 -1
  79. package/Tools/OMP_Global_Config/agent/extensions/command-guard/powershell-syntax.ts +5 -4
  80. package/Tools/OMP_Global_Config/agent/extensions/draft/markdown.ts +226 -0
  81. package/Tools/OMP_Global_Config/agent/extensions/draft/ooxml.ts +222 -0
  82. package/Tools/OMP_Global_Config/agent/extensions/draft/pdf.ts +63 -0
  83. package/Tools/OMP_Global_Config/agent/extensions/draft/zip.ts +73 -0
  84. package/Tools/OMP_Global_Config/agent/extensions/draft.ts +211 -0
  85. package/Tools/OMP_Global_Config/agent/extensions/jev-runtime.ts +1 -1
  86. package/Tools/OMP_Global_Config/agent/extensions/lib/maker-routing.ts +16 -47
  87. package/Tools/OMP_Global_Config/agent/extensions/mcp-selection.ts +32 -8
  88. package/Tools/OMP_Global_Config/agent/extensions/skim.ts +75 -43
  89. package/Tools/OMP_Global_Config/agent/prompt-copies/RULES.en.md +2 -1
  90. package/Tools/OMP_Global_Config/agent/rules/harness-policy.json +5 -6
  91. package/Tools/OMP_Global_Config/agent/rules/omp-harness.md +1 -1
  92. package/Tools/OMP_Global_Config/agent/rules/subagent.md +18 -14
  93. package/Tools/OMP_Global_Config/agent/sop/_common.md +4 -4
  94. package/Tools/OMP_Global_Config/agent/sop/_writer.md +6 -0
  95. package/Tools/OMP_Global_Config/agent/sop/maker.md +1 -1
  96. package/Tools/OMP_Global_Config/agent/tools/git-finalizer/index.ts +46 -3
  97. package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +182 -0
  98. package/bin/cuelo.js +5 -0
  99. package/package.json +7 -7
  100. /package/.next/static/{MYIe6QFbh4yP3_wc_Fetr → S8tJkE71e2D0DgH4X1s0S}/_buildManifest.js +0 -0
  101. /package/.next/static/{MYIe6QFbh4yP3_wc_Fetr → S8tJkE71e2D0DgH4X1s0S}/_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:()=>a,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},32321:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>uU});var r=n(95155),i=n(12115),a=n(73321),s=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 z=L("(max-width: 640px)"),A=L(E);function W(){return!1}function P(){return(0,i.useSyncExternalStore)(z.subscribe,z.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 O(){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 H({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(!0),j=(0,i.useCallback)(async e=>{k(!0),y(null);try{let t=await _(e),n=t.path??e??"/";c(n),p(t.parentPath??null),m(n),g(t.directories??[]),v(t.drives??null)}catch(e){y(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),j()},[j]);let S=h.trim()!==d,C=!!d&&!S&&!n,N=!!u||/^[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":s("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:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=h.trim();t&&j(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 j(u??void 0),disabled:w||!N,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:N?"pointer":"default",opacity:N?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:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:h,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{m(e.target.value),y(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:w||!h.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!h.trim()?"default":"pointer",opacity:w||!h.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==x?(0,r.jsx)(r.Fragment,{children:x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(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)(O,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):f.length>0?f.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(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:s("directoryPicker.noSubdirectories")}),(b||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:b??a})]}),(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:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!C,title:s(S?"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:C?1:.6,cursor:C?"pointer":"default"},children:s(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:a}){let{t:s}=(0,R.s)(),l=(0,i.useRef)(null),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[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",z=n||S,A=(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()&&!z){C(!0),I(null);try{let{cwd:e}=await q("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{d(!0),A()},[A]),(0,i.useEffect)(()=>{if(!o||c)return;let e=l.current;return e?.showModal(),()=>e?.close()},[o,c]),(0,i.useEffect)(()=>{let e;if(!L||c)return;let t=!1,n=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await A();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[L,c,A]),!o)return null;if(c)return(0,r.jsx)(H,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??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(),z||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:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:U().sources,children:[(0,r.jsx)("span",{className:U().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:z,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:U().body,children:[(0,r.jsxs)("section",{className:U().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:y||z,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void W(),disabled:y||k||L||z,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:U().login,role:"status",children:[(0,r.jsx)("p",{children:s("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(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:U().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:z}),y?(0,r.jsx)("p",{role:"status",children:s("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:z,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?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),_.length>$&&(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:U().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("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:z,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:U().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:z,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:U().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:U().footer,children:[(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:z,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:U().primary,disabled:z||!v.trim(),children:z?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){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:'"Plus Jakarta Sans", Geist, ui-sans-serif, system-ui, sans-serif',fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},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[a,s]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(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,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:en[Math.floor(Math.random()*en.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.0/18.8.0":"CUELO",n),o=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;o(t),t&&(s.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,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)",minWidth:"6ch"},children:(0,r.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",letterSpacing:"-0.01em"}: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 ea({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,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,z]=(0,i.useState)(!0),[A,W]=(0,i.useState)(null),[F,_]=(0,i.useState)(null),[D,O]=(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),[ez,eA]=(0,i.useState)(null),[eW,eP]=(0,i.useState)(""),[eF,e_]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,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}})()),[ta,ts]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ts(function(){try{let e=window.localStorage.getItem(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&&z(!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&&z(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),ts(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),ts(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===ta.size?window.localStorage.removeItem(Y):window.localStorage.setItem(Y,JSON.stringify([...ta]))}catch{}},[ta]);let tI=(0,i.useCallback)(e=>{ts(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 a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;to.current=!0,tn(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(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&&O(e.home),U(!0===e.cloudProjects)}).catch(()=>{})},[]);let tT=(0,i.useRef)(!1),tM=(0,i.useCallback)(e=>{if(!e)return null;if(eU&&eU.forCwd===e||eU?.worktrees.some(t=>t.path===e))return eU.projectRoot;let t=E.find(t=>t.cwd===e);return t?.projectRoot??e},[eU,E]),t$=(0,i.useRef)(null);(0,i.useEffect)(()=>{t$.current!==F&&(t$.current=F,p?.(F,tM(F)))},[F,p,tM]);let tR=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tR.current&&(tR.current=u,_(u))},[u]);let[tE,tL]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!F)return void eq(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(F)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eq(null);eq({forCwd:F,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eq(null)}),()=>{e=!0}},[F,tE,d]),(0,i.useEffect)(()=>{if(0!==M.length&&!l&&null===F){if(s&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===s);if(e){_(e.cwd),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,s,l,n,o,ey,ek]);let tz=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eH){eB(!0),eO(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 eO(n.error??b("workspace.unable"));let r=n.cwd??t,i=N(r),a=ey.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tu([{key:i,path:r,hidden:!1}])}catch{}_(r),e_(!1)}catch{eO(b("workspace.unable"))}finally{eB(!1)}}},[tu,eH,ey.projects,b]),tA=(0,i.useCallback)(()=>{e_(!0),eO(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),a?.(t,e)},[F,a]),[tD,tO]=(0,i.useState)(!1),[tH,tB]=(0,i.useState)(null),tU=(0,i.useCallback)(async()=>{tO(!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{tO(!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);eA(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{eA(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let n=tZ.indexOf(e),r=n+t;if(n<0||r<0||r>=tZ.length)return;let i=new Set(tZ),a=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...tY],l=a[n],o=a[r];[s[l],s[o]]=[s[o],s[l]],tQ();try{await tu(s.map((e,t)=>({key:N(e),path:e,order:t})))}catch{}},t4=new Map;for(let e of E){let t=e.projectRoot??e.cwd;if(!t)continue;let 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,a=(t4.get(n)??[]).slice().sort((e,t)=>{let n=Number(ta.has(t.id))-Number(ta.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t8)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(t8)||t.toLowerCase().includes(t8),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t8));return s||0!==l.length?[{project:e,key:n,name:i,sessions:s?a: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",a=new Set,s="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=>a.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let 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:s,running:!1,sessions:o}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ta,b("sidebar.pinned")),[y,ta,tt,E,b]),na=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),ns=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:H,{busy:eH,error:eD,onCancel:()=>{e_(!1),eO(null)},onSelect:e=>void tz(e)}),tm&&(0,r.jsx)(es,{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"},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:tA,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,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:tA,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,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")}),A&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),ez&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:ez}),!L&&ek&&!A&&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&&!A&&nn.map(t=>{let n,i,a;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:s,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=nr.has(o.toLowerCase())&&Q((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),D)||null,h=!em.has(s)&&!t8,m=eu.has(s),f=eT===s,g=tZ.indexOf(s),x=eE||t6||g<=0,v=eE||t6||g>=tZ.length-1,y=function(e){let t=new Map;for(let 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===s?e5:void 0,onMouseEnter:()=>ex(s),onMouseLeave:()=>ex(e=>e===s&&ev!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>tq(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,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(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e3.current=!0,eM(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,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_(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||eg===s?1:0,pointerEvents:w||eg===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,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===s?null:s),eV(!1),eG(!1),eQ(null),u||_(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===s?"var(--bg-selected)":"transparent",color:u&&ns&&!ns.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===s||ev===s?1:0,pointerEvents:w||eg===s||ev===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(s),children:(0,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===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[na&&eU&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:ns?b("sidebar.switchWorktreeTitle",{path:ns.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(s))?.alias??"",void(e3.current=!1,eA(null),eR(e),eM(s),tQ())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,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(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,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(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,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(s,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,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")]}),(a=0===nu(t4.get(l)??[])||tg,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{tQ(),tb(null),tf({kind:"project",project:s,label:o})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,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:ta,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(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!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")}),A&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),!L&&!A&&(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")})]})),tH&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tH}),!L&&!A&&0===ni.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!A&&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:ta.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function es({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let 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],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&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=>{a||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")})]}),s&&(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:s})]}),(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:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function 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:a,onSelect:s,onTogglePin:l}){let{t:o}=(0,R.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,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:()=>s(e),title:`${d}
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9575],{13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},32321:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>uU});var r=n(95155),i=n(12115),a=n(73321),s=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 z=L("(max-width: 640px)"),A=L(E);function W(){return!1}function P(){return(0,i.useSyncExternalStore)(z.subscribe,z.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 O(){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 H({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(!0),j=(0,i.useCallback)(async e=>{k(!0),y(null);try{let t=await _(e),n=t.path??e??"/";c(n),p(t.parentPath??null),m(n),g(t.directories??[]),v(t.drives??null)}catch(e){y(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),j()},[j]);let S=h.trim()!==d,C=!!d&&!S&&!n,N=!!u||/^[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":s("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:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=h.trim();t&&j(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 j(u??void 0),disabled:w||!N,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:N?"pointer":"default",opacity:N?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:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:h,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{m(e.target.value),y(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:w||!h.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!h.trim()?"default":"pointer",opacity:w||!h.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==x?(0,r.jsx)(r.Fragment,{children:x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(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)(O,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):f.length>0?f.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void j(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:s("directoryPicker.noSubdirectories")}),(b||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:b??a})]}),(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:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!C,title:s(S?"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:C?1:.6,cursor:C?"pointer":"default"},children:s(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:a}){let{t:s}=(0,R.s)(),l=(0,i.useRef)(null),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[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",z=n||S,A=(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()&&!z){C(!0),I(null);try{let{cwd:e}=await q("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{d(!0),A()},[A]),(0,i.useEffect)(()=>{if(!o||c)return;let e=l.current;return e?.showModal(),()=>e?.close()},[o,c]),(0,i.useEffect)(()=>{let e;if(!L||c)return;let t=!1,n=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await A();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[L,c,A]),!o)return null;if(c)return(0,r.jsx)(H,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??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(),z||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:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:U().sources,children:[(0,r.jsx)("span",{className:U().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:z,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:U().body,children:[(0,r.jsxs)("section",{className:U().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:y||z,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void W(),disabled:y||k||L||z,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:U().login,role:"status",children:[(0,r.jsx)("p",{children:s("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(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:U().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:z}),y?(0,r.jsx)("p",{role:"status",children:s("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:z,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?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),_.length>$&&(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:U().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("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:z,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:U().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void A(),disabled:z,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:U().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:U().footer,children:[(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:z,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:U().primary,disabled:z||!v.trim(),children:z?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){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:'"Plus Jakarta Sans", Geist, ui-sans-serif, system-ui, sans-serif',fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},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[a,s]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(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,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:en[Math.floor(Math.random()*en.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.2/18.8.6":"CUELO",n),o=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;o(t),t&&(s.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,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)",minWidth:"6ch"},children:(0,r.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",letterSpacing:"-0.01em"}: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 ea({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,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,z]=(0,i.useState)(!0),[A,W]=(0,i.useState)(null),[F,_]=(0,i.useState)(null),[D,O]=(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),[ez,eA]=(0,i.useState)(null),[eW,eP]=(0,i.useState)(""),[eF,e_]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,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}})()),[ta,ts]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ts(function(){try{let e=window.localStorage.getItem(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&&z(!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&&z(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),ts(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),ts(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===ta.size?window.localStorage.removeItem(Y):window.localStorage.setItem(Y,JSON.stringify([...ta]))}catch{}},[ta]);let tI=(0,i.useCallback)(e=>{ts(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 a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;to.current=!0,tn(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(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&&O(e.home),U(!0===e.cloudProjects)}).catch(()=>{})},[]);let tT=(0,i.useRef)(!1),tM=(0,i.useCallback)(e=>{if(!e)return null;if(eU&&eU.forCwd===e||eU?.worktrees.some(t=>t.path===e))return eU.projectRoot;let t=E.find(t=>t.cwd===e);return t?.projectRoot??e},[eU,E]),t$=(0,i.useRef)(null);(0,i.useEffect)(()=>{t$.current!==F&&(t$.current=F,p?.(F,tM(F)))},[F,p,tM]);let tR=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tR.current&&(tR.current=u,_(u))},[u]);let[tE,tL]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!F)return void eq(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(F)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eq(null);eq({forCwd:F,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eq(null)}),()=>{e=!0}},[F,tE,d]),(0,i.useEffect)(()=>{if(0!==M.length&&!l&&null===F){if(s&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===s);if(e){_(e.cwd),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,s,l,n,o,ey,ek]);let tz=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eH){eB(!0),eO(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 eO(n.error??b("workspace.unable"));let r=n.cwd??t,i=N(r),a=ey.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tu([{key:i,path:r,hidden:!1}])}catch{}_(r),e_(!1)}catch{eO(b("workspace.unable"))}finally{eB(!1)}}},[tu,eH,ey.projects,b]),tA=(0,i.useCallback)(()=>{e_(!0),eO(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),a?.(t,e)},[F,a]),[tD,tO]=(0,i.useState)(!1),[tH,tB]=(0,i.useState)(null),tU=(0,i.useCallback)(async()=>{tO(!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{tO(!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);eA(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{eA(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let n=tZ.indexOf(e),r=n+t;if(n<0||r<0||r>=tZ.length)return;let i=new Set(tZ),a=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...tY],l=a[n],o=a[r];[s[l],s[o]]=[s[o],s[l]],tQ();try{await tu(s.map((e,t)=>({key:N(e),path:e,order:t})))}catch{}},t4=new Map;for(let e of E){let t=e.projectRoot??e.cwd;if(!t)continue;let 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,a=(t4.get(n)??[]).slice().sort((e,t)=>{let n=Number(ta.has(t.id))-Number(ta.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t8)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(t8)||t.toLowerCase().includes(t8),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t8));return s||0!==l.length?[{project:e,key:n,name:i,sessions:s?a: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",a=new Set,s="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=>a.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let 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:s,running:!1,sessions:o}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ta,b("sidebar.pinned")),[y,ta,tt,E,b]),na=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),ns=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:H,{busy:eH,error:eD,onCancel:()=>{e_(!1),eO(null)},onSelect:e=>void tz(e)}),tm&&(0,r.jsx)(es,{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"},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:tA,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,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:tA,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,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")}),A&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),ez&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:ez}),!L&&ek&&!A&&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&&!A&&nn.map(t=>{let n,i,a;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:s,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=nr.has(o.toLowerCase())&&Q((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),D)||null,h=!em.has(s)&&!t8,m=eu.has(s),f=eT===s,g=tZ.indexOf(s),x=eE||t6||g<=0,v=eE||t6||g>=tZ.length-1,y=function(e){let t=new Map;for(let 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===s?e5:void 0,onMouseEnter:()=>ex(s),onMouseLeave:()=>ex(e=>e===s&&ev!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>tq(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,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(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e3.current=!0,eM(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,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_(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||eg===s?1:0,pointerEvents:w||eg===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,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===s?null:s),eV(!1),eG(!1),eQ(null),u||_(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===s?"var(--bg-selected)":"transparent",color:u&&ns&&!ns.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===s||ev===s?1:0,pointerEvents:w||eg===s||ev===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(s),children:(0,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===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[na&&eU&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:ns?b("sidebar.switchWorktreeTitle",{path:ns.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(s))?.alias??"",void(e3.current=!1,eA(null),eR(e),eM(s),tQ())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,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(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t6?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,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(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,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(s,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,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")]}),(a=0===nu(t4.get(l)??[])||tg,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{tQ(),tb(null),tf({kind:"project",project:s,label:o})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,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:ta,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(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!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")}),A&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:A}),!L&&!A&&(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")})]})),tH&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tH}),!L&&!A&&0===ni.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!A&&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:ta.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function es({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let 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],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&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=>{a||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")})]}),s&&(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:s})]}),(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:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function 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:a,onSelect:s,onTogglePin:l}){let{t:o}=(0,R.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,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:()=>s(e),title:`${d}
2
2
  ${e.cwd}
3
3
  ${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,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":a,"aria-label":o(a?"sidebar.unpin":"sidebar.pin"),title:o(a?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:a?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(el,{filled:a})})]})}function ed({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let 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})}),a(t)}catch{}},[a]);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"})}),s("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:s("sidebar.noArchivedSessions")}),d.map(e=>{let i=$(e.firstMessage)??e.firstMessage,a=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,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:a}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function ec({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,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:a.has(e.session.id),isPinned:s.has(e.session.id),onClick:()=>l(e.session),onTogglePin:()=>c(e.session.id),onRenamed:o,onDeleted:e=>d?.(e),onArchived:e=>u?.(e),depth:p,hasChildren: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:a,pinnedSessionIds:s,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:a,isPinned:s,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]),z=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),c?.(e.id)}catch{N(!1)}}},[e.id,e.transient,c]),A=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),W=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?z():S(!0)},[z]),P=(0,i.useCallback)(e=>{e.stopPropagation(),z()},[z]),F=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),_=(0,i.useCallback)(t=>{(function(e,t=window){let 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":""}${a?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:l,onContextMenu:j||b?void 0:_,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||b?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,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&&a&&(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(s?"sidebar.unpin":"sidebar.pin"),"aria-label":g(s?"sidebar.unpin":"sidebar.pin"),"aria-pressed":s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:s?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(el,{filled:s})}),(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:A,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,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 a=e,s=eS(a);("│"===s||"┃"===s)&&" "===eS(a=ej(a,0))&&(a=ej(a,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}(a),o=l>=0?ek(a)[l]?.char:void 0;("│"===o||"┃"===o)&&(a=ej(a,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)}}(a))}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,a,s]=[t[e+2],t[e+3],t[e+4]];[i,a,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${a}, ${s})`:n.backgroundColor=`rgb(${i}, ${a}, ${s})`),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 ez(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 eA(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=>!ez(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 a of i)"toolCall"===a.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let 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))}(a,t.get(a.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:a.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,eO=new Map,eH="command",eB="autolearn-saved";function eU(e){return"custom"===e.role&&(e.customType===eH||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=[],a=[];for(let n=0;n<e.length;n++){let s=n<t.length;!(r.has(e[n])||s&&eK(t[n]))&&(i.push(e[n]),s&&a.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=a.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<=a.length&&a.splice(t,0,e.entryId)}return{messages:i,entryIds:a}}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,a=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){a.length>0&&".."!==a[a.length-1]?a.pop():i||n||r||a.push(e);continue}a.push(e)}let s=a.join("/");return n?s:r?`//${s}`:i?`/${s}`:s}function e2(e,t,n=t){let r,i,a,s,l;if(!e)return null;let o=e.split("#",1)[0].split("?",1)[0].trim();if(!o)return null;let d=null,c=null,u=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(/\/+$/,""),s=(a=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(s===(l=a?i.toLowerCase():i)||s.startsWith(`${l}/`)))?null:f}function e4(e,t,n){let r=new Set,i=[];for(let a of e){if("toolCall"!==a.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")}(a.toolName))continue;let e=t?.get(a.toolCallId);if(!e||e.isError)continue;let s=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(a.input);if(!s||!/^[a-zA-Z]:[\\/]/.test(s)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(s))continue;let l=function(e,t){let 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,a=i(e),s=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(a),o=a.startsWith("//");if(l||o)n=a;else if(a.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${a}`:a}else{if(!s)return null;n=`${s}/${a}`}return e1(n)}(s,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"}}var e8=n(65063),e6=n(7644),e3=n(32316);function e7(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e9(e){return e7(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function te(e){let t=e7(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tt(e,t){if(!t)return e;let n=e7(e),r=e7(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var tn=n(88374),tr=n(63280),ti=n(94764),ta=n(63835),ts=n(54152),tl=n(84678),to=n(98164);let td={...ti.j,attributes:{...ti.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...ti.j.strip||[],"iframe","object","style","form"]};function tc(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,a=0,s=null,l=new Map;for(let e=0;e<n.length;e++){var o;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let d=t.match(/^ {0,3}(`{3,}|~{3,})/);if(d){let e=d[1][0],n=d[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},a=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)||(s=e),a=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){a=0,r.push(t);continue}if(a||t.includes("`")){a=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,a),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=>tp(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 a=tu(n,e+1,t,l);if(a){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<a.index;i++)r.push(tp(n[i],t));a.content&&r.push(`${t}${a.content}`),r.push(`${t}$$`),e=a.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],i=tu(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let a=e+1;a<i.index;a++)r.push(tp(n[a],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 tu(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 a,s,l,o;let t=e[i];if(a=t,""===(s=n)?/^ {0,3}\$\$\s*$/.test(a):a.startsWith(s)&&/^\$\$\s*$/.test(a.slice(s.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(o=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(o)))return 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 tp(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let th={singleTilde:!1},tm=[[ts.A,["yaml"]],[tl.A,th],to.A],tf=[[ts.A,["yaml"]],[tl.A,th],to.A],tg=[tr.A,[ta.A,td],[tn.A,{throwOnError:!1,strict:!1}]],tx=[tr.A,[ta.A,td],[tn.A,{throwOnError:!1,strict:!1}]],tv="pi-theme",tb=["light","dark","auto"],ty={preference:"auto",theme:"light"},tw="omp-theme",tk=null,tj=0,tS=new Set,tC=null,tN=!1;function tI(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tT(e){return"auto"===e?tI():e}let tM="--omp-md-";function t$(e){let t=document.documentElement,n=tk?.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(tM)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(tM)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tw,e)}catch{}}function tR(){if(tC)return tC;let e=function(){try{let e=localStorage.getItem(tv);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tw);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=tT(e);return t$(t),tC={preference:e,theme:t}}function tE(e,t,n){if(t$(t),n)try{localStorage.setItem(tv,e)}catch{}tC={preference:e,theme:t},tS.forEach(e=>e())}function tL(){let e=tR();if("auto"!==e.preference)return;let t=tI();t!==e.theme&&tE("auto",t,!1)}function tz(e){return tS.add(e),tR(),tN||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tL),window.addEventListener("focus",tL),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tL()}),tN=!0),tL(),()=>{tS.delete(e)}}function tA(){return tR()}function tW(){return ty}async function tP(e){let t=++tj,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===tj){tk=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(tk))}catch{}t$(tR().theme)}}function tF(e){let t=(0,i.useSyncExternalStore)(tz,tA,tW);(0,i.useEffect)(()=>{e?.syncWithOmp&&tP(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=tT(e),r=()=>{tE(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let a=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(a,window.innerWidth-a),Math.max(s,window.innerHeight-s));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${a}px ${s}px)`,`circle(${l}px at ${a}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=tR().preference,r=tb.indexOf(t),tb[(r+1)%tb.length]),e)},[n]),a=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:a,isDark:"dark"===t.theme}}function t_(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 tD={...e6.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...e6.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function tO({code:e,isStreaming:t,defaultPreview:a=!1}){let{isDark:s}=tF(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(a),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),m=`${s?"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));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:s?"dark":"default"}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,a=await r.render(i,e);t||u({key:m,status:"ready",svg:a.svg})})().catch(()=>{t||u({key:m,status:"error"})}),()=>{t=!0}},[e,m,s,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)(tB,{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)(tH,{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 tH({svg:e,onClose:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null),[s,l]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,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:s<=.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*s),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:s>=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*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tB=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:a}){let{isDark:s}=tF(),{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:()=>{t_(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:l(o?"i18n.copied":"i18n.copy")})]})]}),a?(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)(e8.A,{language:t||"text",style:s?e6.xJ:tD,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 tU({children:e,className:t,isStreaming:n,cwd:a,onOpenFile:s}){let l=(0,i.useMemo)(()=>tc(e),[e]),o=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let a=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===a?(0,r.jsx)(tO,{code:s.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(tB,{code:s.replace(/\n$/,""),lang:a,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=s?e2(e,a):null;return i&&s?(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(),s(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,a):null,s=i?`/api/files/${e9(i)}?type=read`:e;return(0,r.jsx)("img",{src:s,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[a,n,s]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(e3.oz,{remarkPlugins:tm,rehypePlugins:tg,components:o,children:l})})}let tq=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,tK=/(?:\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 tV(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let tJ={hideThinkingBlock:!1},tG=new Set,tY=tJ,tZ=0;function tX(e){return tG.add(e),()=>{tG.delete(e)}}function tQ(){return tY}function t0(){return tJ}async function t1(e){let t=++tZ,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!==tZ||i.hideThinkingBlock!==tY.hideThinkingBlock&&(tY={hideThinkingBlock:!0===i.hideThinkingBlock},tG.forEach(e=>e()))}function t2(){return(0,i.useSyncExternalStore)(tX,tQ,t0)}var t4=n(64178);let t5={faces:new Map,pins:new Map},t8=[],t6=t5,t3=null,t7=new Map,t9=new Set;function ne(e){return t9.add(e),()=>{t9.delete(e)}}function nt(e){t6=e,t9.forEach(e=>e())}function nn(e){return Number.isSafeInteger(e)&&e>0}function nr(e,t){return`${e}:${t}`}function ni(e,t,n){if(!t)return null;if(nn(n)){let e=t6.faces.get(nr(t,n));if(e)return e}let r=e?t6.pins.get(e):void 0;if(r&&r.provider===t){let e=t6.faces.get(nr(t,r.credentialId));if(e)return e}return(0,t4.e$)(t)}async function na(e,t,n){if(!t||nn(n)||(0,t4.e$)(t))return ni(e,t,n);try{let{data:n}=await (0,t4.ST)(e);if(n?.state==="resolved"&&n.provider===t&&nn(n.credentialId)){let r=new Map(t6.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),nt({faces:t6.faces,pins:r})}}catch{}return ni(e,t,void 0)}function ns(e,t,n){let r=!!t&&!nn(n)&&!!e;return(0,i.useEffect)(()=>{r&&e&&t&&function(e,t){let n=Date.now(),r=t6.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,a=t7.get(i);void 0!==a&&n-a<3e4||(t7.set(i,n),(0,t4.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||!nn(i))return;let a=new Map(t6.pins);a.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),nt({faces:t6.faces,pins:a})}).catch(()=>{}))}(e,t)},[r,e,t]),(0,i.useSyncExternalStore)(ne,()=>ni(e,t,n),()=>null)}var nl=n(2730);let no={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","dock.label":"서브에이전트","dock.running":"실행 중 {count}","dock.awaiting":"판정 대기 {count}","dock.jump":"발주 카드로 이동 — {title}","dock.openPanel":"서브에이전트 상세 열기 — {title}","run.dispatching":"발주 중","run.pending":"대기","run.running":"실행 중","run.completed":"실행 완료","run.failed":"실행 실패","run.aborted":"중단됨","run.unobserved":"실행 상태 미관측","verdict.accepted":"Main 수용","verdict.rework":"Main 재작업 요청","verdict.held":"Main 보류","verdict.none":"검수 미기록","verdict.attempt":"{attempt}차","detail.stage":"현재 단계","detail.stageNone":"기록 없음","detail.model":"모델","detail.modelNone":"미관측","detail.fallback":"대체 모델","detail.agentId":"담당 ID","detail.reason":"판정 사유","detail.source.live":"실시간 관측","detail.source.record":"세션 기록","detail.openSubagents":"서브에이전트 상세 열기","detail.openProcess":"작업 기록 열기","summary.files":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.expand":"턴 요약 펼치기","summary.collapse":"턴 요약 접기","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.heading.unverified":"미확인","summary.check.exit":"exit {code}","summary.check.error":"오류로 끝남","summary.check.unobserved":"결과 미관측","summary.u.checkFailed":"검사 실패 — {command}","summary.u.checkUnobserved":"검사 결과 미관측 — {command}","delivery.title":"보낸 입력 {count}","delivery.kind.steer":"지금 지시","delivery.kind.followUp":"완료 후 요청","delivery.stage.sending":"보내는 중","delivery.stage.accepted":"접수됨 \xb7 전달 대기","delivery.stage.delivered":"전달됨 \xb7 대화에 들어감","delivery.stage.failed":"보내지 못함 \xb7 입력창에 되돌림","delivery.stage.unconfirmed":"전달 확인 못 함 \xb7 큐에서 빠짐","delivery.images":"이미지 {count}개","delivery.showOlder":"이전 {count}개 더 보기","delivery.showRecent":"최근 {count}개만 보기","live.nativeVoice":"기본 음성"},en:{"dispatch.title":"Subagents: {count}","dispatch.tally":"{running} running \xb7 {done} finished \xb7 {accepted} accepted by Main","dispatch.expand":"Show dispatch details","dispatch.collapse":"Hide dispatch details","dock.label":"Subagents","dock.running":"{count} running","dock.awaiting":"{count} awaiting verdict","dock.jump":"Go to the dispatch card — {title}","dock.openPanel":"Open subagent details — {title}","run.dispatching":"Dispatching","run.pending":"Queued","run.running":"Running","run.completed":"Run finished","run.failed":"Run failed","run.aborted":"Stopped","run.unobserved":"Run state not observed","verdict.accepted":"Accepted by Main","verdict.rework":"Main asked for rework","verdict.held":"Held by Main","verdict.none":"No review recorded","verdict.attempt":"attempt {attempt}","detail.stage":"Current step","detail.stageNone":"Not recorded","detail.model":"Model","detail.modelNone":"Not observed","detail.fallback":"fallback","detail.agentId":"Agent ID","detail.reason":"Review note","detail.source.live":"live","detail.source.record":"session record","detail.openSubagents":"Open subagent details","detail.openProcess":"Open work log","summary.files":"{count} files changed","summary.checks":"{count} checks","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.expand":"Show turn summary","summary.collapse":"Hide turn summary","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.heading.unverified":"Unverified","summary.check.exit":"exit {code}","summary.check.error":"ended with an error","summary.check.unobserved":"result not observed","summary.u.checkFailed":"Check failed — {command}","summary.u.checkUnobserved":"Check result not observed — {command}","delivery.title":"{count} sent","delivery.kind.steer":"Now","delivery.kind.followUp":"After this run","delivery.stage.sending":"Sending","delivery.stage.accepted":"Received \xb7 waiting to deliver","delivery.stage.delivered":"Delivered \xb7 in the conversation","delivery.stage.failed":"Not sent \xb7 back in the composer","delivery.stage.unconfirmed":"Delivery not confirmed \xb7 left the queue","delivery.images":"{count} image(s)","delivery.showOlder":"Show {count} earlier","delivery.showRecent":"Show only the latest {count}","live.nativeVoice":"default voice"},"zh-CN":{"dispatch.title":"{count} 个子代理","dispatch.tally":"运行中 {running} \xb7 运行完成 {done} \xb7 Main 已接受 {accepted}","dispatch.expand":"展开派发详情","dispatch.collapse":"收起派发详情","dock.label":"子代理","dock.running":"运行中 {count}","dock.awaiting":"等待判定 {count}","dock.jump":"转到派发卡片 — {title}","dock.openPanel":"打开子代理详情 — {title}","run.dispatching":"派发中","run.pending":"等待中","run.running":"运行中","run.completed":"运行完成","run.failed":"运行失败","run.aborted":"已中止","run.unobserved":"未观测到运行状态","verdict.accepted":"Main 已接受","verdict.rework":"Main 要求返工","verdict.held":"Main 暂缓","verdict.none":"未记录审查","verdict.attempt":"第 {attempt} 次","detail.stage":"当前步骤","detail.stageNone":"无记录","detail.model":"模型","detail.modelNone":"未观测","detail.fallback":"备用模型","detail.agentId":"代理 ID","detail.reason":"审查说明","detail.source.live":"实时观测","detail.source.record":"会话记录","detail.openSubagents":"打开子代理详情","detail.openProcess":"打开工作记录","summary.files":"变更文件 {count}","summary.checks":"检查 {count}","summary.checksFailed":"失败 {count}","summary.unverified":"未确认 {count}","summary.expand":"展开本轮摘要","summary.collapse":"收起本轮摘要","summary.heading.files":"变更文件","summary.heading.checks":"已运行的检查","summary.heading.unverified":"未确认","summary.check.exit":"exit {code}","summary.check.error":"以错误结束","summary.check.unobserved":"未观测到结果","summary.u.checkFailed":"检查失败 — {command}","summary.u.checkUnobserved":"未观测到检查结果 — {command}","delivery.title":"已发送 {count}","delivery.kind.steer":"立即指示","delivery.kind.followUp":"完成后请求","delivery.stage.sending":"发送中","delivery.stage.accepted":"已接收 \xb7 等待送达","delivery.stage.delivered":"已送达 \xb7 已进入对话","delivery.stage.failed":"未发送 \xb7 已退回输入框","delivery.stage.unconfirmed":"未能确认送达 \xb7 已离开队列","delivery.images":"图片 {count} 张","delivery.showOlder":"显示更早的 {count} 条","delivery.showRecent":"仅显示最近 {count} 条","live.nativeVoice":"默认语音"}};function nd(){let{locale:e}=(0,R.s)();return{st:(0,i.useCallback)((t,n)=>(0,nl.u0)(e,t,no,n),[e]),locale:e}}function nc({seed:e,size:t,provider:n}){let[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(!1);return a?(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,t4.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,t4.xl)(e),children:(0,r.jsx)("img",{className:"account-avatar",src:(0,t4.uk)(e),width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>s(!0)})}),l&&(0,r.jsx)(nu,{seed:e,provider:n,onClose:()=>o(!1)})]})}function nu({seed:e,provider:t,onClose:n}){let{t:a}=(0,R.s)(),s=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let l=(0,t4.xl)(e);return(0,F.createPortal)((0,r.jsxs)("dialog",{ref:s,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,t4.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,t4.bN)(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:a("i18n.close")})]}),document.body)}function np(e){let t,n=[],r=null,i=0,a=0,s=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(!(s>0||l>0)){if(c.startsWith("--- ")){u(),t=nh(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:nh(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]),a=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:a++,text:h,type:"context"}}),s>0&&s--,l>0&&l--):"-"===p?(o.push({lineNo:i++,text:h}),s>0&&s--):"+"===p?(d.push({lineNo:a++,text:h}),l>0&&l--):""!==c&&(u(),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 nh(e){return e.split(" ")[0].trim()}function nm({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,a="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":a?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":a?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,a&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let nf="/icons/catppuccin";function ng({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${nf}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${nf}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function nx({size:e=14,open:t=!1}){return(0,r.jsx)(ng,{name:t?"_folder_open":"_folder",size:e})}function nv({size:e=14}){return(0,r.jsx)(ng,{name:"_file",size:e})}let nb={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 ny(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)(ng,{name:i,size:t});let a=nb[n.split(".").pop()??""];return a?(0,r.jsx)(ng,{name:a,size:t}):(0,r.jsx)(nv,{size:t})}function nw({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=te(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:[ny(i,12),(0,r.jsx)("span",{children:i})]},e)})})}var nk=n(59959);let nj={verdicts:new Map,runs:new Map,latestByAgent:new Map};function nS(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function nC(e){return"string"==typeof e&&e.trim()?e:null}function nN(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 nI(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function nT(e,t){if(t?.isError)return null;let n=nS(e.input.tasks),r=nS(t?.details?.progress),i=Math.max(n.length,r.length),a=[];for(let s=0;s<i;s++){let i=r.find(e=>e.index===s)??r[s],l=n[s],o=nC(i?.id)??nC(l?.name);o&&a.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:o,agent:nC(i?.agent)??nC(l?.agent),task:nC(i?.task)??nC(l?.task)??"",spawned:!!t})}return a}let nM=/<task-result\b([^>]*)>/g,n$=/(\w+)="([^"]*)"/g;function nR(e,t,n){let r,i=t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&n.latestByAgent.get(e.agentId)===e.key),a=i?{key:e.key,identity:"live",live:i.assignment?i:{...i,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},s=(0,nk.$V)(a),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:s.title,explicitTitle:s.explicitTitle,stage:i?s.stage:null,model:i?(0,nk.A7)(a):null,run:r,runSource:o,verdict:d&&d.length>0?d[d.length-1]:null}}function nE(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function nL(e,t,n){let r=-1;n.forEach((e,t)=>{"user"===e.role&&(r=t)});let i=n.slice(0,r+1).flatMap(nE),a=n.slice(r+1).flatMap(nE),s=t.findIndex(e=>"user"===e.role),l=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===l?{continuing:null,atCompaction:[...i,...a]}:{continuing:{position:l,calls:a},atCompaction:i}}let nz={dispatching:"running",pending:"running",running:"running",completed:"awaiting",failed:"awaiting",aborted:"awaiting",unobserved:null},nA=(0,i.createContext)({ledger:nj,subagents:[],toolResults:new Map}),nW={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},nP={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function nF({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(nW[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(nP[n]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function n_({calls:e}){let{ledger:t,subagents:n,toolResults:a,onOpenPanel:s,focusedDispatch:l}=(0,i.useContext)(nA),{st:o}=nd(),[d,c]=(0,i.useState)(!1),u=(0,i.useId)(),p=(0,i.useMemo)(()=>e.flatMap(e=>nT(e,a.get(e.toolCallId))??[]).map(e=>nR(e,n,t)),[e,a,n,t]);if(0===p.length)return null;let h=0,m=0,f=0;for(let e of p)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(h+=1),"completed"===e.run&&(m+=1),e.verdict?.verdict==="accepted"&&(f+=1);return(0,r.jsxs)("section",{className:l&&p.some(e=>e.member.key===l)?"answer-dispatch answer-dispatch-flash":"answer-dispatch","aria-label":o("dispatch.title",{count:p.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":d,"aria-controls":u,title:o(d?"dispatch.collapse":"dispatch.expand"),onClick:()=>c(e=>!e),children:[(0,r.jsx)("span",{className:"answer-dispatch-heading",children:o("dispatch.title",{count:p.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:o("dispatch.tally",{running:h,done:m,accepted:f})}),(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:u,children:p.map(e=>(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)(nF,{maker:e,st:o})]}),d&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??o("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("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 ${o("detail.fallback")}`:""}`:o("detail.modelNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${o("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.verdict?.reason&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:o("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key))}),d&&s&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:o("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:o("detail.openProcess")})]})]})}function nD({summary:e,onOpenFile:t}){let{ledger:n,subagents:a,toolResults:s}=(0,i.useContext)(nA),{st:l}=nd(),[o,d]=(0,i.useState)(!1),c=(0,i.useId)(),u=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>nT(e,s.get(e.toolCallId))??[]).map(e=>nR(e,a,n)),[e.dispatchCalls,s,a,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)(nw,{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)(nF,{maker:e,st:l})]},`maker-${e.member.key}`))]})]})]})]})}let nO=/^att_[0-9a-f]{32}$/,nH=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nB(e){return"string"==typeof e&&nO.test(e)}function nU(e){return"string"==typeof e&&nH.test(e)}class nq extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let nK={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},nV={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},nJ={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function nG(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&&nV[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&nJ[r]?"text":null}let nY={".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 nZ(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?nY[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 nX(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function nQ(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,...nB(i.attachmentId)?{attachmentId:i.attachmentId}:{}}),n+=i.size,r+=i.text.length))}}return t}async function n0(e){let t,n=nG(e);if(!n)throw new nq("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new nq("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await re(e);else{try{t=await e.text()}catch(e){throw new nq("read_failed",e instanceof Error?e.message:String(e))}rt(t)}return{name:e.name,mimeType:nK[n],size:e.size,text:t}}function n1(e,t){let n=nQ(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=`${rn}${JSON.stringify(r)}${rr}
@@ -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!==a)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=eO.get(n);if(i)return i;let a=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(()=>eO.delete(n));return eO.set(n,a),a})(e,t).then(e=>{n&&s(e)}),()=>{n=!1}},[a,e,t]),!a)return null;let u=Array.from({length:a},(e,t)=>t).filter(e=>!d.has(e));return 0===u.length?null:(0,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)(rk,{src:eF(e,t,l),onClose:()=>o(null)})]})}function rk({src:e,onClose:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,F.createPortal)((0,r.jsxs)("dialog",{ref:a,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 rj({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(ru,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rS({block:e,duration:t,sessionId:n,entryId:a,blockIndex:s}){let{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){d(null),u(!1),h(null);return}let t=!1;return n&&a?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=rc.get(r);if(i)return rc.delete(r),rc.set(r,i),i;let a=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 rc.delete(r),e});if(rc.set(r,a),rc.size>100){let e=rc.keys().next().value;e&&rc.delete(e)}return a})(n,a,s).then(e=>{t||d(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(l("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,s,a,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)(tU,{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 rC({block:e,result:t,duration:n}){let a,s=e.toolName.toLowerCase(),l="edit"===s||s.startsWith("edit_")||s.endsWith(".edit")||s.endsWith("_edit")||s.includes("str_replace")||s.includes("replace_editor"),[o,d]=(0,i.useState)(l),c=JSON.stringify(e.input,null,2),u="todo"===s||s.endsWith(".todo")||s.endsWith("_todo"),p="bash"===s||s.startsWith("bash ")||s.endsWith(".bash")||s.endsWith("_bash"),h=t&&!t.isError?function(e){let t=e.details;if(!rP(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"===(a=e5(e,t)).kind||0===a.phases.length?null:a.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)(rR,{command:rP(e.input)&&"string"==typeof e.input.command?e.input.command:"",output:g??"",pending:!t,isError:v,duration:n,local:s.includes("(local)")});if(u&&m)return(0,r.jsx)(r$,{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 a=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==a)return String(a).slice(0,120);try{return JSON.stringify(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)(rT,{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)(rE,{diff:h})}),t&&v&&(0,r.jsx)(rF,{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)(rF,{text:g??"",isEmpty:x,isError:!1})]})}let rN={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 rI(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function rT({toolName:e,isError:t}){let n,i=(n=e.trim().toLowerCase()).includes("str_replace")||n.includes("replace_editor")||rI(n,"edit")?"edit":rI(n,"read")||rI(n,"cat")?"read":rI(n,"write")||rI(n,"save")?"write":rI(n,"glob")||rI(n,"find")?"glob":rI(n,"grep")||rI(n,"search")?"grep":rI(n,"bash")||rI(n,"shell")||rI(n,"exec")?"bash":rI(n,"todo")?"todo":rI(n,"eval")?"eval":rI(n,"task")||rI(n,"agent")?"task":rI(n,"browser")||rI(n,"web_search")||rI(n,"fetch")?"browser":rI(n,"image")||rI(n,"inspect_image")?"image":"generic",a=t?"var(--danger)":rN[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:a},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)(rM,{kind:i})})})}function rM({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 r$({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)(nm,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function rR({command:e,output:t,pending:n,isError:i,duration:a,local:s}){let{isDark:l}=tF(),{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)(e8.A,{className:"shell-command-code",language:"bash",style:l?e6.xJ:e6.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "}),s&&(0,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(),a=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 ${a}`.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!==a&&(0,r.jsxs)("div",{className:"shell-output-footer",children:[a,"s"]})]})}function rE({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(rL,{text:e.text})})}function rL({text:e}){let{t}=(0,R.s)(),n=(0,i.useMemo)(()=>np(e),[e]);if(!n)return(0,r.jsx)(rW,{text:e});let a=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:[a&&(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)(rz,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(rz,{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)(rA,{cell:e.left,side:"left"}),(0,r.jsx)(rA,{cell:e.right,side:"right"})]},t))})]},n))})}function rz({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 rA({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?"-":" ",a="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:a,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 rW({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 rP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rF({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 r_({message:e}){let{t}=(0,R.s)(),n=rB(e.content),a=(0,i.useMemo)(()=>{let e,t,r,i,a;return e=[],t=[],r=n.match(tK),i=r?.[1]??"",a=r?.index===void 0?n:n.slice(0,r.index),i.replace(tq,(n,r,i)=>{let a=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...a):t.push(...a),""}),{body:a.trim(),readFiles:e,modifiedFiles:t}},[n]),s=rf(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:tV(l)})}),s&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(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")}),a.body?(0,r.jsx)(tU,{className:"markdown-compaction-message",children:a.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(rD,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function rD({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)(rO,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(rO,{title:n("i18n.readFiles"),files:e})]})}function rO({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 rH({message:e,cwd:t,onOpenFile:n}){var a;let s,{t:l}=(0,R.s)(),o=!1===e.display,[d,c]=(0,i.useState)(!o),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=rB(e.content),g="string"==typeof(a=e.content)?[]:a.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=rf(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=rU(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)(tU,{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?(s=f.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"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:()=>{t_(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 rB(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rU(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 rq({message:e,sessionId:t}){let[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===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?a(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{l(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:m?[{type:"text",text:m}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rC,{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:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,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 rK({summary:e,onJump:t,onOpenPanel:n}){let{st:i}=nd();if(!e)return null;let{target:a}=e,s=a.position;if(null===s&&!n)return null;let l=i(null!==s?"dock.jump":"dock.openPanel",{title:a.maker.title});return(0,r.jsxs)("button",{type:"button",className:"run-status-line answer-dock-line","data-tone":"accent",title:l,onClick:()=>{null!==s?t(s,a.maker.member.key):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:a.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 rV=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,rJ="cuelo-chat-search",rG="cuelo-chat-search-active";function rY(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 rZ({open:e,onClose:t,containerRef:n,index:a,renderedStart:s,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)(()=>()=>{rY(rJ,[]),rY(rG,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){rY(rJ,[]),rY(rG,[]),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 a=(e.textContent??"").toLowerCase(),s=n.get(i);s||(s=[],n.set(i,s));for(let n=a.indexOf(t);-1!==n;n=a.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),s.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 a=[];if(!t)return a;for(let s=0;s<e.length;s++){let l=s>=r&&s<i?n.get(s)??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[s],t);for(let e=0;e<l;e++)a.push({item:s,k:e})}return a}(a,w,n,s,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(rY(rJ,o),i<0){rY(rG,[]),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>=s&&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){rY(rG,[]),f&&d(u.item);return}let g=e.get(u.item)?.[u.k];if(rY(rG,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,a,s,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 rX({questions:e,containerRef:t,layoutKey:n,onJump:a,label:s}){let l=(0,i.useRef)(null),[o,d]=(0,i.useState)(-1),[c,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=c&&e.length>=2;(0,i.useEffect)(()=>{let n=t.current;if(!n||!p)return;let r=0,i=null,a=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,a=0,s=i.length-1,l=i.length-1;for(;a<=s;){let e=a+s>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(l=e,s=e-1):a=e+1}let o=l>=0?Number(i[l].dataset.chatItem):-1,c=-1;for(let t of e){if(t.item>o)break;c=t.item}d(c)},s=()=>{r||(r=requestAnimationFrame(a))};return r=requestAnimationFrame(a),n.addEventListener("scroll",s,{passive:!0}),()=>{n.removeEventListener("scroll",s),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":s,children:(0,r.jsx)("div",{ref:l,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(rQ,{question:e,position:t,count:h,active:e.item===o,focusable:e.item===f,onJump:a,onMoveFocus:m},e.item))})})}let rQ=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:a,onJump:s,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:a?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${o}`,title:o,onClick:()=>s(e.item),onKeyDown:e=>l(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function r0({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 r1={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function r2({compaction:e,t}){let[n,a]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;a(Date.now());let t=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((n-e.startedAt)/1e3)),l=e.reason&&!0===r1[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(r0,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),l?` \xb7 ${l}`:""]})}function r4({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 r5=n(39092),r8=n.n(r5);let r6=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],r3={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},r7=["approval","choice","done","failed","blocked","working"],r9={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},ie={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function it(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function ir(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(r9,e)?e:null}function ii(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:a,ko:s}=i;if("string"!=typeof e||""===e)continue;let l=ir(a);if(null===l)continue;let o=t+e.replace(/^\/+/,""),d=n.get(l);d?d.push(o):n.set(l,[o]),"string"==typeof s&&""!==s.trim()&&r.set(o,s.trim())}return{files:n,lines:r}}function ia(e,t,n){let r=t&&Object.hasOwn(r3,t)?r3[t]:null;return r?e.get(r)?.get(n)??null:null}async function is(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return function(e){let t=new Map;if("object"!=typeof e||null===e)return t;let{characters: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:a}=e;if("string"!=typeof n||""===n)continue;let s=ii(r,"/audio/completion/"),l=ii(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=ir(e);if(null===i)continue;let a=t.get(i);a?a.push(r.trim()):t.set(i,[r.trim()])}return t}(a),d=new Map;for(let e of r7){let t=s.files.get(e)??[],n=new Map;for(let e of t){let t=s.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 il(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,a=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&a>=r?a+1:a]}function io(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 id=["01","02","03"];function ic(e,t,n){if(!e||"streaming"===t||!r6.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),a=il(id.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 a?{src:a,alt:r9[r]}:null}let iu=new Map,ip=(0,i.createContext)(iu);function ih({utterances:e,children:t}){return(0,r.jsx)(ip.Provider,{value:e,children:t})}function im({turnIndex:e,turnEntryId:t,sessionId:n,cwd:a,onOpenFile:s}){let l=(0,i.useContext)(ip).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)(ig,{utterance:e,sessionId:n,cwd:a,onOpenFile:s},e.key))}):null}function ig({utterance:e,sessionId:t,cwd:n,onOpenFile:a}){let s=ns(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=s?.alias??h??(0,t4.bN)(e.provider),f=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==f?`작업 \xb7 ${h}`:null,x=ic(s?.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)",...s?{minHeight:40}:null},children:[s&&(0,r.jsx)(nc,{seed:s.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)(tU,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:a,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)(r8(),{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 ix=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function iv(e,t,n,r){if("string"!=typeof n)return[];let i=ix.exec(n),a=i?.[1],s=i?.[2];return a&&s?[{toolCallId:e,...t?{name:t}:{},alias:a,model:s,batchSize:r}]:[]}function ib(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(...iv(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(...iv(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function iy(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 iw=/^agent:\/\/([^/?#]+)\/?$/i;function ik(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?iw.exec(e.path):null,a=i?.[1],s=e.content;if(!a||"string"!=typeof s)continue;let l=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:a,message:s,...l?.from?{from:l.from}:{},...l?.receipts?{receipts:l.receipts}:{}})}return n}var ij=n(75514);let iS=["greeting","utterance","message","text"],iC=function(e){let t=(0,i.useMemo)(()=>(0,nk.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 a of n.subagents){if(t.has(a.name))continue;let n=[...i].reverse().find(e=>e.name===a.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},a="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,s="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==a||void 0!==s)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==a?{resolvedModel:a,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),i}(a,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),a="string"==typeof t.task?ix.exec(t.task):null,s=a?.[1],l=a?.[2],o=i.find(e=>e.name===t.id)??(s&&l?r.requests.find(e=>e.alias===s&&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]),a=(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]),s=(0,ij._Z)(a,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&a.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:a}=e,s="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",l="failed"===s,o=a?.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 a=t?.model.trim()??"",s=a.indexOf("/");return s>0?a.slice(0,s):n?.trim()||void 0}(i,a,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:a}=t.irc;if(a||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let a=e.sends[t];if(a.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))}(a.send,i.id)&&a.send.from===n){h=a.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",...iS]){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&&a?a.alias:c,text:x,status:s})}),0===p.length&&"settled"!==s&&d){let e=l?i.progress?.retryFailure?.errorMessage?.trim():void 0;p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:d,accountSessionId:null,label:l&&a?a.alias:c,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[r,s,e.sessionProvider])},iN="web6",iI=[],iT=[],iM=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 a=`${t}?sessionId=${encodeURIComponent(i)}`,s=await e(a,{signal:r});if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json(),o=l&&"object"==typeof l&&"consults"in l?l.consults:null;if(!Array.isArray(o))throw Error("consults 배열이 아니다");return o.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let 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:a,text:s,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 a&&""!==a?a:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof l&&""!==l?l:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(iT),a=(0,i.useRef)(""),s=e.sessionId??"",l=s.length>0;return(0,i.useEffect)(()=>{if(!l){a.current="",r(iT);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(s,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===a.current)return;a.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,l,s]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return iI;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 iI;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 a=t.error??"";0!==a.trim().length&&i.push({key:`${iN}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${iN}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return i.length>0?i:iI})(n,e.messages,s),[n,e.messages,s])},i$={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function iR(e){return e.trim()}function iE(e){return iR(e.text)||(e.images>0?"[Image]":"")}function iL(e){let t=e.filter(e=>!i$[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 iz(e,t){switch(t.type){case"submit":return iL([...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 iL(e.map(e=>e.id===t.id&&i$[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${iR(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 a=!1,s=e.map(e=>{if(!i$[e.stage])return e;let t=`${e.kind}\u0000${iE(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-1),e.inQueue&&"accepted"===e.stage)?e:(a=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(a=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return a?s:e}(e,t.steering,t.followUp);case"user-message":{let n=iR(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(i$[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&iR(e.text)===n&&e.images===t.images);if(!r)return e;return iL(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>i$[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=iR(t.text),i=e.find(e=>n(e)&&e.kind===t.kind&&(iR(e.text)===r||iE(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 iA={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},iW={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function iP({rows:e,removeLabel:t,onRemove:n}){let a,{st:s}=nd(),[l,o]=(0,i.useState)(!1),{rows:d,hidden:c}=(a=Math.max(0,e.length-4),l||0===a?{rows:e,hidden:a}:{rows:e.slice(a),hidden:a}),u=e.length>4;return(0,i.useEffect)(()=>{u||o(!1)},[u]),(0,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?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:c})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:d.map(e=>{let i=n2(e.text),a=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?s("delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,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:s(iA[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:s(iW[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${a}`,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 iF=(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"})]}),i_=(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 iD({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?iF:i_})})})}let iO=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u");class iH{#e;#t;#n;#r;#i;#a;constructor(e=()=>new AudioContext){this.#t=null,this.#n=0,this.#r=0,this.#i=null,this.#a=new Set,this.#e=e}unlock(){let e=this.#s();e?.state==="suspended"&&e.resume().catch(()=>{})}get speaking(){return this.#a.size>0}push(e,t){if(e<this.#n)return;e>this.#n&&this.reset(e);let n=this.#s();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 a=n.createBuffer(1,i,24e3),s=a.getChannelData(0),l=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let e=0;e<i;e+=1)s[e]=l.getInt16(2*e,!0)/32768;let o=n.createBufferSource();o.buffer=a,o.connect(n.destination);let d=Math.max(n.currentTime+.05,this.#r);o.onended=()=>{this.#a.delete(o)},this.#a.add(o),o.start(d),this.#r=d+a.duration}reset(e){for(let t of(this.#n=Math.max(this.#n,e),this.#r=0,this.#i=null,this.#a)){t.onended=null;try{t.stop()}catch{}}this.#a.clear()}close(){this.reset(this.#n);let e=this.#t;this.#t=null,e&&e.close().catch(()=>{})}#s(){if(this.#t&&"closed"!==this.#t.state)return this.#t;try{this.#t=this.#e()}catch{this.#t=null}return this.#t}}function iB(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 iU={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0},iq={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",voice:"chat.liveVoiceFailed",failed:"chat.liveFailed"},iK=(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"})]}),iV=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function iJ({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:a}=(0,R.s)(),s=function(e,t,n){let{locale:r}=(0,R.s)(),[a,s]=(0,i.useState)("idle"),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,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(()=>{}),s(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,a=N.current+1;N.current=a,o(null),c(null),v(!0),s("connecting"),S.current?.close();let l=new iH;l.unlock(),S.current=l;let d=e;if(!d&&t){try{d=await t()}catch{d=void 0}if(N.current!==a)return}if(!d){N.current===a&&(v(!1),T("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";N.current===a&&(v(!1),T("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(N.current!==a){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(a),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},a=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}(l),N.current!==a)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===a&&(C.current=iB(g.voice))),!f.ok||!x||!y){if(N.current===a){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!==a)return void fetch(`/api/live/call/${encodeURIComponent(x)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:y}),N.current!==a){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===a){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;if("string"!=typeof t.state||(r=t.state,!0!==iU[r]))return;"closed"===t.state?I("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&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&&iO.test(e)&&I("idle")}return}if("voice"===t.type&&"voice"in t){let e=iB(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===a&&j.current&&T("failed")},s("live")}catch(e){N.current===a&&T("failed",e instanceof Error?e.message:String(e))}finally{N.current===a&&v(!1)}},[e,t,n,r,T,I]),$=(0,i.useCallback)(()=>{if("idle"===a||"closed"===a||"error"===a){x||M();return}I("idle")},[x,a,M,I]);return(0,i.useEffect)(()=>()=>I("closed"),[I]),{state:a,failure:l,detail:d,transcript:u,voice:h,supported:f,toggle:$}}(e,t,n),l="connecting"===s.state||"live"===s.state||"working"===s.state,o="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,d=a(l?"chat.liveStop":"chat.liveStart"),c=!1===s.supported?iq.unsupported:s.failure?iq[s.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}(s.voice,a):null;return(0,r.jsxs)("div",{role:"group","aria-label":a("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[c&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:a(c)}),o&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a(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:s.toggle,disabled:!s.supported||!u,"aria-pressed":l,title:p?a(p):d,"aria-label":p?a(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?iV:iK})})]})}let iG={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 iY({sessionId:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void a(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 s=Array.isArray(i.handles)?i.handles:[],l=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==l,a(l)}catch{}},s=async()=>{await i(),t||(n=window.setTimeout(()=>void s(),r?5e3:3e4))};return s(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:iG,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}function iZ(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 iX=new Map,iQ="ompweb-drafts-for-reload-v1",i0=!1,i1=new Map,i2=new Map,i4="\0stale",i5=new Map,i8=0,i6=new Map,i3=new Map,i7=new Map,i9=new Map,ae=new Map,at=(e,t,n)=>n9(e,t,n.length?{sentAttachmentIds:n}:{}),an=null,ar=!1;function ai(){if(i0||"u"<typeof sessionStorage)return;i0=!0;let e=sessionStorage.getItem(iQ);if(e){sessionStorage.removeItem(iQ);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)&&(iX.set(e[0],as(t)),"string"==typeof t.draftId&&t.draftId&&(i1.set(e[0],t.draftId),i2.set(t.draftId,i4)),af(e[0]))}}catch{}}}function aa(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(iQ,JSON.stringify([...iX.entries()].map(([e,t])=>{let n=i1.get(e);return[e,n?{...as(t),draftId:n}:as(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function as(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function al(e){return!e.value&&0===e.images.length&&0===e.documents.length}function ao(e){ai();let t=iX.get(e);return t?as(t):null}function ad(e,t){ai(),al(t)?iX.delete(e):iX.set(e,as(t)),af(e)}function ac(e){iX.delete(e),af(e)}function au(e,t,n,r,i,a=[]){let s=[...t??[],...r].filter(iZ).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=nQ([...i??[],...a]);return{value:e.trim()?n.trim()?`${e}
18
18
 
19
- ${n}`:e:n,images:s,documents:l}}function ap(e,t,n){if(e===t)return n?as(n):ao(t);let r=ao(e),i=n&&!al(n)?as(n):r??(n?as(n):null),a=ao(t),s=i1.get(e);if(i1.delete(e),s&&!i1.has(t)&&i1.set(t,s),ac(e),!i)return a;let l=a?au(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return ad(t,l),as(l)}function ah(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function am(e){ai();let t=i1.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)}`}(),i1.set(e,t)),t}function af(e){let t=ah(iX.get(e)?.documents),n=t.length?am(e):i1.get(e);for(let[e,n]of i3){for(let e of t)n.delete(e);0===n.size&&i3.delete(e)}let r=`${n??""}|${t.join(",")}`;i9.get(e)!==r&&(0!==t.length||n?i9.set(e,r):i9.delete(e),ak())}async function ag(e){let t=am(e);i6.set(t,(i6.get(t)??0)+1),await ae.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(i6.get(t)??1)-1;if(r>0?i6.set(t,r):i6.delete(t),e){let n=i3.get(t)??new Set;n.add(e),i3.set(t,n)}i2.set(t,i4),ak()}}}function ax(e,t){let n=i7.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&i7.delete(e),[...n].sort()}async function av(){if(!at)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 i1)t(n,ah(iX.get(e)?.documents));for(let{draftId:e,ids:n}of i5.values())t(e,n);for(let[e,n]of i3)t(e,n);for(let e of i2.keys())t(e,[]);for(let e of i7.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(i6.has(e))return!1;let n=i2.get(e);return ax(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=i6.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=ax(r,i),a=at(r,i,e).then(()=>{0===i.length?i2.delete(r):i2.set(r,i.join(","));let t=i7.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&i7.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});ae.set(r,a),await a,ae.get(r)===a&&ae.delete(r)}n?function(){if(aw)return;aw=!0;let e=setTimeout(()=>{aw=!1,ak()},ay);"object"==typeof e&&"unref"in e&&e.unref(),ay=Math.min(2*ay,6e4)}():ay=ab}let ab=5e3,ay=5e3,aw=!1;function ak(){if(at){if(an){ar=!0;return}an=Promise.resolve().then(av).finally(()=>{an=null,ar&&(ar=!1,ak())})}}let aj=Math.floor(Number.MAX_SAFE_INTEGER/1048576),aS=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function aC(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=aj}async function aN(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!aC(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:aC((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:aS.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:aS.autoCleanupEnabled,orphanGraceDays:7}}async function aI(e={}){return aN(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function aT(e){return aN(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function aM(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 a$(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function aR(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 aE="omp-web:model-picks";function aL(){try{let e=JSON.parse(window.localStorage.getItem(aE)??"{}");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 az(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,n-2*s)),d=Math.max(0,e-a-s),c=Math.max(0,n-t-a-s),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 aA(e,t,n){return Math.min(e*t,n)}function aW(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:l,minHeight:o,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=az(i.top,i.bottom,n,aA(n,r,a),{gap:s,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,a,s,l,o,d,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 aP=n(14755);async function aF(e,t,n,r,i,a,s){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await s?.()??[],d=[...aX,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await 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 a_(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let aD=["off","default","full"],aO={off:"none",default:"default",full:"full"},aH=aP.IN.join(" \xb7 "),aB=aP.C1.filter(e=>!aP.IN.includes(e)).join(" \xb7 ");function aU(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let aq=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),aK=0,aV={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function aJ(e,t){return aq.compare(e.name||e.modelId,t.name||t.modelId)||aq.compare(e.provider,t.provider)||aq.compare(e.modelId,t.modelId)}let aG=["auto","off","minimal","low","medium","high","xhigh","max"],aY=["low","medium","high","xhigh"],aZ={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},aX=[{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"}],aQ=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],a0={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},a1={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function a2(e,t,n){let r=e.name.toLowerCase(),i=a4(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function a4(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function a5(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function a8(e){return{data:e.data,mimeType:e.mimeType}}function a6(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function a3(e){return(e??[]).filter(iZ).slice(0,10).map(a6)}let a7=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,a9="\n\nTranscript of the audio ";function se(e){return nQ(e).map(e=>{let t=n6(e),n="audio"===t&&e.attachmentId&&!e.text.includes(a9)?a7.exec(e.text):null;return{...e,id:++aK,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function st({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 sn(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 sr extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let si="composer:unkeyed";async function sa(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new sr("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 ss(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sl({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 so({error:e}){return e?(0,r.jsx)(sl,{tone:"error",title:"Model error",body:e}):null}function sd({warnings:e}){return e&&0!==e.length?(0,r.jsx)(sl,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sc=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,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:z=null,fastModeBusy:A=!1,onFastModeToggle:W,retryInfo:F,deliveryRows:_=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,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,ea,es,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:em}=nd(),ef=_.some(e=>e.removable),eg=P(),[ex,ev]=(0,i.useState)(()=>Z?ao(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(aL())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,ez]=(0,i.useState)(!1),[eA,eW]=(0,i.useState)(null),[eP,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?a3(ao(Z)?.images):[]),[eO,eH]=(0,i.useState)(()=>Z?se(ao(Z)?.documents):[]),[eB,eU]=(0,i.useState)(null),eq=(0,i.useMemo)(()=>eO.filter(e=>"ready"===e.status),[eO]),eK=eO.some(e=>"ready"!==e.status||a_(e)),eV=eO.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(a9))),eJ=ex.trimStart(),eG=0===e_.length&&0===eO.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),[ta,ts]=(0,i.useState)(null),[tl,to]=(0,i.useState)(null),td=X&&tl?.cwd===X?tl.values:{},tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),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)(eO);t$.current=ex,tR.current=e_,tL.current=eO,(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"),n2(t)?.message??t),a=a3("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 iZ(r)?[r]:[]})),s=se((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n2(n)?.documents??[]));t$.current=i,tR.current=a,tL.current=s,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(ss),a)),eH(s),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 ap(e,t);let n={value:t$.current,images:tR.current.map(a8),documents:tL.current.filter(e=>"ready"===e.status).map(st)},r=ap(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 a=a3(r.images),s=sn(se(r.documents),tL.current),l=r.value;t$.current=l,tR.current=a,tL.current=s,ev(l),eD(e=>(e.forEach(ss),a)),eH(s),e2(null),e7(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tM.current,a=r??i,s=a===i,l=!s&&a?ao(a):null,o=au(e,t,s?t$.current:l?.value??"",s?tR.current.map(a8):l?.images??[],n,s?tL.current.filter(e=>"ready"===e.status).map(st):l?.documents??[]);if(a&&ad(a,o),!s)return;let d=t?.length?[...a3(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=sn(se(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=a3(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tR.current=i,i}),eH(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),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+a;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tY(e)}}));let tz=(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:n4(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(ss);let r=[...t,...n];return tR.current=r,r})}finally{tE.current-=i.length}}},[eh]),tA=(0,i.useCallback)(async e=>{for(let t of e){let e=nG(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:n4(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:n4(0x1000000)}));continue}let n={id:++aK,name:t.name,mimeType:nK[e],size:t.size,text:"",status:"extracting"},r=[...tL.current,n];tL.current=r,eH(r);try{let e=await n0(t);if(tL.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new nq("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,eH(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,eH(r),!e)continue;i instanceof nq?"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,eH(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,eH(n),!0},[]),tF=(0,i.useCallback)((e,t,n)=>{if(!e||e===tM.current)return;let r=ao(e);r?.documents.some(e=>e.attachmentId===t)&&ad(e,{...r,documents:se(r.documents).map(e=>e.attachmentId===t?n(e):e).map(st)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tO=(0,i.useRef)(new Set),tH=(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=n3({...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 sr&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof sr&&"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 a=new AbortController;tD.current.set(e,a),tP(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await sa(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new sr("Invalid transcription result",null,null,null);let i=r.transcript;tP(e,e=>tH(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(n,e,e=>tH(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tP(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof sr&&"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)===a&&tD.current.delete(e)}},[eh,tB,tP,tF,tH]),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 sr("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await sa(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 tJ=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tP(e,e=>({...e,transcription:{state:"skipped"}}))},[tP]),tG=(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:++aK,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tL.current,i];tL.current=a,eH(a);let s=(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]?nX("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?nX("utf-16be",t.subarray(2)):t.includes(0)?null:nX("utf-8",t)??nX("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tW(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await aI().catch(()=>aS)).uploadLimitMb),r.size>n){tW(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:r.name,limit:n4(n)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tW(i.id,l))continue;let o=tM.current??si,d=await ag(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tO.current.has(i.id))continue;let e=await n7(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),a=n3({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tW(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:n4(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tW(i.id,h))c=e.id;else if(!tO.current.has(i.id)&&o!==tM.current){let t=ao(o)??{value:"",images:[],documents:[]};ad(o,{...t,documents:[...t.documents,st(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 a of e)a.type.startsWith("image/")?t.push(a):null!==nG(a)?n.push(a):nZ(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tz(t),tA(n.filter(e=>e.size<=8388608)),tG(r,"audio"),tG([...i,...a],"file")])},[tA,tG,tz]),tZ=(0,i.useCallback)(e=>{eD(t=>{let n=[...t],[r]=n.splice(e,1);return r&&ss(r),tR.current=n,n})},[]),tX=(0,i.useCallback)(e=>{let t=tL.current.find(t=>t.id===e);if(tO.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 i3)t.delete(n)&&(0===t.size&&i3.delete(e),ak())}let r=tL.current.filter(t=>t.id!==e);tL.current=r,eH(r)},[]),tQ=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(ss),[]))},[]),t0=(0,i.useCallback)(()=>{tL.current=[],eH([])},[]),t1=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&ac(Z),tM.current&&tM.current!==Z&&ac(tM.current),tQ(),t0(),eU(null),tc.current&&(tc.current.style.height="auto")},[t0,tQ,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&ad(Z,{value:ex,images:e_.map(a8),documents:eq.map(st)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&ad(e,{value:t$.current,images:tR.current.map(a8),documents:tL.current.filter(e=>"ready"===e.status).map(st)});let t=Z?ao(Z):null;tM.current=Z;let n=t?.value??"",r=a3(t?.images),i=se(t?.documents);t$.current=n,tR.current=r,tL.current=i,ev(n),e2(null),e7(!1),eD(e=>(e.forEach(ss),r)),eH(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(ss)},[]);let t2=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=ah(t);if(0===n.length)return()=>{};let r=++i8;return i5.set(r,{draftId:am(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=i5.get(r);if(t){if(i5.delete(r),"accepted"===e){let e=i7.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);i7.set(t.draftId,e)}ak()}}}(tM.current??si,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t5=(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,a=eq.length?eq:void 0;if(r.startsWith("/")){await aF(r,B,K,t=>t2(a,()=>e(t,i,a)),eU,!!(i||a),q)&&t1();return}t1(),t2(a,()=>e(r,i,a))},[ex,eJ,e_,eq,eK,l,K,B,q,e,t1,G,t2]),t8=eJ.startsWith("/")&&!/\s/.test(eJ.slice(1))?eJ.slice(1).toLowerCase():null,t6=(()=>{if(null===t8)return[];let e=[...l?[]:aX,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=a4(e,eh).toLowerCase();return t.includes(t8)||n.includes(t8)}).sort((e,t)=>{let n=a2(e,t8,eh)-a2(t,t8,eh);return 0!==n?n:a1[e.source]-a1[t.source]||aq.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=aQ.map(e=>{let t=t6.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!a5(e,td)),...t.filter(e=>a5(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(t8?"chat.match":"chat.command"):eh(t8?"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(aM(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:aR(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:aR(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||a$(e.entry.path)-a$(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tt.entries,nr):[],[nr,tt,X]),na=!!(nr&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!na||!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=>ts({cwd:X,query:nr,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[na,nr,X]);let ns=na&&null!==ta&&ta.cwd===X&&ta.query===nr,nl=ns?ta.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 nc=null!==e1,nu=aW(tb,e3,{viewportFraction:.44,cap:360}),np=aW(tb,eZ,{viewportFraction:.56,cap:460}),nh=aW(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nc||!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)=>a$(e.path)-a$(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)}))},[nc,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 a=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 a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e1.quoted),s=r+a.text+i,l=r.length+a.cursorOffset;ev(s),e2(aM(s.slice(0,l))),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e1,ex]);(0,i.useEffect)(()=>{e8>=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`)})},[]),nv=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eJ.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!s)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await aF(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(s.documents,()=>Y(e,l,s.images,s.documents))},eU,!!(s.images?.length||s.documents?.length),q)&&t1();return}t1(),"steer"===e&&n?t2(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t2(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,n,a,t1,G,t2]),nb=(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,a=r.top+r.height/2,s=-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-a;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(s=n,l=d)}return s>=0?s:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t3.length,eQ]),nw=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tk.current<100,s=tw.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(e3&&!s){if("ArrowDown"===e.key){e.preventDefault(),te(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),te(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e7(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[e9]){e.preventDefault(),nf(D[e9]);return}}if(eZ&&null!==t8){if("ArrowDown"===e.key){e.preventDefault(),e0(nb("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(nb("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(nb("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(nb("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&&!s){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&&!s&&!l&&D.length>0&&0===ex.trim().length){e.preventDefault(),eX(!1),e5(!1),te(D.length-1),e7(!0);return}if("Escape"===e.key&&!s&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(n||a)?nv(n?"steer":"followup"):t5())},[l,n,a,t,eZ,t8,t3,eQ,ng,nv,t5,nb,e4,e1,nl,e8,nm,e3,D,e9,nf,ex]),nk=(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===t8){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}))},[t8,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(aJ):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(aJ),nC=g??null,nN=t4.bo.find(e=>e.alias===nC)?.provider??null,nI=nN?nS.filter(e=>e.provider===nN):nS,nT=(ea=ej.trim().toLocaleLowerCase())?nI.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):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})),nz=(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}(aL(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(aE,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}`)},nA=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")} ${tV(S.tokensBefore)} -> ${tV(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:tV(nW)})})`:null,nF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},n_="auto"===(es=I??"auto")?M?`auto ≤ ${nF(M)??M}`:"auto":L?L[es]??es:es,nD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,nO=$&&nD?eh("chat.currentReasoning",{level:nD}):null,nH=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...aY.filter(nH).map(e=>({level:"auto",ceiling:e})),...aG.filter(e=>"auto"!==e&&nH(e)).map(e=>({level:e,ceiling:null}))],nU=Object.entries(aO).find(([,e])=>e===(C??"default"))?.[0]??"default";return(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)&&ez(!1),tx.current&&!tx.current.contains(e.target)&&eF(!1),!tv.current||tv.current.contains(e.target)||tc.current?.contains(e.target)||e7(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eF(!1)},[eg]),(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)(so,{error:p}),(0,r.jsx)(sd,{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})}),O&&ef&&(0,r.jsxs)("button",{onClick:O,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)(iP,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("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||eO.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}`)),eO.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||a_(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"}}):ny(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"):aV[e.mimeType]," \xb7 ",n4(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,a,l=e.attachmentId,o=e.transcription,d=o?.state==="confirm"||o?.state==="running"?o.plan:null,c=d?eh("chat.transcribePlanSummary",{duration:null===d.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:d.estimatedCalls}):null,u=o?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:o?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:o.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,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)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tJ(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tJ(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,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,...aU(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.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,nu.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!==t8&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...aU(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(a0[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=a5(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")})]}),a4(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:a4(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&&(el=tr&&(!tt||tt.cwd!==X),eo=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ed=tt?.truncated&&!ns?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...aU(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:el?eh("chat.loadingFiles"):eh("chat.files",{label:eo,hint:ed})}),(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:el||0!==nl.length?nl.map((e,t)=>{let n=t===e8,i=e.path.split("/").pop()??e.path,a=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)(nx,{size:14}):ny(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),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:na&&!ns?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||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,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:nw,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;nn(t.value,t.selectionStart)},onInput:nk,onPaste:nj,placeholder:l&&(n||a)?eh("chat.steerPlaceholder"):l?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),l?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nv("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")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nv("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")]})]}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t5,disabled:!nt,"aria-busy":eK||void 0,title:eK?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"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"})]}),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:[(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e_.length||eO.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||eO.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||eO.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=e_.length||eO.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"})]})}),f&&t4.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}=az(eM.top,eM.bottom,e,aA(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,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,...a,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:t4.bo.map(e=>{let t=e.alias===nC;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),f((0,t4.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,t4.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)})})})})()]}),(nS.length>0||nA||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:nA??(nS.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=az(ew.top,ew.bottom,e,aA(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight: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})=>nz(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=>nz(e,"all"))]},e.provider))]})]})})()]}),$&&(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),ez(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level: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&&eA&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=az(eA.top,eA.bottom,e,aA(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eA.top+6}:{top:eA.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eA.left,width:"max-content",minWidth:Math.max(180,eA.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nF(i),s=t?`auto ≤ ${a??t}`:a??e,l=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(aZ[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{ez(!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:[s,null!==a&&(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)})})})()]}),W&&(ec=A?eh("chat.fastModeBusy"):null===z?eh("chat.fastModeUnknown"):z.active?eh("chat.fastModeActive"):z.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eu=A||l||b,ep=z?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${z?.active?" is-active":""}`,onClick:W,disabled:eu,"aria-pressed":null===z?void 0:z.enabled,"aria-busy":A||void 0,title:ec,"aria-label":ec,style:{flexShrink:0,opacity:l?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:z?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===z?"3 2":void 0,style:{opacity:ep&&!z?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})),!eg&&nO&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nO}),(0,r.jsx)(iY,{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)(s.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:[!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:aD.map(e=>{let t=aO[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:aH}):eh("chat.allBuiltInTools",{tools:`${aH} + ${aB}`});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")})]})})}),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),ez(!1),eF(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,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"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter: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"})}),eh("chat.stop")]}),(0,r.jsx)(iJ,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),void 0!==J&&(0,r.jsx)(iD,{soundEnabled:V??!0,onToggle:J})]})]}),eg&&nO&&(0,r.jsx)("div",{style:{marginTop:4,padding:"0 4px",fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:nO})]})]})});function su({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 sp({phases:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=function(e){let t=0,n=0,r=null,i=null,a=null;for(let s of e)for(let e of s.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:s,task:e}):"blocked"===e.status?a||(a={phase:s,task:e}):i||(i={phase:s,task:e}))}let s=r??i??a,l=t+n;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:n,completed:t,total:l,percent:l>0?Math.round(t/l*100):null}}(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:()=>a(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=>s||"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)(nm,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":s,onClick:()=>l(e=>!e),children:t(s?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sh(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function sm(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 sf(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 sg=n(62503);class sx extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function sv(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 sx(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let sb="ompweb-update-client-id",sy="ompweb-update-resume-intent-v2",sw="ompweb-update-return-v1",sk="cuelo-restart-return-v1",sj="ompweb-update-failure-return-v1",sS="ompweb:update-wake";function sC(e){return null===e||"running"===e?null:"failed"===e?3e4:8e3}function sN(){let e=sessionStorage.getItem(sb);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(sb,t),t}function sI(){sessionStorage.removeItem(sy)}function sT(){let e=sessionStorage.getItem(sw);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function sM(e){let t=sT();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(sw,JSON.stringify(n))}catch{}return n}async function s$(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:sN(),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 sR(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=sT();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(sw,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sI();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sS,{detail:{sessionId:e.sessionId}}))}async function sE(e){let t=function(e){let t=sessionStorage.getItem(sj);if(!t)return null;sessionStorage.removeItem(sj);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?(sI(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(sS,{detail:{sessionId:e.sessionId}})),"failed"):(await sR(e),"resumed")}function sL(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 sz(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 sA(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function sW(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function sP(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 sF(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 s_(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function sD(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 sO=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class sH 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 sB(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function sU(e){return new Promise(t=>setTimeout(t,e))}function sq(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function sK(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:sq(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:sq(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=sq(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function sV(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 sJ(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(sV).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function sG(e){return"user"===e.role?`user:${sJ(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 sY(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 sZ(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}let sX={count:50,end:null};function sQ(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),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function s0(e,t,n){let{startIndex:r,endIndex:i}=sQ(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function s1({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:r9[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(r8(),{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 s2(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=(n2(t)?.message??t).trim();return n.length>0?n:null}function s4(e){return`omp-cues:${e}`}function s5(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(s4(e),JSON.stringify(n.slice(-200)))}catch{}}let s8=[];function s6(e){return`omp-web:interrupted-dismissed:${e}`}let s3=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,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:a,cwd:s,sessionId:f})},[N,x,e,t,n,a,s,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 a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let l of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,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 a=eY(i.memory),s=i.skill,l=s?{action:eY(s.action),name:eY(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:l}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...l?{skill:l}:{}})}}(l.blocks??e.content??[],r,(e,t)=>{if(o.has(e))return;o.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(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,a]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),a=new Map;for(let[s,l]of(e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.anchorIdx,t)}),a)){if(s===n)continue;let e=i.find(e=>e>s);r.set(l,{from:s+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||!rV.test(e))continue;let a=t.get(n.toolCallId),s=a?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}(a):null,l=null===s?a?.isError?"failed":"unobserved":0===s?"passed":"failed";r.push({toolCallId:n.toolCallId,command:e,state:l,exitCode:s})}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,a.from,a.to),n,s));return r},[g,e,n,s,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)(rg,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:l,entryId:t[i],onFork:o||d||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:o?void 0:h,prevAssistantEntryId:o?void 0:b,onEditContent: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}`)},z=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":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((a,o)=>{let d=y+o,c=b?.position===d?(0,r.jsx)(n_,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,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>=a.idx&&r<m}).map(e=>(0,r.jsx)(s1,{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)(rg,{message:k,cwd:s,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,r.jsx)(im,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:l}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx)),j,S,x]},`message-${a.idx}`);let C=e4(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:eL(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,r.jsx)(n_,{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 s7({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!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:z,jumpRequest:A=null,onJumpHandled:W}){var P,_;let D,O,H,{t:B}=(0,R.s)(),U=(0,i.useRef)(E);U.current=E;let q=(0,i.useRef)(null),K=(0,i.useRef)(L);K.current=L;let[J,G]=(0,i.useState)([]),Y=(0,i.useRef)(J);Y.current=J;let Z=(0,i.useRef)(0),X=(0,i.useRef)([]),Q=(0,i.useRef)([]),ee=(0,i.useRef)(null),et=(0,i.useRef)(0),en=(0,i.useRef)(-1),er=(0,i.useRef)(-1),ei=(0,i.useCallback)(()=>{let e=ee.current?.current;return e?{sessionId:e,turn:et.current}:null},[]),ea=(0,i.useCallback)(e=>ee.current?.current===e.sessionId&&et.current===e.turn,[]),es=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;Z.current=Math.max(Z.current+1,Date.now());let i={id:Z.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};G(e=>{let t=[...e,a];return null!==a.anchorEntryId&&s5(n.sessionId,t),t})},[]),el=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ea(n)&&("working"!==t||er.current!==n.turn);i()&&U.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&es(e,t,n,r)}).catch(()=>{})},[ea,es]),eo=(0,i.useCallback)(async(e,t,n)=>{let r=(await na(e,t,n))?.alias??null;return r&&K.current?.(r),r},[]),ed=(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=io(e[n]),a=0;for(let t=r;t<=n;t++)io(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(X.current,Q.current);eo(t.sessionId,n,r).then(n=>{el(n,e,t,i)})},[el,eo]),[ec,eu]=(0,i.useState)(0),ep=(0,i.useRef)([]),eh=(0,i.useCallback)(e=>{if(et.current+=1,null!==it(e.outcome)){let t=e.sessionId;ep.current.push({completion:e,trigger:t?{sessionId:t,turn:et.current}:null}),eu(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ep.current.splice(0)){let n=it(e.outcome),r="neutral"===n?null:n;t?ed(r,t,e.provider,e.credentialId):U.current(null,r).catch(()=>{})}},[ec,ed]);let em=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ef,error:eg,messages:ex,entryIds:ev,streamState:eb,agentRunning:ey,bashRunning:ek,pendingBash:ej,modelNames:eS,modelList:eC,modelError:eN,modelScopeWarnings:eI,modelThinkingLevels:eT,modelThinkingLevelMaps:eM,modelRoles:e$,toolPreset:eR,thinkingLevel:eE,effectiveThinkingLevel:ez,thinkingCeiling:eF,fastMode:eD,fastModeBusy:eO,handleFastModeToggle:eB,retryInfo:eG,contextUsage:eY,forkingEntryId:eX,isCompacting:eQ,compaction:e0,compactError:e1,compactResult:e2,displayModel:e4,modelSwitching:e8,sessionStats:e6,runStateKnown:e3,compactedWork:e7,slashCommands:e9,slashCommandsLoading:te,deliveryRows:tt,subagents:tn,todoPhases:tr,notices:ti,extensionDialog:ta,extensionResponse:ts,extensionCustomUi:tl,extensionStatuses:to,extensionWidgets:td,respondToExtensionUi:tc,sendExtensionCustomInput:tu,isAutoModelSelection:tp,agentPhase:th,isNew:tm,autoFollowPaused:tf,resumeAutoFollow:tg,pauseAutoFollow:tx,goalStatus:tv,sessionIdRef:tb,messagesEndRef:ty,scrollContainerRef:tw,handleSend:tk,handleAbort:tj,handleFork:tS,handleNavigate:tC,handleModelChange:tN,handleRoleModelChange:tI,handleMainPresetChange:tT,newSessionAccount:tM,handleCompact:t$,handleSteer:tR,handleFollowUp:tE,handlePromptWithStreamingBehavior:tL,handleAbortCompaction:tz,handleRecallQueue:tA,handleRemoveQueuedMessage:tW,handleBuiltinSlashCommand:tP,handleToolPresetChange:tF,handleThinkingLevelChange:t_,loadSlashCommands:tD,ensureNewSession:tO,refreshLiveTranscript:tH}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=a&&a.sessionId===t?.id?a: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)(sz,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[z,A]=(0,i.useState)(!1),[W,P]=(0,i.useState)(null),[F,_]=(0,i.useState)({}),[D,O]=(0,i.useState)([]),[H,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,ea]=(0,i.useState)("default"),[es,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),[ez,eA]=(0,i.useState)(!1),[eW,eP]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eO]=(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)(sK,{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,ta]=(0,i.useState)([]),[ts,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(iz,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{E||tu({type:"idle"})},[E]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iE(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${iR(t)}`,s=n.get(a)??0;s>0?n.set(a,s-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,ts),[tc,ts]),[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),tz=(0,i.useRef)(null),tA=(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),tO=(0,i.useRef)(!1),tH=(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),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,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,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,l&&(e.input+=l.input??0,e.output+=l.output??0,e.cacheRead+=l.cacheRead??0,e.cacheWrite+=l.cacheWrite??0,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:s,toolResults:a,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&&sF(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&&sF(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 a=r??null;if(!a){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}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=eV(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(s.messages),nm(s.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let l=!n&&t8.current===e;if(l||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!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(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=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&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(sA(i.queuedMessages)),void 0!==i.subagents&&td(e=>sL(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=na.current.then(async()=>{tj.current===e&&await nf(e)});return na.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}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let l=eV(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(l.messages),nm(l.entryIds),M(s.context.compactedWork??null),ej(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nm,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await sv(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),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 a={cwd:r,type:"ensure_session",toolNames:(0,aP.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),l=t0.current,o=l?.body===s?l.createRequestId:sB();t0.current={body:s,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:o})});if(!d.ok)throw Error(`HTTP ${d.status}`);let c=await d.json();t0.current=null,t=c.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),c.model&&t2.current===e&&(eR(c.model),e||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 sv(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 sv(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(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tF.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&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 sH(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 sv(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 sv(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??sB(),message:t,type:e.type??"info"}})},[]),nR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eH,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),a=null;for(let e=i.length-1;e>=0;e--)if(!eK(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eq}${n.seq}`,baseEntryId:a,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(sm(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":ta(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},[]),nz=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=sD(tC.current,tN.current);tz.current=e?{entryId:e.entryId,key:sG(e.message)}:null,tA.current+=1},[]),nA=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let n=sD(tC.current,tN.current),r=n?.message,i=tz.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:sG(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=s_(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=nA();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===n;s?.(e?nA():t)})},[s,nA]),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 a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(td(e=>sL(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eY(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eO(sP(s)),ty.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.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 sU(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 sU(600)}},[n_]),nO=(0,i.useCallback)(async e=>{let t=tP.current+1;for(tP.current=t;tW.current&&tP.current===t&&tj.current===e;){await sU(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,A(!1),P(null);return}catch{}}},[nf]),nH=(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 a=i.state;if(eA(a?.isCompacting??!1),eO(sP(a)),tl(sA(a?.queuedMessages)),a?.contextUsage!==void 0&&ej(a.contextUsage??null),td(e=>sL(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.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(!ez){eB.current=null,eO(null);return}eO(e=>e??{startedAt:Date.now(),reason:eB.current})},[ez]),(0,i.useEffect)(()=>{if(!E&&!ez)return;let e=()=>{let e=tj.current;e&&nU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,ez,nU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&nH(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,nH]),(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(sS,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sS,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 a=e.context.messages,s=new Map;for(let e of a){let t=sG(e);s.set(t,(s.get(t)??0)+1)}let l=Math.min(r.length,i.length);for(let e of r.slice(0,l)){let t=sG(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=sG(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let 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&&nz(),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&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>sL(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(sA(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();eA(!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,sg.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=s_(t)),t&&"user"===t.role){let e=(0,sg.B)(t),n=sJ(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&sJ(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,sg.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 sL(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=>sL(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=>sL(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;eO(e=>e?{...e,reason:t}:e)}eA(!0),eP(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)eP(e.errorMessage),e_(null);else if(!e.aborted){e_(sY(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,nz,nF,nL,nm,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tW.current||ni.current)return"unknown";let l=n1(n,a??[]),o=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}nz();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=sJ(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 sv(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),f=!0,await sv(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 sv(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 sx&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof sx&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&h)return nD(h,d),"unknown";t$.current=!1,tT.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&sJ(t)===s?e.slice(0,-1):e}),n$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,sZ(i),a,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,nz,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}),A(!0);try{let e=tj.current??t?.id??await ny();if(!e)throw Error("Unable to create a session for the shell command");await sv(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),A(!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 sv(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sv(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 sv(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&&(sv(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&&sv(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 sv(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 sv(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,a=t4.current,s=t5.current;try{t2.current=t,t4.current=n??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await sv(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=a,t5.current=s,n$({type:"error",message:i(n)});let t=tj.current;return t&&await nf(t),!1}finally{ni.current=!1,eL(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await sv(a,r),await nf(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),n$({type:"error",message:i(e)}),await nf(a),!1}finally{ni.current=!1,eL(!1)}},[n$,eT,eo,m,nf,Q,es]),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 sv(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&&!ez){eB.current="manual",eA(!0),eP(null),e_(null);try{let t=await sv(e,{type:"compact"});e_(sY(t,"manual")),await nf(e,!0)}catch(e){eP(e instanceof Error?e.message:String(e)),e_(null)}finally{eA(!1)}}},[ez,nf]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();_(s.models),B(s.modelError??null),q(s.modelScopeWarnings??[]),V(s.thinkingLevels??{}),G(s.thinkingLevelMaps??{}),Z(s.roles??[]);let l=s.modelList??[];if(O(l),m&&!tj.current){let e=(s.defaultModel?l.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[m,r,t?.cwd]),n2=(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(),a=await ny(),s=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(!a||ez)return s({handled:!0,error:"No active session to compact"});eB.current="manual",eA(!0),eP(null),e_(null);let e=await sv(a,{type:"compact",...i?{customInstructions:i}:{}});return e_(sY(e,"manual")),await nf(a,!0)&&nb(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await sv(a,{type:"reload"}),await Promise.all([nf(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await sv(a,{type:"set_session_name",name:i}),await nf(a)&&nb(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await sv(a,{type:"get_session_stats"});return e&&e5(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await sv(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nV();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await sv(a,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(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 s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tW.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eY({kind:"running_command"});try{await nI(a);let e=await sv(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nf(a,!0)&&nb(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eY(null),tj.current===a&&nF(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await sv(a,{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 s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[n$,nR,nI,ny,nV,ez,n0,nf,nw,nv,nb,h,nF]),n4=(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,sZ(n),r),"returned";let a=n1(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:a,images:s?.length??0});try{return await sv(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to steer:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,sZ(n),r,i),"returned"}},[n$,e.chatInputRef]),n5=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,sZ(r),i),"returned";let s=n1(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:s,images:l?.length??0});try{return await sv(a,{type:"prompt",message:s,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,sZ(r),i,a),"returned"}},[n$,e.chatInputRef]),n8=(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,sZ(n),r),"returned";let a=n1(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:a,images:s?.length??0});try{return await sv(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to follow up:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,sZ(n),r,i),"returned"}},[n$,e.chatInputRef]),n6=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await sv(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n3=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await sv(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$]),n7=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await sv(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$]),n9=(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 sv(i,{type:"set_thinking_ceiling",ceiling:n}),await sv(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 re=e=>e?`${e}|${ev.current}`:null,rt=t?.id??tj.current,rn=re(rt),rr=ep&&ep.key===rn?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rn&&rt&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(rt)}`).then(e=>e.json()).then(t=>{eg.current===e&&re(tj.current)===rn&&eh({key:rn,value:(t.running?sW(t.state):void 0)??null})}).catch(()=>{})},[rn,E,eE]);let ri=(0,i.useCallback)(async()=>{let e=tj.current??await ny(),t=re(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&re(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=sW(await sv(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await sv(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;n$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(sW(await sv(e,{type:"get_state"}))??null)}catch{i(null)}}finally{ef(!1)}},[ny,ep,n$]),ra=(0,i.useCallback)(async e=>{let t=(0,aP.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await sv(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),rs=(0,i.useCallback)(e=>{tH.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=rs;let rl=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tJ.current=0,rs(!0),rl("smooth")},[rl,rs]),rd=(0,i.useCallback)(()=>{tJ.current=0,rs(!1)},[rs]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!sO.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,A(!0),nO(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eA(n.isCompacting),eO(sP(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&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(sA(n.queuedMessages)),void 0!==n.subagents&&td(e=>sL(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&&!z||!tH.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tG.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[E,z,S.length,$.streamingMessage,eG,W,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tO.current){tO.current=!0,rl("instant");return}if(!t9.current&&tH.current){let e=Date.now()-ne.current<1500;rl(tT.current||tW.current||e?"instant":"smooth")}}},[S.length,E,z,rl,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:H,modelScopeWarnings:U,modelThinkingLevels:K,modelThinkingLevelMaps:J,modelRoles:Y,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:ez,compaction:eD,compactError:eW,compactResult:eF,currentModel:nl,displayModel:no,modelSwitching:eE,sessionStats:nd,runStateKnown:eU,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ts,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:n4,handleFollowUp:n8,handlePromptWithStreamingBehavior:n5,handleAbortCompaction:n6,handleRecallQueue:n3,handleRemoveQueuedMessage:n7,handleBuiltinSlashCommand:n2,handleToolPresetChange:ra,handleThinkingLevelChange:n9,fastMode:rr,fastModeBusy:em,handleFastModeToggle:ri,loadTools:nv,loadSlashCommands:nw,ensureNewSession:ny,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:z,pendingBash:W,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:eh,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tB=ns(e?.id,e4?.provider,void 0),tU=tB?.alias;(0,i.useEffect)(()=>{tU&&K.current?.(tU)},[tU]);let tq=(0,i.useMemo)(()=>{if(!e4)return null;let e=tm?tM:t4.bo.find(e=>e.alias===tB?.alias)?.oauthPosition;return t4.bo.find(t=>t.provider===e4.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[e4,tm,tM,tB]),tK=e4?.provider,tV=e4?.modelId,tJ=tB?.alias,tG=tB?.seed,tY=(0,i.useRef)(tB);tY.current=tB,(0,i.useEffect)(()=>{y&&y(tK&&tV?{provider:tK,modelId:tV,face:tY.current,presetAlias:tq,isNew:tm}:null)},[y,tK,tV,tJ,tG,tq,tm]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let tZ=ey||ek,tX=e?.id;X.current=ex,Q.current=ev,ee.current=tb;let tQ=(0,i.useRef)(!0);tQ.current=!tf;let t0=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ey&&!t0.current&&(et.current+=1),t0.current=ey},[ey]),(0,i.useEffect)(()=>()=>{et.current+=1},[]),(0,i.useEffect)(()=>{G(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(s4(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[]}}(tX),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===tX)])},[tX]),(0,i.useEffect)(()=>{let e=tb.current;e&&Y.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&G(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=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 a=0;for(let s=i;s<r;s++)if(io(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,ex,ev);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(s5(e,r),r):t})},[ex,ev,tb]);let t5=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tb.current,t=t5.current;if(t5.current=e?{sessionId:e,entryIds:ev}: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 a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&r.push(t[a])}return r}(t.entryIds,ev,ex),r=ei();if(0===n.length||!r)return;let i=ni(e,"web6",void 0)?.alias??null;for(let e of n)Y.current.some(t=>t.anchorEntryId===e)||el(i,"done",r,{kind:"entry",entryId:e})},[ev,ex,tb,ei,el]);let t8=ey&&th?.kind==="running_tools"&&th.tools.length>0&&th.tools.every(e=>"wait"===e.name),t6=ef||s,{hideThinkingBlock:t3}=(P=t??e?.cwd??null,D=t2(),(0,i.useEffect)(()=>{t1(P).catch(()=>{})},[P]),D),t7=(0,i.useMemo)(()=>({hideThinking:t3}),[t3]);(0,i.useEffect)(()=>{if(!ta||q.current===ta.id)return;q.current=ta.id;let e=ei();if(e){var t;er.current=e.turn,ed("select"===(t=ta.method)||"ask"===t?"choice":"approval",e,e4?.provider,void 0)}},[ta,e4?.provider,ei,ed]),(0,i.useEffect)(()=>(v=tZ?tj:null,()=>void(v=null)),[tZ,tj]),(0,i.useEffect)(()=>{N?.(tZ)},[N,tZ]),(0,i.useEffect)(()=>()=>N?.(!1),[N]),(0,i.useEffect)(()=>{I?.(t8)},[t8,I]),(0,i.useEffect)(()=>()=>I?.(!1),[I]),(0,i.useEffect)(()=>{T?.(null!==ta)},[T,ta]),(0,i.useEffect)(()=>()=>T?.(!1),[T]);let{main:t9,process:ne}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,l=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),l=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.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:a,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(),a=i.idx,r.push(i);continue}if(eU(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(a,[{idx:i.idx}],0);continue}let s=eW(t,n),d=!1;for(let e of s){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(a,[{idx:i.idx,blocks:e.blocks}],eP(e.blocks)),o.collect(i.idx,e.blocks)}!d&&eA(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(ex,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 a=i,s=a+1;for(;s<e.length&&!eJ(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,l=[],o=0,d=0,c=e_(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:d++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,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&&a.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(a.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),s+=eP(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&eA(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,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(ex,{sessionBusy:tZ,isStreaming:eb.isStreaming,hideThinking:t7.hideThinking}),t7),[ex,tZ,eb.isStreaming,t7]),nt=(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 a=-1,s=-1;t.forEach((e,t)=>{let n=nE(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=r.get(o.position);e?e.calls.push(...n):r.set(o.position,{calls:[...n],placement:l?"after":"before"})}}"user"===e.role&&(a=t),eJ(e)&&(s=t)});let{continuing:l}=nL(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})(t9,ex,e7?.messages),[t9,ex,e7]),nn=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=nL(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 a=e.findIndex(e=>e.idx>i),s=-1===a?e.length:a;return{position:s,jumpTo:s<e.length?s:e.length>0?e.length-1:null,calls:r}})(t9,ex,e7?.messages),[t9,ex,e7]),[nr,nl]=(0,i.useState)(sX),{startIndex:no,endIndex:nd,hasLater:nc}=sQ(t9.length,nr),nu=null!==nr.end&&nc,np=(0,i.useRef)(t9.length);np.current=t9.length;let nh=(0,i.useRef)(null),nm=(0,i.useRef)(null),nf=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nr.end&&nr.end>=t9.length&&nl(e=>({count:e.count,end:null}))},[nr.end,t9.length]),(0,i.useEffect)(()=>{let e=nh.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nf.current=t.scrollHeight-t.scrollTop,nl(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nr,t9.length,tw]),(0,i.useEffect)(()=>{if(null==nf.current)return;let e=tw.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nf.current),nf.current=null}},[nr.count,tw]),(0,i.useEffect)(()=>{let e=nm.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nl(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=sQ(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(np.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nr,t9.length,tw]);let[ng,nx]=(0,i.useState)(null),[nv,nb]=(0,i.useState)(null),[ny,nw]=(0,i.useState)(0),nk=(0,i.useRef)(null),nj=(0,i.useCallback)((e,t=null)=>{tx(),nk.current={item:e,dispatchKey:t},nx(null),nb(null),nl(t=>s0(np.current,e,t)),nw(e=>e+1)},[tx]);(0,i.useLayoutEffect)(()=>{let e,t=nk.current,n=tw.current;if(null===t||!n)return;let r=n.querySelector(`[data-chat-item="${t.item}"]`);if(!r)return;nk.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?nb(t.dispatchKey):nx(t.item)},[ny,nr,t9,tw]),(0,i.useEffect)(()=>{if(null===ng)return;let e=setTimeout(()=>nx(null),1800);return()=>clearTimeout(e)},[ng]),(0,i.useEffect)(()=>{if(null===nv)return;let e=setTimeout(()=>nb(null),1800);return()=>clearTimeout(e)},[nv]);let nW=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>nl(sX));let e=tw.current;e&&(e.scrollTop=e.scrollHeight)},[tw]),nP=(0,i.useCallback)(()=>{nu&&nW(),tg()},[nu,nW,tg]),nF=(0,i.useRef)(null),[n_,nD]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!A||nF.current===A.id||A.sessionId!==e?.id||ef||0===ex.length)return;nF.current=A.id,W?.(A.id);let t=ev.indexOf(A.entryId);if(t<0)return void nD(!0);let n=0;for(let e=0;e<t9.length;e++){let r=t9[e].idx;if(r>t||(n=e,r===t))break}nj(n)},[A,e?.id,ef,ex.length,ev,t9,nj,W]),(0,i.useEffect)(()=>{if(!n_)return;let e=setTimeout(()=>nD(!1),6e3);return()=>clearTimeout(e)},[n_]);let[nO,nH]=(0,i.useState)(!1),[nB,nU]=(0,i.useState)(0),nq=(0,i.useMemo)(()=>nO?t9.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,ex).toLowerCase()):s8,[nO,t9,ex]),nK=(0,i.useCallback)(e=>{tx(),nl(t=>s0(np.current,e,t))},[tx]),nV=(0,i.useCallback)(()=>nH(!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=tw.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(),nH(!0),nU(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tw]);let nJ=(0,i.useMemo)(()=>{let e=[];return t9.forEach((t,n)=>{if("message"!==t.kind)return;let r=s2(ex[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[t9,ex]),nG=`${no}:${nd}`,nY=ev.length>0?ev[ev.length-1]:null,[nZ,nX]=(0,i.useState)(null),nQ=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nQ.current||!e3||ef||!e?.id||(nQ.current=!0,tZ||!nY||!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}(ex)||function(e){try{return window.localStorage.getItem(s6(e))}catch{return null}}(e.id)!==nY&&nX(nY))},[e3,ef,e?.id,tZ,nY,ex]);let n0=(0,i.useCallback)(()=>{e?.id&&nZ&&function(e,t){try{window.localStorage.setItem(s6(e),t)}catch{}}(e.id,nZ),nX(null)},[e?.id,nZ]),n2=null!==nZ&&nZ===nY&&!tZ&&!nu,n4=e6?[e6.sessionId,e6.sessionFile??"",e6.sessionName??"",e6.userMessages,e6.assistantMessages,e6.toolCalls,e6.toolResults,e6.totalMessages,e6.tokens.input,e6.tokens.output,e6.tokens.cacheRead,e6.tokens.cacheWrite,e6.tokens.total,e6.cost??0,e6.totalActiveMs??0].join("|"):null,n5=(0,i.useRef)(e6);n5.current=e6,(0,i.useEffect)(()=>{f?.(n5.current)},[n4,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let n8=eY?`${eY.percent??"null"}|${eY.contextWindow}|${eY.tokens??"null"}`:null,n6=(0,i.useRef)(eY);n6.current=eY,(0,i.useEffect)(()=>{x?.(n6.current)},[n8,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(tn)},[b,tn]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:n3,handleDragEnter:n7,handleDragOver:n9,handleDragLeave:re,handleDrop:rt}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{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=>{tZ||p?.current?.addAttachments(e)},[tZ,p])),rn=(0,i.useMemo)(()=>{var e;return e=e7?.messages,e&&e.length>0?[...e,...ex]:ex},[e7,ex]),rr=(0,i.useMemo)(()=>{let e=new Map;for(let t of rn)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rn]),ri=(0,i.useMemo)(()=>{let e,t,n,r;return e=new Map,t=new Map,n=new Map,r=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},rn.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rr.get(e.toolCallId);if(t)for(let r of nT(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(nI(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=nC(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:nC(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 nS(t.details?.jobs)){if("task"!==e.type)continue;let t=nC(e.id);t&&r(t,nN(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of nI(t.content).matchAll(nM)){let t=Object.fromEntries([...e[1].matchAll(n$)].map(e=>[e[1],e[2]]));t.id&&r(t.id,nN(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:n}},[rn,rr]),ra=(0,i.useMemo)(()=>({ledger:ri,subagents:tn,toolResults:rr,onOpenPanel:w,focusedDispatch:nv}),[ri,tn,rr,w,nv]),rs=(0,i.useMemo)(()=>(function(e,t,n,r,i,a,s=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of n)for(let n of t.calls)o.set(n.toolCallId,e);if(s?.jumpTo!=null)for(let e of s.calls)o.set(e.toolCallId,s.jumpTo);let d=[];if(e.forEach((e,n)=>{if("assistant"!==e.role)return;let s=n>l;for(let n of e.content??[])if("toolCall"===n.type&&"task"===n.toolName)for(let e of nT(n,t.get(n.toolCallId))??[]){let t=nR(e,r,i),l=nz[t.run],c=null;"running"===l&&("live"===t.runSource||s&&a)?c="running":"awaiting"===l&&s&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(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]}})(rn,rr,nt,tn,ri,tZ,nn),[rn,rr,nt,tn,ri,tZ,nn]),rl=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),ro=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ex.length-1;n>=0;n-=1){let r=s2(ex[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ex]),rd=(0,i.useMemo)(()=>(function(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)})(ex,rr,tr,e7?.todoPhases??null),[ex,rr,tr,e7]),rc=(0,i.useMemo)(()=>iy(eb.streamingMessage).join("|"),[eb.streamingMessage]),ru=(0,i.useMemo)(()=>JSON.stringify(ib(eb.streamingMessage)),[eb.streamingMessage]),rp=(0,i.useMemo)(()=>JSON.stringify(ik(eb.streamingMessage)),[eb.streamingMessage]),rh=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=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),s=[],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=iy(r),d=ik(r,a);if(0===i.length&&0===d.length||o<0)continue;let c=ib(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=l.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(a,e),s.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...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 s.sort((e,t)=>e.index-t.index)})(ex,ev,rc.length>0?rc.split("|"):[],JSON.parse(ru),JSON.parse(rp)),[ex,ev,rc,ru,rp]),rm=e?.id??tb.current??void 0,rf=(O=iC(_=(0,i.useMemo)(()=>({sessionId:rm,sessionProvider:e4?.provider,turns:rh,messages:ex,subagents:tn}),[rm,e4?.provider,rh,ex,tn])),H=iM(_),(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,...H])),[O,H])),rx=tm&&0===ex.length&&!eb.isStreaming&&!tZ,rv=e?.cwd??t??void 0,rb=e4?eT[`${e4.provider}:${e4.modelId}`]??null:null,ry=e4?eM[`${e4.provider}:${e4.modelId}`]??null:null,rw=(0,i.useRef)(null),rk=(0,i.useRef)(null),rj=(0,i.useCallback)(()=>{rw.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(C?.(rj),()=>C?.(null)),[rj,C]),(0,i.useLayoutEffect)(()=>{let e=rk.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tw.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tw.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[ef,tw]);let rS=(0,i.useCallback)((...e)=>(null!==nr.end&&nW(),tk(...e)),[tk,nr.end,nW]),rC=(0,r.jsx)("div",{ref:rw,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(sc,{ref:p,sessionId:e?.id??tb.current??void 0,onEnsureSession:tm&&t?tO:void 0,onLiveTranscriptPersisted:tH,onSend:rS,onAbort:tj,onSteer:ey?tR:void 0,onFollowUp:ey?tE:void 0,onPromptWithStreamingBehavior:ey?tL:void 0,isStreaming:tZ,model:e4,isAutoModelSelection:tp,modelNames:eS,modelList:eC,modelError:eN,modelScopeWarnings:eI,onModelChange:tN,onMainPresetChange:e||tm?tT:void 0,mainPresetActiveAlias:tq,modelRoles:e$,onRoleModelChange:tI,modelSwitching:e8,onCompact:e||tm?t$:void 0,onAbortCompaction:tz,isCompacting:eQ,compactError:e1,compactResult:e2,toolPreset:eR,onToolPresetChange:e||tm?tF:void 0,thinkingLevel:eE,effectiveThinkingLevel:ez,thinkingCeiling:eF,onThinkingLevelChange:e||tm?t_:void 0,fastMode:eD,fastModeBusy:eO,onFastModeToggle:e||tm?eB:void 0,availableThinkingLevels:rb,thinkingLevelMap:ry,retryInfo:eG,deliveryRows:tt,inputHistory:ro,onRecallQueue:tA,onRemoveQueuedMessage:tW,slashCommands:e9,slashCommandsLoading:te,onLoadSlashCommands:tD,onBuiltinCommand:tP,soundEnabled:M,onSoundToggle:$,onAudioUnlock:z,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rN=eb.streamingMessage,rI=(0,i.useMemo)(()=>rN?eW(rN,{isStreaming:!0}):[],[rN]),rT=(0,i.useMemo)(()=>rI.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rI]),rM=(0,i.useMemo)(()=>rI.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rI]),r$=rN?.role==="assistant"?rN:null,rR=ey&&(th?.kind==="running_tools"||(r$?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rE=r$?.provider??e4?.provider,rL=r$?.credentialId;(0,i.useEffect)(()=>{if(!rR)return;let e=ei();e&&en.current!==e.turn&&er.current!==e.turn&&(en.current=e.turn,ed("working",e,rE,rL))},[rR,rE,rL,ei,ed]);let[rz,rA]=(0,i.useState)(null),rW=(0,i.useCallback)(e=>{rA(e)},[]),rP=(0,i.useMemo)(()=>ej?{role:"bashExecution",command:ej.command,output:"",excludeFromContext:ej.excludeFromContext}:null,[ej]),rF=(0,i.useMemo)(()=>{let e=[ey&&!rN&&th?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}(th,B):null,ek&&!ej?B("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[ey,rN,th,ek,ej,B]);(0,i.useEffect)(()=>{if(!rz)return void k?.(null);let e=[],t=[],n=0;if(rN&&rM.length>0){let r=rz.messages.length+e.length;for(let i of(e.push(rN),rM))t.push({idx:r,blocks:i}),n+=eP(i)}if(rP&&(t.push({idx:rz.messages.length+e.length}),e.push(rP)),0===t.length)return void k?.(rF?{...rz,status:rF}:rz);let r=-1;for(let e=rz.messages.length-1;e>=0;e--)if(eJ(rz.messages[e])){r=e;break}let i=rz.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),k?.({...rz,groups:i,messages:[...rz.messages,...e],status:rF})},[rz,rM,rN,rP,rF,k]),(0,i.useEffect)(()=>()=>k?.(null),[k]);let r_=td.filter(e=>"belowEditor"!==e.placement),rD=td.filter(e=>"belowEditor"===e.placement);return eg?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eg}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":t6,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n7,onDragOver:n9,onDragLeave:re,onDrop:rt,children:[t6?(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:B("chat.loadingSession")})}):null,n3&&!tZ&&(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:B("chat.attachFile")})}),tl&&(0,r.jsx)(li,{request:tl,onInput:tu}),rx&&!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.0"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.8.0"]})]})]})]}),(0,r.jsx)(lt,{notices:ti,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)(rZ,{open:nO,onClose:nV,containerRef:tw,index:nq,renderedStart:no,renderedEnd:nd,contentKey:ex,onReveal:nK,onProgrammaticScroll:tx,focusRequest:nB,t:B}),n_&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:B("chat.jumpMissing")}),(0,r.jsx)(lt,{notices:ti,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tw,className:"chat-session-scroll 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)(le,{widgets:r_}),(0,r.jsx)(nA.Provider,{value:ra,children:(0,r.jsx)(ih,{utterances:rf,children:(0,r.jsx)(s3,{messages:ex,entryIds:ev,toolResultsMap:rr,modelNames:eS,messageCwd:rv,onOpenFile:j,sessionBusy:tZ,isNew:tm,isStreaming:eb.isStreaming,handleFork:tS,forkingEntryId:eX,handleNavigate:tC,handleEditContent:em,sessionId:e?.id??tb.current??void 0,main:t9,dispatchSlots:nt,compactedDispatch:nn,process:ne,startIndex:no,endIndex:nd,sentinelRef:nh,laterSentinelRef:nm,flashItem:ng,t:B,cues:J,cueFollowRef:tQ,onProcessLogChange:rW})})}),!nu&&eb.isStreaming&&eb.streamingMessage&&rT.length>0&&(0,r.jsx)(rg,{message:eL(eb.streamingMessage,rT),sessionId:e?.id??tb.current??void 0,isStreaming:!0,modelNames:eS,cwd:rv,onOpenFile:j}),n2&&(0,r.jsx)(r4,{onDismiss:n0,t:B}),(0,r.jsx)("div",{ref:ty})]})})}),(0,r.jsx)(rX,{questions:nJ,containerRef:tw,layoutKey:nG,onJump:nj,label:B("chat.questionRail")}),(tZ&&tf||nu)&&(0,r.jsxs)("button",{type:"button",onClick:nP,"aria-label":B("chat.jumpToBottom"),title:B("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,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"})]}),B("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rk,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[ta&&(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)(lr,{request:ta,onRespond:tc,onActivity:e=>void tu(e,"activity"),delivery:ts})})}),(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)(r2,{compaction:e0,t:B}),(0,r.jsx)(s9,{goal:tv,t:B}),(0,r.jsx)(rK,{summary:rs,onJump:nj,onOpenPanel:rl}),(0,r.jsx)(le,{widgets:rD}),rd&&(0,r.jsx)(sp,{phases:rd})]})}),rC,(0,r.jsx)(su,{statuses:to})]})]})}function s9({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tV(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tV(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 le({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 lt({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 a="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:a,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 ln({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:l,children:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let 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:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:a},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 lr({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,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)(ln,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,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:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,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 a=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=a.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]??[],a=r?i.includes(n)?i.filter(e=>e!==n):[...i,n]:[n];return{...t,[e]:a}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,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:s("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:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,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:s("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:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(ln,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,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:s("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)(tU,{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:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,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:s("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:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(ln,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,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:s("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:s("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:s("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:s("chat.submit")}):null]})]})})}function li({request:e,onInput:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),l=eC(e.lines);return(0,i.useEffect)(()=>{a.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")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.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(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.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 a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eN(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function la({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,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"===s.kind?s.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=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),c(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let 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"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,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:a?a.name?.trim()||a.firstMessage?.trim()||a.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,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var ls=n(50640),ll=n(73620);let lo=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function ld(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 lc=["tags","categories","keywords","tag","category"];function lu({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,a=lc.find(t=>Array.isArray(e[t])),s=a?e[a].map(ld).filter(Boolean):[],l=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.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=ld(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 lp={source:"Source",preview:"Preview",diff:"Diff"},lh={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},lm={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 lg(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function lx(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=lg(n.startContainer),i=lg(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let a=Number(r.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(a)||!Number.isInteger(s))return null;if(a<s){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return a>s?null:{startLine:a,endLine:s}}function lv({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,a)=>{let s=e.children??[],l=s[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?s[0]:null,c=o?s.slice(1):s;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":a+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,ls.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${a}`}),(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,ls.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${a}-${r}`}))})]},`source-line-${a}`)})}function lb(e,t,n,r={}){let i=e9(e),a=new URLSearchParams({type:t});for(let[e,t]of(n&&a.set("sessionId",n),Object.entries(r)))void 0!==t&&a.set(e,String(t));return`/api/files/${i}?${a.toString()}`}function ly({filePath:e,sourceSessionId:t}){let{t:n}=(0,R.s)();return(0,r.jsx)("a",{href:lb(e,"download",t),download:te(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 lw(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lk({patch:e}){let t,{t:n}=(0,R.s)(),i=(t=np(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 a=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)s.add(t);let l=[],o=0;for(;o<i.length;)if(s.has(o)){let e=[];for(;o<i.length&&s.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!s.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lh},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?"-":" ",a="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:lm,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:a,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 lj({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=te(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(lb(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=lb(e,"read",n,o?{v:o}:void 0),b=null!=c?lw(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:tt(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:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(ly,{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 lS({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=te(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(lb(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=lb(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:tt(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:lw(c)}),(0,r.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(ly,{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 lC({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eR(e),g="pdf"===f,x=g?lb(e,"read",n,o?{v:o}:void 0):lb(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(lb(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(lb(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:tt(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===f?"docx preview":"pdf"}),null!=c&&(0,r.jsx)("span",{children:lw(c)}),(0,r.jsx)(ly,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]})]}),(0,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:a("i18n.previewFile",{file:te(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function lN({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o}){let d;return eE(e)?(0,r.jsx)(lj,{filePath:e,cwd:t,sourceSessionId:n}):null!==(e$[eR(e)]??null)?(0,r.jsx)(lS,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(d=eR(e))||"docx"===d?d:null)?(0,r.jsx)(lC,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(lI,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o})}function lI({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:a,onMentionLines:s,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d}){let c,u,{isDark:p}=tF(),{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),[z,A]=(0,i.useState)(null),W=(0,i.useCallback)(e=>fetch(lb(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()}`),a=await i.json();if(n!==E.current)return;x(i.ok&&a.supported&&"string"==typeof a.patch?a: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(lb(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 O=(0,i.useMemo)(()=>m?.language==="markdown"?tc(m.content):"",[m]),H=(0,i.useMemo)(()=>m?.language==="markdown"?function(e){let t=function(e){let t=lo.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,ll.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;A(s&&"source"===S&&e?lx(e,window.getSelection()):null)};if(e(),s&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,S,s]);let B=(0,i.useCallback)(n=>{s&&n&&s(tt(e,t),n.startLine,n.endLine)},[t,e,s]);if((0,i.useEffect)(()=>{if(!s||"source"!==S)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=L.current,r=n?lx(n,window.getSelection()):null;r&&(e.preventDefault(),B(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,B,s]),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=e7(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 ${lw(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:tt(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:lp[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(l||s)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{z&&s?B(z):l?.(tt(e,t),!1)},title:z&&s?`${h("i18n.mentionSelectedLines")} (L${z.startLine}${z.startLine!==z.endLine?`-L${z.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!l&&!s,className:"file-viewer-icon-button",children:(0,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)(ly,{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)(lk,{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:[H?.data&&(0,r.jsx)(lu,{data:H.data}),(0,r.jsx)(e3.oz,{remarkPlugins:tf,rehypePlugins:tx,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===i?(0,r.jsx)(tO,{code:a.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tB,{code:a.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 s=a?e2(e,J,t??J):null;return s&&a?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(s))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...a}){delete a.node;let s="string"==typeof e?e2(e,J,t??J):null,l=s?lb(s,"read",n):e;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...a})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:O})]}):(0,r.jsx)(e8.A,{className:N?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?e6.xJ:e6.vs,showLineNumbers:!0,lineNumberStyle:{...lm},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...lh,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)(lv,{...e,wrapLines:N}),wrapLongLines:N,children:q})})]})}function lT({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:a}){let{t:s,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(),a(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,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:ny(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(),a(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:o===e.id?"var(--bg-hover)":"transparent",border:"none",color:o===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("i18n.close"),"aria-label":`${s("i18n.close")} ${e.label}`,children:(0,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 lM=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],l$=new Set(lM);function lR(e){return void 0!==e&&l$.has(e)}function lE(e){if(!e)return[...lM];let t=new Set(e);return lM.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function lL(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return lR(n)?n:"inherit"}function lz(e,t){let n=e.lastIndexOf(":"),r=lR(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var lA=n(98795),lW=n.n(lA);function lP(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function lF({value:e,options:t,onChange:n,disabled:a=!1,placeholder:s="Select…",searchPlaceholder:l="Search options…",noResultsLabel:o="No matching options",ariaLabel:d,className:c,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),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=lP(v.trim());return e?t.filter(t=>lP(`${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}=aW(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:`${lW().root}${c?` ${c}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:lW().trigger,disabled:a,"aria-label":d,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,r.jsx)("span",{className:j?lW().value:lW().placeholder,children:j?.label??(e||s)}),(0,r.jsx)("svg",{className:lW().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:lW().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:lW().searchWrap,children:[(0,r.jsxs)("svg",{className:lW().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:lW().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:lW().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:lW().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:lW().optionCopy,children:[(0,r.jsx)("span",{className:lW().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:lW().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:lW().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:lW().empty,children:o})})]})]})}let l_=["global","project"],lD=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function lO(e){return`${e.provider}/${e.id}`}function lH({cwd:e,onRolesChanged:t}){let{t:n}=(0,R.s)(),[a,s]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,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){s([]),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 a=await r.json();if(a.error)throw Error(a.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();s(a.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{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})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(a.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>a.filter(e=>!e.hidden),[a]),k=w.some(e=>lD.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:l_.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}`:lz(e.selector??"","inherit"),i=lL(e.selector),a=lE(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=lD.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}),s&&(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:s&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(lF,{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=>lO(e)===t),r=n?d[`${n.provider}:${n.id}`]:void 0,i=lL(e.selector),a=lE(r).includes(i)?i:"inherit";y(e.role,lz(t,a))},options:[{value:"",label:n("roles.unset")},...l.map(e=>({value:lO(e),label:`${e.name} — ${e.provider}`,searchText:lO(e)})),...t&&!l.some(e=>lO(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:a.map(a=>{let s=i===a;return(0,r.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===a?n("roles.thinkingInherit"):a,onClick:()=>{s||y(e.role,lz(t,a))},style:{padding:"3px 7px",border:`1px solid ${s?"var(--accent)":"var(--border)"}`,borderRadius:4,background:s?"var(--bg-selected)":"transparent",color:s?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:s?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:a},a)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function lB(e){window.open(e,"_blank","noopener,noreferrer")}var lU=n(67381),lq=n(64433),lK=n(70350),lV=n(88195),lJ=n(9312),lG=n(87275),lY=n(22008),lZ=n(95476),lX=n(35029),lQ=n(14489),l0=n(78728),l1=n(19872),l2=n(7751),l4=n(92526),l5=n(48238),l8=n(57794),l6=n(41098),l3=n(84604),l7=n(15315),l9=n(74278),oe=n(55457),ot=n(71437),on=n(29167),or=n(97283),oi=n(34166),oa=n(33889),os=n(85486),ol=n(74068),oo=n(83546),od=n(83709);let oc={anthropic:{Icon:lU.A,hasColor:!1},openai:{Icon:lq.A,hasColor:!1},"openai-codex":{Icon:lq.A,hasColor:!1},google:{Icon:lK.A,hasColor:!0},"google-vertex":{Icon:lK.A,hasColor:!0},"ant-ling":{Icon:oa.A,hasColor:!0},deepseek:{Icon:lV.A,hasColor:!0},groq:{Icon:lJ.A,hasColor:!1},mistral:{Icon:lG.A,hasColor:!0},moonshotai:{Icon:lY.A,hasColor:!1},"moonshotai-cn":{Icon:lY.A,hasColor:!1},moonshot:{Icon:lY.A,hasColor:!1},minimax:{Icon:lZ.A,hasColor:!0},"minimax-cn":{Icon:lZ.A,hasColor:!0},fireworks:{Icon:lX.A,hasColor:!0},huggingface:{Icon:lQ.A,hasColor:!0},cerebras:{Icon:l0.A,hasColor:!0},openrouter:{Icon:l1.A,hasColor:!1},xai:{Icon:l2.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:l4.A,hasColor:!0},"cloudflare-workers-ai":{Icon:l4.A,hasColor:!0},"vercel-ai-gateway":{Icon:l5.A,hasColor:!1},"github-copilot":{Icon:l8.A,hasColor:!1},"amazon-bedrock":{Icon:l6.A,hasColor:!0},"azure-openai-responses":{Icon:l3.A,hasColor:!0},"kimi-coding":{Icon:l7.A,hasColor:!0},nvidia:{Icon:os.A,hasColor:!0},opencode:{Icon:ol.A,hasColor:!1},"opencode-go":{Icon:ol.A,hasColor:!1},qwen:{Icon:l9.A,hasColor:!0},xiaomi:{Icon:oo.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oo.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oo.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oo.A,hasColor:!1},zai:{Icon:od.A,hasColor:!1},"zai-coding-cn":{Icon:od.A,hasColor:!1},zhipu:{Icon:oe.A,hasColor:!0},cohere:{Icon:ot.A,hasColor:!0},perplexity:{Icon:on.A,hasColor:!0},together:{Icon:or.A,hasColor:!0},grok:{Icon:oi.A,hasColor:!1}},ou=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function op({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 oh={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 om({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...oh,fontFamily:i?"var(--font-mono)":"inherit"}})}function of({value:e,onChange:t,placeholder:n,mono:a,onKeyDown:s,autoComplete:l="off",spellCheck:o=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,R.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,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:s,placeholder:n,style:{...oh,paddingRight:34,fontFamily:a?"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 og({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:oh})}function ox({value:e,onChange:t,options:n,required:i}){let{t:a}=(0,R.s)();return(0,r.jsx)(lF,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${a("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function ov({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 ob({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 oy({name:e,provider:t,onChange:n,onRename:a,onDelete:s,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,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)(ob,{children:o("i18n.provider")}),(0,r.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:o("i18n.delete")})]}),(0,r.jsxs)(op,{label:o("i18n.providerName"),children:[(0,r.jsx)(om,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>a(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:4,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:o("i18n.rename")})]}),(0,r.jsx)(op,{label:"Base URL",children:(0,r.jsx)(om,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(op,{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)(op,{label:"API",children:(0,r.jsx)(ox,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:ou,required:!0})}),(0,r.jsxs)(op,{label:"Headers",children:[(0,r.jsx)(oC,{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:{...oh,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 ow=["off","minimal","low","medium","high","xhigh","max"],ok={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oj({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:ow.map(e=>{let t=n[e],a=e in n?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=ok[e],o={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,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"===a?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===a?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===a?"line-through":"none"},children:e})]}),(0,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"===a?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===a?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===a?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,s||e),style:{...o,..."string"===a?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:s,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==a&&i(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===a?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===a?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oS={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oC({headers:e,onChange:t}){let[n,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),s=(0,i.useRef)(n.length),l=e=>{a(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:{...oh,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:{...oh,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:()=>a(e=>[...e,{id:s.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function oN({providerName:e,provider:t,model:n,onChange:a,onDelete:s}){let[l,o]=(0,i.useState)({phase:"idle"}),{t:d}=(0,R.s)(),[c,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>a({...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 s=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${s}`),o=await l.json();if(i!==p.current)return;if(!l.ok||o.error||!o.recommendation)return void u({phase:"error",message:o.error??`HTTP ${l.status}`});let d=function(e,t){let 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??{}},a=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],a=!0,r+=1);a&&(n.cost=i)}return{model:n,appliedCount:r}}(n,o.recommendation.preset);d.appliedCount>0&&(h.current=n,a(d.model)),u({phase:"success",recommendation:o.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,n,a,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)(ob,{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:s,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(op,{label:"ID *",children:(0,r.jsx)(om,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(op,{label:"Name",children:(0,r.jsx)(om,{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,a(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsx)(op,{label:"API override",children:(0,r.jsx)(ox,{value:n.api??"",onChange:e=>m("api",e||void 0),options:ou})}),(0,r.jsxs)(op,{label:"Headers",children:[(0,r.jsx)(oC,{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)(ov,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(ov,{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)(ov,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oS}};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)(ov,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>a({...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)(ob,{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)(oj,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(op,{label:"Context window (tokens)",children:(0,r.jsx)(og,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(op,{label:"Max output tokens",children:(0,r.jsx)(og,{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)(ob,{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)(op,{label:e,children:(0,r.jsx)(og,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void a({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let oI={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function oT({provider:e,onRefresh:t,relogin:n}){let a=n?.onLoginSucceeded,[s,l]=(0,i.useState)({phase:"idle"}),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=void 0!==n;(0,i.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),c(""),u.current?.close(),u.current=null},[e.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,i.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,c(""),l({phase:"success"}),t(),a?.())},[t,a]),x=(0,i.useCallback)(()=>{u.current?.close(),p.current=!1,l({phase:"connecting"}),c("");let t=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);u.current=t,t.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),lB(n.url)):"device_code"===n.type?(l({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),lB(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"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(ob,{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)(nc,{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"===s.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"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,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"===s.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":s.message}),"auth"===s.phase&&(0,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:s.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(s.token,d)},placeholder:"auth"===s.phase?"Paste the redirect URL or code":s.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>y(s.token,d),disabled:!d.trim(),style:{padding:"6px 12px",background:d.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:d.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:d.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:o("i18n.submit")})]})]}),"device_code"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(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(oI[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:o("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.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 oM({provider:e,onRefresh:t}){let[n,a]=(0,i.useState)(""),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,R.s)();(0,i.useEffect)(()=>{a(""),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}`):(a(""),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)(ob,{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)(op,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(of,{value:n,onChange:a,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:s||!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:s||!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":s?"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 o$({id:e,size:t}){let n=oc[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 oR({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:a,onAddCustom:s,onClose:l}){let[o,d]=(0,i.useState)(""),{t:c}=(0,R.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=o.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),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:()=>{s(),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,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)(o$,{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:()=>{a(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,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)(o$,{id:e.id,size:28})]},e.id))]})})]})})}function oE({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:a,relogin:s}){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)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[w,k]=(0,i.useState)([]),[j,S]=(0,i.useState)([]),[C,N]=(0,i.useState)(!1),I=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>k(e.providers)).catch(()=>{})},[]),T=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),M=(0,i.useCallback)(()=>{I(),T()},[I,T]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{c(e.providers?e:{...e,providers:{}})}).catch(()=>c({providers:{}})).finally(()=>p(!1)),M()},[M]);let $=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;d.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),y({type:"provider",name:e})},[d.providers]),E=(0,i.useCallback)((e,t)=>{c(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)},[]),z=(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})},[]),A=(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??[]],a=new Set(i.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),F=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},a=[...i.models??[]];return a[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:a}}}})},[]),_=(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),a?.(),setTimeout(()=>v(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[d,a]),O=Object.entries(d.providers??{}),H=w.filter(e=>e.loggedIn),B=j.filter(e=>e.configured),U=(()=>{if(!b)return null;if("roles"===b.type)return(0,r.jsx)(lH,{cwd:e??null,onRolesChanged:a});if("oauth"===b.type){let e=w.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oT,{provider:e,onRefresh:M,relogin:s?.target.provider===e.id?s:void 0},e.id):null}if("apikey"===b.type){let e=j.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oM,{provider:e,onRefresh:M},e.id):null}if("provider"===b.type){let e=d.providers?.[b.name];return e?(0,r.jsx)(oy,{name:b.name,provider:e,onChange:e=>E(b.name,e),onRename:e=>L(b.name,e),onDelete:()=>z(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)(oN,{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)"}}),H.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)(o$,{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)(o$,{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)}),(H.length>0||B.length>0)&&O.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")}):O.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(),A(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,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)(oR,{oauthProviders:w,apiKeyProviders:j,onSelectOAuth:e=>y({type:"oauth",providerId:e}),onSelectApiKey:e=>y({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>N(!1)})]})}function oL(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oz(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function oA(e){let t=oz(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function oW(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function oP(e){return e?e.slice(0,8):"unknown"}function oF({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 o_({skill:e,cwd:t,onToggle:n,toggling:i,saveError:a,updateStatus:s,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=oz(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 oL(e)}(e.filePath)}),(0,r.jsx)(oF,{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")}),a&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),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:oP(s?.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")}),s?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:oP(s.latestVersion)}),(l||s&&"update-available"!==s.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":s?.state==="up-to-date"?"#16a34a":s?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):s?.state==="up-to-date"?p("i18n.upToDate"):s?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):s?.message||p("i18n.checkFailed")}),s?.state==="update-available"&&(0,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 oD({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,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}`)),a()}catch(e){v(String(e))}finally{g(null)}},[a,w,e]),N="global"===w?"~/.claude/skills/":`${oL(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:s("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:s("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,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?s("i18n.searching"):s("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:s("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,a=e.package.indexOf("@"),l=a>-1?e.package.slice(0,a):e.package,o=a>-1?e.package.slice(a+1):null;return(0,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?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("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 oO({cwd:e,onClose:t,embedded:n=!1}){let a=P(),{t:s}=(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),[z,A]=(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&&A(t=>({...t,[oA(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(oW).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=oW(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 a=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:a,latestVersion:a}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,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&&A(t=>({...t,[oA(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),O=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%":a?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":a?"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:s("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:oL(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:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,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:s("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:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===oz(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===oz(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===oz(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===oz(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===oz(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,a=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:a?"var(--border)":"var(--accent)",boxShadow:a?"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:a?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=oW(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:s("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),a=n.filter(e=>e.disableModelInvocation),l=z[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),a.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>A(t=>({...t,[e]:!l})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),s("i18n.dormant")," (",a.length,")"]}),l&&a.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"})]}),s("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(oD,{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:O?(0,r.jsx)(o_,{skill:O,cwd:e,onToggle:D,toggling:f.has(O.filePath),saveError:x,updateStatus:oW(O)?w[oW(O)]:void 0,checkingUpdate:!!oW(O)&&j.has(oW(O)),updating:I===oW(O),updateError:M,onCheckUpdate:()=>void F(O),onUpdate:()=>void _(O)},O.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("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?s("i18n.checking"):s("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?s("i18n.update"):s("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:s("i18n.close")})]})]})})}let oH="global";function oB(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oU(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function oq(e){return`${e.scope}\0${e.source}`}function oK(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 oV(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 oJ(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function oG({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 oY({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 oZ(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 oX({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 oQ({installDir:e,source:t,busy:n,actionError:a,onSourceChange:s,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,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:oB(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=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=oU(t);n!==t&&(e.preventDefault(),s(n))},onBlur:e=>s(oU(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:{...oZ(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:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function o0({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:a,sessionId:s,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=oq(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)(oX,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(oY,{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:oZ(u||p),children:d(n===`update:${c}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:o,disabled:!s||p||u,style:oZ(!s||p||u),title:d(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:oZ(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:oJ(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:oV(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:oK(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?oB(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:oB(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)(oG,{pkg:e})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function o1({cwd:e,sessionId:t,onClose:n,onReloaded:a,embedded:s=!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=>oq(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=>oq(t)===e)?e:n.packages[0]?oq(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=oq(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]?oq(i.packages[0]):null),0===i.packages.length&&v(!0),N(o("i18n.packageRemoved"));else{let e={install:o("i18n.packageInstalled"),update:o("i18n.packageUpdated"),disable:o("i18n.packageDisabledRestartRequired"),enable:o("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,o]),z=(0,i.useCallback)(async()=>{let t=oU(b).trim();if(!t)return;y(t);let n=`${oH}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,a,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:oH,cwd:e})}),l=await s.json();if(!s.ok||l.error)throw Error(l.error??`HTTP ${s.status}`);c(l);let d=(r=l.packages,a=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===oH&&e.source===i)??r.find(e=>e.scope===oH&&e.source===`npm:${a}`)??r.find(e=>e.scope===oH&&e.source.endsWith(i)));g(d?oq(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]),A=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await sv(t,{type:"reload"}),a?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,a,t,o]),W=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:s?"100%":l?"calc(100vw - 16px)":860,maxWidth:s?"none":"calc(100vw - 16px)",height:s?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:s?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:s?"none":"1px solid var(--border)",borderRadius:8*!s,display:"flex",flexDirection:"column",boxShadow:s?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,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:oB(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=oq(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:oJ(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:oK(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:oV(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)(oQ,{installDir:d?.installDir,source:b,busy:W,actionError:j,onSourceChange:y,onInstall:z}):u?null:T?(0,r.jsx)(o0,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:A},oq(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:oZ(u||null!==w),children:o("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:oZ(!1),children:o("i18n.close")})]})]})})}var o2=n(13004),o4=n.n(o2);function o5(){let[e,t]=(0,i.useState)(null),[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[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),a(null)}catch(e){a(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:o4().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:o4().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:o4().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:o4().reloadNotice,children:(0,r.jsx)("span",{children:o})})]}),(0,r.jsxs)("div",{className:o4().settingsBody,children:[(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:o4().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:o4().settingDescription,children:"Set a password below before turning this on."}),s&&(0,r.jsx)("div",{className:o4().error,children:s})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("button",{type:"button",className:o4().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:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:o4().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{className:o4().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:o4().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{className:o4().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:o4().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:o4().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:o4().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:o4().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:o4().settingControl,children:(0,r.jsx)("a",{className:o4().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:o4().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:o4().settingControl})]})]})]})]})}let o8="/api/live/character-voice",o6={ready:"chat.liveVoiceStateReady","not-prepared":"chat.liveVoiceStateNotPrepared",preparing:"chat.liveVoiceStatePreparing","needs-check":"chat.liveVoiceStateNeedsCheck",failed:"chat.liveVoiceStateFailed","missing-asset":"chat.liveVoiceStateMissingAsset"},o3={failed:!0,"needs-check":!0,"missing-asset":!0};async function o7(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 o9(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[a,s]=(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{s(await o7(await fetch(o8,{cache:"no-store"})))}catch(t){o(t instanceof Error?t.message:e("chat.liveVoiceLoadFailed"))}},[e]);(0,i.useEffect)(()=>{f()},[f]);let g=a?.preparing===!0;(0,i.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>void f(),2e3);return()=>clearTimeout(e)},[g,a,f]);let x=(0,i.useCallback)(async e=>{m(!0),o(null);try{return s(await o7(await fetch(o8,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(!a)return(0,r.jsx)("div",{className:o4().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"});let b=a.configured,y=l??a.lastError??null;return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:o4().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsxs)("div",{className:o4().settingsBody,children:[(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e("chat.liveVoiceKeyLabel")}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:t,className:o4().settingLabel,style:{display:"block"},children:e("chat.liveVoiceKeyLabel")}),(0,r.jsx)("div",{className:o4().settingDescription,children:e("chat.liveVoiceKeyHelp")}),b&&a.keyHint&&(0,r.jsx)("div",{className:o4().saveState,style:{overflowWrap:"anywhere"},children:e("chat.liveVoiceKeySaved",{hint:a.keyHint})})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{id:t,className:o4().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:o4().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:o4().dangerButton,disabled:h||g,onClick:()=>void x({method:"DELETE"}),children:e("chat.liveVoiceKeyRemove")}),(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:h||!d.trim(),onClick:()=>void v(),children:e("chat.liveVoiceKeySave")})]})]})]}),(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e("chat.liveVoicePrepare")}),(0,r.jsxs)("div",{className:o4().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:o4().settingDescription,style:{display:"block",color:"var(--text)"},children:e("chat.liveVoiceConsent")}),(0,r.jsxs)("div",{className:o4().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:o4().settingControl,style:{alignItems:"center"},children:(0,r.jsx)("button",{type:"button",className:o4().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:o4().error,role:"alert",style:{overflowWrap:"anywhere"},children:y})]}),(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e("chat.liveVoiceCharacters")}),(0,r.jsx)("ul",{"aria-live":"polite",style:{listStyle:"none",margin:0,padding:0},children:a.characters.map(t=>(0,r.jsxs)("li",{className:o4().settingRow,style:{minHeight:44},title:t.error,children:[(0,r.jsxs)("div",{className:o4().settingLabel,style:{marginBottom:0},children:[t.alias,"provisional"===t.tuning&&(0,r.jsxs)("span",{className:o4().settingDescription,style:{fontWeight:400},children:[" \xb7 ",e("chat.liveVoiceProvisional")]})]}),(0,r.jsx)("div",{className:o4().settingControl,style:{fontSize:12,color:o3[t.state]?"var(--danger)":"ready"===t.state?"var(--text)":"var(--text-muted)"},children:e(o6[t.state])})]},t.id))})]})]})]})}function de(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return aI({signal:e.signal}).then(e=>{s(e),o(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let f=(0,i.useCallback)(async e=>{p(!0),c(null),m(!1);try{let t=await aT(e);s(t),o(String(t.uploadLimitMb)),m(!0)}catch(e){c(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return a?(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:o4().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:o4().settingsBody,children:(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:o4().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:o4().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{id:t,className:o4().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:l,disabled:u,onChange:e=>o(e.target.value),onBlur:()=>{let t=l.trim();if(t===String(a.uploadLimitMb))return;let 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:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:o4().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:o4().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:a.orphanGraceDays})})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("button",{type:"button",className:o4().switch,"data-on":a.autoCleanupEnabled,"aria-pressed":a.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!a.autoCleanupEnabled})})})]}),d&&(0,r.jsx)("div",{className:o4().error,role:"alert",style:{overflowWrap:"anywhere"},children:d}),h&&!d&&(0,r.jsx)("div",{className:o4().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:o4().empty,children:d?`${e("chat.attachmentSettingsLoadFailed")}: ${d}`:"…"})}function dt({cwd:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[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)}`:"",s=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),o=await s.json();if(n!==b.current||r.signal.aborted)return;if(!s.ok||!o.projects)throw Error(o.error??`HTTP ${s.status}`);let d=o.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=o.projects,a(o.projects),l(null),d&&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 s=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=s,a(s),"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:o4().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,r.jsx)("button",{type:"button",className:o4().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:o4().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:o4().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,r.jsx)("div",{className:o4().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,r.jsx)("div",{className:o4().settingsBody,children:(0,r.jsxs)("section",{className:o4().group,children:[0===n.length&&(0,r.jsx)("div",{className:o4().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=c===e.cwd,a=o?.cwd===e.cwd?o:null,s=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),l=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:o4().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:o4().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:o4().settingDescription,style:{fontWeight:600},children:s})]}),(0,r.jsx)("code",{className:o4().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:o4().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:o4().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:o4().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),a&&(0,r.jsx)("div",{className:o4().settingDescription,style:{color:"var(--text)"},children:"revoke"===a.action?t("trust.confirmRevoke"):a.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:o4().saveState,children:m.text})]}),l&&(0,r.jsx)("div",{className:o4().error,role:"alert",children:l})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:o4().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:o4().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"===a.action?o4().dangerButton:o4().primaryButton,disabled:N,onClick:()=>void C(e.cwd,a.action),children:"revoke"===a.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:o4().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:o4().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:o4().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이다"}}}'),dr=[{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"}],di={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 da({kind:e}){return(0,r.jsx)("svg",{className:o4().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:di[e]??di.tools})}function ds({field:e,busy:t,onSave:n}){let[a,s]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:o4().textInput,type:"secret"===e.type?"password":"text",value:a,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{a!==l&&("secret"!==e.type||a.length>0)&&n(a)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function dl({field:e,busy:t,onSave:n}){let a=JSON.stringify(e.value??{},null,2),[s,l]=(0,i.useState)(a),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(a),d(null)},[a]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:o4().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(s!==a)try{n(JSON.parse(s)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,r.jsx)("div",{className:o4().error,children:o})]})}function dd({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],a=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let a=[...i];[a[e],a[r]]=[a[r],a[e]],n(a)};return(0,r.jsx)("div",{className:o4().multiSelect,children:e.options?.map(s=>{let l=i.indexOf(s.value);return(0,r.jsxs)("span",{className:o4().choice,"data-selected":l>=0,title:s.description,children:[(0,r.jsx)("button",{type:"button",className:o4().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:s.label}),e.ordered&&l>=0&&(0,r.jsxs)("span",{className:o4().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>a(l,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>a(l,1),children:"→"})]})]},s.value)})})}function dc({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:o4().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(lF,{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)(dd,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(dl,{field:e,busy:t,onSave:n}):(0,r.jsx)(ds,{field:e,busy:t,onSave:n})}function du({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:e.label}),(0,r.jsx)("div",{className:o4().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:o4().error,children:n})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)(dc,{field:e,busy:t,onSave:i})})]})}function dp({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:o4().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:o4().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:o4().themePreviewPanel,children:[(0,r.jsx)("div",{className:o4().themePreviewLine}),(0,r.jsx)("div",{className:o4().themePreviewLine})]})]})}let dh='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',dm=new Set(["hideThinkingBlock"]);function df({cwd:e,sessionId:t,initialSection:n="models",onClose:a,onModelsChanged:s,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}=tF(),{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(dh)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(dh)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let z=(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 tP(e),await L()):dm.has(t.path)?await t1(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]),A=(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,A))??[],[c?.fields,A]),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)(()=>{s?.(),a()},[a,s]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sv(t,{type:"reload"}),j(!1),l?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),O=c?.tabs.find(e=>e.id===P),H=g.trim()?`${E("Search")} \xb7 ${F.length}`:O?.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:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:t}),n.map(e=>(0,r.jsx)(du,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void z(e,t)},e.path))]},t):null}),U=()=>p?(0,r.jsx)("div",{className:o4().empty,children:E("Loading omp settings…")}):m||!c?(0,r.jsx)("div",{className:o4().empty,children:m??E("Settings unavailable")}):(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:H}),(0,r.jsx)("p",{className:o4().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:o4().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:o4().settingsBody,children:F.length?B(F,O?.groups??[]):(0,r.jsx)("div",{className:o4().empty,children:E("No settings match this search.")})})]});return(0,r.jsx)("div",{className:o4().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&_()},children:(0,r.jsxs)("div",{ref:$,tabIndex:-1,className:o4().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,r.jsxs)("aside",{className:o4().sidebar,children:[(0,r.jsxs)("div",{className:o4().brand,children:[(0,r.jsx)("div",{className:o4().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:o4().title,children:E("Settings")}),(0,r.jsx)("code",{className:o4().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,r.jsxs)("div",{className:o4().searchWrap,children:[(0,r.jsxs)("svg",{className:o4().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:o4().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:o4().nav,children:[(0,r.jsx)("div",{className:o4().navLabel,children:E("Configuration")}),dr.map(t=>{let n=t.labelKey?M(t.labelKey):E(t.label);return(0,r.jsxs)("button",{type:"button",className:o4().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)(da,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:o4().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:o4().navButton,"data-active":!g&&P===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,r.jsx)(da,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:o4().closeRail,children:(0,r.jsxs)("button",{type:"button",className:o4().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:o4().content,children:g.trim()?U():"models"===o?(0,r.jsx)(oE,{cwd:e,embedded:!0,onClose:_,onModelsChanged:s}):"themes"===o?c?(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:E("Themes")}),(0,r.jsxs)("p",{className:o4().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:o4().settingsBody,children:[(0,r.jsx)("div",{className:o4().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:o4().themeCard,children:[(0,r.jsx)(dp,{mode:e,palette:n}),(0,r.jsxs)("div",{className:o4().themeCardBody,children:[(0,r.jsxs)("div",{className:o4().themeCardHeader,children:[(0,r.jsxs)("span",{className:o4().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,r.jsx)("span",{className:o4().themeActive,children:E("Active on web")})]}),(0,r.jsx)(lF,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void z(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:o4().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:o4().empty,children:p?E("Loading themes…"):m??E("Themes unavailable")}):"skills"===o&&e?(0,r.jsx)(oO,{cwd:e,embedded:!0,onClose:_}):"plugins"===o&&e?(0,r.jsx)(o1,{cwd:e,sessionId:t,embedded:!0,onClose:_,onReloaded:l}):"mcp"===o?(0,r.jsx)(dg,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,r.jsx)(o5,{}):"trust"===o?(0,r.jsx)(dt,{cwd:e}):"live-voice"===o?(0,r.jsx)(o9,{}):"attachments"===o?(0,r.jsx)(de,{}):U()})]})})}function dg({cwd:e,sessionId:t,onReloaded:n}){let[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,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}`);s(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=a?"user"===l?a.user:a.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(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})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${l}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:r.name,enabled:!r.enabled})}),s=await a.json();if(!a.ok||s.error)throw Error(s.error??`HTTP ${a.status}`);await w(),t&&(await sv(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:o4().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:o4().settingsBody,children:a?(0,r.jsxs)("div",{className:o4().mcpLayout,children:[(0,r.jsxs)("aside",{className:o4().mcpList,children:[(0,r.jsxs)("div",{className:o4().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:o4().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",a.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:o4().scopeButton,"data-active":"project"===l,disabled:!a.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",a.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:o4().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:o4().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${l}:${e.name}`;return(0,r.jsxs)("div",{className:o4().serverRow,"data-active":d===t,children:[(0,r.jsxs)("button",{type:"button",className:o4().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,r.jsx)("span",{className:o4().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:o4().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:o4().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:o4().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:o4().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:o4().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:o4().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:o4().editorHeader,children:[(0,r.jsx)("input",{className:o4().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:o4().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:o4().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:o4().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:o4().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:o4().error,children:f}),(0,r.jsx)("div",{className:o4().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:o4().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:o4().empty,children:f??"Loading MCP configuration…"})})]})}let dx="cuelo-notification-prompt-dismissed";function dv({variant:e,locale:t,permission:n,dismissed:i,request:a,dismiss:s}){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:a,children:l?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,r.jsx)(d.k.Item,{disabled:"denied"===n,onClick:"default"===n?a: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 db({cwd:e,busy:t,scheduled:n,error:a,onCancel:s,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[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||s()},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}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:a})]})]}),(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:s,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 dy=n(55681),dw=n(54265);let dk={kind:"loading"};function dj(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,ij.Ch)(e.status)?"var(--accent)":"var(--success)"}function dS(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let dC={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function dN(e){return e.lastUpdate||e.progress?.durationMs||0}function dI(){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 dT({sessionId:e,sessionCwd:t,record:n,client:a,visible:s,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,ij._Z)(o,{sessionId:e,client:a,enabled:s}).get(n.key)?.state??dk;(0,i.useEffect)(()=>{if(!s||"ready-live"!==c.kind&&"ready-archive"!==c.kind)return;let e=requestAnimationFrame(()=>{let e=d.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[c,s]);let u="ready-live"===c.kind?c.entries:[],p=(0,i.useMemo)(()=>{let e=new Map;for(let t of u)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[u]),h=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:dI(),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:dS(n)})]}),n.live&&(0,r.jsx)("span",{style:{color:dj(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)(rg,{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 dM({record:e,onSelect:t}){let n=e.live,i=e.archive,a=(0,nk.$V)(e),s=n?.id||i?.name||"Subagent",l=dS(e),o=(0,nk.wX)(e),d=(0,nk.A7)(e),c=d.modelShort??"모델 미확인",u=d.effort??"추론 미확인",p="known"===o.kind?o.label:"역할 미확인";return(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:t,"data-identity":e.identity,title:`${s}
19
+ ${n}`:e:n,images:s,documents:l}}function ap(e,t,n){if(e===t)return n?as(n):ao(t);let r=ao(e),i=n&&!al(n)?as(n):r??(n?as(n):null),a=ao(t),s=i1.get(e);if(i1.delete(e),s&&!i1.has(t)&&i1.set(t,s),ac(e),!i)return a;let l=a?au(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return ad(t,l),as(l)}function ah(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function am(e){ai();let t=i1.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)}`}(),i1.set(e,t)),t}function af(e){let t=ah(iX.get(e)?.documents),n=t.length?am(e):i1.get(e);for(let[e,n]of i3){for(let e of t)n.delete(e);0===n.size&&i3.delete(e)}let r=`${n??""}|${t.join(",")}`;i9.get(e)!==r&&(0!==t.length||n?i9.set(e,r):i9.delete(e),ak())}async function ag(e){let t=am(e);i6.set(t,(i6.get(t)??0)+1),await ae.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(i6.get(t)??1)-1;if(r>0?i6.set(t,r):i6.delete(t),e){let n=i3.get(t)??new Set;n.add(e),i3.set(t,n)}i2.set(t,i4),ak()}}}function ax(e,t){let n=i7.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&i7.delete(e),[...n].sort()}async function av(){if(!at)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 i1)t(n,ah(iX.get(e)?.documents));for(let{draftId:e,ids:n}of i5.values())t(e,n);for(let[e,n]of i3)t(e,n);for(let e of i2.keys())t(e,[]);for(let e of i7.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(i6.has(e))return!1;let n=i2.get(e);return ax(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=i6.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=ax(r,i),a=at(r,i,e).then(()=>{0===i.length?i2.delete(r):i2.set(r,i.join(","));let t=i7.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&i7.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});ae.set(r,a),await a,ae.get(r)===a&&ae.delete(r)}n?function(){if(aw)return;aw=!0;let e=setTimeout(()=>{aw=!1,ak()},ay);"object"==typeof e&&"unref"in e&&e.unref(),ay=Math.min(2*ay,6e4)}():ay=ab}let ab=5e3,ay=5e3,aw=!1;function ak(){if(at){if(an){ar=!0;return}an=Promise.resolve().then(av).finally(()=>{an=null,ar&&(ar=!1,ak())})}}let aj=Math.floor(Number.MAX_SAFE_INTEGER/1048576),aS=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function aC(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=aj}async function aN(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!aC(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:aC((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:aS.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:aS.autoCleanupEnabled,orphanGraceDays:7}}async function aI(e={}){return aN(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function aT(e){return aN(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function aM(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 a$(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function aR(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 aE="omp-web:model-picks";function aL(){try{let e=JSON.parse(window.localStorage.getItem(aE)??"{}");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 az(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,n-2*s)),d=Math.max(0,e-a-s),c=Math.max(0,n-t-a-s),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 aA(e,t,n){return Math.min(e*t,n)}function aW(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:l,minHeight:o,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=az(i.top,i.bottom,n,aA(n,r,a),{gap:s,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,a,s,l,o,d,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 aP=n(14755);async function aF(e,t,n,r,i,a,s){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await s?.()??[],d=[...aX,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await 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 a_(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let aD=["off","default","full"],aO={off:"none",default:"default",full:"full"},aH=aP.IN.join(" \xb7 "),aB=aP.C1.filter(e=>!aP.IN.includes(e)).join(" \xb7 ");function aU(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let aq=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),aK=0,aV={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function aJ(e,t){return aq.compare(e.name||e.modelId,t.name||t.modelId)||aq.compare(e.provider,t.provider)||aq.compare(e.modelId,t.modelId)}let aG=["auto","off","minimal","low","medium","high","xhigh","max"],aY=["low","medium","high","xhigh"],aZ={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},aX=[{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"}],aQ=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],a0={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},a1={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function a2(e,t,n){let r=e.name.toLowerCase(),i=a4(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function a4(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function a5(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function a8(e){return{data:e.data,mimeType:e.mimeType}}function a6(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function a3(e){return(e??[]).filter(iZ).slice(0,10).map(a6)}let a7=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,a9="\n\nTranscript of the audio ";function se(e){return nQ(e).map(e=>{let t=n6(e),n="audio"===t&&e.attachmentId&&!e.text.includes(a9)?a7.exec(e.text):null;return{...e,id:++aK,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function st({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 sn(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 sr extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let si="composer:unkeyed";async function sa(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new sr("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 ss(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sl({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 so({error:e}){return e?(0,r.jsx)(sl,{tone:"error",title:"Model error",body:e}):null}function sd({warnings:e}){return e&&0!==e.length?(0,r.jsx)(sl,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sc=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,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:z=null,fastModeBusy:A=!1,onFastModeToggle:W,retryInfo:F,deliveryRows:_=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,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,ea,es,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:em}=nd(),ef=_.some(e=>e.removable),eg=P(),[ex,ev]=(0,i.useState)(()=>Z?ao(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(aL())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,ez]=(0,i.useState)(!1),[eA,eW]=(0,i.useState)(null),[eP,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?a3(ao(Z)?.images):[]),[eO,eH]=(0,i.useState)(()=>Z?se(ao(Z)?.documents):[]),[eB,eU]=(0,i.useState)(null),eq=(0,i.useMemo)(()=>eO.filter(e=>"ready"===e.status),[eO]),eK=eO.some(e=>"ready"!==e.status||a_(e)),eV=eO.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(a9))),eJ=ex.trimStart(),eG=0===e_.length&&0===eO.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),[ta,ts]=(0,i.useState)(null),[tl,to]=(0,i.useState)(null),td=X&&tl?.cwd===X?tl.values:{},tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),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)(eO);t$.current=ex,tR.current=e_,tL.current=eO,(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"),n2(t)?.message??t),a=a3("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 iZ(r)?[r]:[]})),s=se((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n2(n)?.documents??[]));t$.current=i,tR.current=a,tL.current=s,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(ss),a)),eH(s),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 ap(e,t);let n={value:t$.current,images:tR.current.map(a8),documents:tL.current.filter(e=>"ready"===e.status).map(st)},r=ap(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 a=a3(r.images),s=sn(se(r.documents),tL.current),l=r.value;t$.current=l,tR.current=a,tL.current=s,ev(l),eD(e=>(e.forEach(ss),a)),eH(s),e2(null),e7(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tM.current,a=r??i,s=a===i,l=!s&&a?ao(a):null,o=au(e,t,s?t$.current:l?.value??"",s?tR.current.map(a8):l?.images??[],n,s?tL.current.filter(e=>"ready"===e.status).map(st):l?.documents??[]);if(a&&ad(a,o),!s)return;let d=t?.length?[...a3(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=sn(se(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=a3(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tR.current=i,i}),eH(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),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+a;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tY(e)}}));let tz=(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:n4(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(ss);let r=[...t,...n];return tR.current=r,r})}finally{tE.current-=i.length}}},[eh]),tA=(0,i.useCallback)(async e=>{for(let t of e){let e=nG(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:n4(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:n4(0x1000000)}));continue}let n={id:++aK,name:t.name,mimeType:nK[e],size:t.size,text:"",status:"extracting"},r=[...tL.current,n];tL.current=r,eH(r);try{let e=await n0(t);if(tL.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new nq("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,eH(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,eH(r),!e)continue;i instanceof nq?"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,eH(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,eH(n),!0},[]),tF=(0,i.useCallback)((e,t,n)=>{if(!e||e===tM.current)return;let r=ao(e);r?.documents.some(e=>e.attachmentId===t)&&ad(e,{...r,documents:se(r.documents).map(e=>e.attachmentId===t?n(e):e).map(st)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tO=(0,i.useRef)(new Set),tH=(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=n3({...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 sr&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof sr&&"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 a=new AbortController;tD.current.set(e,a),tP(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await sa(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new sr("Invalid transcription result",null,null,null);let i=r.transcript;tP(e,e=>tH(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(n,e,e=>tH(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tP(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof sr&&"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)===a&&tD.current.delete(e)}},[eh,tB,tP,tF,tH]),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 sr("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await sa(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 tJ=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tP(e,e=>({...e,transcription:{state:"skipped"}}))},[tP]),tG=(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:++aK,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tL.current,i];tL.current=a,eH(a);let s=(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]?nX("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?nX("utf-16be",t.subarray(2)):t.includes(0)?null:nX("utf-8",t)??nX("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tW(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await aI().catch(()=>aS)).uploadLimitMb),r.size>n){tW(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:r.name,limit:n4(n)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tW(i.id,l))continue;let o=tM.current??si,d=await ag(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tO.current.has(i.id))continue;let e=await n7(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),a=n3({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tW(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:n4(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tW(i.id,h))c=e.id;else if(!tO.current.has(i.id)&&o!==tM.current){let t=ao(o)??{value:"",images:[],documents:[]};ad(o,{...t,documents:[...t.documents,st(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 a of e)a.type.startsWith("image/")?t.push(a):null!==nG(a)?n.push(a):nZ(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tz(t),tA(n.filter(e=>e.size<=8388608)),tG(r,"audio"),tG([...i,...a],"file")])},[tA,tG,tz]),tZ=(0,i.useCallback)(e=>{eD(t=>{let n=[...t],[r]=n.splice(e,1);return r&&ss(r),tR.current=n,n})},[]),tX=(0,i.useCallback)(e=>{let t=tL.current.find(t=>t.id===e);if(tO.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 i3)t.delete(n)&&(0===t.size&&i3.delete(e),ak())}let r=tL.current.filter(t=>t.id!==e);tL.current=r,eH(r)},[]),tQ=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(ss),[]))},[]),t0=(0,i.useCallback)(()=>{tL.current=[],eH([])},[]),t1=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&ac(Z),tM.current&&tM.current!==Z&&ac(tM.current),tQ(),t0(),eU(null),tc.current&&(tc.current.style.height="auto")},[t0,tQ,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&ad(Z,{value:ex,images:e_.map(a8),documents:eq.map(st)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&ad(e,{value:t$.current,images:tR.current.map(a8),documents:tL.current.filter(e=>"ready"===e.status).map(st)});let t=Z?ao(Z):null;tM.current=Z;let n=t?.value??"",r=a3(t?.images),i=se(t?.documents);t$.current=n,tR.current=r,tL.current=i,ev(n),e2(null),e7(!1),eD(e=>(e.forEach(ss),r)),eH(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(ss)},[]);let t2=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=ah(t);if(0===n.length)return()=>{};let r=++i8;return i5.set(r,{draftId:am(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=i5.get(r);if(t){if(i5.delete(r),"accepted"===e){let e=i7.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);i7.set(t.draftId,e)}ak()}}}(tM.current??si,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t5=(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,a=eq.length?eq:void 0;if(r.startsWith("/")){await aF(r,B,K,t=>t2(a,()=>e(t,i,a)),eU,!!(i||a),q)&&t1();return}t1(),t2(a,()=>e(r,i,a))},[ex,eJ,e_,eq,eK,l,K,B,q,e,t1,G,t2]),t8=eJ.startsWith("/")&&!/\s/.test(eJ.slice(1))?eJ.slice(1).toLowerCase():null,t6=(()=>{if(null===t8)return[];let e=[...l?[]:aX,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=a4(e,eh).toLowerCase();return t.includes(t8)||n.includes(t8)}).sort((e,t)=>{let n=a2(e,t8,eh)-a2(t,t8,eh);return 0!==n?n:a1[e.source]-a1[t.source]||aq.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=aQ.map(e=>{let t=t6.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!a5(e,td)),...t.filter(e=>a5(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(t8?"chat.match":"chat.command"):eh(t8?"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(aM(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:aR(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:aR(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||a$(e.entry.path)-a$(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tt.entries,nr):[],[nr,tt,X]),na=!!(nr&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!na||!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=>ts({cwd:X,query:nr,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[na,nr,X]);let ns=na&&null!==ta&&ta.cwd===X&&ta.query===nr,nl=ns?ta.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 nc=null!==e1,nu=aW(tb,e3,{viewportFraction:.44,cap:360}),np=aW(tb,eZ,{viewportFraction:.56,cap:460}),nh=aW(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nc||!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)=>a$(e.path)-a$(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)}))},[nc,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 a=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 a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e1.quoted),s=r+a.text+i,l=r.length+a.cursorOffset;ev(s),e2(aM(s.slice(0,l))),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e1,ex]);(0,i.useEffect)(()=>{e8>=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`)})},[]),nv=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eJ.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!s)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await aF(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(s.documents,()=>Y(e,l,s.images,s.documents))},eU,!!(s.images?.length||s.documents?.length),q)&&t1();return}t1(),"steer"===e&&n?t2(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t2(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,n,a,t1,G,t2]),nb=(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,a=r.top+r.height/2,s=-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-a;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(s=n,l=d)}return s>=0?s:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t3.length,eQ]),nw=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tk.current<100,s=tw.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(e3&&!s){if("ArrowDown"===e.key){e.preventDefault(),te(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),te(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e7(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[e9]){e.preventDefault(),nf(D[e9]);return}}if(eZ&&null!==t8){if("ArrowDown"===e.key){e.preventDefault(),e0(nb("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(nb("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(nb("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(nb("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&&!s){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&&!s&&!l&&D.length>0&&0===ex.trim().length){e.preventDefault(),eX(!1),e5(!1),te(D.length-1),e7(!0);return}if("Escape"===e.key&&!s&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(n||a)?nv(n?"steer":"followup"):t5())},[l,n,a,t,eZ,t8,t3,eQ,ng,nv,t5,nb,e4,e1,nl,e8,nm,e3,D,e9,nf,ex]),nk=(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===t8){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}))},[t8,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(aJ):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(aJ),nC=g??null,nN=t4.bo.find(e=>e.alias===nC)?.provider??null,nI=nN?nS.filter(e=>e.provider===nN):nS,nT=(ea=ej.trim().toLocaleLowerCase())?nI.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):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})),nz=(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}(aL(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(aE,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}`)},nA=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")} ${tV(S.tokensBefore)} -> ${tV(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:tV(nW)})})`:null,nF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},n_="auto"===(es=I??"auto")?M?`auto ≤ ${nF(M)??M}`:"auto":L?L[es]??es:es,nD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,nO=$&&nD?eh("chat.currentReasoning",{level:nD}):null,nH=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...aY.filter(nH).map(e=>({level:"auto",ceiling:e})),...aG.filter(e=>"auto"!==e&&nH(e)).map(e=>({level:e,ceiling:null}))],nU=Object.entries(aO).find(([,e])=>e===(C??"default"))?.[0]??"default";return(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)&&ez(!1),tx.current&&!tx.current.contains(e.target)&&eF(!1),!tv.current||tv.current.contains(e.target)||tc.current?.contains(e.target)||e7(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eF(!1)},[eg]),(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)(so,{error:p}),(0,r.jsx)(sd,{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})}),O&&ef&&(0,r.jsxs)("button",{onClick:O,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)(iP,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("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||eO.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}`)),eO.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||a_(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"}}):ny(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"):aV[e.mimeType]," \xb7 ",n4(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,a,l=e.attachmentId,o=e.transcription,d=o?.state==="confirm"||o?.state==="running"?o.plan:null,c=d?eh("chat.transcribePlanSummary",{duration:null===d.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:d.estimatedCalls}):null,u=o?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:o?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:o.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,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)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tJ(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tJ(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,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,...aU(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.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,nu.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!==t8&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...aU(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(a0[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=a5(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")})]}),a4(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:a4(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&&(el=tr&&(!tt||tt.cwd!==X),eo=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ed=tt?.truncated&&!ns?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...aU(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:el?eh("chat.loadingFiles"):eh("chat.files",{label:eo,hint:ed})}),(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:el||0!==nl.length?nl.map((e,t)=>{let n=t===e8,i=e.path.split("/").pop()??e.path,a=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)(nx,{size:14}):ny(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),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:na&&!ns?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||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,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:nw,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;nn(t.value,t.selectionStart)},onInput:nk,onPaste:nj,placeholder:l&&(n||a)?eh("chat.steerPlaceholder"):l?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),l?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nv("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")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nv("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")]})]}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t5,disabled:!nt,"aria-busy":eK||void 0,title:eK?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"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"})]}),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:[(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e_.length||eO.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||eO.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||eO.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=e_.length||eO.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"})]})}),f&&t4.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}=az(eM.top,eM.bottom,e,aA(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,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,...a,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:t4.bo.map(e=>{let t=e.alias===nC;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),f((0,t4.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,t4.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)})})})})()]}),(nS.length>0||nA||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:nA??(nS.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=az(ew.top,ew.bottom,e,aA(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight: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})=>nz(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=>nz(e,"all"))]},e.provider))]})]})})()]}),$&&(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),ez(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level: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&&eA&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=az(eA.top,eA.bottom,e,aA(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eA.top+6}:{top:eA.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eA.left,width:"max-content",minWidth:Math.max(180,eA.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nF(i),s=t?`auto ≤ ${a??t}`:a??e,l=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(aZ[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{ez(!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:[s,null!==a&&(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)})})})()]}),W&&(ec=A?eh("chat.fastModeBusy"):null===z?eh("chat.fastModeUnknown"):z.active?eh("chat.fastModeActive"):z.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eu=A||l||b,ep=z?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${z?.active?" is-active":""}`,onClick:W,disabled:eu,"aria-pressed":null===z?void 0:z.enabled,"aria-busy":A||void 0,title:ec,"aria-label":ec,style:{flexShrink:0,opacity:l?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:z?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===z?"3 2":void 0,style:{opacity:ep&&!z?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})),!eg&&nO&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nO}),(0,r.jsx)(iY,{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)(s.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:[!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:aD.map(e=>{let t=aO[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:aH}):eh("chat.allBuiltInTools",{tools:`${aH} + ${aB}`});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")})]})})}),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),ez(!1),eF(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,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"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter: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"})}),eh("chat.stop")]}),(0,r.jsx)(iJ,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),void 0!==J&&(0,r.jsx)(iD,{soundEnabled:V??!0,onToggle:J})]})]}),eg&&nO&&(0,r.jsx)("div",{style:{marginTop:4,padding:"0 4px",fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:nO})]})]})});function su({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 sp({phases:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=function(e){let t=0,n=0,r=null,i=null,a=null;for(let s of e)for(let e of s.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:s,task:e}):"blocked"===e.status?a||(a={phase:s,task:e}):i||(i={phase:s,task:e}))}let s=r??i??a,l=t+n;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:n,completed:t,total:l,percent:l>0?Math.round(t/l*100):null}}(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:()=>a(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=>s||"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)(nm,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":s,onClick:()=>l(e=>!e),children:t(s?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sh(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function sm(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 sf(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 sg=n(62503);class sx extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function sv(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 sx(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let sb="ompweb-update-client-id",sy="ompweb-update-resume-intent-v2",sw="ompweb-update-return-v1",sk="cuelo-restart-return-v1",sj="ompweb-update-failure-return-v1",sS="ompweb:update-wake";function sC(e){return null===e||"running"===e?null:"failed"===e?3e4:8e3}function sN(){let e=sessionStorage.getItem(sb);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(sb,t),t}function sI(){sessionStorage.removeItem(sy)}function sT(){let e=sessionStorage.getItem(sw);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function sM(e){let t=sT();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(sw,JSON.stringify(n))}catch{}return n}async function s$(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:sN(),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 sR(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=sT();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(sw,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sI();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sS,{detail:{sessionId:e.sessionId}}))}async function sE(e){let t=function(e){let t=sessionStorage.getItem(sj);if(!t)return null;sessionStorage.removeItem(sj);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?(sI(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(sS,{detail:{sessionId:e.sessionId}})),"failed"):(await sR(e),"resumed")}function sL(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 sz(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 sA(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function sW(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function sP(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 sF(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 s_(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function sD(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 sO=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class sH 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 sB(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function sU(e){return new Promise(t=>setTimeout(t,e))}function sq(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function sK(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:sq(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:sq(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=sq(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function sV(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 sJ(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(sV).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function sG(e){return"user"===e.role?`user:${sJ(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 sY(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 sZ(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}let sX={count:50,end:null};function sQ(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),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function s0(e,t,n){let{startIndex:r,endIndex:i}=sQ(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function s1({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:r9[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(r8(),{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 s2(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=(n2(t)?.message??t).trim();return n.length>0?n:null}function s4(e){return`omp-cues:${e}`}function s5(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(s4(e),JSON.stringify(n.slice(-200)))}catch{}}let s8=[];function s6(e){return`omp-web:interrupted-dismissed:${e}`}let s3=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,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:a,cwd:s,sessionId:f})},[N,x,e,t,n,a,s,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 a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let l of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,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 a=eY(i.memory),s=i.skill,l=s?{action:eY(s.action),name:eY(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:l}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...l?{skill:l}:{}})}}(l.blocks??e.content??[],r,(e,t)=>{if(o.has(e))return;o.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(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,a]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),a=new Map;for(let[s,l]of(e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.anchorIdx,t)}),a)){if(s===n)continue;let e=i.find(e=>e>s);r.set(l,{from:s+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||!rV.test(e))continue;let a=t.get(n.toolCallId),s=a?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}(a):null,l=null===s?a?.isError?"failed":"unobserved":0===s?"passed":"failed";r.push({toolCallId:n.toolCallId,command:e,state:l,exitCode:s})}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,a.from,a.to),n,s));return r},[g,e,n,s,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)(rg,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:l,entryId:t[i],onFork:o||d||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:o?void 0:h,prevAssistantEntryId:o?void 0:b,onEditContent: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}`)},z=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":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((a,o)=>{let d=y+o,c=b?.position===d?(0,r.jsx)(n_,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,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>=a.idx&&r<m}).map(e=>(0,r.jsx)(s1,{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)(rg,{message:k,cwd:s,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,r.jsx)(im,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:l}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx)),j,S,x]},`message-${a.idx}`);let C=e4(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[c,z(d,L(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:eL(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,r.jsx)(n_,{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 s7({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!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:z,jumpRequest:A=null,onJumpHandled:W}){var P,_;let D,O,H,{t:B}=(0,R.s)(),U=(0,i.useRef)(E);U.current=E;let q=(0,i.useRef)(null),K=(0,i.useRef)(L);K.current=L;let[J,G]=(0,i.useState)([]),Y=(0,i.useRef)(J);Y.current=J;let Z=(0,i.useRef)(0),X=(0,i.useRef)([]),Q=(0,i.useRef)([]),ee=(0,i.useRef)(null),et=(0,i.useRef)(0),en=(0,i.useRef)(-1),er=(0,i.useRef)(-1),ei=(0,i.useCallback)(()=>{let e=ee.current?.current;return e?{sessionId:e,turn:et.current}:null},[]),ea=(0,i.useCallback)(e=>ee.current?.current===e.sessionId&&et.current===e.turn,[]),es=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;Z.current=Math.max(Z.current+1,Date.now());let i={id:Z.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};G(e=>{let t=[...e,a];return null!==a.anchorEntryId&&s5(n.sessionId,t),t})},[]),el=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ea(n)&&("working"!==t||er.current!==n.turn);i()&&U.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&es(e,t,n,r)}).catch(()=>{})},[ea,es]),eo=(0,i.useCallback)(async(e,t,n)=>{let r=(await na(e,t,n))?.alias??null;return r&&K.current?.(r),r},[]),ed=(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=io(e[n]),a=0;for(let t=r;t<=n;t++)io(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(X.current,Q.current);eo(t.sessionId,n,r).then(n=>{el(n,e,t,i)})},[el,eo]),[ec,eu]=(0,i.useState)(0),ep=(0,i.useRef)([]),eh=(0,i.useCallback)(e=>{if(et.current+=1,null!==it(e.outcome)){let t=e.sessionId;ep.current.push({completion:e,trigger:t?{sessionId:t,turn:et.current}:null}),eu(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ep.current.splice(0)){let n=it(e.outcome),r="neutral"===n?null:n;t?ed(r,t,e.provider,e.credentialId):U.current(null,r).catch(()=>{})}},[ec,ed]);let em=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ef,error:eg,messages:ex,entryIds:ev,streamState:eb,agentRunning:ey,bashRunning:ek,pendingBash:ej,modelNames:eS,modelList:eC,modelError:eN,modelScopeWarnings:eI,modelThinkingLevels:eT,modelThinkingLevelMaps:eM,modelRoles:e$,toolPreset:eR,thinkingLevel:eE,effectiveThinkingLevel:ez,thinkingCeiling:eF,fastMode:eD,fastModeBusy:eO,handleFastModeToggle:eB,retryInfo:eG,contextUsage:eY,forkingEntryId:eX,isCompacting:eQ,compaction:e0,compactError:e1,compactResult:e2,displayModel:e4,modelSwitching:e8,sessionStats:e6,runStateKnown:e3,compactedWork:e7,slashCommands:e9,slashCommandsLoading:te,deliveryRows:tt,subagents:tn,todoPhases:tr,notices:ti,extensionDialog:ta,extensionResponse:ts,extensionCustomUi:tl,extensionStatuses:to,extensionWidgets:td,respondToExtensionUi:tc,sendExtensionCustomInput:tu,isAutoModelSelection:tp,agentPhase:th,isNew:tm,autoFollowPaused:tf,resumeAutoFollow:tg,pauseAutoFollow:tx,goalStatus:tv,sessionIdRef:tb,messagesEndRef:ty,scrollContainerRef:tw,handleSend:tk,handleAbort:tj,handleFork:tS,handleNavigate:tC,handleModelChange:tN,handleRoleModelChange:tI,handleMainPresetChange:tT,newSessionAccount:tM,handleCompact:t$,handleSteer:tR,handleFollowUp:tE,handlePromptWithStreamingBehavior:tL,handleAbortCompaction:tz,handleRecallQueue:tA,handleRemoveQueuedMessage:tW,handleBuiltinSlashCommand:tP,handleToolPresetChange:tF,handleThinkingLevelChange:t_,loadSlashCommands:tD,ensureNewSession:tO,refreshLiveTranscript:tH}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=a&&a.sessionId===t?.id?a: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)(sz,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[z,A]=(0,i.useState)(!1),[W,P]=(0,i.useState)(null),[F,_]=(0,i.useState)({}),[D,O]=(0,i.useState)([]),[H,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,ea]=(0,i.useState)("default"),[es,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),[ez,eA]=(0,i.useState)(!1),[eW,eP]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eO]=(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)(sK,{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,ta]=(0,i.useState)([]),[ts,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(iz,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{E||tu({type:"idle"})},[E]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iE(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${iR(t)}`,s=n.get(a)??0;s>0?n.set(a,s-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,ts),[tc,ts]),[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),tz=(0,i.useRef)(null),tA=(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),tO=(0,i.useRef)(!1),tH=(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),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,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,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,l&&(e.input+=l.input??0,e.output+=l.output??0,e.cacheRead+=l.cacheRead??0,e.cacheWrite+=l.cacheWrite??0,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:s,toolResults:a,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&&sF(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&&sF(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 a=r??null;if(!a){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}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=eV(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(s.messages),nm(s.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let l=!n&&t8.current===e;if(l||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!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(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=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&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(sA(i.queuedMessages)),void 0!==i.subagents&&td(e=>sL(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=na.current.then(async()=>{tj.current===e&&await nf(e)});return na.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}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let l=eV(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(l.messages),nm(l.entryIds),M(s.context.compactedWork??null),ej(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nm,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await sv(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),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 a={cwd:r,type:"ensure_session",toolNames:(0,aP.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),l=t0.current,o=l?.body===s?l.createRequestId:sB();t0.current={body:s,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:o})});if(!d.ok)throw Error(`HTTP ${d.status}`);let c=await d.json();t0.current=null,t=c.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),c.model&&t2.current===e&&(eR(c.model),e||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 sv(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 sv(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(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tF.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&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 sH(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 sv(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 sv(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??sB(),message:t,type:e.type??"info"}})},[]),nR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eH,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),a=null;for(let e=i.length-1;e>=0;e--)if(!eK(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eq}${n.seq}`,baseEntryId:a,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(sm(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":ta(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},[]),nz=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=sD(tC.current,tN.current);tz.current=e?{entryId:e.entryId,key:sG(e.message)}:null,tA.current+=1},[]),nA=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let n=sD(tC.current,tN.current),r=n?.message,i=tz.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:sG(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=s_(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=nA();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===n;s?.(e?nA():t)})},[s,nA]),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 a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(td(e=>sL(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eY(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eO(sP(s)),ty.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.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 sU(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 sU(600)}},[n_]),nO=(0,i.useCallback)(async e=>{let t=tP.current+1;for(tP.current=t;tW.current&&tP.current===t&&tj.current===e;){await sU(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,A(!1),P(null);return}catch{}}},[nf]),nH=(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 a=i.state;if(eA(a?.isCompacting??!1),eO(sP(a)),tl(sA(a?.queuedMessages)),a?.contextUsage!==void 0&&ej(a.contextUsage??null),td(e=>sL(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.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(!ez){eB.current=null,eO(null);return}eO(e=>e??{startedAt:Date.now(),reason:eB.current})},[ez]),(0,i.useEffect)(()=>{if(!E&&!ez)return;let e=()=>{let e=tj.current;e&&nU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,ez,nU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&nH(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,nH]),(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(sS,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sS,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 a=e.context.messages,s=new Map;for(let e of a){let t=sG(e);s.set(t,(s.get(t)??0)+1)}let l=Math.min(r.length,i.length);for(let e of r.slice(0,l)){let t=sG(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=sG(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let 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&&nz(),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&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>sL(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(sA(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();eA(!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,sg.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=s_(t)),t&&"user"===t.role){let e=(0,sg.B)(t),n=sJ(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&sJ(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,sg.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 sL(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=>sL(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=>sL(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;eO(e=>e?{...e,reason:t}:e)}eA(!0),eP(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)eP(e.errorMessage),e_(null);else if(!e.aborted){e_(sY(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,nz,nF,nL,nm,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tW.current||ni.current)return"unknown";let l=n1(n,a??[]),o=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}nz();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=sJ(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 sv(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),f=!0,await sv(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 sv(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 sx&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof sx&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&h)return nD(h,d),"unknown";t$.current=!1,tT.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&sJ(t)===s?e.slice(0,-1):e}),n$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,sZ(i),a,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,nz,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}),A(!0);try{let e=tj.current??t?.id??await ny();if(!e)throw Error("Unable to create a session for the shell command");await sv(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),A(!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 sv(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sv(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 sv(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&&(sv(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&&sv(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 sv(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 sv(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,a=t4.current,s=t5.current;try{t2.current=t,t4.current=n??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await sv(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=a,t5.current=s,n$({type:"error",message:i(n)});let t=tj.current;return t&&await nf(t),!1}finally{ni.current=!1,eL(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await sv(a,r),await nf(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),n$({type:"error",message:i(e)}),await nf(a),!1}finally{ni.current=!1,eL(!1)}},[n$,eT,eo,m,nf,Q,es]),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 sv(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&&!ez){eB.current="manual",eA(!0),eP(null),e_(null);try{let t=await sv(e,{type:"compact"});e_(sY(t,"manual")),await nf(e,!0)}catch(e){eP(e instanceof Error?e.message:String(e)),e_(null)}finally{eA(!1)}}},[ez,nf]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();_(s.models),B(s.modelError??null),q(s.modelScopeWarnings??[]),V(s.thinkingLevels??{}),G(s.thinkingLevelMaps??{}),Z(s.roles??[]);let l=s.modelList??[];if(O(l),m&&!tj.current){let e=(s.defaultModel?l.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[m,r,t?.cwd]),n2=(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(),a=await ny(),s=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(!a||ez)return s({handled:!0,error:"No active session to compact"});eB.current="manual",eA(!0),eP(null),e_(null);let e=await sv(a,{type:"compact",...i?{customInstructions:i}:{}});return e_(sY(e,"manual")),await nf(a,!0)&&nb(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await sv(a,{type:"reload"}),await Promise.all([nf(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await sv(a,{type:"set_session_name",name:i}),await nf(a)&&nb(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await sv(a,{type:"get_session_stats"});return e&&e5(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await sv(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nV();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await sv(a,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(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 s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tW.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eY({kind:"running_command"});try{await nI(a);let e=await sv(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nf(a,!0)&&nb(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eY(null),tj.current===a&&nF(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await sv(a,{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 s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[n$,nR,nI,ny,nV,ez,n0,nf,nw,nv,nb,h,nF]),n4=(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,sZ(n),r),"returned";let a=n1(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:a,images:s?.length??0});try{return await sv(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to steer:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,sZ(n),r,i),"returned"}},[n$,e.chatInputRef]),n5=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,sZ(r),i),"returned";let s=n1(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:s,images:l?.length??0});try{return await sv(a,{type:"prompt",message:s,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,sZ(r),i,a),"returned"}},[n$,e.chatInputRef]),n8=(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,sZ(n),r),"returned";let a=n1(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:a,images:s?.length??0});try{return await sv(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to follow up:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,sZ(n),r,i),"returned"}},[n$,e.chatInputRef]),n6=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await sv(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n3=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await sv(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$]),n7=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await sv(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$]),n9=(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 sv(i,{type:"set_thinking_ceiling",ceiling:n}),await sv(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 re=e=>e?`${e}|${ev.current}`:null,rt=t?.id??tj.current,rn=re(rt),rr=ep&&ep.key===rn?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rn&&rt&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(rt)}`).then(e=>e.json()).then(t=>{eg.current===e&&re(tj.current)===rn&&eh({key:rn,value:(t.running?sW(t.state):void 0)??null})}).catch(()=>{})},[rn,E,eE]);let ri=(0,i.useCallback)(async()=>{let e=tj.current??await ny(),t=re(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&re(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=sW(await sv(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await sv(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;n$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(sW(await sv(e,{type:"get_state"}))??null)}catch{i(null)}}finally{ef(!1)}},[ny,ep,n$]),ra=(0,i.useCallback)(async e=>{let t=(0,aP.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await sv(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),rs=(0,i.useCallback)(e=>{tH.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=rs;let rl=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tJ.current=0,rs(!0),rl("smooth")},[rl,rs]),rd=(0,i.useCallback)(()=>{tJ.current=0,rs(!1)},[rs]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!sO.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,A(!0),nO(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eA(n.isCompacting),eO(sP(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&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(sA(n.queuedMessages)),void 0!==n.subagents&&td(e=>sL(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&&!z||!tH.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tG.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[E,z,S.length,$.streamingMessage,eG,W,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tO.current){tO.current=!0,rl("instant");return}if(!t9.current&&tH.current){let e=Date.now()-ne.current<1500;rl(tT.current||tW.current||e?"instant":"smooth")}}},[S.length,E,z,rl,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:H,modelScopeWarnings:U,modelThinkingLevels:K,modelThinkingLevelMaps:J,modelRoles:Y,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:ez,compaction:eD,compactError:eW,compactResult:eF,currentModel:nl,displayModel:no,modelSwitching:eE,sessionStats:nd,runStateKnown:eU,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ts,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:n4,handleFollowUp:n8,handlePromptWithStreamingBehavior:n5,handleAbortCompaction:n6,handleRecallQueue:n3,handleRemoveQueuedMessage:n7,handleBuiltinSlashCommand:n2,handleToolPresetChange:ra,handleThinkingLevelChange:n9,fastMode:rr,fastModeBusy:em,handleFastModeToggle:ri,loadTools:nv,loadSlashCommands:nw,ensureNewSession:ny,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:z,pendingBash:W,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:eh,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tB=ns(e?.id,e4?.provider,void 0),tU=tB?.alias;(0,i.useEffect)(()=>{tU&&K.current?.(tU)},[tU]);let tq=(0,i.useMemo)(()=>{if(!e4)return null;let e=tm?tM:t4.bo.find(e=>e.alias===tB?.alias)?.oauthPosition;return t4.bo.find(t=>t.provider===e4.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[e4,tm,tM,tB]),tK=e4?.provider,tV=e4?.modelId,tJ=tB?.alias,tG=tB?.seed,tY=(0,i.useRef)(tB);tY.current=tB,(0,i.useEffect)(()=>{y&&y(tK&&tV?{provider:tK,modelId:tV,face:tY.current,presetAlias:tq,isNew:tm}:null)},[y,tK,tV,tJ,tG,tq,tm]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let tZ=ey||ek,tX=e?.id;X.current=ex,Q.current=ev,ee.current=tb;let tQ=(0,i.useRef)(!0);tQ.current=!tf;let t0=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ey&&!t0.current&&(et.current+=1),t0.current=ey},[ey]),(0,i.useEffect)(()=>()=>{et.current+=1},[]),(0,i.useEffect)(()=>{G(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(s4(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[]}}(tX),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===tX)])},[tX]),(0,i.useEffect)(()=>{let e=tb.current;e&&Y.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&G(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=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 a=0;for(let s=i;s<r;s++)if(io(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,ex,ev);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(s5(e,r),r):t})},[ex,ev,tb]);let t5=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tb.current,t=t5.current;if(t5.current=e?{sessionId:e,entryIds:ev}: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 a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&r.push(t[a])}return r}(t.entryIds,ev,ex),r=ei();if(0===n.length||!r)return;let i=ni(e,"web6",void 0)?.alias??null;for(let e of n)Y.current.some(t=>t.anchorEntryId===e)||el(i,"done",r,{kind:"entry",entryId:e})},[ev,ex,tb,ei,el]);let t8=ey&&th?.kind==="running_tools"&&th.tools.length>0&&th.tools.every(e=>"wait"===e.name),t6=ef||s,{hideThinkingBlock:t3}=(P=t??e?.cwd??null,D=t2(),(0,i.useEffect)(()=>{t1(P).catch(()=>{})},[P]),D),t7=(0,i.useMemo)(()=>({hideThinking:t3}),[t3]);(0,i.useEffect)(()=>{if(!ta||q.current===ta.id)return;q.current=ta.id;let e=ei();if(e){var t;er.current=e.turn,ed("select"===(t=ta.method)||"ask"===t?"choice":"approval",e,e4?.provider,void 0)}},[ta,e4?.provider,ei,ed]),(0,i.useEffect)(()=>(v=tZ?tj:null,()=>void(v=null)),[tZ,tj]),(0,i.useEffect)(()=>{N?.(tZ)},[N,tZ]),(0,i.useEffect)(()=>()=>N?.(!1),[N]),(0,i.useEffect)(()=>{I?.(t8)},[t8,I]),(0,i.useEffect)(()=>()=>I?.(!1),[I]),(0,i.useEffect)(()=>{T?.(null!==ta)},[T,ta]),(0,i.useEffect)(()=>()=>T?.(!1),[T]);let{main:t9,process:ne}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,l=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),l=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.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:a,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(),a=i.idx,r.push(i);continue}if(eU(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(a,[{idx:i.idx}],0);continue}let s=eW(t,n),d=!1;for(let e of s){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(a,[{idx:i.idx,blocks:e.blocks}],eP(e.blocks)),o.collect(i.idx,e.blocks)}!d&&eA(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(ex,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 a=i,s=a+1;for(;s<e.length&&!eJ(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,l=[],o=0,d=0,c=e_(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:d++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,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&&a.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(a.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),s+=eP(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&eA(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,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(ex,{sessionBusy:tZ,isStreaming:eb.isStreaming,hideThinking:t7.hideThinking}),t7),[ex,tZ,eb.isStreaming,t7]),nt=(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 a=-1,s=-1;t.forEach((e,t)=>{let n=nE(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=r.get(o.position);e?e.calls.push(...n):r.set(o.position,{calls:[...n],placement:l?"after":"before"})}}"user"===e.role&&(a=t),eJ(e)&&(s=t)});let{continuing:l}=nL(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})(t9,ex,e7?.messages),[t9,ex,e7]),nn=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=nL(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 a=e.findIndex(e=>e.idx>i),s=-1===a?e.length:a;return{position:s,jumpTo:s<e.length?s:e.length>0?e.length-1:null,calls:r}})(t9,ex,e7?.messages),[t9,ex,e7]),[nr,nl]=(0,i.useState)(sX),{startIndex:no,endIndex:nd,hasLater:nc}=sQ(t9.length,nr),nu=null!==nr.end&&nc,np=(0,i.useRef)(t9.length);np.current=t9.length;let nh=(0,i.useRef)(null),nm=(0,i.useRef)(null),nf=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nr.end&&nr.end>=t9.length&&nl(e=>({count:e.count,end:null}))},[nr.end,t9.length]),(0,i.useEffect)(()=>{let e=nh.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nf.current=t.scrollHeight-t.scrollTop,nl(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nr,t9.length,tw]),(0,i.useEffect)(()=>{if(null==nf.current)return;let e=tw.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nf.current),nf.current=null}},[nr.count,tw]),(0,i.useEffect)(()=>{let e=nm.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nl(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=sQ(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(np.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nr,t9.length,tw]);let[ng,nx]=(0,i.useState)(null),[nv,nb]=(0,i.useState)(null),[ny,nw]=(0,i.useState)(0),nk=(0,i.useRef)(null),nj=(0,i.useCallback)((e,t=null)=>{tx(),nk.current={item:e,dispatchKey:t},nx(null),nb(null),nl(t=>s0(np.current,e,t)),nw(e=>e+1)},[tx]);(0,i.useLayoutEffect)(()=>{let e,t=nk.current,n=tw.current;if(null===t||!n)return;let r=n.querySelector(`[data-chat-item="${t.item}"]`);if(!r)return;nk.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?nb(t.dispatchKey):nx(t.item)},[ny,nr,t9,tw]),(0,i.useEffect)(()=>{if(null===ng)return;let e=setTimeout(()=>nx(null),1800);return()=>clearTimeout(e)},[ng]),(0,i.useEffect)(()=>{if(null===nv)return;let e=setTimeout(()=>nb(null),1800);return()=>clearTimeout(e)},[nv]);let nW=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>nl(sX));let e=tw.current;e&&(e.scrollTop=e.scrollHeight)},[tw]),nP=(0,i.useCallback)(()=>{nu&&nW(),tg()},[nu,nW,tg]),nF=(0,i.useRef)(null),[n_,nD]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!A||nF.current===A.id||A.sessionId!==e?.id||ef||0===ex.length)return;nF.current=A.id,W?.(A.id);let t=ev.indexOf(A.entryId);if(t<0)return void nD(!0);let n=0;for(let e=0;e<t9.length;e++){let r=t9[e].idx;if(r>t||(n=e,r===t))break}nj(n)},[A,e?.id,ef,ex.length,ev,t9,nj,W]),(0,i.useEffect)(()=>{if(!n_)return;let e=setTimeout(()=>nD(!1),6e3);return()=>clearTimeout(e)},[n_]);let[nO,nH]=(0,i.useState)(!1),[nB,nU]=(0,i.useState)(0),nq=(0,i.useMemo)(()=>nO?t9.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,ex).toLowerCase()):s8,[nO,t9,ex]),nK=(0,i.useCallback)(e=>{tx(),nl(t=>s0(np.current,e,t))},[tx]),nV=(0,i.useCallback)(()=>nH(!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=tw.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(),nH(!0),nU(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tw]);let nJ=(0,i.useMemo)(()=>{let e=[];return t9.forEach((t,n)=>{if("message"!==t.kind)return;let r=s2(ex[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[t9,ex]),nG=`${no}:${nd}`,nY=ev.length>0?ev[ev.length-1]:null,[nZ,nX]=(0,i.useState)(null),nQ=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nQ.current||!e3||ef||!e?.id||(nQ.current=!0,tZ||!nY||!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}(ex)||function(e){try{return window.localStorage.getItem(s6(e))}catch{return null}}(e.id)!==nY&&nX(nY))},[e3,ef,e?.id,tZ,nY,ex]);let n0=(0,i.useCallback)(()=>{e?.id&&nZ&&function(e,t){try{window.localStorage.setItem(s6(e),t)}catch{}}(e.id,nZ),nX(null)},[e?.id,nZ]),n2=null!==nZ&&nZ===nY&&!tZ&&!nu,n4=e6?[e6.sessionId,e6.sessionFile??"",e6.sessionName??"",e6.userMessages,e6.assistantMessages,e6.toolCalls,e6.toolResults,e6.totalMessages,e6.tokens.input,e6.tokens.output,e6.tokens.cacheRead,e6.tokens.cacheWrite,e6.tokens.total,e6.cost??0,e6.totalActiveMs??0].join("|"):null,n5=(0,i.useRef)(e6);n5.current=e6,(0,i.useEffect)(()=>{f?.(n5.current)},[n4,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let n8=eY?`${eY.percent??"null"}|${eY.contextWindow}|${eY.tokens??"null"}`:null,n6=(0,i.useRef)(eY);n6.current=eY,(0,i.useEffect)(()=>{x?.(n6.current)},[n8,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(tn)},[b,tn]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:n3,handleDragEnter:n7,handleDragOver:n9,handleDragLeave:re,handleDrop:rt}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{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=>{tZ||p?.current?.addAttachments(e)},[tZ,p])),rn=(0,i.useMemo)(()=>{var e;return e=e7?.messages,e&&e.length>0?[...e,...ex]:ex},[e7,ex]),rr=(0,i.useMemo)(()=>{let e=new Map;for(let t of rn)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rn]),ri=(0,i.useMemo)(()=>{let e,t,n,r;return e=new Map,t=new Map,n=new Map,r=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},rn.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rr.get(e.toolCallId);if(t)for(let r of nT(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(nI(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=nC(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:nC(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 nS(t.details?.jobs)){if("task"!==e.type)continue;let t=nC(e.id);t&&r(t,nN(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of nI(t.content).matchAll(nM)){let t=Object.fromEntries([...e[1].matchAll(n$)].map(e=>[e[1],e[2]]));t.id&&r(t.id,nN(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:n}},[rn,rr]),ra=(0,i.useMemo)(()=>({ledger:ri,subagents:tn,toolResults:rr,onOpenPanel:w,focusedDispatch:nv}),[ri,tn,rr,w,nv]),rs=(0,i.useMemo)(()=>(function(e,t,n,r,i,a,s=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of n)for(let n of t.calls)o.set(n.toolCallId,e);if(s?.jumpTo!=null)for(let e of s.calls)o.set(e.toolCallId,s.jumpTo);let d=[];if(e.forEach((e,n)=>{if("assistant"!==e.role)return;let s=n>l;for(let n of e.content??[])if("toolCall"===n.type&&"task"===n.toolName)for(let e of nT(n,t.get(n.toolCallId))??[]){let t=nR(e,r,i),l=nz[t.run],c=null;"running"===l&&("live"===t.runSource||s&&a)?c="running":"awaiting"===l&&s&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(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]}})(rn,rr,nt,tn,ri,tZ,nn),[rn,rr,nt,tn,ri,tZ,nn]),rl=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),ro=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ex.length-1;n>=0;n-=1){let r=s2(ex[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ex]),rd=(0,i.useMemo)(()=>(function(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)})(ex,rr,tr,e7?.todoPhases??null),[ex,rr,tr,e7]),rc=(0,i.useMemo)(()=>iy(eb.streamingMessage).join("|"),[eb.streamingMessage]),ru=(0,i.useMemo)(()=>JSON.stringify(ib(eb.streamingMessage)),[eb.streamingMessage]),rp=(0,i.useMemo)(()=>JSON.stringify(ik(eb.streamingMessage)),[eb.streamingMessage]),rh=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=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),s=[],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=iy(r),d=ik(r,a);if(0===i.length&&0===d.length||o<0)continue;let c=ib(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=l.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(a,e),s.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...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 s.sort((e,t)=>e.index-t.index)})(ex,ev,rc.length>0?rc.split("|"):[],JSON.parse(ru),JSON.parse(rp)),[ex,ev,rc,ru,rp]),rm=e?.id??tb.current??void 0,rf=(O=iC(_=(0,i.useMemo)(()=>({sessionId:rm,sessionProvider:e4?.provider,turns:rh,messages:ex,subagents:tn}),[rm,e4?.provider,rh,ex,tn])),H=iM(_),(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,...H])),[O,H])),rx=tm&&0===ex.length&&!eb.isStreaming&&!tZ,rv=e?.cwd??t??void 0,rb=e4?eT[`${e4.provider}:${e4.modelId}`]??null:null,ry=e4?eM[`${e4.provider}:${e4.modelId}`]??null:null,rw=(0,i.useRef)(null),rk=(0,i.useRef)(null),rj=(0,i.useCallback)(()=>{rw.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(C?.(rj),()=>C?.(null)),[rj,C]),(0,i.useLayoutEffect)(()=>{let e=rk.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tw.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tw.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[ef,tw]);let rS=(0,i.useCallback)((...e)=>(null!==nr.end&&nW(),tk(...e)),[tk,nr.end,nW]),rC=(0,r.jsx)("div",{ref:rw,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(sc,{ref:p,sessionId:e?.id??tb.current??void 0,onEnsureSession:tm&&t?tO:void 0,onLiveTranscriptPersisted:tH,onSend:rS,onAbort:tj,onSteer:ey?tR:void 0,onFollowUp:ey?tE:void 0,onPromptWithStreamingBehavior:ey?tL:void 0,isStreaming:tZ,model:e4,isAutoModelSelection:tp,modelNames:eS,modelList:eC,modelError:eN,modelScopeWarnings:eI,onModelChange:tN,onMainPresetChange:e||tm?tT:void 0,mainPresetActiveAlias:tq,modelRoles:e$,onRoleModelChange:tI,modelSwitching:e8,onCompact:e||tm?t$:void 0,onAbortCompaction:tz,isCompacting:eQ,compactError:e1,compactResult:e2,toolPreset:eR,onToolPresetChange:e||tm?tF:void 0,thinkingLevel:eE,effectiveThinkingLevel:ez,thinkingCeiling:eF,onThinkingLevelChange:e||tm?t_:void 0,fastMode:eD,fastModeBusy:eO,onFastModeToggle:e||tm?eB:void 0,availableThinkingLevels:rb,thinkingLevelMap:ry,retryInfo:eG,deliveryRows:tt,inputHistory:ro,onRecallQueue:tA,onRemoveQueuedMessage:tW,slashCommands:e9,slashCommandsLoading:te,onLoadSlashCommands:tD,onBuiltinCommand:tP,soundEnabled:M,onSoundToggle:$,onAudioUnlock:z,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rN=eb.streamingMessage,rI=(0,i.useMemo)(()=>rN?eW(rN,{isStreaming:!0}):[],[rN]),rT=(0,i.useMemo)(()=>rI.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rI]),rM=(0,i.useMemo)(()=>rI.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rI]),r$=rN?.role==="assistant"?rN:null,rR=ey&&(th?.kind==="running_tools"||(r$?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rE=r$?.provider??e4?.provider,rL=r$?.credentialId;(0,i.useEffect)(()=>{if(!rR)return;let e=ei();e&&en.current!==e.turn&&er.current!==e.turn&&(en.current=e.turn,ed("working",e,rE,rL))},[rR,rE,rL,ei,ed]);let[rz,rA]=(0,i.useState)(null),rW=(0,i.useCallback)(e=>{rA(e)},[]),rP=(0,i.useMemo)(()=>ej?{role:"bashExecution",command:ej.command,output:"",excludeFromContext:ej.excludeFromContext}:null,[ej]),rF=(0,i.useMemo)(()=>{let e=[ey&&!rN&&th?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}(th,B):null,ek&&!ej?B("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[ey,rN,th,ek,ej,B]);(0,i.useEffect)(()=>{if(!rz)return void k?.(null);let e=[],t=[],n=0;if(rN&&rM.length>0){let r=rz.messages.length+e.length;for(let i of(e.push(rN),rM))t.push({idx:r,blocks:i}),n+=eP(i)}if(rP&&(t.push({idx:rz.messages.length+e.length}),e.push(rP)),0===t.length)return void k?.(rF?{...rz,status:rF}:rz);let r=-1;for(let e=rz.messages.length-1;e>=0;e--)if(eJ(rz.messages[e])){r=e;break}let i=rz.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),k?.({...rz,groups:i,messages:[...rz.messages,...e],status:rF})},[rz,rM,rN,rP,rF,k]),(0,i.useEffect)(()=>()=>k?.(null),[k]);let r_=td.filter(e=>"belowEditor"!==e.placement),rD=td.filter(e=>"belowEditor"===e.placement);return eg?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eg}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":t6,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n7,onDragOver:n9,onDragLeave:re,onDrop:rt,children:[t6?(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:B("chat.loadingSession")})}):null,n3&&!tZ&&(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:B("chat.attachFile")})}),tl&&(0,r.jsx)(li,{request:tl,onInput:tu}),rx&&!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.2"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.8.6"]})]})]})]}),(0,r.jsx)(lt,{notices:ti,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)(rZ,{open:nO,onClose:nV,containerRef:tw,index:nq,renderedStart:no,renderedEnd:nd,contentKey:ex,onReveal:nK,onProgrammaticScroll:tx,focusRequest:nB,t:B}),n_&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:B("chat.jumpMissing")}),(0,r.jsx)(lt,{notices:ti,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tw,className:"chat-session-scroll 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)(le,{widgets:r_}),(0,r.jsx)(nA.Provider,{value:ra,children:(0,r.jsx)(ih,{utterances:rf,children:(0,r.jsx)(s3,{messages:ex,entryIds:ev,toolResultsMap:rr,modelNames:eS,messageCwd:rv,onOpenFile:j,sessionBusy:tZ,isNew:tm,isStreaming:eb.isStreaming,handleFork:tS,forkingEntryId:eX,handleNavigate:tC,handleEditContent:em,sessionId:e?.id??tb.current??void 0,main:t9,dispatchSlots:nt,compactedDispatch:nn,process:ne,startIndex:no,endIndex:nd,sentinelRef:nh,laterSentinelRef:nm,flashItem:ng,t:B,cues:J,cueFollowRef:tQ,onProcessLogChange:rW})})}),!nu&&eb.isStreaming&&eb.streamingMessage&&rT.length>0&&(0,r.jsx)(rg,{message:eL(eb.streamingMessage,rT),sessionId:e?.id??tb.current??void 0,isStreaming:!0,modelNames:eS,cwd:rv,onOpenFile:j}),n2&&(0,r.jsx)(r4,{onDismiss:n0,t:B}),(0,r.jsx)("div",{ref:ty})]})})}),(0,r.jsx)(rX,{questions:nJ,containerRef:tw,layoutKey:nG,onJump:nj,label:B("chat.questionRail")}),(tZ&&tf||nu)&&(0,r.jsxs)("button",{type:"button",onClick:nP,"aria-label":B("chat.jumpToBottom"),title:B("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,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"})]}),B("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rk,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[ta&&(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)(lr,{request:ta,onRespond:tc,onActivity:e=>void tu(e,"activity"),delivery:ts})})}),(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)(r2,{compaction:e0,t:B}),(0,r.jsx)(s9,{goal:tv,t:B}),(0,r.jsx)(rK,{summary:rs,onJump:nj,onOpenPanel:rl}),(0,r.jsx)(le,{widgets:rD}),rd&&(0,r.jsx)(sp,{phases:rd})]})}),rC,(0,r.jsx)(su,{statuses:to})]})]})}function s9({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tV(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tV(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 le({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 lt({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 a="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:a,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 ln({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:l,children:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let 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:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:a},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 lr({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,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)(ln,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,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:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,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 a=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=a.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]??[],a=r?i.includes(n)?i.filter(e=>e!==n):[...i,n]:[n];return{...t,[e]:a}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,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:s("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:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,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:s("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:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(ln,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,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:s("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)(tU,{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:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,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:s("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:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(ln,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,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:s("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:s("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:s("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:s("chat.submit")}):null]})]})})}function li({request:e,onInput:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),l=eC(e.lines);return(0,i.useEffect)(()=>{a.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")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.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(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.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 a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eN(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function la({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,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"===s.kind?s.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=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),c(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let 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"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,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:a?a.name?.trim()||a.firstMessage?.trim()||a.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,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var ls=n(50640),ll=n(73620);let lo=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function ld(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 lc=["tags","categories","keywords","tag","category"];function lu({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,a=lc.find(t=>Array.isArray(e[t])),s=a?e[a].map(ld).filter(Boolean):[],l=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.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=ld(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 lp={source:"Source",preview:"Preview",diff:"Diff"},lh={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},lm={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 lg(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function lx(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=lg(n.startContainer),i=lg(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let a=Number(r.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(a)||!Number.isInteger(s))return null;if(a<s){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return a>s?null:{startLine:a,endLine:s}}function lv({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,a)=>{let s=e.children??[],l=s[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?s[0]:null,c=o?s.slice(1):s;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":a+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,ls.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${a}`}),(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,ls.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${a}-${r}`}))})]},`source-line-${a}`)})}function lb(e,t,n,r={}){let i=e9(e),a=new URLSearchParams({type:t});for(let[e,t]of(n&&a.set("sessionId",n),Object.entries(r)))void 0!==t&&a.set(e,String(t));return`/api/files/${i}?${a.toString()}`}function ly({filePath:e,sourceSessionId:t}){let{t:n}=(0,R.s)();return(0,r.jsx)("a",{href:lb(e,"download",t),download:te(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 lw(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function lk({patch:e}){let t,{t:n}=(0,R.s)(),i=(t=np(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 a=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)s.add(t);let l=[],o=0;for(;o<i.length;)if(s.has(o)){let e=[];for(;o<i.length&&s.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!s.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...lh},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?"-":" ",a="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:lm,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:a,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 lj({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=te(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(lb(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=lb(e,"read",n,o?{v:o}:void 0),b=null!=c?lw(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:tt(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:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(ly,{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 lS({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=te(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(lb(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=lb(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:tt(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:lw(c)}),(0,r.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(ly,{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 lC({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eR(e),g="pdf"===f,x=g?lb(e,"read",n,o?{v:o}:void 0):lb(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(lb(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(lb(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:tt(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===f?"docx preview":"pdf"}),null!=c&&(0,r.jsx)("span",{children:lw(c)}),(0,r.jsx)(ly,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:a(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]})]}),(0,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:a("i18n.previewFile",{file:te(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function lN({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o}){let d;return eE(e)?(0,r.jsx)(lj,{filePath:e,cwd:t,sourceSessionId:n}):null!==(e$[eR(e)]??null)?(0,r.jsx)(lS,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(d=eR(e))||"docx"===d?d:null)?(0,r.jsx)(lC,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(lI,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o})}function lI({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:a,onMentionLines:s,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d}){let c,u,{isDark:p}=tF(),{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),[z,A]=(0,i.useState)(null),W=(0,i.useCallback)(e=>fetch(lb(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()}`),a=await i.json();if(n!==E.current)return;x(i.ok&&a.supported&&"string"==typeof a.patch?a: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(lb(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 O=(0,i.useMemo)(()=>m?.language==="markdown"?tc(m.content):"",[m]),H=(0,i.useMemo)(()=>m?.language==="markdown"?function(e){let t=function(e){let t=lo.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,ll.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;A(s&&"source"===S&&e?lx(e,window.getSelection()):null)};if(e(),s&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,S,s]);let B=(0,i.useCallback)(n=>{s&&n&&s(tt(e,t),n.startLine,n.endLine)},[t,e,s]);if((0,i.useEffect)(()=>{if(!s||"source"!==S)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=L.current,r=n?lx(n,window.getSelection()):null;r&&(e.preventDefault(),B(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,B,s]),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=e7(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 ${lw(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:tt(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:lp[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(l||s)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{z&&s?B(z):l?.(tt(e,t),!1)},title:z&&s?`${h("i18n.mentionSelectedLines")} (L${z.startLine}${z.startLine!==z.endLine?`-L${z.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!l&&!s,className:"file-viewer-icon-button",children:(0,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)(ly,{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)(lk,{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:[H?.data&&(0,r.jsx)(lu,{data:H.data}),(0,r.jsx)(e3.oz,{remarkPlugins:tf,rehypePlugins:tx,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===i?(0,r.jsx)(tO,{code:a.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tB,{code:a.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 s=a?e2(e,J,t??J):null;return s&&a?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(s))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...a}){delete a.node;let s="string"==typeof e?e2(e,J,t??J):null,l=s?lb(s,"read",n):e;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...a})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:O})]}):(0,r.jsx)(e8.A,{className:N?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?e6.xJ:e6.vs,showLineNumbers:!0,lineNumberStyle:{...lm},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...lh,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)(lv,{...e,wrapLines:N}),wrapLongLines:N,children:q})})]})}function lT({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:a}){let{t:s,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(),a(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,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:ny(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(),a(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:o===e.id?"var(--bg-hover)":"transparent",border:"none",color:o===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("i18n.close"),"aria-label":`${s("i18n.close")} ${e.label}`,children:(0,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 lM=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],l$=new Set(lM);function lR(e){return void 0!==e&&l$.has(e)}function lE(e){if(!e)return[...lM];let t=new Set(e);return lM.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function lL(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return lR(n)?n:"inherit"}function lz(e,t){let n=e.lastIndexOf(":"),r=lR(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var lA=n(98795),lW=n.n(lA);function lP(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function lF({value:e,options:t,onChange:n,disabled:a=!1,placeholder:s="Select…",searchPlaceholder:l="Search options…",noResultsLabel:o="No matching options",ariaLabel:d,className:c,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),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=lP(v.trim());return e?t.filter(t=>lP(`${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}=aW(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:`${lW().root}${c?` ${c}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:lW().trigger,disabled:a,"aria-label":d,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,r.jsx)("span",{className:j?lW().value:lW().placeholder,children:j?.label??(e||s)}),(0,r.jsx)("svg",{className:lW().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:lW().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:lW().searchWrap,children:[(0,r.jsxs)("svg",{className:lW().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:lW().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:lW().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:lW().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:lW().optionCopy,children:[(0,r.jsx)("span",{className:lW().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:lW().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:lW().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:lW().empty,children:o})})]})]})}let l_=["global","project"],lD=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function lO(e){return`${e.provider}/${e.id}`}function lH({cwd:e,onRolesChanged:t}){let{t:n}=(0,R.s)(),[a,s]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,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){s([]),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 a=await r.json();if(a.error)throw Error(a.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();s(a.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{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})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(a.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>a.filter(e=>!e.hidden),[a]),k=w.some(e=>lD.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:l_.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}`:lz(e.selector??"","inherit"),i=lL(e.selector),a=lE(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=lD.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}),s&&(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:s&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(lF,{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=>lO(e)===t),r=n?d[`${n.provider}:${n.id}`]:void 0,i=lL(e.selector),a=lE(r).includes(i)?i:"inherit";y(e.role,lz(t,a))},options:[{value:"",label:n("roles.unset")},...l.map(e=>({value:lO(e),label:`${e.name} — ${e.provider}`,searchText:lO(e)})),...t&&!l.some(e=>lO(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:a.map(a=>{let s=i===a;return(0,r.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===a?n("roles.thinkingInherit"):a,onClick:()=>{s||y(e.role,lz(t,a))},style:{padding:"3px 7px",border:`1px solid ${s?"var(--accent)":"var(--border)"}`,borderRadius:4,background:s?"var(--bg-selected)":"transparent",color:s?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:s?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:a},a)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function lB(e){window.open(e,"_blank","noopener,noreferrer")}var lU=n(67381),lq=n(64433),lK=n(70350),lV=n(88195),lJ=n(9312),lG=n(87275),lY=n(22008),lZ=n(95476),lX=n(35029),lQ=n(14489),l0=n(78728),l1=n(19872),l2=n(7751),l4=n(92526),l5=n(48238),l8=n(57794),l6=n(41098),l3=n(84604),l7=n(15315),l9=n(74278),oe=n(55457),ot=n(71437),on=n(29167),or=n(97283),oi=n(34166),oa=n(33889),os=n(85486),ol=n(74068),oo=n(83546),od=n(83709);let oc={anthropic:{Icon:lU.A,hasColor:!1},openai:{Icon:lq.A,hasColor:!1},"openai-codex":{Icon:lq.A,hasColor:!1},google:{Icon:lK.A,hasColor:!0},"google-vertex":{Icon:lK.A,hasColor:!0},"ant-ling":{Icon:oa.A,hasColor:!0},deepseek:{Icon:lV.A,hasColor:!0},groq:{Icon:lJ.A,hasColor:!1},mistral:{Icon:lG.A,hasColor:!0},moonshotai:{Icon:lY.A,hasColor:!1},"moonshotai-cn":{Icon:lY.A,hasColor:!1},moonshot:{Icon:lY.A,hasColor:!1},minimax:{Icon:lZ.A,hasColor:!0},"minimax-cn":{Icon:lZ.A,hasColor:!0},fireworks:{Icon:lX.A,hasColor:!0},huggingface:{Icon:lQ.A,hasColor:!0},cerebras:{Icon:l0.A,hasColor:!0},openrouter:{Icon:l1.A,hasColor:!1},xai:{Icon:l2.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:l4.A,hasColor:!0},"cloudflare-workers-ai":{Icon:l4.A,hasColor:!0},"vercel-ai-gateway":{Icon:l5.A,hasColor:!1},"github-copilot":{Icon:l8.A,hasColor:!1},"amazon-bedrock":{Icon:l6.A,hasColor:!0},"azure-openai-responses":{Icon:l3.A,hasColor:!0},"kimi-coding":{Icon:l7.A,hasColor:!0},nvidia:{Icon:os.A,hasColor:!0},opencode:{Icon:ol.A,hasColor:!1},"opencode-go":{Icon:ol.A,hasColor:!1},qwen:{Icon:l9.A,hasColor:!0},xiaomi:{Icon:oo.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oo.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oo.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oo.A,hasColor:!1},zai:{Icon:od.A,hasColor:!1},"zai-coding-cn":{Icon:od.A,hasColor:!1},zhipu:{Icon:oe.A,hasColor:!0},cohere:{Icon:ot.A,hasColor:!0},perplexity:{Icon:on.A,hasColor:!0},together:{Icon:or.A,hasColor:!0},grok:{Icon:oi.A,hasColor:!1}},ou=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function op({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 oh={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 om({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...oh,fontFamily:i?"var(--font-mono)":"inherit"}})}function of({value:e,onChange:t,placeholder:n,mono:a,onKeyDown:s,autoComplete:l="off",spellCheck:o=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,R.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,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:s,placeholder:n,style:{...oh,paddingRight:34,fontFamily:a?"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 og({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:oh})}function ox({value:e,onChange:t,options:n,required:i}){let{t:a}=(0,R.s)();return(0,r.jsx)(lF,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${a("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function ov({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 ob({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 oy({name:e,provider:t,onChange:n,onRename:a,onDelete:s,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,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)(ob,{children:o("i18n.provider")}),(0,r.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:o("i18n.delete")})]}),(0,r.jsxs)(op,{label:o("i18n.providerName"),children:[(0,r.jsx)(om,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>a(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:4,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:o("i18n.rename")})]}),(0,r.jsx)(op,{label:"Base URL",children:(0,r.jsx)(om,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(op,{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)(op,{label:"API",children:(0,r.jsx)(ox,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:ou,required:!0})}),(0,r.jsxs)(op,{label:"Headers",children:[(0,r.jsx)(oC,{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:{...oh,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 ow=["off","minimal","low","medium","high","xhigh","max"],ok={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oj({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:ow.map(e=>{let t=n[e],a=e in n?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=ok[e],o={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,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"===a?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===a?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===a?"line-through":"none"},children:e})]}),(0,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"===a?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===a?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===a?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,s||e),style:{...o,..."string"===a?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:s,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==a&&i(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===a?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===a?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oS={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oC({headers:e,onChange:t}){let[n,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),s=(0,i.useRef)(n.length),l=e=>{a(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:{...oh,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:{...oh,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:()=>a(e=>[...e,{id:s.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function oN({providerName:e,provider:t,model:n,onChange:a,onDelete:s}){let[l,o]=(0,i.useState)({phase:"idle"}),{t:d}=(0,R.s)(),[c,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>a({...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 s=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${s}`),o=await l.json();if(i!==p.current)return;if(!l.ok||o.error||!o.recommendation)return void u({phase:"error",message:o.error??`HTTP ${l.status}`});let d=function(e,t){let 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??{}},a=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],a=!0,r+=1);a&&(n.cost=i)}return{model:n,appliedCount:r}}(n,o.recommendation.preset);d.appliedCount>0&&(h.current=n,a(d.model)),u({phase:"success",recommendation:o.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,n,a,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)(ob,{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:s,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(op,{label:"ID *",children:(0,r.jsx)(om,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(op,{label:"Name",children:(0,r.jsx)(om,{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,a(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsx)(op,{label:"API override",children:(0,r.jsx)(ox,{value:n.api??"",onChange:e=>m("api",e||void 0),options:ou})}),(0,r.jsxs)(op,{label:"Headers",children:[(0,r.jsx)(oC,{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)(ov,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(ov,{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)(ov,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oS}};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)(ov,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>a({...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)(ob,{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)(oj,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(op,{label:"Context window (tokens)",children:(0,r.jsx)(og,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(op,{label:"Max output tokens",children:(0,r.jsx)(og,{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)(ob,{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)(op,{label:e,children:(0,r.jsx)(og,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void a({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let oI={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function oT({provider:e,onRefresh:t,relogin:n}){let a=n?.onLoginSucceeded,[s,l]=(0,i.useState)({phase:"idle"}),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=void 0!==n;(0,i.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),c(""),u.current?.close(),u.current=null},[e.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,i.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,c(""),l({phase:"success"}),t(),a?.())},[t,a]),x=(0,i.useCallback)(()=>{u.current?.close(),p.current=!1,l({phase:"connecting"}),c("");let t=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);u.current=t,t.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),lB(n.url)):"device_code"===n.type?(l({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),lB(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"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(ob,{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)(nc,{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"===s.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"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,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"===s.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":s.message}),"auth"===s.phase&&(0,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:s.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(s.token,d)},placeholder:"auth"===s.phase?"Paste the redirect URL or code":s.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>y(s.token,d),disabled:!d.trim(),style:{padding:"6px 12px",background:d.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:d.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:d.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:o("i18n.submit")})]})]}),"device_code"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(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(oI[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:o("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.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 oM({provider:e,onRefresh:t}){let[n,a]=(0,i.useState)(""),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,R.s)();(0,i.useEffect)(()=>{a(""),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}`):(a(""),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)(ob,{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)(op,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(of,{value:n,onChange:a,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:s||!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:s||!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":s?"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 o$({id:e,size:t}){let n=oc[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 oR({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:a,onAddCustom:s,onClose:l}){let[o,d]=(0,i.useState)(""),{t:c}=(0,R.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=o.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),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:()=>{s(),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,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)(o$,{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:()=>{a(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,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)(o$,{id:e.id,size:28})]},e.id))]})})]})})}function oE({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:a,relogin:s}){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)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[w,k]=(0,i.useState)([]),[j,S]=(0,i.useState)([]),[C,N]=(0,i.useState)(!1),I=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>k(e.providers)).catch(()=>{})},[]),T=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),M=(0,i.useCallback)(()=>{I(),T()},[I,T]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{c(e.providers?e:{...e,providers:{}})}).catch(()=>c({providers:{}})).finally(()=>p(!1)),M()},[M]);let $=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;d.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),y({type:"provider",name:e})},[d.providers]),E=(0,i.useCallback)((e,t)=>{c(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)},[]),z=(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})},[]),A=(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??[]],a=new Set(i.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),F=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},a=[...i.models??[]];return a[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:a}}}})},[]),_=(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),a?.(),setTimeout(()=>v(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[d,a]),O=Object.entries(d.providers??{}),H=w.filter(e=>e.loggedIn),B=j.filter(e=>e.configured),U=(()=>{if(!b)return null;if("roles"===b.type)return(0,r.jsx)(lH,{cwd:e??null,onRolesChanged:a});if("oauth"===b.type){let e=w.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oT,{provider:e,onRefresh:M,relogin:s?.target.provider===e.id?s:void 0},e.id):null}if("apikey"===b.type){let e=j.find(e=>e.id===b.providerId);return e?(0,r.jsx)(oM,{provider:e,onRefresh:M},e.id):null}if("provider"===b.type){let e=d.providers?.[b.name];return e?(0,r.jsx)(oy,{name:b.name,provider:e,onChange:e=>E(b.name,e),onRename:e=>L(b.name,e),onDelete:()=>z(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)(oN,{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)"}}),H.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)(o$,{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)(o$,{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)}),(H.length>0||B.length>0)&&O.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")}):O.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(),A(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,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)(oR,{oauthProviders:w,apiKeyProviders:j,onSelectOAuth:e=>y({type:"oauth",providerId:e}),onSelectApiKey:e=>y({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>N(!1)})]})}function oL(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oz(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function oA(e){let t=oz(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function oW(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function oP(e){return e?e.slice(0,8):"unknown"}function oF({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 o_({skill:e,cwd:t,onToggle:n,toggling:i,saveError:a,updateStatus:s,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=oz(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 oL(e)}(e.filePath)}),(0,r.jsx)(oF,{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")}),a&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),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:oP(s?.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")}),s?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:oP(s.latestVersion)}),(l||s&&"update-available"!==s.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":s?.state==="up-to-date"?"#16a34a":s?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):s?.state==="up-to-date"?p("i18n.upToDate"):s?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):s?.message||p("i18n.checkFailed")}),s?.state==="update-available"&&(0,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 oD({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,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}`)),a()}catch(e){v(String(e))}finally{g(null)}},[a,w,e]),N="global"===w?"~/.claude/skills/":`${oL(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:s("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:s("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,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?s("i18n.searching"):s("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:s("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,a=e.package.indexOf("@"),l=a>-1?e.package.slice(0,a):e.package,o=a>-1?e.package.slice(a+1):null;return(0,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?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("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 oO({cwd:e,onClose:t,embedded:n=!1}){let a=P(),{t:s}=(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),[z,A]=(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&&A(t=>({...t,[oA(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(oW).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=oW(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 a=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:a,latestVersion:a}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,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&&A(t=>({...t,[oA(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),O=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%":a?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":a?"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:s("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:oL(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:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,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:s("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:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===oz(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===oz(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===oz(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===oz(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===oz(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,a=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:a?"var(--border)":"var(--accent)",boxShadow:a?"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:a?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=oW(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:s("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),a=n.filter(e=>e.disableModelInvocation),l=z[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),a.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>A(t=>({...t,[e]:!l})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),s("i18n.dormant")," (",a.length,")"]}),l&&a.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"})]}),s("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(oD,{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:O?(0,r.jsx)(o_,{skill:O,cwd:e,onToggle:D,toggling:f.has(O.filePath),saveError:x,updateStatus:oW(O)?w[oW(O)]:void 0,checkingUpdate:!!oW(O)&&j.has(oW(O)),updating:I===oW(O),updateError:M,onCheckUpdate:()=>void F(O),onUpdate:()=>void _(O)},O.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("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?s("i18n.checking"):s("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?s("i18n.update"):s("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:s("i18n.close")})]})]})})}let oH="global";function oB(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oU(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function oq(e){return`${e.scope}\0${e.source}`}function oK(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 oV(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 oJ(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function oG({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 oY({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 oZ(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 oX({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 oQ({installDir:e,source:t,busy:n,actionError:a,onSourceChange:s,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,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:oB(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=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=oU(t);n!==t&&(e.preventDefault(),s(n))},onBlur:e=>s(oU(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:{...oZ(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:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function o0({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:a,sessionId:s,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=oq(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)(oX,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(oY,{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:oZ(u||p),children:d(n===`update:${c}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:o,disabled:!s||p||u,style:oZ(!s||p||u),title:d(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:oZ(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:oJ(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:oV(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:oK(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?oB(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:oB(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)(oG,{pkg:e})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function o1({cwd:e,sessionId:t,onClose:n,onReloaded:a,embedded:s=!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=>oq(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=>oq(t)===e)?e:n.packages[0]?oq(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=oq(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]?oq(i.packages[0]):null),0===i.packages.length&&v(!0),N(o("i18n.packageRemoved"));else{let e={install:o("i18n.packageInstalled"),update:o("i18n.packageUpdated"),disable:o("i18n.packageDisabledRestartRequired"),enable:o("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,o]),z=(0,i.useCallback)(async()=>{let t=oU(b).trim();if(!t)return;y(t);let n=`${oH}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,a,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:oH,cwd:e})}),l=await s.json();if(!s.ok||l.error)throw Error(l.error??`HTTP ${s.status}`);c(l);let d=(r=l.packages,a=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===oH&&e.source===i)??r.find(e=>e.scope===oH&&e.source===`npm:${a}`)??r.find(e=>e.scope===oH&&e.source.endsWith(i)));g(d?oq(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]),A=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await sv(t,{type:"reload"}),a?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,a,t,o]),W=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:s?"100%":l?"calc(100vw - 16px)":860,maxWidth:s?"none":"calc(100vw - 16px)",height:s?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:s?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:s?"none":"1px solid var(--border)",borderRadius:8*!s,display:"flex",flexDirection:"column",boxShadow:s?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,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:oB(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=oq(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:oJ(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:oK(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:oV(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)(oQ,{installDir:d?.installDir,source:b,busy:W,actionError:j,onSourceChange:y,onInstall:z}):u?null:T?(0,r.jsx)(o0,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:A},oq(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:oZ(u||null!==w),children:o("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:oZ(!1),children:o("i18n.close")})]})]})})}var o2=n(13004),o4=n.n(o2);function o5(){let[e,t]=(0,i.useState)(null),[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[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),a(null)}catch(e){a(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:o4().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:o4().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:o4().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:o4().reloadNotice,children:(0,r.jsx)("span",{children:o})})]}),(0,r.jsxs)("div",{className:o4().settingsBody,children:[(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:o4().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:o4().settingDescription,children:"Set a password below before turning this on."}),s&&(0,r.jsx)("div",{className:o4().error,children:s})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("button",{type:"button",className:o4().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:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:o4().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{className:o4().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:o4().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{className:o4().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:o4().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:o4().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:o4().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:o4().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:o4().settingControl,children:(0,r.jsx)("a",{className:o4().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:o4().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:o4().settingControl})]})]})]})]})}let o8="/api/live/character-voice",o6={ready:"chat.liveVoiceStateReady","not-prepared":"chat.liveVoiceStateNotPrepared",preparing:"chat.liveVoiceStatePreparing","needs-check":"chat.liveVoiceStateNeedsCheck",failed:"chat.liveVoiceStateFailed","missing-asset":"chat.liveVoiceStateMissingAsset"},o3={failed:!0,"needs-check":!0,"missing-asset":!0};async function o7(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 o9(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[a,s]=(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{s(await o7(await fetch(o8,{cache:"no-store"})))}catch(t){o(t instanceof Error?t.message:e("chat.liveVoiceLoadFailed"))}},[e]);(0,i.useEffect)(()=>{f()},[f]);let g=a?.preparing===!0;(0,i.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>void f(),2e3);return()=>clearTimeout(e)},[g,a,f]);let x=(0,i.useCallback)(async e=>{m(!0),o(null);try{return s(await o7(await fetch(o8,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(!a)return(0,r.jsx)("div",{className:o4().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"});let b=a.configured,y=l??a.lastError??null;return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:o4().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsxs)("div",{className:o4().settingsBody,children:[(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e("chat.liveVoiceKeyLabel")}),(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("label",{htmlFor:t,className:o4().settingLabel,style:{display:"block"},children:e("chat.liveVoiceKeyLabel")}),(0,r.jsx)("div",{className:o4().settingDescription,children:e("chat.liveVoiceKeyHelp")}),b&&a.keyHint&&(0,r.jsx)("div",{className:o4().saveState,style:{overflowWrap:"anywhere"},children:e("chat.liveVoiceKeySaved",{hint:a.keyHint})})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{id:t,className:o4().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:o4().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:o4().dangerButton,disabled:h||g,onClick:()=>void x({method:"DELETE"}),children:e("chat.liveVoiceKeyRemove")}),(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:h||!d.trim(),onClick:()=>void v(),children:e("chat.liveVoiceKeySave")})]})]})]}),(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e("chat.liveVoicePrepare")}),(0,r.jsxs)("div",{className:o4().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:o4().settingDescription,style:{display:"block",color:"var(--text)"},children:e("chat.liveVoiceConsent")}),(0,r.jsxs)("div",{className:o4().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:o4().settingControl,style:{alignItems:"center"},children:(0,r.jsx)("button",{type:"button",className:o4().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:o4().error,role:"alert",style:{overflowWrap:"anywhere"},children:y})]}),(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:e("chat.liveVoiceCharacters")}),(0,r.jsx)("ul",{"aria-live":"polite",style:{listStyle:"none",margin:0,padding:0},children:a.characters.map(t=>(0,r.jsxs)("li",{className:o4().settingRow,style:{minHeight:44},title:t.error,children:[(0,r.jsxs)("div",{className:o4().settingLabel,style:{marginBottom:0},children:[t.alias,"provisional"===t.tuning&&(0,r.jsxs)("span",{className:o4().settingDescription,style:{fontWeight:400},children:[" \xb7 ",e("chat.liveVoiceProvisional")]})]}),(0,r.jsx)("div",{className:o4().settingControl,style:{fontSize:12,color:o3[t.state]?"var(--danger)":"ready"===t.state?"var(--text)":"var(--text-muted)"},children:e(o6[t.state])})]},t.id))})]})]})]})}function de(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return aI({signal:e.signal}).then(e=>{s(e),o(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let f=(0,i.useCallback)(async e=>{p(!0),c(null),m(!1);try{let t=await aT(e);s(t),o(String(t.uploadLimitMb)),m(!0)}catch(e){c(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return a?(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:o4().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:o4().settingsBody,children:(0,r.jsxs)("section",{className:o4().group,children:[(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:o4().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:o4().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("input",{id:t,className:o4().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:l,disabled:u,onChange:e=>o(e.target.value),onBlur:()=>{let t=l.trim();if(t===String(a.uploadLimitMb))return;let 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:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:o4().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:o4().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:a.orphanGraceDays})})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)("button",{type:"button",className:o4().switch,"data-on":a.autoCleanupEnabled,"aria-pressed":a.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!a.autoCleanupEnabled})})})]}),d&&(0,r.jsx)("div",{className:o4().error,role:"alert",style:{overflowWrap:"anywhere"},children:d}),h&&!d&&(0,r.jsx)("div",{className:o4().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:o4().empty,children:d?`${e("chat.attachmentSettingsLoadFailed")}: ${d}`:"…"})}function dt({cwd:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[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)}`:"",s=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),o=await s.json();if(n!==b.current||r.signal.aborted)return;if(!s.ok||!o.projects)throw Error(o.error??`HTTP ${s.status}`);let d=o.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=o.projects,a(o.projects),l(null),d&&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 s=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=s,a(s),"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:o4().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,r.jsx)("button",{type:"button",className:o4().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:o4().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:o4().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,r.jsx)("div",{className:o4().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,r.jsx)("div",{className:o4().settingsBody,children:(0,r.jsxs)("section",{className:o4().group,children:[0===n.length&&(0,r.jsx)("div",{className:o4().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=c===e.cwd,a=o?.cwd===e.cwd?o:null,s=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),l=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:o4().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:o4().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:o4().settingDescription,style:{fontWeight:600},children:s})]}),(0,r.jsx)("code",{className:o4().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:o4().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:o4().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:o4().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),a&&(0,r.jsx)("div",{className:o4().settingDescription,style:{color:"var(--text)"},children:"revoke"===a.action?t("trust.confirmRevoke"):a.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:o4().saveState,children:m.text})]}),l&&(0,r.jsx)("div",{className:o4().error,role:"alert",children:l})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:o4().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:o4().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"===a.action?o4().dangerButton:o4().primaryButton,disabled:N,onClick:()=>void C(e.cwd,a.action),children:"revoke"===a.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:o4().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:o4().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:o4().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이다"}}}'),dr=[{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"}],di={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 da({kind:e}){return(0,r.jsx)("svg",{className:o4().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:di[e]??di.tools})}function ds({field:e,busy:t,onSave:n}){let[a,s]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:o4().textInput,type:"secret"===e.type?"password":"text",value:a,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{a!==l&&("secret"!==e.type||a.length>0)&&n(a)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function dl({field:e,busy:t,onSave:n}){let a=JSON.stringify(e.value??{},null,2),[s,l]=(0,i.useState)(a),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(a),d(null)},[a]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:o4().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(s!==a)try{n(JSON.parse(s)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,r.jsx)("div",{className:o4().error,children:o})]})}function dd({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],a=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let a=[...i];[a[e],a[r]]=[a[r],a[e]],n(a)};return(0,r.jsx)("div",{className:o4().multiSelect,children:e.options?.map(s=>{let l=i.indexOf(s.value);return(0,r.jsxs)("span",{className:o4().choice,"data-selected":l>=0,title:s.description,children:[(0,r.jsx)("button",{type:"button",className:o4().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:s.label}),e.ordered&&l>=0&&(0,r.jsxs)("span",{className:o4().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>a(l,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>a(l,1),children:"→"})]})]},s.value)})})}function dc({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:o4().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(lF,{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)(dd,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(dl,{field:e,busy:t,onSave:n}):(0,r.jsx)(ds,{field:e,busy:t,onSave:n})}function du({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:o4().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:o4().settingLabel,children:e.label}),(0,r.jsx)("div",{className:o4().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:o4().error,children:n})]}),(0,r.jsx)("div",{className:o4().settingControl,children:(0,r.jsx)(dc,{field:e,busy:t,onSave:i})})]})}function dp({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:o4().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:o4().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:o4().themePreviewPanel,children:[(0,r.jsx)("div",{className:o4().themePreviewLine}),(0,r.jsx)("div",{className:o4().themePreviewLine})]})]})}let dh='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',dm=new Set(["hideThinkingBlock"]);function df({cwd:e,sessionId:t,initialSection:n="models",onClose:a,onModelsChanged:s,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}=tF(),{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(dh)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(dh)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let z=(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 tP(e),await L()):dm.has(t.path)?await t1(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]),A=(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,A))??[],[c?.fields,A]),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)(()=>{s?.(),a()},[a,s]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sv(t,{type:"reload"}),j(!1),l?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),O=c?.tabs.find(e=>e.id===P),H=g.trim()?`${E("Search")} \xb7 ${F.length}`:O?.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:o4().group,children:[(0,r.jsx)("h3",{className:o4().groupTitle,children:t}),n.map(e=>(0,r.jsx)(du,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void z(e,t)},e.path))]},t):null}),U=()=>p?(0,r.jsx)("div",{className:o4().empty,children:E("Loading omp settings…")}):m||!c?(0,r.jsx)("div",{className:o4().empty,children:m??E("Settings unavailable")}):(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:H}),(0,r.jsx)("p",{className:o4().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:o4().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:o4().settingsBody,children:F.length?B(F,O?.groups??[]):(0,r.jsx)("div",{className:o4().empty,children:E("No settings match this search.")})})]});return(0,r.jsx)("div",{className:o4().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&_()},children:(0,r.jsxs)("div",{ref:$,tabIndex:-1,className:o4().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,r.jsxs)("aside",{className:o4().sidebar,children:[(0,r.jsxs)("div",{className:o4().brand,children:[(0,r.jsx)("div",{className:o4().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:o4().title,children:E("Settings")}),(0,r.jsx)("code",{className:o4().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,r.jsxs)("div",{className:o4().searchWrap,children:[(0,r.jsxs)("svg",{className:o4().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:o4().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:o4().nav,children:[(0,r.jsx)("div",{className:o4().navLabel,children:E("Configuration")}),dr.map(t=>{let n=t.labelKey?M(t.labelKey):E(t.label);return(0,r.jsxs)("button",{type:"button",className:o4().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)(da,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:o4().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:o4().navButton,"data-active":!g&&P===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,r.jsx)(da,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:o4().closeRail,children:(0,r.jsxs)("button",{type:"button",className:o4().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:o4().content,children:g.trim()?U():"models"===o?(0,r.jsx)(oE,{cwd:e,embedded:!0,onClose:_,onModelsChanged:s}):"themes"===o?c?(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:E("Themes")}),(0,r.jsxs)("p",{className:o4().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:o4().settingsBody,children:[(0,r.jsx)("div",{className:o4().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:o4().themeCard,children:[(0,r.jsx)(dp,{mode:e,palette:n}),(0,r.jsxs)("div",{className:o4().themeCardBody,children:[(0,r.jsxs)("div",{className:o4().themeCardHeader,children:[(0,r.jsxs)("span",{className:o4().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,r.jsx)("span",{className:o4().themeActive,children:E("Active on web")})]}),(0,r.jsx)(lF,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void z(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:o4().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:o4().empty,children:p?E("Loading themes…"):m??E("Themes unavailable")}):"skills"===o&&e?(0,r.jsx)(oO,{cwd:e,embedded:!0,onClose:_}):"plugins"===o&&e?(0,r.jsx)(o1,{cwd:e,sessionId:t,embedded:!0,onClose:_,onReloaded:l}):"mcp"===o?(0,r.jsx)(dg,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,r.jsx)(o5,{}):"trust"===o?(0,r.jsx)(dt,{cwd:e}):"live-voice"===o?(0,r.jsx)(o9,{}):"attachments"===o?(0,r.jsx)(de,{}):U()})]})})}function dg({cwd:e,sessionId:t,onReloaded:n}){let[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,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}`);s(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=a?"user"===l?a.user:a.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(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})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${l}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:r.name,enabled:!r.enabled})}),s=await a.json();if(!a.ok||s.error)throw Error(s.error??`HTTP ${a.status}`);await w(),t&&(await sv(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:o4().scrollContent,children:[(0,r.jsxs)("header",{className:o4().contentHeader,children:[(0,r.jsx)("h2",{className:o4().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:o4().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:o4().settingsBody,children:a?(0,r.jsxs)("div",{className:o4().mcpLayout,children:[(0,r.jsxs)("aside",{className:o4().mcpList,children:[(0,r.jsxs)("div",{className:o4().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:o4().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",a.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:o4().scopeButton,"data-active":"project"===l,disabled:!a.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",a.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:o4().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:o4().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${l}:${e.name}`;return(0,r.jsxs)("div",{className:o4().serverRow,"data-active":d===t,children:[(0,r.jsxs)("button",{type:"button",className:o4().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,r.jsx)("span",{className:o4().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:o4().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:o4().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:o4().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:o4().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:o4().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:o4().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:o4().editorHeader,children:[(0,r.jsx)("input",{className:o4().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:o4().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:o4().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:o4().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:o4().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:o4().error,children:f}),(0,r.jsx)("div",{className:o4().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:o4().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:o4().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:o4().empty,children:f??"Loading MCP configuration…"})})]})}let dx="cuelo-notification-prompt-dismissed";function dv({variant:e,locale:t,permission:n,dismissed:i,request:a,dismiss:s}){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:a,children:l?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,r.jsx)(d.k.Item,{disabled:"denied"===n,onClick:"default"===n?a: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 db({cwd:e,busy:t,scheduled:n,error:a,onCancel:s,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[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||s()},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}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:a})]})]}),(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:s,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 dy=n(55681),dw=n(54265);let dk={kind:"loading"};function dj(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,ij.Ch)(e.status)?"var(--accent)":"var(--success)"}function dS(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let dC={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function dN(e){return e.lastUpdate||e.progress?.durationMs||0}function dI(){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 dT({sessionId:e,sessionCwd:t,record:n,client:a,visible:s,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,ij._Z)(o,{sessionId:e,client:a,enabled:s}).get(n.key)?.state??dk;(0,i.useEffect)(()=>{if(!s||"ready-live"!==c.kind&&"ready-archive"!==c.kind)return;let e=requestAnimationFrame(()=>{let e=d.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[c,s]);let u="ready-live"===c.kind?c.entries:[],p=(0,i.useMemo)(()=>{let e=new Map;for(let t of u)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[u]),h=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:dI(),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:dS(n)})]}),n.live&&(0,r.jsx)("span",{style:{color:dj(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)(rg,{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 dM({record:e,onSelect:t}){let n=e.live,i=e.archive,a=(0,nk.$V)(e),s=n?.id||i?.name||"Subagent",l=dS(e),o=(0,nk.wX)(e),d=(0,nk.A7)(e),c=d.modelShort??"모델 미확인",u=d.effort??"추론 미확인",p="known"===o.kind?o.label:"역할 미확인";return(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:t,"data-identity":e.identity,title:`${s}
20
20
  ${d.model??"모델 미확인"} \xb7 ${u}
21
21
  ${a.title}${a.stage?`
22
22
  현재 단계: ${a.stage}`:""}`,"aria-label":`${p} ${s}, 업무 ${a.title}${a.stage?`, 현재 단계 ${a.stage}`:""}, ${n?n.status:i?.status??"미확인"}, 모델 ${d.model??"미확인"}, 추론 ${u}`,style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"4px 8px",width:"100%",marginBottom:8,padding:12,border:"1px solid var(--seed-color-stroke-neutral-weak)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-default)",color:"var(--seed-color-fg-neutral)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===o.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":o.agent,title:`${o.agent} \xb7 ${dC[o.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),o.label]}):(0,r.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,r.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:a.title})]}),n?(0,r.jsx)("span",{style:{color:dj(n),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:n.status}):i?(0,r.jsx)("span",{style:{color:"failed"===i.status?"var(--danger)":"aborted"===i.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:i.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),a.stage&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${a.stage}`,style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)"},children:[(0,r.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",a.stage]}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":d.model?d.effort?"both":"model":d.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[c,d.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",u]})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 8px",minWidth:0,color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)"},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("span",{children:l})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 10px",color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)",fontVariantNumeric:"tabular-nums"},children:[n?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",n.progress.toolCount]}),(0,r.jsxs)("span",{children:[n.progress.tokens.toLocaleString()," Token"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}초`;let n=Math.floor(t/60);return n<60?`${n}분${t%60?` ${t%60}초`:""}`:`${Math.floor(n/60)}시간 ${n%60}분`}(n.progress.durationMs)})]}),i&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===i.messages?"메시지 수 미확인":`메시지 ${i.messages}`}),(0,r.jsxs)("span",{children:[(i.bytes/1024).toFixed(+(i.bytes<10240))," KB"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Date.now()-e);return t<1e4?"방금 전":t<6e4?`${Math.floor(t/1e3)}초 전`:t<36e5?`${Math.floor(t/6e4)}분 전`:t<864e5?`${Math.floor(t/36e5)}시간 전`:`${Math.floor(t/864e5)}일 전`}(i.modified)})]})]})]})}function d$({title:e,sessionId:t,sessionPath:n,sessionCwd:a,liveSubagents:s,client:l,visible:o=!0,onClose:d,onReturnFocus:c}){let u=(0,i.useMemo)(()=>l??(0,nk.Et)(),[l]),[p,h]=(0,i.useState)([]),[m,f]=(0,i.useState)({kind:"loading"}),[g,x]=(0,i.useState)({kind:"loading"}),[v,b]=(0,i.useState)(!1),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(0);(0,i.useEffect)(()=>{h([]),f({kind:"loading"}),x({kind:"loading"}),b(!1),w(null)},[t]),(0,i.useEffect)(()=>{if(!o||!t)return;let e=!1,n=!1,r=null,i=async()=>{if(e||n||"visible"!==document.visibilityState)return;n=!0,r=new AbortController;let[i,a]=await Promise.allSettled([u.getLiveSnapshots(t,r.signal),u.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===i.status)h(i.value.subagents),f(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=(0,ij.HK)(i.reason);f("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===a.status)b(!0===a.value.listTruncated),x(a.value.subagents.length>0?{kind:"ready",data:a.value.subagents}:{kind:"empty",data:[]});else{let e=(0,ij.HK)(a.reason);x("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};i();let a=setInterval(()=>void i(),ij.P0),s=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",s),()=>{e=!0,r?.abort(),clearInterval(a),document.removeEventListener("visibilitychange",s)}},[k,u,t,o]);let S=(0,i.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let i of[...e,...t]){let e=n.get(i.id);if(!e){r.push(i.id),n.set(i.id,i);continue}let[t,a]=dN(i)>=dN(e)?[i,e]:[e,i];n.set(i.id,{...t,assignment:t.assignment??a.assignment,description:t.description??a.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(s,p),[s,p]),C="ready"===g.kind||"empty"===g.kind?g.data:[],N=(0,i.useMemo)(()=>(0,nk.IA)(S,C),[C,S]),I=y?N.find(e=>e.key===y)??null:null;if((0,i.useEffect)(()=>{y&&!I&&w(null)},[I,y]),I&&t)return(0,r.jsx)(dT,{sessionId:t,sessionCwd:a,record:I,client:u,visible:o,onBack:()=>w(null)});let T=0===N.length&&"loading"===m.kind&&"loading"===g.kind,M=0===N.length&&("empty"===m.kind||0===s.length)&&"empty"===g.kind;return(0,r.jsxs)("section",{"aria-label":"Subagent 기록","data-state":T?"loading":M?"empty":"ready",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:750,letterSpacing:"0.08em",textTransform:"uppercase"},children:e}),(0,r.jsx)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9},children:t?.slice(0,8)||"세션 없음"})]}),(0,r.jsx)("button",{type:"button",onClick:()=>j(e=>e+1),"aria-label":"Subagent 기록 새로고침",title:"새로고침",style:dI(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})})}),d&&(0,r.jsx)("button",{type:"button",onClick:()=>{d?.(),c?.()},"aria-label":"Subagent 기록 닫기",title:"닫기",style:dI(),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?T?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):M?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,r.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:N.map(e=>(0,r.jsx)(dM,{record:e,onSelect:()=>w(e.key)},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!T&&"loading"===m.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!T&&"loading"===g.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===m.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:m.message}),"error"===m.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:m.message}),"unreachable"===g.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:g.message}),"error"===g.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:g.message}),v&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let dR=["process","efficiency","subagents","files","resource","sidechat"];function dE({activeView:e,onViewChange:t,viewLabels:n,sessionId:i,sessionPath:a,sessionName:o,sessionCwd:d,liveSubagents:c,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:m,resourceSlot:f,efficiencySlot:g,visible:x=!0,onClose:v,onReturnFocus:b}){return(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":e,children:(0,r.jsxs)(dy.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:e,onValueChange:e=>t(e),children:[(0,r.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,r.jsxs)(dy.J.List,{"aria-label":"보조 패널 보기",children:[dR.map(e=>{let t="subagents"===e?c.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(dy.J.Trigger,{value:e,"aria-label":t>0?`${n[e]} (실행 중 ${t})`:void 0,children:[(0,r.jsx)("span",{className:"auxiliary-deck-tab-label",children:n[e]}),t>0&&(0,r.jsx)(dw.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,r.jsx)(dy.J.Indicator,{})]}),v&&(0,r.jsx)(s.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{v?.(),b?.()},"aria-label":"보조 패널 닫기",children:(0,r.jsx)(l.In,{size:"16px",svg:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})})]}),(0,r.jsx)(dy.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(dy.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(dy.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(d$,{title:n.subagents,sessionId:i,sessionPath:a,sessionCwd:d,liveSubagents:c,client:u,visible:x&&"subagents"===e})}),(0,r.jsx)(dy.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,r.jsx)(dy.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:m}),(0,r.jsx)(dy.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:f})]})})}function dL({title:e,data:t,onOpenFile:n}){let{t:a}=(0,R.s)(),l=t?.groups??[],[o,d]=(0,i.useState)(()=>new Set);return(0,r.jsxs)("section",{className:"process-log","aria-label":e,children:[(0,r.jsxs)("header",{className:"process-log-header",children:[(0,r.jsx)("h2",{children:e}),(0,r.jsx)("span",{className:"process-log-count",children:l.length>0?`${l.length} ${a(1===l.length?"process.turn":"process.turns")}`:""})]}),(0,r.jsxs)("div",{className:"process-log-body",children:[t?.status?(0,r.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,r.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),t.status]}):null,0===l.length?(0,r.jsx)("p",{className:"process-log-empty",children:a("process.empty")}):l.map((e,i)=>{let l=o.has(e.anchorIdx),c=function(e){if(!e||"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(" ")).replace(/\s+/g," ").trim();return 0===t.length?null:t.length>72?`${t.slice(0,72)}…`:t}(t?.messages[e.anchorIdx]),u=[`${e.messageCount} ${a(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${a(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(s.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!l,onClick:()=>d(t=>{let n=new Set(t);return n.has(e.anchorIdx)?n.delete(e.anchorIdx):n.add(e.anchorIdx),n}),title:l?a("chat.expandProcess"):a("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:c??a("chat.processDetails")}),(0,r.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!l&&(0,r.jsx)("div",{className:"process-log-entries",children:e.entries.map((i,a)=>{let s=t?.messages[i.idx];return s?(0,r.jsx)(rg,{message:i.blocks?eL(s,i.blocks,{omitUsage:!0}):s,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[i.idx],sessionId:t?.sessionId,showTimestamp:!1},`process-${e.anchorIdx}-${a}`):null})})]},`turn-${e.anchorIdx}-${i}`)})]})]})}let dz=6,dA="omp-btw-log:",dW="omp-btw-log-index";function dP(e){return e.trim().toLowerCase()}function dF(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function d_(e){if(!Array.isArray(e))return[];let t=[],n=0;for(let r of e){if(!r||"object"!=typeof r||"string"!=typeof r.q||"string"!=typeof r.a)continue;let e={q:r.q,a:r.a,at:"number"==typeof r.at&&Number.isFinite(r.at)?r.at:0};t.push(e),n+=e.q.length+e.a.length}for(;t.length>40||n>12e4;){let e=t.shift();if(!e)break;n-=e.q.length+e.a.length}return t}function dD(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function dO(e,t={}){let n=t.now??Date.now,r=new Map,i=new Set,a=!1,s=[],l=t=>{if(e)try{e.removeItem(t)}catch{}},o=e=>{r.delete(e),i.delete(e),l(dA+e)},d=()=>{let e=new Set,t=[];for(let n of(s.sort((e,t)=>t.updatedAt-e.updatedAt),s))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):o(n.id));s=t},c=()=>{if(!a){if(a=!0,e)try{let t=e.getItem(dW),n=t?JSON.parse(t):[];Array.isArray(n)&&(s=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:dP(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{s=[]}d()}},u=e=>{c();for(let t=s.length-1;t>=0;t-=1){if(s[t].id===e)continue;let[n]=s.splice(t,1);return o(n.id),!0}return!1},p=t=>{if(e){try{e.setItem(dW,JSON.stringify(s));return}catch(e){if(!dD(e)||!u(t))return}try{e.setItem(dW,JSON.stringify(s))}catch{}}},h=t=>{let n=dP(t);if(!n)return[];if(i.has(n))return dF(r.get(n)??[]);if(e)try{let t=e.getItem(dA+n);if(t){let e=JSON.parse(t),i=d_(e?.entries);return r.set(n,i),dF(i)}}catch{}return dF(r.get(n)??[])},m=e=>{let t=dP(e);t&&(c(),s=s.filter(e=>e.id!==t),o(t),p(null))};return{read:h,append:(t,a)=>((t,a)=>{let l=dP(t);if(!l)return[];let o=d_(a),h=n();if(r.set(l,dF(o)),c(),(s=s.filter(e=>e.id!==l)).unshift({id:l,updatedAt:h}),d(),p(l),!e)return dF(o);let m=JSON.stringify({updatedAt:h,entries:o});try{return e.setItem(dA+l,m),i.delete(l),dF(o)}catch(e){if(!dD(e)||!u(l))return i.add(l),dF(o)}p(l);try{e.setItem(dA+l,m),i.delete(l)}catch{i.add(l)}return dF(o)})(t,[...h(t),a]),history:(e,t=dz)=>h(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:m,cleanup:(t,r)=>{if(!t.complete)return;c();let i=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=dP(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);i.set(t,Number.isFinite(n)?n:0)}let a=r?dP(r):null,o=n();for(let e of[...s])if(e.id!==a){if(!i.has(e.id)){m(e.id);continue}o-Math.max(i.get(e.id)??0,e.updatedAt)>6048e5&&m(e.id)}if(!e||"function"!=typeof e.key||"number"!=typeof e.length)return;let d=[];try{for(let t=0;t<e.length;t+=1){let n=e.key(t);if(!n?.startsWith(dA))continue;let r=dP(n.slice(dA.length));i.has(r)||r===a||d.push(n)}}catch{return}for(let e of d)l(e)}}}function dH(){let e=new Map,t=new Map,n=new Map,r=e=>{n.get(e)?.forEach(e=>{e()})};return{read(t){let n=e.get(t);return n?{...n.snapshot}:null},begin(t,n){if(e.has(t))return null;let i=new AbortController;return e.set(t,{snapshot:{sessionId:t,question:n,text:"",model:null},controller:i}),r(t),{controller:i}},ingest(t,n){let i=e.get(t);i&&("d"===n.t?i.snapshot.text+=n.v:"done"===n.t?i.snapshot.text=n.v||i.snapshot.text:"m"===n.t&&(i.snapshot.model=n.v),r(t))},abort(t){let n=e.get(t);return!!n&&(n.controller.abort(),!0)},finish(n,i){e.has(n)&&(e.delete(n),t.set(n,i),r(n))},takeOutcome(e){let n=t.get(e)??null;return n&&t.delete(e),n},subscribe(e,t){let r=n.get(e);return r||(r=new Set,n.set(e,r)),r.add(t),()=>{r.delete(t),0===r.size&&n.delete(e)}}}}class dB extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function dU(e){let t;try{t=JSON.parse(e)}catch{throw new dB("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new dB("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new dB("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class dq{push(e){this.buffer+="string"==typeof e?e:this.decoder.decode(e,{stream:!0});let t=this.buffer.split("\n");return this.buffer=t.pop()??"",t.flatMap(e=>e.trim()?[dU(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[dU(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function dK(e){let t=await e.text().catch(()=>"");if(!t)return`HTTP ${e.status}`;try{let e=JSON.parse(t);if("string"==typeof e.error&&e.error)return e.error}catch{}return t}function dV(e=!1){return{minHeight:30,padding:"4px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",fontWeight:650}}function dJ({children:e}){return(0,r.jsx)("div",{className:"side-chat-question",style:{alignSelf:"flex-end",maxWidth:"92%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55},children:e})}function dG({children:e,streaming:t=!1}){return(0,r.jsxs)("div",{className:`side-chat-answer${t?" is-streaming":""}`,style:{alignSelf:"flex-start",maxWidth:"100%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.58},children:[e?(0,r.jsx)(tU,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function dY({identity:e,status:t,utteranceKey:n,children:i}){let a=ns(e?.sessionId,e?.provider,e?.credentialId),s=ic(a?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[a&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(nc,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:a.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[i,s&&(0,r.jsx)("img",{src:s.src,alt:s.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function dZ({title:e,sessionId:t,sessionPath:n,sessionName:a,historyStore:s,flights:l,sessionCensus:o,client:d,visible:c=!0,onClose:u,onReturnFocus:p}){let h,m,f=(0,i.useMemo)(()=>d??function(e=(e,t)=>fetch(e,t),t="/api/sidecars/sidechat/ask"){return{async ask(n){let r;try{r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:n.sessionPath,question:n.question,history:n.history.slice(-dz)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new dB("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new dB("http",await dK(r),r.status);if(!r.body)throw new dB("stream","사이드채팅 스트림을 열 수 없습니다.");let i=r.body.getReader(),a=new dq,s="",l=null,o=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)s+=t.v;else if("done"===t.t)s=t.v||s;else if("m"===t.t)l=t.v;else throw new dB("server",t.v)};try{for(;;){let e=await i.read();if(e.done)break;o(a.push(e.value))}o(a.finish())}catch(e){if(n.signal?.aborted||e instanceof dB)throw e;throw new dB("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{i.releaseLock()}if(!s)throw new dB("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:s,model:l}}}}(),[d]),g=t?.toLowerCase()??null,[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)({}),w=g??"",k=b[w]??"",j=(e,t)=>{y(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,i.useState)(0),[N,I]=(0,i.useState)({}),[T,M]=(0,i.useState)({}),[$,R]=(0,i.useState)({}),[E,L]=(0,i.useState)(null),[z,A]=(0,i.useState)(null),[W,P]=(0,i.useState)({}),[F,_]=(0,i.useState)({}),[D,O]=(0,i.useState)({}),H=(0,i.useRef)((h=new Set,m=new Set,{claim:e=>!(!e||h.has(e)||m.has(e))&&(h.add(e),!0),markSent(e){h.delete(e),m.add(e)},release(e){h.delete(e)}})),B=(0,i.useRef)(!0),U=(0,i.useRef)(g),q=(0,i.useRef)(c),K=(0,i.useRef)(null),V=(0,i.useRef)(!1),J=(0,i.useRef)(0),G=(0,i.useRef)(null);U.current=g,q.current=c,(0,i.useEffect)(()=>(B.current=!0,()=>{B.current=!1}),[]),(0,i.useEffect)(()=>{v(g?s.read(g):[])},[s,g]),(0,i.useEffect)(()=>{if(L(null),!g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0;return{provider:t.provider,..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&L(t?{...t,sessionId:g}:null)}).catch(()=>{e&&L(null)}),()=>{e=!1}},[g]),(0,i.useEffect)(()=>{if(!g)return;let e=()=>{if(!B.current||U.current!==g)return;let e=l.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)I(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),y(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;R(e=>({...e,[g]:t}))}v(s.read(g))}else null===l.read(g)&&v(s.read(g));C(e=>e+1)},t=l.subscribe(g,e);return e(),t},[l,s,g]),(0,i.useEffect)(()=>{o&&s.cleanup(o,g)},[s,g,o]),(0,i.useEffect)(()=>{c&&K.current?.focus()},[c,g]),(0,i.useEffect)(()=>{if(!c)return;let e=requestAnimationFrame(()=>{let e=G.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,c]);let Y=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=l.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await f.ask({sessionPath:n,question:e,history:s.history(g),signal:r,onEvent:e=>l.ingest(g,e)});s.append(g,{q:e,a:t.text,at:Date.now()}),l.finish(g,{kind:"done",model:t.model})}catch(n){let t=l.read(g)?.text??"";if(r.aborted){let n=!1;t&&(s.append(g,{q:e,a:t,at:Date.now()}),n=!0),l.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof dB?n.kind:"unknown",i=n instanceof Error?n.message:String(n);l.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:i})}}finally{B.current&&q.current&&K.current?.focus()}},Z=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(H.current.claim(r)){_(e=>({...e,[r]:"sending"})),O(e=>{let t={...e};return delete t[r],t});try{var i,a;let t,s=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),l=null;try{l=await s.json()}catch{}if(!s.ok){if(l&&"object"==typeof l&&"error"in l&&"string"==typeof l.error)throw Error(l.error);throw Error(`HTTP ${s.status}`)}let o=function(e){if(!e||"object"!=typeof e||!("running"in e)||"boolean"!=typeof e.running)return null;if(!e.running)return!1;if(!("state"in e)||!e.state||"object"!=typeof e.state)return null;let t=e.state;return"isStreaming"in t&&"boolean"==typeof t.isStreaming&&"isPromptRunning"in t&&"boolean"==typeof t.isPromptRunning&&"isBashRunning"in t&&"boolean"==typeof t.isBashRunning&&"isCompacting"in t&&"boolean"==typeof t.isCompacting&&"isHandoffRunning"in t&&"boolean"==typeof t.isHandoffRunning?t.isStreaming||t.isPromptRunning||t.isBashRunning||t.isCompacting||t.isHandoffRunning:null}(l);if(null===o)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let d=(i=e.q,a=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",i,"","[사이드채팅 답변]",a,...t?["","[추가 지시]",t]:[]].join("\n"));await sv(g,{type:o?"steer":"prompt",message:d}),H.current.markSent(r),_(e=>({...e,[r]:"sent"}))}catch(e){H.current.release(r),_(e=>{let t={...e};return delete t[r],t}),O(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},X=()=>{if(g&&null!==l.read(g))return void l.abort(g);let e=k.trim();e&&(j(w,""),Y(e))},Q=N[g??""]??[],ee=T[g??""],et=g?l.read(g):null,en=x.length>0||Q.length>0||null!==et,er=et?.model??$[g??""],ei=!g||!n,ea=null!==et,es=!ea&&!ei&&k.trim().length>0,el=!g||ea,eo=E?.sessionId===g?E:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==et,"data-state":g&&n?et?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[a||g?.slice(0,8)||"세션 없음",er?` \xb7 ${er}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===l.read(g)&&(s.clear(g),v([]),I(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:el,style:dV(el),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...dV(),width:32,padding:0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{ref:G,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,i=`${g}:${n}`,a=F[i],s=z===i;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(dJ,{children:e.q}),(0,r.jsx)(dY,{identity:eo,status:"settled",utteranceKey:n,children:(0,r.jsx)(dG,{children:e.a})}),"sent"===a?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!s&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>A(i),style:{...dV(),alignSelf:"flex-start"},children:"메인에 보내기"}),s&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value:W[i]??"",onChange:e=>P(t=>({...t,[i]:e.target.value})),style:{width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",padding:"7px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void Z(e,n,W[i]??""),disabled:"sending"===a,style:dV("sending"===a),children:"sending"===a?"보내는 중…":"메인으로 전송"}),"sending"!==a&&(0,r.jsx)("button",{type:"button",onClick:()=>A(null),style:dV(),children:"취소"})]})]}),D[i]&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:D[i]})]})]},n)}),Q.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(dJ,{children:e.question}),(0,r.jsxs)(dY,{identity:eo,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(dG,{children:e.partialAnswer}),(0,r.jsx)("div",{role:"alert","data-error-kind":e.kind,style:{padding:"7px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:e.message})]})]},`${e.question}:${t}`)),et&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(dJ,{children:et.question}),(0,r.jsx)(dY,{identity:eo,status:"streaming",utteranceKey:`stream:${et.question}`,children:(0,r.jsx)(dG,{streaming:!0,children:et.text})})]}),!en&&(0,r.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,r.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,r.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,r.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),ee&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:ee})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),X()},style:{display:"flex",flexDirection:"column",gap:6,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,r.jsx)("textarea",{ref:K,id:"side-chat-question",rows:4,value:k,onChange:e=>j(w,e.target.value),onCompositionStart:()=>{V.current=!0},onCompositionEnd:()=>{V.current=!1,J.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-J.current<100;if(V.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}ea||(e.preventDefault(),X())},disabled:ea||ei,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ei?"세션 파일이 준비되면 질문할 수 있습니다.":ea?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!ea&&!es,style:dV(!ea&&!es),children:ea?"중단":"전송"})]})]})]})}function dX(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}let dQ="min-h-9 border border-border bg-bg px-3 text-xs font-medium text-text transition-colors hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50";function d0(...e){return e.filter(Boolean).join(" ")}function d1(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),i=Math.floor(n%1440/60),a=n%60;return r>0?`${r}d ${i}h 후 리셋`:i>0?`${i}h ${a}m 후 리셋`:`${a}m 후 리셋`}function d2(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let i=Math.floor(r/1440),a=Math.floor(r%1440/60),s=r%60;return i>0?`${i}d ${a}h 후 만료`:a>0?`${a}h ${s}m 후 만료`:`${s}m 후 만료`}function d4(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function d5(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function d8(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function d6(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function d3(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function d7(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function d9({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:t})]})}function ce({state:e,loading:t,subject:n}){return t&&"idle"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[n," 불러오는 중…"]}):"error"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsxs)("div",{className:"font-medium",children:[n,"을 불러오지 못했습니다."]}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:e.error.message}),(0,r.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===e.status?(0,r.jsxs)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:["마지막 데이터를 표시합니다. 새로고침 실패: ",e.error.message]}):null}function ct(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${t.getMonth()+1}/${t.getDate()} ${n}:${r}`}function cn({limit:e,now:t,detailed:n}){let i="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,a=Math.max(0,Math.min(100,100*i)),s=Math.round(100*i),l=function(e,t){let n=e.window,r=e.amount?.usedFraction;if(!n?.resetsAt||"number"!=typeof r)return null;let i=Math.max(0,n.resetsAt-t),a=100*r,s=Math.max(0,100-a);if(!n.durationMs){let e=i/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?s/e:s}}let l=Math.min(n.durationMs,Math.max(0,n.durationMs-i)),o=n.durationMs>432e5,d=o?864e5:36e5,c=n.durationMs/d,u=i/d,p=l/n.durationMs*100;return{burnOnly:!1,unit:o?"하루":"시간",partial:u<1,burn:u>=1?s/u:s,pacePct:p,deltaPct:a-p,nominal:100/c}}(e,t),o=e.daySlot,d=o?.usedPct==null||null==o.baselinePct?null:Math.max(0,Math.min(o.baselinePct,100)),c=null==d?null:Math.max(d,Math.min(100*i,100)),u=l?.pacePct==null?null:Math.min(l.pacePct,99.6),p=s>=90,h=l?.deltaPct!=null&&l.deltaPct>=.5?l.deltaPct:null,m=o?"unknown"===o.quality||null==o.usedPct?"구간 사용 — 기록 부족":"approx"===o.quality?`구간 사용 ≈${o.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${o.usedPct.toFixed(1)}%`:null;return(0,r.jsxs)("div",{className:"usage-limit py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:e.label||e.id}),i>=1?(0,r.jsx)("span",{className:"usage-chip","data-tone":"danger",children:i>1?"한도 초과":"한도 도달"}):null,null!=h?(0,r.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${h.toFixed(1)}%`}):null,(0,r.jsxs)("span",{className:d0("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[s,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":s,children:[(0,r.jsx)("div",{className:d0("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${a}%`}}),null!=d&&null!=c&&c>d?(0,r.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${d}%`,width:`${c-d}%`,boxShadow:"inset 1px 0 var(--bg-panel)"}}):null,null!=u?(0,r.jsx)("div",{className:"absolute inset-y-0 w-0.5 bg-text",style:{left:`${u}%`,boxShadow:"0 0 0 1px color-mix(in srgb, var(--bg-panel) 80%, transparent)"},"aria-hidden":"true"}):null,i>1?(0,r.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),m||e.window?.resetsAt?(0,r.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,r.jsx)("span",{className:"min-w-0 truncate",children:m??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:d1(e.window.resetsAt,t)}):null]}):null,n?(0,r.jsxs)("dl",{className:"m-0 mt-1.5 border-s-2 border-border ps-2.5",children:[l?.pacePct!=null?(0,r.jsx)(d9,{label:"페이스",value:`${l.pacePct.toFixed(1)}%`}):null,l?(0,r.jsx)(d9,{label:l.partial?"남은 한도":`앞으로 ${l.unit}`,value:`${l.burn.toFixed(1)}%`}):null,l?.nominal!=null?(0,r.jsx)(d9,{label:"균등 배분 기준",value:`${l.nominal.toFixed(1)}%/${"하루"===l.unit?"일":"시간"} \xb7 계산값`}):null,o?(0,r.jsx)(d9,{label:"구간",value:`${ct(o.slotStart)} ~ ${ct(o.slotEnd)} \xb7 ${o.slotIndex+1}/${o.slotCount}`}):null,o?(0,r.jsx)(d9,{label:"기록 품질",value:function(e){let t;if("unknown"===e.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";let n=null==e.gapMs||0===e.gapMs?null:(t=Math.round(e.gapMs/6e4))<60?`${t}분`:`${Math.floor(t/60)}시간 ${t%60}분`;return"exact"===e.quality?n?`실측 \xb7 경계 ${n} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${n??"?"} 전 표본`}(o)}):null]}):null]})}let cr={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function ci({confirmId:e,pending:t,primaryRef:n,summary:i,onConfirm:a,onCancel:s}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),s())},children:[(0,r.jsxs)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:["저장된 리셋 ",i]}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:d0(dQ,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:a,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:dQ,disabled:t,onClick:s,children:"취소"})]})]})}function ca({report:e,brokerOk:t,now:n,active:a,identity:s,recommendation:l,pendingAction:o,feedback:d,onToggle:c,onReset:u}){let p=e.metadata??{},h=s??(0,t4.k)([e])[0],m=e.credentialId,f=Number.isSafeInteger(m)&&m>0,g=e.accountRole,x="usage-only"===g?"사용량":"control-only"===g?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,b=a?"active":e.disabled?"off":v?"auto-blocked":"idle",y="toggle"===o?"전환 중…":"reset"===o?"리셋 사용 중…":f?a?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${d1(e.autoBlockedUntilMs,n)}`:"control-only"===g?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===g?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,i.useId)(),k=(0,i.useId)(),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),M=(0,i.useRef)(null),$=(0,i.useRef)(null),R=(0,i.useRef)(!1),E=(0,i.useRef)(!1),L="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,z=function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e),A=z?.id??null,W=d2(z?.expiresAt??null,n),P=L?.availableCount,F=L&&"unavailable"!==L.state?"empty"===L.state||0===P?"없음":`${P??L.credits.length}개${W?` \xb7 ${W}`:""}`:"확인 불가",_=function(e){if("anthropic"!==e.provider)return null;let t=e.savedReset,n=t?.credits.find(e=>e.id===t.nextCreditId)??t?.credits[0],r=[...new Set((n?.clears??[]).map(e=>cr[e]).filter(e=>void 0!==e))];return r.length?`${r.join("\xb7")} 한도만`:null}(e),D=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let n="number"==typeof e.naturalResetAt?d1(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=d2(e.expiresAt??null,t),r="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${n&&"만료됨"!==n?n:"곧 만료"}됩니다.${r}`}(l,n),O=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&L?.state==="available"&&0!==P&&null!=A;(0,i.useLayoutEffect)(()=>{if(I)return void $.current?.focus();if(R.current){var e;R.current=!1,e=M.current,e?.focus()}},[I]),(0,i.useEffect)(()=>{"reset"!==o&&(e.disabled||!t||L?.state!=="available")&&(R.current=!1,T(null))},[t,o,e.disabled,L?.state]);let H=async()=>{if(I&&!E.current){E.current=!0;try{await u(e,I.creditId)}finally{E.current=!1,R.current=!0,T(null)}}},B=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),U=o?"pending":a?"active":e.disabled?"off":v?"blocked":"idle";return(0,r.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":b,"aria-current":a?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(nc,{seed:h.seed,size:48,provider:e.provider}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("h3",{className:"m-0 flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm font-semibold text-text",children:[(0,r.jsx)("span",{children:h.alias}),(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${(0,t4.bN)(e.provider)}${x?` \xb7 ${x}`:""}`})]}),(0,r.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,r.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":U,role:o?"status":void 0,children:y}),null!=B&&B-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${d1(B,n).replace(/ 후 리셋$/,"")}`}):null]})]}),f?(0,r.jsxs)("span",{className:"resource-account-toggle",children:[(0,r.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,r.jsx)("button",{type:"button",role:"switch",className:d0(dQ,"resource-account-switch min-w-[3.25rem]"),disabled:null!=o||!t,"aria-label":`${h.alias} 계정 사용 설정`,"aria-checked":!e.disabled,"aria-busy":null!=o||void 0,title:t?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{R.current=!1,T(null),c(e)},children:e.disabled?"OFF":"ON"})]}):null]}),e.disabled?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):v?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(e.limits??[]).some(t4.xL)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,d?(0,r.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===d.tone?"alert":"status",children:d.message}):null,(0,r.jsxs)("div",{id:k,className:"resource-account-limits divide-y divide-border",children:[j?(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,r.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:C?h.raw:h.masked||"—"}),h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":C,onClick:()=>N(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(cn,{limit:e,now:n,detailed:j},e.id))]}),(e.limits??[]).length>0||h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":j,"aria-controls":k,onClick:()=>{let e=!j;S(e),e||N(!1)},children:j?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?I?(0,r.jsx)(ci,{confirmId:w,pending:"reset"===o,primaryRef:$,summary:I.summary,onConfirm:()=>{H()},onCancel:()=>{R.current=!0,T(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3 border-t border-border pt-2.5","data-reset-state":t?L&&"unavailable"!==L.state?"empty"===L.state||0===P?"empty":"reset"===o?"pending":"ready":"unavailable":"offline",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,r.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,r.jsx)("span",{className:d0("font-mono text-xs tabular-nums text-text",l?.reason==="expiring-credit"&&"text-warning"),children:F})]}),_?(0,r.jsx)("span",{className:"text-xs text-text-muted",children:_}):null,O?(0,r.jsx)("button",{ref:M,type:"button",className:d0(dQ,"ml-auto flex-none"),disabled:null!=o,onClick:()=>{A&&T({creditId:A,summary:F})},children:"리셋 사용"}):t&&e.disabled&&L?.state==="available"?(0,r.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),D?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:D}):null]}):null]})}function cs({state:e,loading:t,accountState:n,pendingActions:i,feedbackByCredential:a,onToggle:s,onReset:l}){let o=dX(1e4),d=e.data,c=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,u=(0,t4.k)(d?.reports??[]),p=null==c?-1:d?.reports.findIndex(e=>e.credentialId===c)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ce,{state:e,loading:t,subject:"사용량"}),d?.brokerOk===!1?(0,r.jsx)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,r.jsxs)("div",{className:"flex min-h-7 items-center gap-4 border-b border-border bg-bg-raised px-4 text-[11px] font-semibold tracking-[0.08em] text-text-muted uppercase","aria-label":"사용량 그래프 범례",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),d&&0===d.reports.length?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,d?.reports.map((e,t)=>{let c=e.credentialId;return(0,r.jsx)(ca,{report:e,brokerOk:!0===d.brokerOk,now:o,active:t===p,identity:u[t],recommendation:null==c?void 0:n?.resetRecommendations.find(e=>e.credentialId===c),pendingAction:null==c?null:i.get(c)??null,feedback:null==c?void 0:a.get(c),onToggle:s,onReset:l},`${e.provider}:${c??e.metadata?.accountId??e.metadata?.email??t}`)})]})}function cl({model:e}){let t=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,r.jsx)("h3",{className:"m-0 min-w-0 flex-1 truncate text-sm font-semibold text-text",title:e.model,children:e.model}),(0,r.jsx)("span",{className:"text-xs text-text-muted",children:e.provider}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[d4(e.cost)," \xb7 ",d6(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${t}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(d9,{label:"요청",value:d5(e.requests)}),(0,r.jsx)(d9,{label:"요청당",value:d4(e.costPerRequest)}),(0,r.jsx)(d9,{label:"토큰/요청",value:d8(e.tokensPerRequest)}),(0,r.jsx)(d9,{label:"출력/요청",value:d8(e.outputPerRequest)}),(0,r.jsx)(d9,{label:"캐시율",value:d6(e.cacheRate,1)}),(0,r.jsx)(d9,{label:"TTFT",value:d3(e.avgTtft)})]})]})}function co({agent:e}){let t={main:"메인",subagent:"SubAgent",advisor:"advisor"}[e.agentType]??e.agentType,n=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,r.jsx)("h3",{className:"m-0 text-sm font-semibold text-text",children:t}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[d4(e.cost)," \xb7 ",d6(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${n}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(d9,{label:"요청",value:d5(e.requests)}),(0,r.jsx)(d9,{label:"요청당",value:d4(e.costPerRequest)}),(0,r.jsx)(d9,{label:"토큰/요청",value:d8(e.tokensPerRequest)})]})]})}function cd({day:e}){let t=e.models.slice(0,3).map(e=>e.model).join(", ");return(0,r.jsxs)("div",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-baseline gap-3 border-b border-border px-4 py-2 last:border-b-0",children:[(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text-muted",children:d7(e.timestamp)}),(0,r.jsx)("span",{className:"truncate text-xs text-text-muted",title:t,children:t}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:d4(e.cost)})]})}function cc({state:e,loading:t}){let n=e.data;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ce,{state:e,loading:t,subject:"모델 집계"}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{"aria-labelledby":"resource-overall-heading",children:[(0,r.jsx)("h2",{id:"resource-overall-heading",className:"m-0 border-b border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"전체"}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4 px-4 py-3",children:[(0,r.jsx)(d9,{label:"요청",value:d5(n.overall.requests)}),(0,r.jsx)(d9,{label:"비용",value:d4(n.overall.cost)}),(0,r.jsx)(d9,{label:"토큰",value:d8(n.overall.tokens)}),(0,r.jsx)(d9,{label:"캐시율",value:d6(n.overall.cacheRate,1)}),(0,r.jsx)(d9,{label:"캐시 절감",value:d6(n.overall.cacheSavings,1)}),(0,r.jsx)(d9,{label:"평균 TTFT",value:d3(n.overall.avgTtft)})]})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-models-heading",children:[(0,r.jsx)("h2",{id:"resource-models-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"모델별"}),n.models.length?n.models.map(e=>(0,r.jsx)(cl,{model:e},`${e.provider}:${e.model}`)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"모델 기록이 없습니다."})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-agents-heading",children:[(0,r.jsx)("h2",{id:"resource-agents-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"에이전트 종류별"}),n.agents.length?n.agents.map(e=>(0,r.jsx)(co,{agent:e},e.agentType)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"기록이 없습니다."})]}),n.daily.length?(0,r.jsxs)("section",{"aria-labelledby":"resource-daily-heading",children:[(0,r.jsx)("h2",{id:"resource-daily-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"일별 비용"}),n.daily.map(e=>(0,r.jsx)(cd,{day:e},e.timestamp))]}):null,(0,r.jsx)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:"`omp stats` 기준 누적값입니다. 구독 한도 %는 계정 한도 탭에서 확인하세요."})]}):null]})}function cu({reports:e,providerConnections:t}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:"character-roster-intro","aria-labelledby":"character-roster-heading",children:[(0,r.jsx)("h2",{id:"character-roster-heading",children:"호출 가능한 캐릭터"}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"호출\xb7불러\xb7소환"}),"은 캐릭터를 SubAgent로 이 대화에 부릅니다.",(0,r.jsx)("strong",{children:" 교체"}),"는 이 대화의 Main을 바꿉니다."]})]}),(0,r.jsx)("div",{className:"character-roster",role:"list","aria-label":"호출 가능한 캐릭터 목록",children:t4.o.map(n=>{let i=`character-roster-${n.seed}`,a=`character-roster-${n.seed}-status`,s=`${n.provider}/${n.model}`,l=!1,o=!1;if(e){for(let t of e)if(t.provider===n.provider&&(l=!0,!0!==t.disabled)){o=!0;break}}let d="web6"!==n.provider&&(t?.get(n.provider)===!1||l&&!o);return(0,r.jsxs)("article",{className:d0("character-roster-item",d&&"is-unavailable"),role:"listitem","aria-labelledby":i,"aria-describedby":d?a:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(nc,{seed:n.seed,size:48,provider:n.provider}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{id:i,children:n.alias}),d?(0,r.jsx)("span",{id:a,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,r.jsx)("p",{children:n.voice})]})]}),(0,r.jsxs)("dl",{className:"character-roster-model",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"모델"}),(0,r.jsx)("dd",{title:s,children:s})]}),void 0!==n.oauthPosition?(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"계정"}),(0,r.jsxs)("dd",{children:["OAuth ",n.oauthPosition]})]}):null]}),(0,r.jsxs)("dl",{className:"character-roster-examples",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"호출"}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("code",{children:n.summonExample}),(0,r.jsx)("span",{children:n.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"Main 교체"}),(0,r.jsxs)("dd",{children:[n.switchExample?(0,r.jsx)("code",{children:n.switchExample}):(0,r.jsx)("strong",{children:"교체 불가"}),(0,r.jsx)("span",{children:n.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},n.alias)})})]})}function cp({open:e,sessionId:t,activeTab:n,onTabChange:a,usage:l,className:o}){let d=(0,i.useId)(),c=l.state,u=l.loading,[p,h]=(0,i.useState)({status:"idle",data:null,error:null}),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(()=>new Map),[k,j]=(0,i.useState)(()=>new Map),S=(0,i.useRef)(p),C=(0,i.useRef)(null),N=(0,i.useRef)(null),I=(0,i.useRef)(new Set),T=(0,i.useRef)(new Set);S.current=p,(0,i.useEffect)(()=>{if(!e||"characters"!==n)return;let t=new AbortController;return b(null),Promise.all([fetch("/api/auth/all-providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}),fetch("/api/auth/providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()})]).then(([e,n])=>{if(t.signal.aborted)return;let r=new Map(e.providers.map(e=>[e.id,e.configured]));for(let e of n.providers)r.set(e.id,!0===r.get(e.id)||e.loggedIn);b(r)}).catch(()=>{t.signal.aborted||b(null)}),()=>t.abort()},[n,e,c.data]),(0,i.useEffect)(()=>{if(f(null),!e||"usage"!==n||!t)return;let r=(0,t4._Q)({onClear(){f(null)},onResult(e){f("fresh"===e.status?e.data:null)}});return C.current=r,r.setSessionId(t),()=>{r.stop(),C.current===r&&(C.current=null)}},[n,e,t]);let M=(0,i.useCallback)(async e=>{N.current?.abort();let t=new AbortController;N.current=t,x(!0);let n=await (0,t4.t6)({refresh:e,previous:S.current.data,signal:t.signal});N.current!==t||t.signal.aborted||(h(n),x(!1))},[]);(0,i.useEffect)(()=>{e&&"models"===n&&("idle"===S.current.status||"error"===S.current.status)&&M(!1)},[n,e,M]),(0,i.useEffect)(()=>()=>{for(let e of(N.current?.abort(),I.current))e.abort()},[]);let $=(0,i.useCallback)(()=>{"models"===n?M(!0):l.refresh()},[n,M,l]),R=(0,i.useCallback)(()=>l.refresh(),[l]),E=(0,i.useCallback)(async e=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let t=e.credentialId,n=(0,t4.U3)(T.current,t);if(!n)return;let r=new AbortController;I.current.add(r),l.setPaused(!0),w(e=>new Map(e).set(t,"toggle")),j(e=>{let n=new Map(e);return n.delete(t),n});try{await (0,t4.vy)(t,!0===e.disabled,{signal:r.signal});let n=await R();r.signal.aborted||j(r=>new Map(r).set(t,{tone:"status",message:"fresh"===n.status?`계정을 ${e.disabled?"켰습니다":"껐습니다"}.`:"계정 설정 저장됨 \xb7 표시 상태 새로고침 실패."}))}catch(e){if(!r.signal.aborted){let n=e instanceof t4.OO&&("timeout"===e.kind||e.outcomeUnknown);j(r=>new Map(r).set(t,n?{tone:"error",message:"적용 여부 확인 필요 — 새로고침으로 계정 상태를 확인하세요."}:{tone:"error",message:`계정 전환 실패: ${e instanceof Error?e.message:String(e)}`}))}}finally{I.current.delete(r),n(),l.setPaused(T.current.size>0),w(e=>{let n=new Map(e);return n.delete(t),n})}},[R,l]),L=(0,i.useCallback)(async(e,t)=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let n=e.credentialId,r=(0,t4.U3)(T.current,n);if(!r)return;let i=new AbortController;I.current.add(i),l.setPaused(!0),w(e=>new Map(e).set(n,"reset")),j(e=>{let t=new Map(e);return t.delete(n),t});try{let e=await (0,t4.tR)(n,t,{signal:i.signal}),r=function(e){switch(e.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return e.code.startsWith("http_")?{tone:"error",message:`리셋 사용 실패: 서비스 응답 오류 (${e.code})`}:{tone:"error",message:`리셋 사용 실패: ${e.code}`}}}(e),a=await R();if(e.ok){let e="fresh"===a.status?a.data.reports.find(e=>e.credentialId===n):void 0,t=e?.savedReset?.availableCount;r.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}i.signal.aborted||j(e=>new Map(e).set(n,r))}catch(e){e instanceof t4.OO&&(e.outcomeUnknown||"timeout"===e.kind)&&!i.signal.aborted&&await R(),i.signal.aborted||j(t=>new Map(t).set(n,function(e){if(e instanceof t4.OO){if(e.outcomeUnknown||"timeout"===e.kind)return{tone:"error",message:"적용 여부 확인 필요 — 자동으로 다시 시도하지 않았습니다. 새로고침으로 남은 개수를 확인하세요."};switch(e.code){case"account_disabled":return{tone:"error",message:"리셋 사용 실패: 꺼둔 계정에서는 사용할 수 없습니다."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return{tone:"error",message:`리셋 사용 실패: ${e.message}`}}}return{tone:"error",message:`리셋 사용 실패: ${e instanceof Error?e.message:String(e)}`}}(e)))}finally{I.current.delete(i),r(),l.setPaused(T.current.size>0),w(e=>{let t=new Map(e);return t.delete(n),t})}},[R,l]);if(!e)return null;let z="models"===n?p.data?.generatedAt:c.data?.generatedAt,A="models"===n?p.data?.range:void 0,W=A?.from&&A.to?`${d7(A.from)}~${d7(A.to)}`:z?new Date(z).toLocaleTimeString():"",P="models"===n?g:"usage"===n&&u,F=P?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:d0("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",o),"aria-labelledby":d,"aria-busy":P,children:[(0,r.jsx)("h1",{id:d,className:"sr-only",children:"캐릭터"}),(0,r.jsxs)(dy.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>a(e),children:[(0,r.jsxs)(dy.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(dy.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(dy.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(dy.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(dy.J.Indicator,{})]}),(0,r.jsx)(dy.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(cu,{reports:c.data?.reports,providerConnections:v})}),(0,r.jsxs)(dy.J.Content,{value:"usage",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:W}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:$,disabled:P,children:F})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(cs,{state:c,loading:u,accountState:m?.sessionId===t?m:null,pendingActions:y,feedbackByCredential:k,onToggle:e=>{E(e)},onReset:L})]}),(0,r.jsxs)(dy.J.Content,{value:"models",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:W}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:$,disabled:P,children:F})]}),(0,r.jsx)(cc,{state:p,loading:g})]})]})]})}let ch="/api/runs";class cm extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let cf=["completed","error","aborted","interrupted","running"],cg=["main","maker","checker","advisor","unattributed"],cx=["primary","rework","review"],cv=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],cb=["all","attributed"];function cy(e){return"object"==typeof e&&null!==e}function cw(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function ck(e){return!!cy(e)&&"string"==typeof e.runId&&"string"==typeof e.sessionId&&"string"==typeof e.entryId&&"number"==typeof e.index&&Number.isFinite(e.index)&&(null===e.title||"string"==typeof e.title)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&(null===e.endedAt||"number"==typeof e.endedAt&&Number.isFinite(e.endedAt))&&"number"==typeof e.wallClockMs&&Number.isFinite(e.wallClockMs)&&"string"==typeof e.outcome&&cf.includes(e.outcome)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.childCount&&Number.isFinite(e.childCount)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"string"==typeof e.configSignature}function cj(e){return!!cy(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&cg.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&cx.includes(e.purpose))&&cw(e.models)&&cw(e.efforts)&&"number"==typeof e.requestCount&&Number.isFinite(e.requestCount)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.spanMs&&Number.isFinite(e.spanMs)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&"number"==typeof e.endedAt&&Number.isFinite(e.endedAt)&&"number"==typeof e.inputTokens&&Number.isFinite(e.inputTokens)&&"number"==typeof e.outputTokens&&Number.isFinite(e.outputTokens)&&"number"==typeof e.cacheReadTokens&&Number.isFinite(e.cacheReadTokens)&&"number"==typeof e.cacheWriteTokens&&Number.isFinite(e.cacheWriteTokens)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"number"==typeof e.untimedRequests&&Number.isFinite(e.untimedRequests)&&"number"==typeof e.errorCount&&Number.isFinite(e.errorCount)&&"number"==typeof e.abortedCount&&Number.isFinite(e.abortedCount)&&"number"==typeof e.toolCalls&&Number.isFinite(e.toolCalls)}function cS(e){return!!cy(e)&&("role-busy"===e.kind||"unmeasured-gap"===e.kind)&&"string"==typeof e.id&&"number"==typeof e.ms&&Number.isFinite(e.ms)&&"number"==typeof e.relative&&Number.isFinite(e.relative)}function cC(e){return!!cy(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.errors&&Number.isFinite(e.errors)}function cN(e){return!!cy(e)&&"string"==typeof e.kind&&cg.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)}function cI(e){return!!cy(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(cN)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.medianWallClockMs&&Number.isFinite(e.medianWallClockMs)&&"number"==typeof e.medianBusyMs&&Number.isFinite(e.medianBusyMs)&&"number"==typeof e.medianTotalTokens&&Number.isFinite(e.medianTotalTokens)&&"number"==typeof e.medianEstimatedCostUsd&&Number.isFinite(e.medianEstimatedCostUsd)&&"number"==typeof e.totalEstimatedCostUsd&&Number.isFinite(e.totalEstimatedCostUsd)&&"number"==typeof e.unpricedRuns&&Number.isFinite(e.unpricedRuns)&&"number"==typeof e.untimedRuns&&Number.isFinite(e.untimedRuns)&&"number"==typeof e.reworkRuns&&Number.isFinite(e.reworkRuns)&&"number"==typeof e.errorRuns&&Number.isFinite(e.errorRuns)&&"number"==typeof e.childRunsAvg&&Number.isFinite(e.childRunsAvg)&&"number"==typeof e.firstSeenAt&&Number.isFinite(e.firstSeenAt)&&"number"==typeof e.lastSeenAt&&Number.isFinite(e.lastSeenAt)}function cT(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&cv.includes(e))}async function cM(e){try{return await e.json()}catch{throw new cm("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}function c$(e,t){return e instanceof cm||e instanceof Error?e.message:t}let cR={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},cE={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function cL(...e){return e.filter(Boolean).join(" ")}function cz(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function cA(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function cW(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function cP(e){if("number"!=typeof e||!Number.isFinite(e))return"—";let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;let n=Math.round(t/1e3);if(n<60)return`${(t/1e3).toFixed(1)}s`;let r=Math.floor(n/60),i=n-60*r;return r<60?0===i?`${r}m`:`${r}m ${i}s`:`${Math.floor(r/60)}h ${r%60}m`}function cF(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function c_({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"min-w-0 flex-1 truncate text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 flex-none font-mono text-xs tabular-nums text-text",children:t})]})}function cD({share:e,label:t}){let n=Number.isFinite(e)?Math.max(1,Math.min(100,100*e)):1;return(0,r.jsxs)("div",{className:"efficiency-bar","aria-hidden":"true",children:[(0,r.jsx)("div",{className:"efficiency-bar-fill",style:{width:`${n}%`}}),(0,r.jsx)("span",{className:"efficiency-bar-value",children:t})]})}function cO({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",cz(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function cH({outcome:e,t}){return(0,r.jsx)(dw.E,{tone:cR[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function cB({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(dw.E,{tone:"rework"===e?"warning":"neutral",variant:"weak",size:"medium",children:t({primary:"efficiency.purposePrimary",rework:"efficiency.purposeRework",review:"efficiency.purposeReview"}[e]??"efficiency.unmeasuredShort")})}function cU({run:e,selected:t,onSelect:n,t:i}){let a=e.title&&e.title.trim().length>0?e.title:i("efficiency.noTitle");return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",onClick:n,"aria-current":t?"true":void 0,className:cL("efficiency-run-item",t&&"is-selected"),children:[(0,r.jsxs)("span",{className:"efficiency-run-top",children:[(0,r.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,r.jsx)("span",{className:"efficiency-run-title",title:a,children:a}),(0,r.jsx)(cH,{outcome:e.outcome,t:i})]}),(0,r.jsxs)("span",{className:"efficiency-run-meta",children:[(0,r.jsx)("span",{className:"font-mono tabular-nums",children:i("efficiency.elapsedValue").replace("{value}",cP(e.wallClockMs))}),(0,r.jsx)(cO,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:i})]})]})})}function cq({role:e,t}){let n=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),i=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort"),a=e.outputTokens-e.helpers.reduce((e,t)=>e+t.outputTokens,0);return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsxs)("div",{className:"efficiency-card-top",children:[(0,r.jsx)("h4",{className:"efficiency-card-title",title:e.id,children:e.id}),(0,r.jsx)(dw.E,{tone:cE[e.kind]??"neutral",variant:"weak",size:"medium",children:t(`efficiency.role${"main"===e.kind?"Main":"maker"===e.kind?"Maker":"checker"===e.kind?"Checker":"advisor"===e.kind?"Advisor":"Unattributed"}`)}),(0,r.jsx)(cB,{purpose:e.purpose,t:t})]}),(0,r.jsx)("p",{className:"efficiency-model-line",title:n,children:n}),(0,r.jsxs)("p",{className:"efficiency-dim",children:[t("efficiency.effortLabel").replace("{value}",i),` \xb7 ${t("efficiency.requestsValue").replace("{value}",String(e.requestCount))}`,` \xb7 ${t("efficiency.toolCallsValue").replace("{value}",String(e.toolCalls))}`]}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(c_,{label:t("efficiency.busyTime"),value:cP(e.busyMs)}),(0,r.jsx)(c_,{label:t("efficiency.estimatedCost"),value:cz(e.estimatedCostUsd)}),(0,r.jsx)(c_,{label:t("efficiency.tokens"),value:cW(e.totalTokens)}),(0,r.jsx)(c_,{label:t("efficiency.unpricedRequests"),value:cA(e.unpricedRequests)}),(0,r.jsx)(c_,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?cP(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,r.jsx)(c_,{label:t("efficiency.outputTokens"),value:cW(a)})]}),e.ttftRequests>0&&e.ttftRequests<e.requestCount?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.firstTokenPartial",{recorded:e.ttftRequests,total:e.requestCount})}):null,e.untimedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.untimedLowerBound").replace("{value}",cA(e.untimedRequests))}):null,e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null,e.helpers.length>0?(0,r.jsxs)("section",{"aria-label":t("efficiency.helpersTitle"),children:[(0,r.jsx)("p",{className:"efficiency-dim",children:t("efficiency.helpersTitle")}),(0,r.jsx)("dl",{className:"m-0",children:e.helpers.map(e=>(0,r.jsx)(c_,{label:`${e.purpose} \xb7 ${e.model}`,value:t("efficiency.helperCallsValue",{count:e.requestCount,output:cW(e.outputTokens),tokens:cW(e.totalTokens),cost:cz(e.estimatedCostUsd)})},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.helpersIncludedNote")})]}):null]})}function cK({item:e,t}){let n="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,r.jsxs)("li",{className:"efficiency-bottleneck",children:[(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-bottleneck-label",title:n,children:n}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:cP(e.ms)})]}),(0,r.jsx)(cD,{share:e.relative,label:cP(e.ms)})]})}function cV({detail:e,t}){return(0,r.jsxs)("div",{className:"efficiency-detail",children:[(0,r.jsxs)("section",{"aria-label":t("efficiency.summarySection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.summarySection")}),(0,r.jsxs)("div",{className:"efficiency-dual",children:[(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.elapsed")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:cP(e.wallClockMs)})]}),(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.busyTotal")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:cP(e.busyMs)})]})]}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(c_,{label:t("efficiency.estimatedCost"),value:cz(e.estimatedCostUsd)}),(0,r.jsx)(c_,{label:t("efficiency.tokens"),value:cW(e.totalTokens)})]}),e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.rolesSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.rolesSection")}),e.roles.length>0?(0,r.jsx)("div",{className:"efficiency-stack",children:e.roles.map(e=>(0,r.jsx)(cq,{role:e,t:t},e.id))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.bottlenecksSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.bottlenecksSection")}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.bottleneckOrderNote")}),e.bottlenecks.length>0?(0,r.jsx)("ul",{className:"efficiency-stack",children:e.bottlenecks.map(e=>(0,r.jsx)(cK,{item:e,t:t},`${e.kind}:${e.id}`))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.bottlenecksEmpty")}),e.unmeasuredMs>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unmeasuredGapValue").replace("{value}",cP(e.unmeasuredMs))}):null]}),e.toolTotals.length>0?(0,r.jsxs)("section",{"aria-label":t("efficiency.toolsSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.toolsSection")}),(0,r.jsx)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:e.toolTotals.map(e=>(0,r.jsx)(c_,{label:`${e.toolName} \xb7 ${t("efficiency.toolErrorsValue").replace("{value}",String(e.errors))}`,value:cA(e.calls)},e.toolName))})]}):null]})}function cJ(e){return e.map(e=>{let t=e.effort??"–",n=e.count>1?` x${e.count}`:"";return`${e.kind} ${e.model}:${t}${n}`}).join(" \xb7 ")}function cG({response:e,t}){return(0,r.jsx)("section",{className:"efficiency-card",children:(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(c_,{label:t("efficiency.scopeSessions"),value:cA(e.sessionCount)}),(0,r.jsx)(c_,{label:t("efficiency.scopeRuns"),value:cA(e.runCount)}),(0,r.jsx)(c_,{label:t("efficiency.scopeExcludedRuns"),value:cA(e.excludedRunCount)})]})})}function cY({config:e,baselineRuns:t,t:n}){let i=t>0?e.runCount/t:0,a=e.runCount>0?e.reworkRuns/e.runCount:0,s=e.runCount>0?e.errorRuns/e.runCount:0;return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsx)("p",{className:"efficiency-model-line",title:cJ(e.roles),children:cJ(e.roles)}),(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-dim",children:n("efficiency.runsValue").replace("{value}",String(e.runCount))}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:cF(i)})]}),(0,r.jsx)(cD,{share:i,label:cF(i)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(c_,{label:n("efficiency.medianElapsed"),value:cP(e.medianWallClockMs)}),(0,r.jsx)(c_,{label:n("efficiency.medianBusy"),value:cP(e.medianBusyMs)}),(0,r.jsx)(c_,{label:n("efficiency.medianTokens"),value:cW(e.medianTotalTokens)}),(0,r.jsx)(c_,{label:n("efficiency.medianEstimatedCost"),value:cz(e.medianEstimatedCostUsd)}),(0,r.jsx)(c_,{label:n("efficiency.totalEstimatedCost"),value:cz(e.totalEstimatedCostUsd)}),(0,r.jsx)(c_,{label:n("efficiency.reworkRate"),value:cF(a,1)}),(0,r.jsx)(c_,{label:n("efficiency.errorRate"),value:cF(s,1)}),(0,r.jsx)(c_,{label:n("efficiency.unpricedRuns"),value:cA(e.unpricedRuns)}),(0,r.jsx)(c_,{label:n("efficiency.untimedRuns"),value:cA(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",cA(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function cZ({open:e,sessionId:t,activeTab:n,onTabChange:a,client:l,className:d}){let c=(0,i.useId)(),u=(0,i.useId)(),{t:p}=(0,R.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[a]=(0,i.useState)(()=>r??function(e=(e,t)=>fetch(e,t)){let t=async(t,n)=>{let r;try{r=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new cm("unreachable","효율 기록에 연결할 수 없습니다.")}let i=await cM(r);if(!r.ok){var a;throw new cm("http",(a=`HTTP ${r.status}`,null!==i&&"object"==typeof i&&"error"in i&&"string"==typeof i.error&&i.error?i.error:a),r.status)}return{response:r,body:i}};return{async listRuns(e,n,r){let{response:i,body:a}=await t(`${ch}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!cy(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(ck)&&cT(e.unmeasured)))throw new cm("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new cm("invalid-response",t,n)}}(a,"실행 목록 응답이 올바르지 않습니다.",i.status)},async getRun(e,n){let{response:r,body:i}=await t(`${ch}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!ck(e)||!(Array.isArray(e.roles)&&e.roles.every(cj)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(cS)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(cC)&&cT(e.unmeasured)))throw new cm("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new cm("invalid-response",t,n)}}(i,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,i){let a=new URLSearchParams;null!==e&&""!==e&&a.set("folder",e),a.set("sessions",String(n)),a.set("scope",r);let{response:s,body:l}=await t(`/api/experiments?${a.toString()}`,{method:"GET",signal:i});return function(e,t,n=null){try{if(!cy(e)||!((null===e.folder||"string"==typeof e.folder)&&cw(e.folders)&&"string"==typeof e.scope&&cb.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(cI)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&cT(e.unmeasured)))throw new cm("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new cm("invalid-response",t,n)}}(l,"구성 비교 응답이 올바르지 않습니다.",s.status)}}}()),[s,l]=(0,i.useState)({status:"idle",runs:[],error:null}),[o,d]=(0,i.useState)({status:"idle",runId:null,detail:null,error:null}),[c,u]=(0,i.useState)({status:"idle",response:null,error:null}),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null);(0,i.useEffect)(()=>{x.current?.abort(),x.current=null,h(null),d({status:"idle",runId:null,detail:null,error:null}),l({status:"idle",runs:[],error:null})},[e]);let y=(0,i.useCallback)(()=>{if(!t||"governor"!==n||!e)return;g.current?.abort();let r=new AbortController;g.current=r,l(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),a.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&g.current===r){if(0===e.runs.length)return void l({status:"empty",runs:[],error:null});l({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||g.current!==r||l({status:"error",runs:[],error:c$(e,"실행 목록을 불러오지 못했습니다.")})})},[n,a,e,t]),w=(0,i.useCallback)(e=>{if(!t)return;x.current?.abort();let n=new AbortController;x.current=n,d({status:"loading",runId:e,detail:null,error:null}),a.getRun(e,n.signal).then(t=>{n.signal.aborted||x.current!==n||d({status:"ready",runId:e,detail:t,error:null})}).catch(t=>{n.signal.aborted||x.current!==n||d({status:"error",runId:e,detail:null,error:c$(t,"실행 상세를 불러오지 못했습니다.")})})},[a,t]),k=(0,i.useCallback)((e,r="all")=>{if(!t||"lab"!==n)return;v.current?.abort();let i=new AbortController;v.current=i,u(e=>({status:"loading",response:"ready"===e.status||"empty"===e.status?e.response:null,error:null})),a.listExperiments(e,30,r,i.signal).then(e=>{if(!i.signal.aborted&&v.current===i){if(0===e.configs.length)return void u({status:"empty",response:e,error:null});u({status:"ready",response:e,error:null})}}).catch(e=>{i.signal.aborted||v.current!==i||u({status:"error",response:null,error:c$(e,"구성 비교를 불러오지 못했습니다.")})})},[n,a,t]);(0,i.useEffect)(()=>{if(t&&"governor"===n)return y(),()=>{g.current?.abort(),g.current=null}},[n,y,e,t]),(0,i.useEffect)(()=>{if(t&&"lab"===n)return k(b.current),()=>{v.current?.abort(),v.current=null}},[n,k,t]),(0,i.useEffect)(()=>{if(t&&"governor"===n&&null!==p)return w(p),()=>{x.current?.abort(),x.current=null}},[n,w,p,t]),(0,i.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,i.useCallback)(e=>{x.current?.abort(),x.current=null,h(e),null===e&&d({status:"idle",runId:null,detail:null,error:null})},[]);return{list:s,detail:o,experiments:c,selectedRunId:p,selectRun:j,refreshRuns:(0,i.useCallback)(()=>{y()},[y]),refreshExperiments:(0,i.useCallback)((e,t="all")=>{let n=void 0===e?b.current:e;void 0!==e&&(b.current=e,f(e)),k(n,t)},[k]),experimentFolder:m}}({sessionId:t,visible:e,activeTab:n,client:l}),[m,f]=(0,i.useState)(""),g=(0,i.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),x=(0,i.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),v=h.experimentFolder,b=h.experiments.response?.scope??"all";if(!e)return null;let y="governor"===n&&"loading"===h.list.status||"lab"===n&&"loading"===h.experiments.status,w=y?p("efficiency.refreshing"):p("efficiency.refresh"),k="governor"===n?h.list.runs.length>0?p("efficiency.runsValue").replace("{value}",String(h.list.runs.length)):"":h.experiments.response?p("efficiency.runsValue").replace("{value}",String(h.experiments.response.runCount)):"";return(0,r.jsxs)("section",{className:cL("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",d),"aria-labelledby":c,"aria-busy":y,children:[(0,r.jsxs)("header",{className:"flex min-h-12 items-center gap-3 border-b border-border bg-bg px-3",children:[(0,r.jsx)("h1",{id:c,className:"m-0 text-sm font-semibold text-text",children:p("efficiency.title")}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-right font-mono text-[11px] tabular-nums text-text-dim",children:k}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===n?h.refreshRuns():h.refreshExperiments(void 0,b)},disabled:y,children:w})]}),(0,r.jsx)("div",{className:"grid grid-cols-2 border-b border-border bg-bg",role:"tablist","aria-label":p("efficiency.title"),children:["governor","lab"].map(e=>(0,r.jsx)("button",{type:"button",role:"tab","aria-selected":n===e,id:`${u}-${e}-tab`,"aria-controls":u,className:cL("min-h-10 border-0 border-r border-border bg-bg px-4 text-sm text-text-muted last:border-r-0 hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent",n===e&&"bg-bg-selected font-semibold text-text"),onClick:()=>a(e),children:"governor"===e?p("efficiency.governor"):p("efficiency.lab")},e))}),"lab"===n?(0,r.jsxs)("div",{className:"efficiency-folderbar",children:[(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-folder`,children:p("efficiency.folder")}),(0,r.jsxs)("select",{id:`${u}-folder`,className:"efficiency-folder-select",value:v??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;f(t??""),h.refreshExperiments(t,b)},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.folderAll")}),g.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),v&&!g.includes(v)?(0,r.jsx)("option",{value:v,children:v}):null]}),(0,r.jsx)("input",{className:"efficiency-folder-input",value:m,placeholder:p("efficiency.folderPlaceholder"),"aria-label":p("efficiency.folder"),onChange:e=>f(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===m.trim()?null:m.trim();h.refreshExperiments(e,b)}}}),(0,r.jsxs)("div",{className:"col-span-full flex flex-col items-start gap-2",children:[(0,r.jsx)(o.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===b,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all"),children:p("efficiency.scopeAttributed")}),(0,r.jsx)(dw.E,{tone:"attributed"===b?"informative":"neutral",variant:"weak",size:"medium",children:p("attributed"===b?"efficiency.scopeAttributed":"efficiency.scopeAll")})]})]}):null,(0,r.jsx)("div",{id:u,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",role:"tabpanel","aria-labelledby":`${u}-${n}-tab`,children:"governor"===n?t?"idle"===h.list.status||"loading"===h.list.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingRuns")}):"error"===h.list.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.runsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.list.error})]}):"empty"===h.list.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.runsEmpty")}):(0,r.jsxs)("div",{className:"efficiency-governor",children:[(0,r.jsx)("ul",{className:"efficiency-run-list",children:h.list.runs.map(e=>(0,r.jsx)(cU,{run:e,selected:h.selectedRunId===e.runId,onSelect:()=>h.selectRun(h.selectedRunId===e.runId?null:e.runId),t:p},e.runId))}),(0,r.jsx)("div",{className:"efficiency-detail-pane",children:null===h.selectedRunId||"idle"===h.detail.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.selectRun")}):"loading"===h.detail.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingDetail")}):"error"===h.detail.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.detailError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.detail.error})]}):h.detail.detail?(0,r.jsx)(cV,{detail:h.detail.detail,t:p}):null})]}):(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.noSession")}):(()=>{if("idle"===h.experiments.status||"loading"===h.experiments.status)return(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingExperiments")});if("error"===h.experiments.status)return(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.experimentsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.experiments.error})]});let e=h.experiments.response;return"empty"!==h.experiments.status&&e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,r.jsxs)("div",{className:"efficiency-stack",children:[(0,r.jsx)(cG,{response:e,t:p}),e.configs.map(e=>(0,r.jsx)(cY,{config:e,baselineRuns:x,t:p},e.signature))]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.experimentsEmpty")}),e?(0,r.jsx)("div",{className:"efficiency-stack",children:(0,r.jsx)(cG,{response:e,t:p})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")})]})})()})]})}function cX(e){return"message"===e.type&&"message"in e}function cQ(e){let t=e,n=t.branchPreview,r=cX(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&cX(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function c0({node:e,activePathIds:t,depth:n,isLast:i,parentLines:a,onSelect:s}){let{node:l,skipped:o,branchPreview:d,labelEntry:c}=cQ(e),u=t.has(l.entry.id),p=t.has(e.entry.id)||t.has(l.entry.id),h=d?.text??function(e){if("message"===e.type&&"message"in e){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(c),m=d?d.role??null:cX(c)?c.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>s(l.entry.id),children:[a.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),o>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",o]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":p?"var(--text-muted)":"var(--text-dim)",fontWeight:u?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:h})]}),l.children.map((e,o)=>(0,r.jsx)(c0,{node:e,activePathIds:t,depth:n+1,isLast:o===l.children.length-1,parentLines:[...a,!i],onSelect:s},e.entry.id))]})}function c1({tree:e,activeLeafId:t,onLeafChange:n,hasSession:a}){let{t:s}=(0,R.s)(),l=(0,i.useMemo)(()=>t?new Set(function e(n,r){for(let i of n){let n=[...r,i.entry.id];if(i.entry.id===t||i.compressedEntryIds?.includes(t))return n;let a=e(i.children,n);if(a)return a}return null}(e,[])??[]):new Set,[e,t]),o=(0,i.useCallback)(e=>{n(e)},[n]),d=a?!function e(t){if(t.length>1)return!0;for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)?s("i18n.noBranches"):null:s("i18n.noActiveSession"),c=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=cQ(e[0]).node;return t.children.length>1?t.children:[]}(e);return!d&&c.length>0?(0,r.jsx)("div",{className:"branch-navigator-tree",children:c.map((e,t)=>(0,r.jsx)(c0,{node:e,activePathIds:l,depth:0,isLast:t===c.length-1,parentLines:[],onSelect:o},e.entry.id))}):(0,r.jsx)("p",{className:"branch-navigator-empty",children:d??s("i18n.noBranches")})}function c2(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function c4(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function c5(e){let t=e.currentTime;[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n;let s=t+.18*r;a.gain.setValueAtTime(0,s),a.gain.linearRampToValueAtTime(.18,s+.02),a.gain.exponentialRampToValueAtTime(.001,s+.45),i.start(s),i.stop(s+.45)})}async function c8(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function c6(e){let t,n=e.window?.durationMs;if("number"==typeof n&&Number.isFinite(n)&&n>0)return n>=5184e5?"weekly":n<=432e5?"short":"other";let r=(t=e.scope?.windowId,`${"string"==typeof t?t:""} ${e.id} ${e.label??""}`.toLowerCase());return/(^|[^0-9])7d\b|week|7 day|주간/.test(r)?"weekly":/(^|[^0-9])(5h|1h)\b|hour|시간/.test(r)?"short":"other"}function c3(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null}function c7(e){let t=c3(e);return(0,t4.xL)(e)||"warning"===e.status||null!==t&&t>=90}let c9="omp-sidebar-usage-collapsed",ue="omp-sidebar-usage-order";function ut(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function un(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function ur({direction:e}){return(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",children:(0,r.jsx)("polyline",{points:"up"===e?"2.5 7.5 6 4 9.5 7.5":"2.5 4.5 6 8 9.5 4.5"})})}function ui({usage:e,onOpen:t,onRelogin:n}){var a,s;let l,o,d,c,{t:u}=(0,R.s)(),p=P(),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),j=(0,i.useRef)(null),[S,C]=(0,i.useState)(!0);(0,i.useEffect)(()=>{try{C("0"!==window.localStorage.getItem(c9))}catch{}v(function(){try{let e=JSON.parse(window.localStorage.getItem(ue)??"[]");return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}catch{return[]}}())},[]);let N=e.bai,I=e.state.data?.reports??[],T=dX(1e4),M=(l=(0,t4.k)(I),o=[],d=[],I.forEach((e,t)=>{let n=e.authError;if(!0===e.disabled&&!n)return;let r=l[t],i="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>T,a=!0===e.disabled?[]:e.limits??[],s=a.some(e=>e.scope?.shared===!0&&(0,t4.xL)(e)),c=a.some(e=>null!==ut(e)&&"short"!==c6(e)),u=[];for(let e of a){let t=ut(e);null!==t&&(!c||"short"!==c6(e)||c7(e))&&u.push({key:e.id,label:e.label||e.id,percent:Math.round(100*t),state:i?"blocked":s?"account-spent":(0,t4.xL)(e)?"spent":"usable"})}if(0===u.length&&!n)return;let p=n?"auth":i?"blocked":s?"account-spent":"ok",h={orderKey:"string"==typeof e.accountKey&&e.accountKey.length>0?`${e.provider}:${e.accountKey}`:void 0!==e.credentialId?`${e.provider}:#${e.credentialId}`:`${e.provider}:@${t}`,provider:e.provider,alias:r.alias,seed:r.seed,masked:r.masked,..."string"==typeof e.accountKey?{accountKey:e.accountKey}:{},rows:u,state:p,...n?{authError:n}:{},usable:"ok"===p&&u.some(e=>"usable"===e.state)};(h.usable?o:d).push(h)}),a=[...o,...d],c=new Map(x.map((e,t)=>[e,t])),[...a.filter(e=>c.has(e.orderKey)).sort((e,t)=>c.get(e.orderKey)-c.get(t.orderKey)),...a.filter(e=>!c.has(e.orderKey))]);(0,i.useEffect)(()=>{if(null===w)return;let e=[...j.current?.querySelectorAll("[data-order-key]")??[]].find(e=>e.dataset.orderKey===w.orderKey),t=e?.querySelector(`[data-direction="${w.direction}"]`),n=e?.querySelector(`[data-direction="${"up"===w.direction?"down":"up"}"]`);(t&&!t.disabled?t:n)?.focus(),k(null)},[w]);let $=(e,t)=>{let n,r,i,a="up"===t?e-1:e+1;if(a<0||a>=M.length)return;let s=M.map(e=>e.orderKey);[s[e],s[a]]=[s[a],s[e]];let l=(n=new Set(s),r=[...x,...s.filter(e=>!x.includes(e))],i=0,r.map(e=>n.has(e)?s[i++]:e));v(l);try{window.localStorage.setItem(ue,JSON.stringify(l))}catch{}y(u("usage.moved",{account:M[e].alias,position:a+1})),k({orderKey:M[e].orderKey,direction:t})},E=e=>Math.max(1,e.rows.length),L=0,z=h||f?M:M.filter(e=>!(L>=2)&&(L+=E(e),!0)),A=M.slice(z.length).reduce((e,t)=>e+E(t),0),W=M.filter(e=>"auth"===e.state).length,F="measured"===N.status?(s=N.tokens)>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(Math.round(s)):u("empty"===N.status?"usage.baiEmpty":"usage.baiUnmeasured"),_="measured"===N.status&&null!==N.from&&null!==N.to?u("usage.baiRange",{from:un(N.from),to:un(N.to)}):null,D=e=>"auth"===e.state?u(e.authError?.reloginRequired?"usage.authExpired":"usage.authUnavailable"):"blocked"===e.state?u("usage.accountBlocked"):"account-spent"===e.state?u("usage.accountSpent"):null,O=e=>"spent"===e.state?u("usage.limitSpent"):null,H=u("usage.open",{rows:[...z.flatMap(e=>{let t=D(e);return 0===e.rows.length?[`${e.alias} (${t??""}${e.authError?`: ${e.authError.message}`:""})`]:e.rows.map(n=>{let r=O(n)??t;return`${e.alias} ${n.label} ${n.percent}%${null===r?"":` (${r})`}`})}),`${u("usage.bai")} ${F}${null===_?"":` \xb7 ${_}`}`].join(", ")})+(A>0?u("usage.openMore",{count:A}):""),B=M[0],U=void 0===B?{label:u("usage.bai"),value:F,danger:!1}:0===B.rows.length?{label:B.alias,value:D(B)??"",danger:!0}:{label:B.rows[0].label,value:`${B.rows[0].percent}%`,danger:B.rows[0].percent>=90},q=W>0?u("usage.authIssues",{count:W}):null,K=(0,r.jsxs)("div",{className:"navigator-usage",role:"group","aria-label":u("usage.title"),"data-editing":f?"":void 0,onClick:e=>{f||e.target instanceof Element&&e.target.closest("button, a")||t()},children:[(0,r.jsxs)("span",{className:"navigator-usage-header",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-open","aria-label":H,onClick:t,children:u("usage.title")}),null===q?null:(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),M.length>1&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-edit","data-active":f?"":void 0,onClick:()=>g(e=>!e),children:f?u("usage.reorderDone"):u("usage.reorder")})]}),(0,r.jsx)("div",{ref:j,role:f?"list":void 0,"aria-label":f?u("usage.reorderGroup"):void 0,className:"navigator-usage-groups",children:0===M.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:u("usage.none")}):z.map((e,t)=>{let i=D(e);return(0,r.jsxs)("div",{className:"navigator-usage-group","data-order-key":e.orderKey,role:f?"listitem":void 0,children:[(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(nc,{seed:e.seed,size:24,provider:e.provider}),(0,r.jsx)("span",{className:"navigator-usage-alias",children:e.alias}),null===i?null:(0,r.jsx)("span",{className:"navigator-usage-state","data-tone":"auth"===e.state?"danger":void 0,children:i}),f&&(0,r.jsxs)("span",{className:"navigator-usage-moves",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"up","aria-label":u("usage.moveUp",{account:e.alias}),disabled:0===t,onClick:()=>$(t,"up"),children:(0,r.jsx)(ur,{direction:"up"})}),(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"down","aria-label":u("usage.moveDown",{account:e.alias}),disabled:t===M.length-1,onClick:()=>$(t,"down"),children:(0,r.jsx)(ur,{direction:"down"})})]})]}),e.authError&&(0,r.jsxs)("span",{className:"navigator-usage-auth",children:[(0,r.jsx)("span",{className:"navigator-usage-reason",children:e.authError.message}),e.authError.reloginRequired&&n&&!f&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-relogin","aria-label":u("usage.reloginFor",{account:e.alias}),onClick:()=>n({provider:e.provider,alias:e.alias,seed:e.seed,masked:e.masked,...e.accountKey?{accountKey:e.accountKey}:{},reason:e.authError?.message??""}),children:u("usage.relogin")})]}),e.rows.map(e=>{let t=O(e);return(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:e.label}),null===t?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:t}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,r.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)})]},e.orderKey)})}),!f&&(A>0||h)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":h,onClick:()=>m(e=>!e),children:h?u("usage.showLess"):u("usage.showMore",{count:A})}),(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:u("usage.bai")}),(0,r.jsx)("span",{className:"navigator-usage-value",style:"measured"===N.status?void 0:{color:"var(--text-muted)"},children:F})]}),null===_?null:(0,r.jsx)("span",{className:"navigator-usage-account",children:_})]}),(0,r.jsx)("span",{className:"navigator-usage-live","aria-live":"polite",children:b})]});return p?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!S,"aria-label":S?`${H}${null===q?"":`, ${q}`}`:u("usage.showLess"),onClick:()=>{let e=!S;C(e);try{window.localStorage.setItem(c9,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:S?U.label:u("usage.showLess")}),S&&(0,r.jsx)("span",{className:"navigator-usage-value",style:U.danger?{color:"var(--danger)"}:void 0,children:U.value}),S&&null!==q&&(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:S?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),S?null:K]}):K}let ua={snapshot:null,revision:0,streaming:new Map};function us(e,t,n){if(0===e.size)return e;let r=new Set(n.map(e=>e.id)),i=new Map(e);for(let[n,a]of e)(a.generation<t||r.has(n))&&i.delete(n);return i.size===e.size?e:i}function ul(e,t){switch(t.type){case"snapshot":{let n=t.data;if(n.revision<e.revision)return e;let r="sse"===t.source?new Map:us(e.streaming,n.run.generation,n.messages);return{snapshot:n,revision:n.revision,streaming:r}}case"state":{let n=t.data;if(!e.snapshot||n.revision<e.revision)return e;let r={...e.snapshot,revision:n.revision,room:n.room,members:n.members,run:n.run,loadError:n.loadError};return{snapshot:r,revision:n.revision,streaming:us(e.streaming,n.run.generation,r.messages)}}case"message":{let n=t.data;if(!e.snapshot||n.revision<e.revision)return e;let r=function(e,t){let n=e.findIndex(e=>e.id===t.id);if(n>=0){let r=e.slice();return r[n]=t,r}let r=[...e,t];return e.length>0&&e[e.length-1].createdAt>t.createdAt&&r.sort((e,t)=>e.createdAt-t.createdAt),r}(e.snapshot.messages,n.message),i=e.streaming;if(i.has(n.message.id)){let e=new Map(i);e.delete(n.message.id),i=e}return{snapshot:{...e.snapshot,revision:n.revision,messages:r},revision:n.revision,streaming:i}}case"delta":{let n=t.data;if(!e.snapshot||n.generation<e.snapshot.run.generation||e.snapshot.messages.some(e=>e.id===n.messageId))return e;let r=e.streaming.get(n.messageId);if(r&&r.text===n.text&&r.generation===n.generation)return e;let i=new Map(e.streaming);return i.set(n.messageId,{messageId:n.messageId,memberId:n.memberId,text:n.text,generation:n.generation}),{...e,streaming:i}}}}let uo="/api/lounge";function ud(e){try{return JSON.parse(e.data)}catch{return null}}async function uc(e){try{let t=await e.json();if("string"==typeof t?.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}var uu=n(96607);let up=["slow","normal","active"],uh=[5,10,20,30,60,120].filter(e=>e>=1&&e<=120);function um({row:e,lt:t,locale:n,now:i,compact:a}){let s="weekly"!==e.kind?e.label:e.tier?t("lounge.usage.weeklyTier",{tier:e.tier}):t("lounge.usage.weekly"),l="blocked"===e.state?t("lounge.usage.blocked"):"spent"===e.state?t("lounge.usage.spent"):null,o=!a&&null!==e.resetsAt&&e.resetsAt>i?t("lounge.usage.resets",{when:(0,nl.fw)(new Date(e.resetsAt),n,new Date(i))}):null,d="usable"!==e.state;return(0,r.jsxs)("span",{className:"lounge-usage","data-compact":a?"true":void 0,"data-state":e.state,children:[(0,r.jsxs)("span",{className:"lounge-usage-head",children:[(0,r.jsx)("span",{className:"lounge-usage-label",children:s}),o?(0,r.jsx)("span",{className:"lounge-usage-reset",children:o}):null,l?(0,r.jsx)("span",{className:"lounge-usage-state",children:l}):null,(0,r.jsxs)("span",{className:"lounge-usage-value",children:[e.percent,"%"]})]}),a?null:(0,r.jsx)("span",{"aria-hidden":"true",className:"lounge-usage-track",children:(0,r.jsx)("span",{className:"lounge-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:d?"var(--danger)":"var(--metric)"}})})]})}function uf({member:e,lounge:t,usage:n,now:a,disabled:s}){let{lt:l,locale:o}=(0,J.H)(),d=(0,J.a)(e.alias,o),c=function(e,t,n){let r=t.account,i=[],a=[];if(r&&(r.selectionRequired||void 0===r.credentialId))return{selectionRequired:!0,primary:i,warnings:a};let s=(0,t4.k)(e);return e.forEach((e,l)=>{if(e.provider!==t.provider||(r?e.credentialId!==r.credentialId:s[l].alias!==t.alias)||!0===e.disabled)return;let o="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,d=(e.limits??[]).flatMap(t=>{let n=c3(t);if(null===n)return[];let r=o?"blocked":(0,t4.xL)(t)?"spent":"warning"===t.status||n>=90?"warning":"usable",i=t.window?.resetsAt,a=t.scope?.tier??t.scope?.modelId;return[{row:{key:`${e.provider}:${e.credentialId??l}:${t.id}`,label:t.label||t.id,kind:c6(t),tier:"string"==typeof a&&a?a:null,percent:n,resetsAt:"number"==typeof i&&Number.isFinite(i)?i:null,state:r},alert:c7(t)}]}),c=d.filter(({row:e})=>"short"!==e.kind);c.length>0?(i.push(...c.map(({row:e})=>e)),a.push(...d.filter(({row:e,alert:t})=>"short"===e.kind&&t).map(({row:e})=>e))):i.push(...d.map(({row:e})=>e))}),{selectionRequired:!1,primary:i,warnings:a}}(n.state.data?.reports??[],e,a),u=e.weeklyUsage?[{key:`${e.id}:weekly`,label:l("lounge.usage.weekly"),kind:"weekly",tier:null,percent:Math.round(100*e.weeklyUsage.usedFraction),resetsAt:e.weeklyUsage.resetsAt??null,state:e.weeklyUsage.usedFraction>=1?"spent":"usable"}]:c.primary,p=null===n.state.data&&n.loading,h=l(`lounge.state.${e.state}`),m=`lounge-member-${e.id}-status`,f=t.snapshot?.room.participants??[],g=e.account,x=g?.credentialId,v=void 0!==x&&!g?.choices.some(e=>e.credentialId===x),b=void 0!==g&&(g.selectionRequired||void 0===x||v),y=void 0!==g&&g.choices.length>1,[w,k]=(0,i.useState)(!1),j=void 0!==g&&(b||y&&w),S=`lounge-member-${e.id}-account`,C=u.filter(e=>null===e.tier),N=[...u.filter(e=>null!==e.tier),...c.warnings];return(0,r.jsxs)("li",{className:"lounge-member","data-state":e.state,"data-enabled":e.enabled?"true":"false",children:[(0,r.jsxs)("span",{className:"lounge-member-face",children:[(0,r.jsx)(nc,{seed:e.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{className:"lounge-member-dot","aria-hidden":"true"})]}),(0,r.jsxs)("span",{className:"lounge-member-body",children:[(0,r.jsxs)("span",{className:"lounge-member-head",children:[(0,r.jsxs)("span",{className:"lounge-member-title",children:[(0,r.jsx)("span",{className:"lounge-member-name",children:d}),(0,r.jsx)("span",{id:m,className:"lounge-member-state",children:h})]}),(0,r.jsxs)(uu.h.Root,{size:"16",tone:"neutral",className:"lounge-switch",checked:e.enabled,disabled:s,onCheckedChange:n=>{let r=n?[...f.filter(t=>t!==e.id),e.id]:f.filter(t=>t!==e.id);t.updateSettings({participants:r})},children:[(0,r.jsx)(uu.h.HiddenInput,{"aria-label":l("lounge.participate",{name:d}),"aria-describedby":m}),(0,r.jsx)(uu.h.Control,{children:(0,r.jsx)(uu.h.Thumb,{})})]})]}),e.reason?(0,r.jsx)("span",{className:"lounge-member-reason",children:e.reason}):null,C.length+N.length>0?(0,r.jsxs)("span",{className:"lounge-member-usage",children:[C.map(e=>(0,r.jsx)(um,{row:e,lt:l,locale:o,now:a},e.key)),N.map(e=>(0,r.jsx)(um,{row:e,lt:l,locale:o,now:a,compact:!0},e.key))]}):(0,r.jsx)("span",{className:"lounge-member-usage-empty",children:p?l("lounge.usage.loading"):c.selectionRequired?l("lounge.account.required"):l("lounge.usage.none")}),(0,r.jsxs)("span",{className:"lounge-member-meta",children:[(0,r.jsxs)("span",{className:"lounge-member-model",children:[(0,t4.bN)(e.provider)," \xb7 ",e.model]}),y&&!b?(0,r.jsx)("button",{type:"button",className:"lounge-member-account-toggle","aria-expanded":w,"aria-controls":S,onClick:()=>k(e=>!e),children:l("lounge.account.change")}):null]}),j&&g?(0,r.jsxs)("span",{className:"lounge-member-account",children:[(0,r.jsx)("label",{className:"sr-only",htmlFor:S,children:l("lounge.account.for",{name:d})}),(0,r.jsxs)("select",{id:S,className:"lounge-select",value:void 0===x?"":String(x),disabled:s||0===g.choices.length,"aria-describedby":"lounge-account-hint",onChange:n=>{let r=Number(n.target.value);Number.isInteger(r)&&(t.updateSettings({accountBindings:{[e.id]:r}}),k(!1))},children:[void 0===x?(0,r.jsx)("option",{value:"",disabled:!0,children:l("lounge.account.choose")}):null,v?(0,r.jsx)("option",{value:String(x),disabled:!0,children:l("lounge.account.missing",{id:x})}):null,g.choices.map(e=>(0,r.jsx)("option",{value:String(e.credentialId),children:e.label},e.credentialId))]})]}):null]})]})}function ug({lounge:e,usage:t,onOpenLounge:n,loungeOpen:i=!1}){var a;let s,{lt:l,locale:o}=(0,J.H)(),d=dX(1e4),c=e.snapshot,u=c?.room??null,p=c?.members??[],h=c?.loadError??null,m=e.pending.has("settings"),f=null===c||null!==h,g=p.filter(e=>e.enabled).length,x=new Intl.DateTimeFormat(o,{hour:"2-digit",minute:"2-digit"}),v=u&&!uh.includes(u.sleepAfterMinutes)?[...uh,u.sleepAfterMinutes].sort((e,t)=>e-t):uh,b=c?.run??null;return(0,r.jsxs)("div",{id:"navigator-lounge-panel",className:"lounge-panel",children:[(0,r.jsxs)("div",{className:"lounge-panel-room",children:[(0,r.jsxs)("div",{className:"lounge-panel-room-head",children:[(0,r.jsx)("span",{className:"lounge-panel-title",children:l("lounge.title")}),(0,r.jsxs)(uu.h.Root,{size:"24",tone:"neutral",className:"lounge-switch lounge-room-switch",checked:u?.enabled??!1,disabled:f||m,onCheckedChange:t=>{e.updateSettings({enabled:t})},children:[(0,r.jsx)(uu.h.Label,{className:"lounge-room-switch-label",children:u?.enabled?l("lounge.roomOn"):l("lounge.roomOff")}),(0,r.jsx)(uu.h.HiddenInput,{"aria-label":l("lounge.roomSwitch")}),(0,r.jsx)(uu.h.Control,{children:(0,r.jsx)(uu.h.Thumb,{})})]})]}),null===c?(0,r.jsx)("p",{className:"lounge-panel-note",role:e.loadError?"alert":"status",children:e.loadError?l("lounge.loadFailed",{error:e.loadError}):l("lounge.connecting")}):h?(0,r.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:l("lounge.loadFailed",{error:h})}):u&&!u.enabled?(0,r.jsx)("p",{className:"lounge-panel-note",children:l("lounge.roomOffHint")}):u?.asleep?(0,r.jsx)("p",{className:"lounge-panel-note",children:l("lounge.asleep")}):null,"reconnecting"===e.connection&&null!==c?(0,r.jsx)("p",{className:"lounge-panel-note",role:"status",children:l("lounge.reconnecting")}):null,e.actionError?(0,r.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:l("lounge.actionFailed",{error:e.actionError})}):null,n?(0,r.jsx)("button",{type:"button",className:"lounge-panel-open","aria-pressed":i,onClick:n,children:l("lounge.open")}):null]}),(0,r.jsxs)("div",{className:"lounge-panel-members",children:[(0,r.jsxs)("div",{className:"lounge-panel-section-head",children:[(0,r.jsx)("span",{children:l("lounge.members")}),p.length>0?(0,r.jsx)("span",{className:"lounge-panel-count",children:l("lounge.membersCount",{active:g,total:p.length})}):null]}),(0,r.jsx)("ul",{className:"lounge-member-list","aria-label":l("lounge.members"),children:p.map(n=>(0,r.jsx)(uf,{member:n,lounge:e,usage:t,now:d,disabled:f||m},n.id))}),p.some(e=>e.account)?(0,r.jsx)("p",{id:"lounge-account-hint",className:"lounge-panel-hint",children:l("lounge.account.hint")}):null]}),u?(0,r.jsxs)("div",{className:"lounge-panel-settings",role:"group","aria-label":l("lounge.settings"),children:[(0,r.jsx)("div",{className:"lounge-panel-section-head",children:(0,r.jsx)("span",{children:l("lounge.settings")})}),(0,r.jsxs)("div",{className:"lounge-setting",children:[(0,r.jsx)("span",{className:"lounge-setting-label",id:"lounge-pace-label",children:l("lounge.pace")}),(0,r.jsx)("div",{className:"lounge-segmented",role:"radiogroup","aria-labelledby":"lounge-pace-label",children:up.map(t=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":u.pace===t,disabled:f||m,onClick:()=>{u.pace!==t&&e.updateSettings({pace:t})},children:l(`lounge.pace.${t}`)},t))})]}),(0,r.jsxs)("label",{className:"lounge-setting lounge-setting-inline",children:[(0,r.jsx)("span",{className:"lounge-setting-label",children:l("lounge.sleep")}),(0,r.jsx)("select",{className:"lounge-select",value:u.sleepAfterMinutes,disabled:f||m,onChange:t=>{e.updateSettings({sleepAfterMinutes:Number(t.target.value)})},children:v.map(e=>(0,r.jsx)("option",{value:e,children:l("lounge.sleepMinutes",{minutes:e})},e))})]}),(0,r.jsxs)("div",{className:"lounge-setting",children:[(0,r.jsxs)(uu.h.Root,{size:"16",tone:"neutral",className:"lounge-switch lounge-setting-switch",checked:u.autoTalk,disabled:f||m,onCheckedChange:t=>{e.updateSettings({autoTalk:t})},children:[(0,r.jsx)(uu.h.Label,{className:"lounge-setting-label",children:l("lounge.autoTalk")}),(0,r.jsx)(uu.h.HiddenInput,{"aria-describedby":"lounge-autotalk-hint"}),(0,r.jsx)(uu.h.Control,{children:(0,r.jsx)(uu.h.Thumb,{})})]}),(0,r.jsx)("span",{id:"lounge-autotalk-hint",className:"lounge-setting-hint",children:l("lounge.autoTalkHint")}),u.autoTalk&&u.autoTalkPausedReason?(0,r.jsx)("span",{className:"lounge-setting-hint","data-tone":"warning",role:"status",children:u.autoTalkPausedReason}):null]}),(0,r.jsxs)("div",{className:"lounge-panel-limits",children:[b?(0,r.jsx)("span",{children:l("lounge.calls",{window:(a=b.calls.windowMs,(s=Math.round(a/36e5))>=1?new Intl.NumberFormat(o,{style:"unit",unit:"hour",unitDisplay:"long"}).format(s):l("lounge.sleepMinutes",{minutes:Math.max(1,Math.round(a/6e4))})),used:b.calls.used,limit:b.calls.limit})}):null,b?(0,r.jsx)("span",{children:l("lounge.perTurn",{limit:b.perTurnLimit})}):null,u.enabled&&!u.asleep&&null!==u.sleepAt&&u.sleepAt>d?(0,r.jsx)("span",{children:l("lounge.sleepAt",{time:x.format(new Date(u.sleepAt))})}):null]})]}):null]})}let ux="cuelo-lounge-draft",uv=["\uD83D\uDC4D","❤️","\uD83D\uDE02","\uD83D\uDE2E","\uD83D\uDE4F","\uD83D\uDC40"],ub=Math.floor(1600),uy=[],uw=[];function uk(e,t){if(0===t.length)return e;let n=t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),i=RegExp(`(@(?:${n.join("|")}))`,"giu");return e.split(i).map((e,t)=>t%2==1?(0,r.jsx)("span",{className:"lounge-mention",children:e},t):e)}function uj({lounge:e,visible:t=!0,onBack:n}){let{lt:a,locale:l}=(0,J.H)(),o=e.snapshot,d=o?.room??null,c=o?.run??null,u=o?.members??uy,p=o?.messages??uw,h=o?.loadError??null,m=(0,i.useMemo)(()=>new Map(u.map(e=>[e.id,e])),[u]),f=(0,i.useMemo)(()=>new Map(p.map(e=>[e.id,e])),[p]),g=(0,i.useCallback)(e=>{if("user"===e)return a("lounge.you");let t=m.get(e);return t?(0,J.a)(t.alias,l):e},[l,a,m]),x=(0,i.useMemo)(()=>u.flatMap(e=>[(0,J.a)(e.alias,"ko"),(0,J.a)(e.alias,"en")]),[u]),v=(0,i.useMemo)(()=>new Intl.DateTimeFormat(l,{hour:"2-digit",minute:"2-digit"}),[l]),[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.useRef)(null),T=(0,i.useRef)(null),M=(0,i.useRef)(!0),$=(0,i.useId)();(0,i.useEffect)(()=>{y(function(){try{return window.sessionStorage.getItem(ux)??""}catch{return""}}())},[]);let R=(0,i.useCallback)(e=>{y(e);try{e?window.sessionStorage.setItem(ux,e):window.sessionStorage.removeItem(ux)}catch{}},[]),E=e.streaming.map(e=>`${e.messageId}:${e.text.length}`).join("|");(0,i.useLayoutEffect)(()=>{let e=T.current;e&&t&&M.current&&(e.scrollTop=e.scrollHeight)},[p.length,E,t]),(0,i.useEffect)(()=>{let e=T.current;if(!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>{M.current&&(e.scrollTop=e.scrollHeight)});return t.observe(e),()=>t.disconnect()},[]),(0,i.useEffect)(()=>{t&&I.current?.focus({preventScroll:!0})},[t]);let L=(0,i.useMemo)(()=>{if(!j)return[];let e=j.query.toLowerCase();return u.filter(t=>!e||(0,J.a)(t.alias,"ko").toLowerCase().startsWith(e)||(0,J.a)(t.alias,"en").toLowerCase().startsWith(e)||t.id.startsWith(e))},[u,j]),z=d?.enabled===!0&&null===h&&null!==o,A=e.pending.has("send"),W=b.trim(),P=w?f.get(w)??null:null,F=e=>{if(!j)return;let t=(0,J.a)(e.alias,l),n=I.current,r=n?.selectionStart??b.length;R(`${b.slice(0,j.start)}@${t} ${b.slice(r)}`),S(null);let i=j.start+t.length+2;window.requestAnimationFrame(()=>{n?.focus(),n?.setSelectionRange(i,i)})},_=async()=>{!z||A||!W||W.length>2e3||await e.send(W,P?.id)&&(R(""),k(null),M.current=!0)},D=c?.active?c.currentMemberId:null,O=e.streaming.some(e=>e.memberId===D),H=c?.active?c.queuedMemberIds.map(g):[],B=(t,n,i,s)=>{let l="user"===n,o=m.get(n),d=s.message,c=d?.replyToId?f.get(d.replyToId)??null:null;return(0,r.jsxs)("div",{id:d?`lounge-message-${d.id}`:void 0,className:"lounge-bubble-row","data-mine":l?"true":void 0,"data-grouped":s.grouped?"true":void 0,"data-streaming":s.streaming?"true":void 0,children:[l?null:(0,r.jsx)("span",{className:"lounge-bubble-face",children:s.grouped||!o?null:(0,r.jsx)(nc,{seed:o.seed,size:32,provider:o.provider})}),(0,r.jsxs)("div",{className:"lounge-bubble-stack",children:[l||s.grouped?null:(0,r.jsx)("span",{className:"lounge-bubble-name",children:g(n)}),(0,r.jsxs)("div",{className:"lounge-bubble-line",children:[(0,r.jsxs)("div",{className:"lounge-bubble",children:[d?.replyToId?(0,r.jsxs)("button",{type:"button",className:"lounge-bubble-quote",onClick:()=>{document.getElementById(`lounge-message-${d.replyToId}`)?.scrollIntoView({block:"center",behavior:"smooth"})},children:[(0,r.jsx)("span",{className:"lounge-bubble-quote-name",children:c?g(c.memberId):a("lounge.missingMessage")}),(0,r.jsx)("span",{className:"lounge-bubble-quote-text",children:c?c.text:""})]}):null,(0,r.jsx)("div",{className:"lounge-bubble-text",children:i})]}),void 0!==s.createdAt?(0,r.jsx)("time",{className:"lounge-bubble-time",dateTime:new Date(s.createdAt).toISOString(),children:v.format(new Date(s.createdAt))}):null]}),d?(0,r.jsxs)("div",{className:"lounge-bubble-foot",children:[d.reactions.filter(e=>e.by.length>0).map(t=>(0,r.jsxs)("button",{type:"button",className:"lounge-reaction","aria-pressed":t.by.includes("user"),"aria-label":a("lounge.reaction",{emoji:t.emoji,count:t.by.length}),title:t.by.map(g).join(", "),disabled:!z,onClick:()=>{e.react(d.id,t.emoji)},children:[(0,r.jsx)("span",{"aria-hidden":"true",children:t.emoji}),(0,r.jsx)("span",{className:"lounge-reaction-count",children:t.by.length})]},t.emoji)),(0,r.jsxs)("span",{className:"lounge-bubble-actions",children:[(0,r.jsx)("button",{type:"button",className:"lounge-bubble-action",disabled:!z,onClick:()=>{k(d.id),I.current?.focus()},children:a("lounge.reply")}),(0,r.jsx)("button",{type:"button",className:"lounge-bubble-action","aria-expanded":C===d.id,disabled:!z,onClick:()=>N(e=>e===d.id?null:d.id),children:a("lounge.react")})]}),C===d.id?(0,r.jsx)("span",{className:"lounge-reaction-picker",role:"group","aria-label":a("lounge.react"),children:uv.map(t=>(0,r.jsx)("button",{type:"button",onClick:()=>{N(null),e.react(d.id,t)},children:t},t))}):null]}):null]})]},t)},U=D?a("lounge.speaking",{name:g(D)}):null;return(0,r.jsxs)("section",{className:"lounge-view","aria-label":a("lounge.title"),hidden:!t,children:[(0,r.jsxs)("header",{className:"lounge-view-header",children:[n?(0,r.jsx)(s.r,{variant:"ghost",size:"small",className:"lounge-view-back",onClick:n,children:a("lounge.back")}):null,(0,r.jsxs)("div",{className:"lounge-view-heading",children:[(0,r.jsx)("h2",{className:"lounge-view-title",children:a("lounge.title")}),(0,r.jsx)("span",{className:"lounge-view-room","data-on":d?.enabled?"true":"false",children:d?.enabled?a("lounge.roomOn"):a("lounge.roomOff")})]}),(0,r.jsx)("ul",{className:"lounge-view-faces","aria-label":a("lounge.members"),children:u.filter(e=>e.enabled).map(e=>(0,r.jsxs)("li",{className:"lounge-view-face","data-state":e.state,children:[(0,r.jsx)(nc,{seed:e.seed,size:24,provider:e.provider}),(0,r.jsx)("span",{className:"lounge-member-dot","aria-hidden":"true"}),(0,r.jsx)("span",{className:"sr-only",children:`${g(e.id)} ${a(`lounge.state.${e.state}`)}`})]},e.id))})]}),e.loadError&&!o?(0,r.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:a("lounge.loadFailed",{error:e.loadError})}):null,h?(0,r.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:a("lounge.loadFailed",{error:h})}):null,"reconnecting"===e.connection&&o?(0,r.jsx)("p",{className:"lounge-banner",role:"status",children:a("lounge.reconnecting")}):null,e.actionError?(0,r.jsxs)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:[(0,r.jsx)("span",{children:a("lounge.actionFailed",{error:e.actionError})}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:e.dismissActionError,"aria-label":"✕",children:"✕"})]}):null,!d||d.enabled||h?d?.asleep?(0,r.jsx)("p",{className:"lounge-banner",children:a("lounge.asleep")}):d?.autoTalk&&d.autoTalkPausedReason?(0,r.jsx)("p",{className:"lounge-banner",role:"status",children:d.autoTalkPausedReason}):null:(0,r.jsxs)("p",{className:"lounge-banner",children:[(0,r.jsx)("span",{children:a("lounge.roomOffBanner")}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",disabled:e.pending.has("settings"),onClick:()=>{e.updateSettings({enabled:!0})},children:a("lounge.turnOn")})]}),(0,r.jsxs)("div",{ref:T,className:"lounge-log",role:"log","aria-label":a("lounge.messages"),onScroll:e=>{let t=e.currentTarget;M.current=t.scrollHeight-t.scrollTop-t.clientHeight<80},children:[o&&0===p.length&&0===e.streaming.length?(0,r.jsx)("p",{className:"lounge-empty",children:a("lounge.empty")}):null,o||e.loadError?null:(0,r.jsx)("p",{className:"lounge-empty",children:a("lounge.connecting")}),p.map((e,t)=>{let n=t>0?p[t-1]:null,r=null!==n&&n.memberId===e.memberId&&e.createdAt-n.createdAt<3e5&&!e.replyToId;return B(e.id,e.memberId,uk(e.text,x),{message:e,createdAt:e.createdAt,grouped:r})}),e.streaming.map(e=>B(`stream-${e.messageId}`,e.memberId,(0,r.jsxs)(r.Fragment,{children:[uk(e.text,x),(0,r.jsx)("span",{className:"lounge-caret","aria-hidden":"true"})]}),{grouped:!1,streaming:!0})),D&&!O?B(`typing-${D}`,D,(0,r.jsxs)("span",{className:"lounge-typing","aria-hidden":"true",children:[(0,r.jsx)("span",{}),(0,r.jsx)("span",{}),(0,r.jsx)("span",{})]}),{grouped:!1,streaming:!0}):null]}),(0,r.jsxs)("div",{className:"lounge-composer",children:[(0,r.jsxs)("div",{className:"lounge-composer-status",role:"status","aria-live":"polite",children:[U?(0,r.jsx)("span",{children:U}):null,H.length>0?(0,r.jsx)("span",{children:a("lounge.queued",{names:H.join(", ")})}):null]}),P?(0,r.jsxs)("div",{className:"lounge-reply-chip",children:[(0,r.jsxs)("span",{className:"lounge-reply-chip-text",children:[(0,r.jsx)("strong",{children:a("lounge.replyTo",{name:g(P.memberId)})}),(0,r.jsx)("span",{children:P.text})]}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:()=>k(null),children:a("lounge.cancelReply")})]}):null,(0,r.jsxs)("div",{className:"lounge-composer-row",children:[j&&L.length>0?(0,r.jsx)("ul",{id:$,className:"lounge-mention-list",role:"listbox","aria-label":a("lounge.mentionList"),children:L.map((e,t)=>(0,r.jsxs)("li",{id:`${$}-${e.id}`,role:"option","aria-selected":t===j.index,onMouseDown:t=>{t.preventDefault(),F(e)},children:[(0,r.jsx)(nc,{seed:e.seed,size:20,provider:e.provider}),(0,r.jsx)("span",{children:(0,J.a)(e.alias,l)}),(0,r.jsx)("span",{className:"lounge-mention-state",children:a(`lounge.state.${e.state}`)})]},e.id))}):null,(0,r.jsx)("textarea",{ref:I,className:"lounge-composer-input",rows:1,value:b,maxLength:2e3,disabled:!z,placeholder:z?a("lounge.placeholder"):a("lounge.placeholderOff"),"aria-label":a("lounge.composer"),role:"combobox","aria-expanded":null!==j&&L.length>0,"aria-controls":$,"aria-autocomplete":"list","aria-activedescendant":j&&L[j.index]?`${$}-${L[j.index].id}`:void 0,onChange:e=>{var t;let n,r,i=e.target.value;R(i);let a=(t=e.target.selectionStart??i.length,n=i.slice(0,t),(r=/(^|\s)@([^\s@]*)$/u.exec(n))?{start:t-r[2].length-1,query:r[2]}:null);S(a?{...a,index:0}:null)},onBlur:()=>S(null),onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(j&&L.length>0){if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault();let t="ArrowDown"===e.key?1:-1;S({...j,index:(j.index+t+L.length)%L.length});return}if("Enter"===e.key||"Tab"===e.key){e.preventDefault(),F(L[Math.min(j.index,L.length-1)]);return}if("Escape"===e.key){e.preventDefault(),S(null);return}}if("Escape"===e.key&&w){e.preventDefault(),k(null);return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),_())}}}),c?.active?(0,r.jsxs)(s.r,{variant:"neutralOutline",size:"small",className:"lounge-composer-button lounge-stop-button",loading:e.pending.has("stop"),onClick:()=>{e.stop()},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:(0,r.jsx)("rect",{width:"10",height:"10",rx:"2",fill:"currentColor"})}),a("lounge.stop")]}):null,(0,r.jsx)(s.r,{variant:"neutralSolid",size:"small",className:"lounge-composer-button",disabled:!z||!W||W.length>2e3,loading:A,onClick:()=>{_()},children:a("lounge.send")})]}),b.length>=ub?(0,r.jsx)("span",{className:"lounge-composer-counter",children:a("lounge.textLimit",{count:b.length,max:2e3})}):null]})]})}var uS=n(45926),uC=n(86110),uN=n(13994),uI=n(43796),uT=n.n(uI);let uM=[],u$={kind:"loading"};function uR({participant:e,sessionId:t,cwd:n,recipient:a,onBackToMain:s,onOpenFile:l,client:o}){let{ot:d}=(0,uN.v)(),c=(0,uS.Jg)(),u=c(e),p=(0,i.useMemo)(()=>o??(0,nk.Et)(),[o]),{snapshot:h}=e,m=(0,i.useMemo)(()=>[{key:e.key,liveId:h.id,status:h.status}],[e.key,h.id,h.status]),f=(0,ij._Z)(m,{sessionId:t??"",client:p,enabled:!!t}).get(e.key),g=f?.state??u$,x="ready-archive"===g.kind,v=f?.entries??uM,b=(0,i.useMemo)(()=>"ready-live"===g.kind?g.entries:"ready-archive"===g.kind?(0,ij.RO)(g.entries):v,[v,g]),y=(0,i.useMemo)(()=>b.flatMap(e=>"message"in e?[e.message]:[]),[b]),w=(0,i.useMemo)(()=>{let e=new Map;for(let t of y)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[y]),k=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let r of y)if("assistant"===r.role)for(let i of e4(r.content,w,n))e.has(i.filePath)||(e.add(i.filePath),t.push(i));return t},[n,y,w]),[j,S]=(0,i.useState)("transcript"),C=(0,i.useId)(),N=(0,i.useRef)(null);(0,i.useEffect)(()=>{if("transcript"!==j)return;let e=requestAnimationFrame(()=>{let e=N.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[y.length,j]);let I=["transcript","files"],T=e=>{if("ArrowRight"!==e.key&&"ArrowLeft"!==e.key)return;e.preventDefault();let t=I[(I.indexOf(j)+1)%I.length];S(t),document.getElementById(`${C}-${t}-tab`)?.focus()},M=(0,ij.Ch)(e.status)&&h.progress?.lastIntent?.trim()||null,$=e.agent?`${d("office.maker")} \xb7 ${e.agent}`:d("office.maker");return(0,r.jsxs)("section",{className:uT().maker,"aria-label":d("office.makerRecord",{name:e.name}),children:[(0,r.jsxs)("header",{className:uT().makerHeader,children:[(0,r.jsx)(uS.AT,{seat:e.seat,size:32}),(0,r.jsxs)("div",{className:uT().makerIdentity,children:[(0,r.jsx)("h2",{className:uT().makerName,children:e.name}),(0,r.jsxs)("p",{className:uT().makerMeta,children:[(0,r.jsx)("span",{className:uT().viewOnly,children:d("office.viewOnly")}),(0,r.jsx)("span",{children:$}),(0,r.jsx)("span",{className:uT().mono,children:e.model??d("office.modelUnknown")})]})]}),(0,r.jsxs)("span",{className:uT().status,"data-tone":u.tone,children:[(0,r.jsx)("span",{className:uT().dot,"aria-hidden":"true"}),u.status]})]}),(M||"completed"===e.status)&&(0,r.jsx)("p",{className:uT().makerNote,children:M?`${d("office.currentStep")} \xb7 ${M}`:d("office.notAccepted")}),(0,r.jsx)("div",{className:uT().tabs,role:"tablist","aria-label":e.name,children:I.map(e=>(0,r.jsx)("button",{id:`${C}-${e}-tab`,type:"button",role:"tab",className:uT().tab,"aria-selected":j===e,"aria-controls":`${C}-${e}-panel`,tabIndex:j===e?0:-1,onClick:()=>S(e),onKeyDown:T,children:"transcript"===e?d("office.tabTranscript"):d("office.tabFiles",{count:x?"?":k.length})},e))}),(0,r.jsx)("div",{ref:N,id:`${C}-${j}-panel`,role:"tabpanel","aria-labelledby":`${C}-${j}-tab`,className:uT().makerBody,children:"transcript"===j?(0,r.jsxs)(r.Fragment,{children:["loading"===g.kind&&(0,r.jsx)("p",{role:"status",className:uT().bodyNote,children:d("office.loading")}),"unreachable"===g.kind&&(0,r.jsx)("p",{role:"status",className:uT().bodyNote,children:g.message}),"error"===g.kind&&(0,r.jsx)("p",{role:"alert",className:uT().bodyNote,"data-tone":"failed",children:g.message}),"empty"===g.kind&&(0,r.jsx)("p",{role:"status",className:uT().bodyNote,children:g.note??d("office.transcriptEmpty")}),x&&(0,r.jsx)("p",{role:"status",className:uT().bodyNote,children:g.note??d("office.archiveNote")}),"ready-live"===g.kind&&y.map((e,t)=>(0,r.jsx)(rg,{message:e,toolResults:w,cwd:n,onOpenFile:l,showTimestamp:!0,prevTimestamp:y[t-1]?.timestamp},`${t}:${e.timestamp??0}`)),x&&g.entries.map((e,t)=>(0,r.jsxs)("div",{className:uT().archiveEntry,children:[(0,r.jsxs)("span",{className:uT().archiveRole,children:[e.role," \xb7 ",e.kind]}),e.text||d("office.transcriptEmpty")]},`${e.at??0}:${t}`))]}):x?(0,r.jsx)("p",{className:uT().bodyNote,children:d("office.filesArchive")}):0===k.length?(0,r.jsx)("p",{className:uT().bodyNote,children:d("office.filesEmpty")}):(0,r.jsx)("ul",{className:uT().files,children:k.map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:uT().file,onClick:()=>l(e.filePath),title:e.filePath,children:[(0,r.jsx)("span",{className:uT().fileName,children:te(e.filePath)}),(0,r.jsx)("span",{className:uT().filePath,children:e.filePath})]})},e.filePath))})}),(0,r.jsxs)("footer",{className:uT().makerFooter,children:[(0,r.jsx)("p",{className:uT().composerNote,children:d("office.composerNote",{name:c(a).name})}),(0,r.jsx)("button",{type:"button",className:uT().backButton,onClick:s,children:d("office.backToMain")})]})]})}var uE=n(67219),uL=n(14199);let uz="git pull && bun install && bun run build && node Tools/CUELO_Setup/files/native-runtime-patch.js --target .";function uA(e){return"unknown"===e?e:`v${e}`}function uW(){let{locale:e,t}=(0,R.s)(),n=P(),[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)("idle"),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(()=>{let e=g.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=az(e.top,e.bottom,t,aA(t,.72,620),{margin:12,minHeight:0}),i=Math.min(430,window.innerWidth-24),a=Math.max(12,window.innerWidth-i-12);y({left:Math.min(e.right+8,a),width:i,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,i.useEffect)(()=>d?(w(),window.addEventListener("resize",w),window.addEventListener("scroll",w,!0),window.visualViewport?.addEventListener("resize",w),window.visualViewport?.addEventListener("scroll",w),()=>{window.removeEventListener("resize",w),window.removeEventListener("scroll",w,!0),window.visualViewport?.removeEventListener("resize",w),window.visualViewport?.removeEventListener("scroll",w)}):void y(null),[d,w]);let k=(0,i.useCallback)(async e=>{o("loading");try{let t=await fetch("/api/updates",{cache:"no-store",signal:e});if(!t.ok)return;let n=await t.json();s(n),o("ready")}catch{e?.aborted||o("ready")}},[]);if((0,i.useEffect)(()=>{let e=new AbortController;return k(e.signal),()=>e.abort()},[k]),(0,i.useEffect)(()=>()=>{clearTimeout(f.current??void 0),f.current=null},[]),(0,i.useEffect)(()=>{if(!d)return;let e=e=>{g.current?.contains(e.target)||x.current?.contains(e.target)||c(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),c(!1),v.current?.focus({preventScroll:!0}))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[d]),"ready"!==l||!a?.updateAvailable||!a.latestRelease)return null;let j=a.latestRelease,S=j.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(j.publishedAt)):null,C=j.body.trim()||j.name,N=async e=>{try{await t_(e),clearTimeout(f.current??void 0),m(e),f.current=setTimeout(()=>m(null),1600)}catch{p(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:g,"data-dismissible-layer":d?"":void 0,style:{position:"relative",width:"100%"},children:[(0,r.jsxs)("button",{ref:v,type:"button","aria-expanded":d,"aria-haspopup":"dialog",onClick:()=>{c(e=>!e),p(null)},title:t("updates.availableTitle",{version:uA(j.version)}),style:{width:"100%",minHeight:n?44:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"7px 10px",border:"1px solid color-mix(in srgb, var(--warning) 54%, var(--border))",borderRadius:9,background:"color-mix(in srgb, var(--warning) 8%, transparent)",color:"var(--warning)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-mono)",transition:"background 0.12s, border-color 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 14%, var(--bg-hover))",e.currentTarget.style.borderColor="var(--warning)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 8%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--warning) 54%, var(--border))"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:"var(--warning)",boxShadow:"0 0 0 3px color-mix(in srgb, var(--warning) 14%, transparent)"}}),(0,r.jsx)("span",{children:t("updates.available")}),(0,r.jsx)("span",{style:{color:"var(--text)",fontVariantNumeric:"tabular-nums"},children:uA(j.version)})]}),d&&b&&(0,F.createPortal)((0,r.jsxs)("div",{ref:x,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:b.left,top:b.top,bottom:b.bottom,zIndex:700,width:b.width,maxHeight:b.maxHeight,display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-panel)",boxShadow:"0 18px 46px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("div",{style:{padding:"13px 14px 11px",borderBottom:"1px solid var(--border)",background:"linear-gradient(135deg, color-mix(in srgb, var(--warning) 10%, var(--bg-panel)), var(--bg-panel) 65%)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.dialogEyebrow")}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text)",fontSize:15,fontWeight:650},children:t("updates.dialogTitle")})]}),(0,r.jsx)("div",{style:{color:"var(--warning)",fontFamily:"var(--font-mono)",fontSize:12,fontVariantNumeric:"tabular-nums"},children:uA(j.version)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 14px",marginTop:9,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:t("updates.current",{version:uA(a.currentAppVersion)})}),S&&(0,r.jsx)("span",{children:S})]})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.changelog")}),(0,r.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,r.jsx)(tU,{children:C})})]}),(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px 12px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:9,marginBottom:10},children:(0,r.jsx)("a",{href:j.htmlUrl,target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",fontSize:11,textDecoration:"underline",textUnderlineOffset:3},children:t("updates.viewRelease")})}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)"},children:t("updates.manual")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,marginTop:6,padding:"6px 7px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("code",{style:{flex:1,minWidth:0,overflowWrap:"anywhere",color:"var(--text)"},children:uz}),(0,r.jsx)("button",{type:"button",onClick:()=>void N(uz),title:h===uz?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":h===uz?t("updates.commandCopied"):t("updates.copyCommand"),style:{flex:"0 0 auto",width:n?44:24,height:n?44:24,padding:0,border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:h===uz?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:h===uz?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]}),u&&(0,r.jsx)("div",{role:"alert",style:{marginTop:9,color:"var(--danger)",fontSize:11,lineHeight:1.45},children:u})]})]}),document.body)]})}let uP="pi-web:last-open-by-workspace";function uF(){try{return window.localStorage}catch{return null}}function u_(e){let t=e.getItem(uP);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function uD(e,t=uF()){if(t)try{let n=u_(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(uP):t.setItem(uP,JSON.stringify(n))}catch{}}let uO="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",uH="omp-web:wide-chat";function uB(){try{return dO(window.localStorage)}catch{return dO(null)}}function uU({auxiliaryDeck:e,resourcePanel:t,variant:n="chat"}={}){var p,m,f,k;let j,S,C,N,I,T,M,$,E,L,z,P,F,_,D,O,H,B,U="office"===n,q=U?"/office":"/",K=(0,a.useRouter)(),V=(0,a.useSearchParams)(),[J]=(0,i.useState)(()=>{let e;return{requestedCwd:e=V.get("cwd")?.trim()||null,sessionId:e?null:V.get("session")}}),{preference:G,toggleTheme:Y}=tF(),{locale:Z,setLocale:X,t:Q,supportedLocales:ee}=(0,R.s)(),et=function(){let[e,t]=(0,i.useState)(null),[n,r]=(0,i.useState)(!1),a=(0,i.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,i.useEffect)(()=>{try{r("1"===window.localStorage.getItem(dx))}catch{}return a(),window.addEventListener("focus",a),()=>window.removeEventListener("focus",a)},[a]),{permission:e,dismissed:n,request:(0,i.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,a)},[a]),dismiss:(0,i.useCallback)(()=>{r(!0);try{window.localStorage.setItem(dx,"1")}catch{}},[])}}(),en=(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,W);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{let r;n=null,!function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let i=.01>Math.abs(r-1);return e&&i&&t-n>1}({hasFocusedEditable:(r=document.activeElement)instanceof HTMLElement&&(r.isContentEditable||"INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.removeProperty("--app-viewport-height"):t.style.setProperty("--app-viewport-height",`${e.height}px`);let i=0!==window.scrollX||0!==window.scrollY,a=.01>Math.abs(e.scale-1);i&&a&&window.scrollTo(0,0)},i=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return i(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("focusin",i),window.addEventListener("focusout",i),window.addEventListener("pageshow",i),()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("focusin",i),window.removeEventListener("focusout",i),window.removeEventListener("pageshow",i),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]);let{soundEnabled:er,onSoundToggle:ei,playCueSound:es,preloadCueSound:el,unlockAudio:eo,soundEnabledRef:ed}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),a=(0,i.useRef)(null),s=(0,i.useRef)(0),l=(0,i.useRef)(new Map),o=(0,i.useRef)(new Map),d=(0,i.useRef)(new Map),c=(0,i.useRef)(null),u=(0,i.useRef)(new Map),p=(0,i.useRef)(new Map),h=(0,i.useRef)(new Map),m=(0,i.useCallback)(e=>{let t=p.current.get(e);return t||(t=c8(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),f=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),g=(0,i.useCallback)(()=>(c.current??=is(),c.current),[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async e=>{if(!e)return;let t=await g();for(let r of r7){let i=ia(t,e,r);if(i){for(let e of i.stickers){if(h.current.has(e))continue;let t=new Image;t.decoding="async",t.src=e,h.current.set(e,t)}if(n.current)for(let e of i.voices)m(e).catch(()=>{})}}},[g,m]),v=(0,i.useCallback)(()=>{s.current+=1;let e=a.current;if(a.current=null,e)try{e.stop()}catch{}},[]),b=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=f();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[f]);(0,i.useEffect)(()=>{let e=()=>b(),t={capture:!0,passive:!0};return window.addEventListener("pointerdown",e,t),window.addEventListener("keydown",e,t),()=>{window.removeEventListener("pointerdown",e,t),window.removeEventListener("keydown",e,t)}},[b]);let y=(0,i.useCallback)(()=>{let e=!n.current;e?b(!0):v(),n.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,b]),w=(0,i.useCallback)(e=>{if(!n.current)return;let t=f();if(!t)return;v();let r=s.current,i=()=>{if(r===s.current&&n.current&&(!e||e()))try{c5(t)}catch{}};"suspended"===t.state?t.resume().then(i).catch(()=>{}):i()},[f,v]);return{soundEnabled:e,onSoundToggle:y,playCueSound:(0,i.useCallback)(async(e,t="done",r)=>{let i=await g(),c=null===t?null:ia(i,e,t),p=`${e??""}\u0000${t??""}`,h=c?il(c.stickers,o.current.get(p)??null):null;null!==h&&o.current.set(p,h);let x=c?il(c.voices,l.current.get(p)??null):null,b=x?c?.lines.get(x)??null:null;!x&&c&&null!==(b=il(c.captions,d.current.get(p)??null))&&d.current.set(p,b);let y={sticker:h,text:b};if(!n.current||r&&!r())return y;let k=f();if(!k)return y;if(!x)return null!==t&&ie[t]||w(r),y;v();let j=s.current,S=()=>j!==s.current||!n.current||void 0!==r&&!r();return(async()=>{if(!("suspended"===k.state&&(await k.resume().catch(()=>{}),S())))try{let e=u.current.get(x);e||(e=m(x).then(e=>k.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(x),e}),u.current.set(x,e));let t=await e;if(S())return;let n=k.createBufferSource(),r=k.createGain();n.buffer=t,n.connect(r),r.connect(k.destination),r.gain.setValueAtTime(.82,k.currentTime),n.onended=()=>{a.current===n&&(a.current=null)},a.current=n,n.start(),l.current.set(p,x)}catch{if(S()||null!==t&&ie[t])return;try{c5(k)}catch{}}})(),y},[f,w,v,g,m]),preloadCueSound:x,unlockAudio:b,soundEnabledRef:n}}(),ec=function(){let[e,t]=(0,i.useState)({status:"idle",data:null,error:null}),[n,r]=(0,i.useState)(!0),[a,s]=(0,i.useState)(null),l=(0,i.useRef)(null),o=(0,i.useRef)(null),d=(0,i.useCallback)(()=>{o.current?.abort();let e=new AbortController;o.current=e,(0,t4.t6)({signal:e.signal}).then(t=>{e.signal.aborted||s(t)})},[]);(0,i.useEffect)(()=>{let e=(0,t4.oI)({onResult(e){t(e),r(!1)}});return l.current=e,e.start(),d(),()=>{e.stop(),o.current?.abort(),l.current===e&&(l.current=null)}},[d]);let c=(0,i.useCallback)(async()=>{let e=l.current;if(!e)return{status:"error",data:null,error:new t4.OO("사용량 폴링이 시작되지 않았습니다.","aborted")};r(!0),d();let t=await e.refresh();return r(!1),t},[d]);return{state:e,loading:n,refresh:c,setPaused:(0,i.useCallback)(e=>{l.current?.setPaused(e)},[]),bai:(0,i.useMemo)(()=>(function(e){let t=e?.data;if(!t)return{status:"unmeasured"};let n=t.models.filter(e=>"b-ai"===e.provider);return 0===n.length?{status:"empty"}:{status:"measured",tokens:n.reduce((e,t)=>e+t.tokens,0),from:"number"==typeof t.range?.from?t.range.from:null,to:"number"==typeof t.range?.to?t.range.to:null}})(a),[a])}}();p=ec.state.data?.reports,(0,i.useEffect)(()=>{!function(e){let t=e??t8,n=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===t3)return;t3=n;let r=(0,t4.k)(t),i=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!nn(n))return;let a=nr(e.provider,n);i.has(a)||i.set(a,{seed:r[t].seed,alias:r[t].alias})}),nt({faces:i,pins:t6.pins})}(p)},[p]);let[eu,ep]=(0,i.useState)(!1),[eh,em]=(0,i.useState)(!1),ef=function(e=!0){let[t,n]=(0,i.useReducer)(ul,ua),[r,a]=(0,i.useState)("connecting"),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(()=>new Set),p=(0,i.useRef)(!1);p.current=null!==t.snapshot,(0,i.useEffect)(()=>{let t;if(!e)return;let r=!1,i=null,s=new AbortController;fetch(uo,{cache:"no-store",signal:s.signal}).then(async e=>{if(!e.ok)throw Error(await uc(e));let t=await e.json();r||(n({type:"snapshot",source:"get",data:t}),l(null))}).catch(e=>{r||s.signal.aborted||p.current||l(e instanceof Error?e.message:String(e))});let o=()=>{if(r)return;let e=new EventSource("/api/lounge/events");i=e,e.onopen=()=>{r||a("live")},e.onerror=()=>{r||(a("reconnecting"),e.readyState===EventSource.CLOSED&&(e.close(),t=window.setTimeout(o,3e3)))},e.addEventListener("snapshot",e=>{let t=ud(e);t&&!r&&(n({type:"snapshot",source:"sse",data:t}),l(null),a("live"))}),e.addEventListener("state",e=>{let t=ud(e);t&&!r&&n({type:"state",data:t})}),e.addEventListener("message",e=>{let t=ud(e);t&&!r&&n({type:"message",data:t})}),e.addEventListener("delta",e=>{let t=ud(e);t&&!r&&n({type:"delta",data:t})})};return o(),()=>{r=!0,s.abort(),window.clearTimeout(t),i?.close()}},[e]);let h=(0,i.useCallback)(async e=>{let t={...e,requestId:"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,roomId:"main"};u(t=>new Set(t).add(e.action));try{let e=await fetch(uo,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)return d(await uc(e)),!1;let r=await e.json();return r?.snapshot&&n({type:"snapshot",source:"post",data:r.snapshot}),d(null),!0}catch(e){return d(e instanceof Error?e.message:String(e)),!1}finally{u(t=>{let n=new Set(t);return n.delete(e.action),n})}},[]),m=(0,i.useCallback)(e=>h({action:"settings",...e}),[h]),f=(0,i.useCallback)((e,t)=>h(t?{action:"send",text:e,replyToId:t}:{action:"send",text:e}),[h]),g=(0,i.useCallback)(()=>h({action:"stop"}),[h]),x=(0,i.useCallback)((e,t)=>h({action:"reaction",messageId:e,emoji:t}),[h]),v=(0,i.useCallback)(()=>d(null),[]),b=(0,i.useMemo)(()=>[...t.streaming.values()],[t.streaming]);return{snapshot:t.snapshot,streaming:b,connection:r,loadError:s,actionError:o,pending:c,updateSettings:m,send:f,stop:g,react:x,dismissActionError:v}}(eh),eg=(0,i.useRef)(new Set),ex=(0,i.useCallback)(()=>{ed.current&&es(null,"done")},[es,ed]),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(null),eS=(0,i.useRef)(0),eC=(0,i.useRef)(null),[eN,eI]=(0,i.useState)(null),eT=(0,i.useRef)(0),eM=(0,i.useCallback)(e=>{eI(t=>t?.id===e?null:t)},[]),[e$,eR]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{eR("1"===window.localStorage.getItem(uH))}catch{}},[]);let eE=(0,i.useCallback)(()=>{eR(e=>{let t=!e;try{window.localStorage.setItem(uH,t?"1":"0")}catch{}return t})},[]),[eL,ez]=(0,i.useState)(null),[eA,eW]=(0,i.useState)(()=>J.requestedCwd?"validating":"idle"),[eP,eF]=(0,i.useState)(null),[e_,eD]=(0,i.useState)(0),[eO,eH]=(0,i.useState)(0),[eB,eU]=(0,i.useState)(0),[eq,eK]=(0,i.useState)(0),[eV,eJ]=(0,i.useState)(!1),[eG,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)(null),[eQ]=(0,i.useState)(()=>{let e;return e=0,{reset(){e+=1,eX(null)},check(t,n){let r=++e;eX("checking"),t().then(t=>{r===e&&eX("fresh"===t.status?function(e,t){if(!t.accountKey)return"unknown";let n=e.filter(e=>e.provider===t.provider&&e.accountKey===t.accountKey);return n.some(e=>!0!==e.disabled&&!e.authError)?"recovered":n.length>0?"still-failing":"unknown"}(t.data.reports,n):"unknown")},()=>{r===e&&eX("unknown")})}}}),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(0),e5=(0,i.useRef)(null),e8=(0,i.useRef)(null),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useReducer)(g,h),[ta,ts]=(0,i.useState)("characters"),[tl,to]=(0,i.useState)("governor"),[td,tc]=(0,i.useState)(()=>x(0)),[tu]=(0,i.useState)(uB),[tp]=(0,i.useState)(dH),[th,tm]=(0,i.useState)([]),[tf,tg]=(0,i.useState)({sessions:[],complete:!1}),[tx,tv]=(0,i.useState)(!1),[tb,ty]=(0,i.useState)(!1),[tw,tk]=(0,i.useState)(0),tj=(0,i.useRef)(null),tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tN=(0,i.useCallback)(()=>{tk(e=>e+1)},[]),tI=(0,i.useCallback)(e=>{e&&em(!0),ep(e),e||tN()},[tN]),tT=(0,i.useCallback)(e=>{tS.current=e},[]),tM=(0,i.useRef)(!1),[t$,tR]=(0,i.useState)(!1),tE=(0,i.useRef)(!1),tL=(0,i.useRef)(!1),tz=(0,i.useRef)(0),[tA,tW]=(0,i.useState)(!1),[tP,tD]=(0,i.useState)(!1),tO=(0,i.useRef)(null),[tH,tB]=(0,i.useState)(null),[tU,tq]=(0,i.useState)(null),tK=(0,i.useRef)(null),tV=(0,i.useRef)(!1);tK.current=tH,(0,i.useEffect)(()=>{tB(sT())},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||tM.current||"IDLE"===n.phase||!n.requestId||!n.stageHash)return;let r=`${window.location.pathname}${window.location.search}${window.location.hash}`,i=function(e){let t=aa();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:sN(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(sy,JSON.stringify(n))}catch(e){return{entered:!1,error:e instanceof Error?e.message:String(e)}}let r=new URLSearchParams({mode:"wait",requestId:n.requestId,stageHash:n.stageHash,clientId:n.clientId});return window.location.replace(`/api/update-maintenance?${r}`),{entered:!0}}({requestId:n.requestId,stageHash:n.stageHash,sessionId:ev?.id??null,resumeUrl:r});if(i.entered){tM.current=!0;return}t=i.error},r=async()=>{if(!e&&!tM.current)try{let i=tV.current?null:tK.current,a=await s$({sessionId:ev?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:i?{requestId:i.requestId,stageHash:i.stageHash}:null});tz.current=0;let s=!!(a.serverBootId&&tO.current&&a.serverBootId!==tO.current);if(tE.current||s){var r=ev?.id??null;aa();try{sessionStorage.setItem(sk,JSON.stringify({schemaVersion:1,sessionId:r,at:Date.now()}))}catch{}window.location.reload();return}a.serverBootId&&(tO.current=a.serverBootId),tL.current=!0,!e&&a.update&&(tq(a.update),a.update.cleanup&&"running"!==a.update.cleanup.status&&(tV.current=!0)),n(a)}catch{tz.current+=1,!e&&tL.current&&tz.current>=2&&(tE.current=!0,tR(!0))}},i=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",i),r();let a=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(a),window.removeEventListener("ompweb:update-maintenance",i)}},[ev?.id]),(0,i.useEffect)(()=>{if(!t$)return;let e=window.setTimeout(()=>tW(!0),12e4);return()=>window.clearTimeout(e)},[t$]),(0,i.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(sk);if(!r)return!1;try{n=JSON.parse(r)}catch{n=null}return!n||1!==n.schemaVersion||"number"!=typeof n.at||t-n.at>6e4||null!==n.sessionId&&"string"!=typeof n.sessionId?(sessionStorage.removeItem(sk),!1):n.sessionId===e&&(sessionStorage.removeItem(sk),!0)})(ev?.id??null)&&tD(!0)},[ev?.id]),(0,i.useEffect)(()=>{if(!tP)return;let e=window.setTimeout(()=>tD(!1),8e3);return()=>window.clearTimeout(e)},[tP]);let tJ=tH?.requestId??null,tG=tH?.dismissed??!0,tY=tU?.requestId??null,tZ=tU?.deploymentCompleted??!1,tX=tU?.cleanup?.status??null;(0,i.useEffect)(()=>{if(!tJ||tG||tY!==tJ||!tZ)return;let e=sC(tX);if(null===e)return;let t=window.setTimeout(()=>{tB(sM(tJ))},e);return()=>window.clearTimeout(t)},[tJ,tG,tY,tZ,tX]),(0,i.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(sy);if(!e)return null;try{let t=JSON.parse(e);if(2!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"string"!=typeof t.clientId||"string"!=typeof t.resumeUrl||null!==t.sessionId&&"string"!=typeof t.sessionId)return null;return t}catch{return null}}();if(!e||e.sessionId&&ev?.id!==e.sessionId)return;let t=!1;return sE(e).then(e=>{t||"resumed"!==e||(tV.current=!1,tB(sT()),eD(e=>e+1),eU(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[ev?.id]);let tQ=(0,i.useCallback)(e=>{if("Tab"!==e.key)return;let t=tC.current;if(!t)return;let n=Array.from(t.querySelectorAll(uO));if(0===n.length)return;let r=e.shiftKey?n[0]:n[n.length-1],i=document.activeElement;i!==r&&t.contains(i)||(e.preventDefault(),(e.shiftKey?n[n.length-1]:n[0]).focus())},[]),[t0,t1]=(0,i.useState)(!U),[t2,t5]=(0,i.useState)(!1),[t7,t9]=(0,i.useState)(!1),ne=(0,i.useRef)(t0),na=(0,i.useRef)(!1),ns=(0,i.useRef)(!U),nl=(0,i.useRef)(null);ne.current=t0;let no=(j=(m={clientPainted:t2,compactWorkspace:en,requestedOpen:t0}).requestedOpen&&m.clientPainted,{laidOut:m.requestedOpen&&(!m.compactWorkspace||m.clientPainted),presented:j,drawer:j&&m.compactWorkspace}),nd=(0,i.useCallback)(e=>{na.current=e,t1(e),ti(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),nc=(0,i.useRef)(null),nu=(0,i.useRef)(!1),np=(0,i.useRef)(260),nh=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:!1,rightPanelWidth:0}),[]),nm=function(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:a,getMaxWidth:s,growthDirection:l,maxWidth:o,minWidth:d,storageKey:c,widthRef:u}=e,p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(!1),[f,g]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),b=(0,i.useCallback)(()=>Math.min(o,Math.max(d,s())),[s,o,d]),y=(0,i.useCallback)(e=>{var t;let n,r;return t=b(),n=Number.isFinite(e)?e:d,r=Math.max(d,t),Math.round(Math.max(d,Math.min(r,n)))},[b,d]),w=(0,i.useCallback)(e=>{u.current=e,p.current?.style.setProperty(n,`${e}px`)},[n,u]),k=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=y(e),a=i!==u.current;return w(i),g(i),r&&(a||n)&&c4(c,i),i},[w,y,c,u]),j=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),S=(0,i.useCallback)(e=>{let t=h.current;if(t&&t.pointerId===e){h.current=null,j(t),v(!1),k(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[k,j,u]),C=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&S(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),h.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[S,u]),N=(0,i.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let n="right"===l?1:-1,r=y(t.startWidth+(e.clientX-t.startX)*n);w(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[w,y,S,l]),I=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),T=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),$=(0,i.useCallback)(()=>{k(a?.()??r,{forcePersist:!0})},[k,r,a]),R=(0,i.useCallback)(()=>{k(u.current)},[k,u]),E=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===l?"ArrowRight":"ArrowLeft",r="right"===l?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),k(u.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),k(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),k(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),k(b(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),$())},[k,b,l,d,$,u]);return(0,i.useEffect)(()=>{if(m.current)return;m.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(c),t=k(e??a?.()??r,{persist:!1});null!==e&&e!==t&&c4(c,t)},[k,r,a,c]),(0,i.useEffect)(()=>{if(!m.current)return;k(u.current);let e=()=>{k(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[k,u]),(0,i.useEffect)(()=>{if(!x)return;let e=()=>{let e=h.current;e&&S(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[S,x]),(0,i.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,j(e))},[j]),{isResizing:x,panelRef:p,reclampWidth:R,resetWidth:$,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":b(),"aria-valuemin":d,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:$,onKeyDown:E,onLostPointerCapture:M,onPointerCancel:T,onPointerDown:C,onPointerMove:N,onPointerUp:I,role:"separator",tabIndex:0},width:f}}({ariaLabel:Q("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:nh,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:np}),nf=nm.reclampWidth;(0,i.useEffect)(()=>{let e=nl.current;if(e===en)return;t9(!0),null!==e&&(e?na.current=ne.current:ns.current=ne.current),nl.current=en;let t=en?na.current:ns.current;en?nd(t):t1(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>t9(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[en,nd]),(0,i.useEffect)(()=>{t5(!0)},[]),(0,i.useEffect)(()=>{let e=nu.current;if(nu.current=no.drawer,no.drawer){let e=nm.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(uO)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||nc.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[no.drawer,nm.panelRef]),(0,i.useEffect)(()=>{nf()},[nf,tr.activeView]),(0,i.useEffect)(()=>{let e=tj.current;if(!e)return;let t=e=>{tc(t=>{let n=x(e);return t.navigator===n.navigator&&t.deck===n.deck?t:n})};t(e.getBoundingClientRect().width);let n=new ResizeObserver(e=>{let n=e[0]?.contentRect.width;"number"==typeof n&&t(n)});return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>{if(!tw)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>tS.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[tw]),(0,i.useEffect)(()=>{if("command-palette"!==tr.transientLayer)return;let e=tC.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(uO)?.focus()});return()=>cancelAnimationFrame(t)},[tr.transientLayer]),(0,i.useEffect)(()=>{en||"navigator-drawer"!==tr.transientLayer||ti({type:"close-layer"})},[en,tr.transientLayer]),(0,i.useEffect)(()=>{let e=new AbortController;return tg(e=>({...e,complete:!1})),fetch("/api/sessions",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t.sessions))throw Error("Invalid session census");tm(t.sessions),tg({sessions:t.sessions.map(e=>({id:e.id,modified:e.modified})),complete:!0})}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load the complete session census:",e)}),()=>e.abort()},[e_,ev?.id]);let ng=(0,i.useRef)(null),nx=(0,i.useRef)(null),[nv,nb]=(0,i.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),ny=(0,i.useRef)(null),nw=(0,i.useCallback)((e,t,n)=>{ny.current=n,nb(n=>{let r=nH.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),nj=(0,i.useCallback)(e=>{nb(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),ny.current?.(e)},[]),[nS,nC]=(0,i.useState)(null),nN=(0,i.useCallback)(e=>{nC(e)},[]),[nI,nT]=(0,i.useState)(null),[nM,n$]=(0,i.useState)([]),[nR,nE]=(0,i.useState)(null),nL=function(e,{subagents:t,enabled:n}){let[r,a]=(0,i.useState)(uE.h7),[s,l]=(0,i.useState)("floor"),[o,d]=(0,i.useState)(uL.Jq);(0,i.useEffect)(()=>{a(uE.h7)},[e]);let c=(0,i.useCallback)(e=>{a(e),l("target")},[]),u=(0,i.useMemo)(()=>(0,nk.Et)(),[]),p=(0,i.useMemo)(()=>e?t.map(t=>({key:`${e}\u0000${t.id}`,liveId:t.id,status:t.status})):[],[e,t]),h=(0,ij._Z)(p,{sessionId:e??"",client:u,enabled:n&&p.length>0});return{selected:r,select:c,pane:s,setPane:l,accounts:(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;if(!e)return r;for(let i of t){let t=n.get(`${e}\u0000${i.id}`);if(!t)continue;let a=function(e){let{state:t}=e;return("ready-live"===t.kind?t.entries:"ready-archive"===t.kind?(0,ij.RO)(t.entries):e.entries).flatMap(e=>"message"in e?[e.message]:[])}(t);a.some(e=>"assistant"===e.role)&&r.set(i.id,(0,uE.O2)(i,a))}return r})(e,t,h),[h,e,t]),view:o,setView:d}}(ev?.id??null,{subagents:nM,enabled:U}),{ot:nz}=(0,uN.v)(),[nA,nW]=(0,i.useState)(null),[nP,nF]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let n=await t.json(),r=n.fields?.find(e=>"task.maxConcurrency"===e.path),i=r?.value??r?.defaultValue,a="number"==typeof i?i:"string"==typeof i?Number.parseInt(i,10):NaN;!e.signal.aborted&&Number.isFinite(a)&&a>0&&nW(a)}).catch(()=>{}),()=>e.abort()},[]);let[n_,nD]=(0,i.useState)({kind:"idle"}),nO=(0,i.useRef)(null),nH=(0,i.useRef)(ev?.id??null);nH.current=ev?.id??null;let nB=(0,i.useCallback)(e=>{nT(e)},[]),[nU,nq]=(0,i.useState)(null),nK=(0,i.useRef)(null),nV=(0,i.useCallback)((e,t)=>{t_(t).then(()=>{nK.current&&clearTimeout(nK.current),nq(e),nK.current=setTimeout(()=>nq(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nK.current&&clearTimeout(nK.current),nO.current&&clearTimeout(nO.current)},[]),(0,i.useEffect)(()=>()=>eC.current?.abort(),[]);let[nJ,nG]=(0,i.useState)(null),nY=(0,i.useCallback)(e=>{nG(e)},[]),[nZ,nX]=(0,i.useState)(null),[nQ,n0]=(0,i.useState)(null),[n1,n2]=(0,i.useState)(null),[n4,n5]=(0,i.useState)(!1),[n8,n6]=(0,i.useState)("subagents"),n3=(0,i.useCallback)((e,t=!1)=>{ti({type:"select-view",view:e}),n0(null),en&&nd(!1),(t||"chat"===e)&&tN()},[en,tN,nd]),n7=(0,i.useCallback)(e=>{let t=tr.transientLayer===e;n0(null),en&&"navigator-drawer"===tr.transientLayer&&nd(!1),ti({type:"toggle-layer",layer:e}),t&&tN()},[en,tN,nd,tr.transientLayer]),n9=(0,i.useCallback)(()=>{if("chat"!==tr.activeView){n6(tr.activeView),n3("chat",!0);return}n3(n8,!0)},[n8,n3,tr.activeView]),re=(0,i.useCallback)(e=>{n0(null),ti({type:"close-layer"}),en&&nd(!1),eQ.reset(),eY(e)},[en,eQ,nd]),rt=(0,i.useCallback)(()=>{eQ.reset(),eY(null),tN()},[eQ,tN]),rn=ec.refresh,rr=(0,i.useCallback)(()=>{null!==eG&&eQ.check(rn,eG)},[rn,eQ,eG]),ri=(0,i.useCallback)(()=>e6?(e7||(e3(!1),tN()),!0):null!==eG?(rt(),!0):eV?(eJ(!1),tN(),!0):n4?(n5(!1),tN(),!0):nQ?(n0(null),tN(),!0):tr.transientLayer?("navigator-drawer"===tr.transientLayer&&nd(!1),ti({type:"close-layer"}),tN(),!0):"chat"!==tr.activeView&&(ti({type:"select-view",view:"chat"}),tN(),!0),[rt,n4,eG,nQ,e7,e6,tN,nd,eV,tr.activeView,tr.transientLayer]),ra=(0,i.useCallback)(e=>{ti({type:"close-layer"}),en&&nd(!1),n0(t=>t===e?null:e)},[en,nd]),rs=(0,i.useCallback)(()=>{ti({type:"close-layer"}),en&&nd(!1),n0("session")},[en,nd]),rl=(0,i.useCallback)(()=>{if(n0(null),en){let e="navigator-drawer"!==tr.transientLayer;nd(e),e||tN();return}ti({type:"close-layer"}),t1(e=>{let t=!e;return ns.current=t,t})},[en,tN,nd,tr.transientLayer]);(0,i.useEffect)(()=>{if(!nQ||!nx.current)return;let e=()=>{let e=nx.current.getBoundingClientRect();n2({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(nx.current),()=>t.disconnect()},[nQ]);let[ro,rd]=(0,i.useState)([]),[rc,ru]=(0,i.useState)(null),rp=(0,i.useCallback)(()=>{("view-stack"===td.deck||U)&&ti({type:"select-view",view:"chat"}),en&&nd(!1),tN()},[en,U,td.deck,tN,nd]),rh=(0,i.useCallback)((e,t)=>{let n;ng.current?.insertText((n=t?`${e}/`:e).includes(" ")?`@"${n}" `:`@${n} `),rp()},[rp]),rm=(0,i.useCallback)((e,t,n)=>{let r,i,a,s;ng.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`,`${a}${s} `)),rp()},[rp]),rf=J.sessionId,[rg,rx]=(0,i.useState)(null);tF({cwd:ev?.cwd??eL??rg,syncWithOmp:!0});let rv=(0,i.useRef)(null),[rb,ry]=(0,i.useState)(()=>!rf),rw=(0,i.useRef)(!1),rk=(0,i.useRef)(0),rj=(0,i.useCallback)(()=>{rk.current+=1},[]);(0,i.useEffect)(()=>{ev&&function(e,t,n=uF()){if(n)try{let r=u_(n);r[e]=t,n.setItem(uP,JSON.stringify(r))}catch{}}(ev.projectRoot??rv.current??ev.cwd,ev.id)},[ev]),(0,i.useEffect)(()=>{let e=J.requestedCwd;if(!e)return;let t=new AbortController;return eW("validating"),eF(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);rw.current=!0,ez(t.cwd),eW("ready")}).catch(e=>{t.signal.aborted||(eF(e instanceof Error?e.message:String(e)),eW("error"))}),()=>t.abort()},[J]);let rS=(0,i.useCallback)(e=>{let t=++rk.current,n=function(e,t=uF()){if(!t)return null;try{let n=u_(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);n&&fetch("/api/sessions").then(e=>e.ok?e.json():null).then(r=>{if(t!==rk.current)return;let i=r?.sessions.find(e=>e.id===n);if(!i){r&&uD(e);return}(i.projectRoot??i.cwd)!==e?uD(e):(eb(i),eH(e=>e+1),new URLSearchParams(window.location.search).get("session")!==i.id&&K.replace(`?session=${encodeURIComponent(i.id)}`,{scroll:!1}))}).catch(()=>{})},[K]),rC=(0,i.useCallback)((e,t)=>{if(rj(),rx(e),!e)return;let n=t??e,r=rv.current??(ev?ev.projectRoot??ev.cwd:null);if(rv.current=n,rw.current){rw.current=!1;return}r!==n&&(eS.current+=1,eC.current?.abort(),eC.current=null,ew(null),ej(null),eb(null),ez(t=>t&&t!==e?null:t),eH(e=>e+1),nb({sessionId:null,tree:[],leafId:null,navigation:0}),nC(null),n0(null),rd([]),ru(null),ti({type:"select-view",view:"chat"}),rS(n),K.replace(q,{scroll:!1}))},[q,K,ev,rj,rS]),rN=(0,i.useCallback)((e,t,n)=>{ez(null),ej(n),eb(e),nb({sessionId:e.id,tree:[],leafId:null,navigation:0}),eH(e=>e+1),nC(null),ry(!0),en&&!t&&(nd(!1),ti({type:"select-view",view:"chat"})),t&&(rw.current=!0),t||K.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[en,K,nd]),rI=(0,i.useCallback)((e,t=!1)=>{if(rv.current=e.projectRoot??e.cwd,rj(),!t&&ev){let t=(ev.projectRoot??ev.cwd)===(e.projectRoot??e.cwd);if(ev.id===e.id&&t){eS.current+=1,eC.current?.abort(),eC.current=null,ew(null),en&&nd(!1);return}}if(!t&&ey?.id===e.id)return;eS.current+=1;let n=eS.current;if(eC.current?.abort(),t||!ev){eC.current=null,ew(null),rN(e,t,null);return}let r=new AbortController;eC.current=r,ew(e);let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});fetch(`/api/sessions/${encodeURIComponent(e.id)}?${i}`,{cache:"no-store",signal:r.signal}).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();if(r.sessionId!==e.id)throw Error("Session preload returned the wrong session");eS.current===n&&rN(e,!1,r)}).catch(t=>{r.signal.aborted||eS.current!==n||(console.error("Failed to preload session before switching:",t),rN(e,!1,null))}).finally(()=>{eS.current===n&&(eC.current=null,ew(null))})},[rN,rj,en,ey?.id,ev,nd]),rT=(0,i.useCallback)((e,t)=>{eS.current+=1,eC.current?.abort(),eC.current=null,ew(null),ej(null),rj(),eb(null),ez(t),eH(e=>e+1),nb({sessionId:null,tree:[],leafId:null,navigation:0}),nC(null),n0(null),ti({type:"select-view",view:"chat"}),en&&nd(!1),K.replace(q,{scroll:!1})},[q,rj,en,K,nd]),rM=(0,i.useCallback)(e=>{let t=ev?.projectRoot??rv.current??ev?.cwd??rg;if(!t||!ev)return;let n=th.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===ev.id);if(r<0)return;let i=n[r+e];i&&(n0(null),ti({type:"close-layer"}),rI(i),tN())},[rg,th,rI,tN,ev]);f={onNewSession:e=>rT(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>n7("command-palette"),onToggleNavigator:rl,onToggleResources:()=>n3("resource"===tr.activeView?"chat":"resource",!0),onSelectView:e=>n3(e,!0),onCycleView:(0,i.useCallback)(e=>{let t=(c.indexOf(tr.activeView)+e+c.length)%c.length;n3(c[t],!0)},[n3,tr.activeView]),onNavigateSession:rM,onEscape:ri,enabled:!eV&&!e6&&null===eG,activeCwd:rg},(S=(0,i.useRef)(f)).current=f,(0,i.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let n=t.now?.()??Date.now();if(b||e.isComposing||229===e.keyCode||n-y<100)return;let r=e.target,i="u">typeof Element&&r instanceof Element?r:null,a=!!i?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!i?.closest("[data-dismissible-layer], [data-capture-keys], [role='listbox'], [role='menu'], [role='combobox'][aria-expanded='true'], [aria-haspopup][aria-expanded='true']")&&(t.onEscape?.()?(e.preventDefault(),e.stopPropagation()):!(a||i?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(i?.closest("[data-capture-keys]")||!1===t.enabled)return;let s=e.key.toLowerCase(),l=(e.ctrlKey||e.metaKey)&&!e.altKey;if(l&&!e.shiftKey&&"k"===s)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(l&&!e.shiftKey&&"b"===s)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(l&&!e.shiftKey&&"u"===s)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(l&&!e.shiftKey&&/^[1-7]$/.test(s)){if(!t.onSelectView)return;let n=c[Number(s)-1];return n&&(e.preventDefault(),t.onSelectView(n))}l&&e.shiftKey&&("Period"===e.code||"Comma"===e.code)?t.onCycleView&&(e.preventDefault(),t.onCycleView("Period"===e.code?1:-1)):!e.altKey||e.ctrlKey||e.metaKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key?e.ctrlKey&&e.altKey&&!e.metaKey&&"n"===s&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,S.current)},t=()=>w(!0),n=()=>w(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",n,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",n,{capture:!0})}},[]);let r$=(0,i.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&eb(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),rR=(0,i.useCallback)(e=>{rj(),ez(null),eb(e),eD(e=>e+1),r$(e.id),K.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[rj,K,r$]),rE=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&sf({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&rI(e)}})},[rI]),rL=(0,i.useCallback)(e=>{eD(e=>e+1),e5.current?.pending&&e4(e=>e+1),eU(e=>e+1),ev&&r$(ev.id),"completed"===e.outcome&&sh()&&rE({targetSession:ev,title:ev?.name??Q("i18n.sessionComplete"),body:Q("i18n.taskFinished")})},[rE,r$,ev,Q]),rz=(0,i.useCallback)(e=>{var t;sh()&&(t=eg.current,!(!sm(e)||t.has(e.id))&&(t.add(e.id),1)&&rE({targetSession:ev,title:Q("i18n.attentionNeeded"),body:"custom"===e.method?Q("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rE,ev,Q]),rA=(0,i.useCallback)(async()=>{let e=ev?.id;if(e&&"naming"!==n_.kind){nO.current&&clearTimeout(nO.current),n0(null),nD({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok||!n.title)throw Error(n.error||`HTTP ${t.status}`);let r=n.title.trim();if(eD(e=>e+1),nH.current!==e)return;eb(t=>t?.id===e?{...t,name:r}:t),nT(t=>t?.sessionId===e?{...t,sessionName:r}:t),nD({kind:"success"}),nO.current=setTimeout(()=>nD({kind:"idle"}),1800)}catch(t){if(nH.current!==e)return;nD({kind:"error",message:t instanceof Error?t.message:String(t)}),nO.current=setTimeout(()=>nD({kind:"idle"}),5e3)}}},[n_.kind,ev?.id]);(0,i.useEffect)(()=>{nO.current&&clearTimeout(nO.current),nD({kind:"idle"})},[ev?.id]);let rW=(0,i.useCallback)(e=>{rj(),eD(e=>e+1),eH(e=>e+1),ez(null),eb(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),r$(e),K.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[rj,K,r$]),rP=(0,i.useCallback)(()=>{ry(!0)},[]),rF=(0,i.useCallback)(e=>{if(rj(),eD(e=>e+1),ev?.id===e){let e=ev.cwd;eb(null),ez(e??null),eH(e=>e+1),nb({sessionId:null,tree:[],leafId:null,navigation:0}),nC(null),n0(null),ti({type:"select-view",view:"chat"}),tN(),K.replace(q,{scroll:!1})}},[q,rj,tN,ev,K]),r_=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,a=`file:${e}`;rd(n=>{let s=n.find(e=>e.id===a);if(!s)return[...n,{id:a,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:i}];let l=!r||s.sourceSessionId===r,o=!i||s.initialDisplayMode===i;return l&&o?n:n.map(e=>{if(e.id!==a)return e;let t={...e};return r&&(t.sourceSessionId=r),i&&(t.initialDisplayMode=i),t})}),ru(a),ti({type:"select-view",view:"files"}),n0(null),en&&nd(!1)},[en,nd]),rD=(0,i.useCallback)(e=>{r_(e,te(e),{sourceSessionId:ev?.id??null})},[r_,ev?.id]),rO=(0,i.useCallback)(e=>{let t=ro.filter(t=>t.id!==e);rd(t),ru(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===tr.activeView&&n3("chat",!0)},[ro,n3,tr.activeView]),rH=(0,i.useCallback)(()=>{ev&&window.open(`/api/sessions/${encodeURIComponent(ev.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[ev]),rB=eL??(null===ev&&rg?rg:null),rU=null!==ev||null!==rB,rq="chat"!==tr.activeView,rK=ev?.cwd??rB,rV=rb&&!rU,rJ=(0,i.useCallback)((e,t)=>{e5.current=e,e1(e),tn(e.error?Q("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&e3(!1),eK(e=>e+1),eH(e=>e+1))},[Q]);(0,i.useEffect)(()=>{let e=e8.current!==rK;if(e8.current=rK,e&&(e5.current=null,e1(null),e3(!1),tn(null)),!rK)return;let t=e5.current,n=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rK)}`,{signal:n.signal}).then(async e=>{let n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);rJ(n,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>n.abort()},[rJ,rK,e2]);let rG=(0,i.useCallback)(async e=>{if(rK&&!e7){e9(!0),tn(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rK,action:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let r=e5.current;rJ(n,r),(n.trusted||"cancel"===e)&&(e3(!1),tN())}catch(e){tn(e instanceof Error?e.message:String(e))}finally{e9(!1)}}},[rJ,e7,rK,tN]),rY=ro.find(e=>e.id===rc)??null,rZ=rg?te(rg)||rg:null,rX=(ev?.name?.trim()||ev?.firstMessage?.trim()||(rB?Q("i18n.newSession"):rZ)||"CUELO").replace(/\s+/g," ").trim(),rQ=rX.length>96?`${rX.slice(0,93)}…`:rX,r0=rZ?`${rQ} — ${rZ} — CUELO`:`${rQ} — CUELO`,r1=U?`${nz("office.toOffice")} \xb7 ${r0}`:r0,r2=rZ?`${rX} — ${rZ}`:rX,r4=ev?.transient?`${r2} \xb7 ${Q("session.inMemory")}`:r2,r5=nM.filter(e=>"pending"===e.status||"running"===e.status).length,r8=nP?Q("workspace.mainAttention"):tb?Q("workspace.mainWaiting"):tx?Q("workspace.mainWorking"):Q("workspace.mainIdle"),r6=`${nP?"⚠":tb?"○":tx?"●":"○"} Main ${r8} \xb7 Sub ${r5}${nA?`/${nA}`:""}`,r3=(0,i.useCallback)(e=>n3(e,!0),[n3]),r9=U?(0,uE.GM)({main:{provider:nR?.provider??null,modelId:nR?.modelId??null,face:nR?.face??null,state:nP?"attention":tb?"waiting":tx?"working":"idle"},subagents:nM,accounts:nL.accounts,resolveFace:(e,t)=>ni(void 0,e,t)}):null,it=r9?(0,uE.nk)(r9,nL.selected):nL.selected,ir=r9?.participants.find(e=>"main"===e.kind),ii=r9?.participants.find(e=>"maker"===e.kind&&e.key===it),io=U?eu?"target":nL.pane:null,id="floor"===io,ic=rq&&(U||"view-stack"===td.deck),iu=ev?`?session=${encodeURIComponent(ev.id)}`:rB?`?cwd=${encodeURIComponent(rB)}`:"";(0,i.useEffect)(()=>{let e=()=>{document.title!==r1&&(document.title=r1)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[r1]);let ip="ko"===Z?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat"},ih="chat"!==tr.activeView,im=ih?ip[tr.activeView]:ip[n8],ig=(C=nJ&&Number.isFinite(nJ.contextWindow)&&nJ.contextWindow>0?nJ.contextWindow:null,N=nJ&&"number"==typeof nJ.tokens&&Number.isFinite(nJ.tokens)?Math.max(0,nJ.tokens):null,T=null===(I=nJ&&"number"==typeof nJ.percent&&Number.isFinite(nJ.percent)?nJ.percent:null!==N&&null!==C?N/C*100:null)?"normal":I>90?"critical":I>70?"warning":"normal",M=null===N?"?":c2(N),$=null===C?"?":c2(C),E=null===I?"?":`${I.toFixed(0)}%`,{level:T,percent:I,fillPercent:null===I?0:Math.min(100,Math.max(0,I)),readout:null===C?null:`${E} \xb7 ${M}/${$}`,usedLabel:M,limitLabel:$,percentLabel:E}),ix=ig.readout,iv=ix?Q("chat.contextUsageTitle",{used:ig.usedLabel,limit:ig.limitLabel,percent:ig.percentLabel}):null,ib="critical"===ig.level?Q("chat.contextUsageCritical"):"warning"===ig.level?Q("chat.contextUsageWarning"):null,iy=(k=nI?.userMessages,!ev||ev.transient?"unsaved":("number"==typeof k?k:0)>0||ev.messageCount>0?null:"no-messages"),iw="unsaved"===iy?Q("title.unsaved"):"no-messages"===iy?Q("title.noMessages"):null,ik=iw??("error"===n_.kind?n_.message:null),iS="naming"===n_.kind?Q("title.generating"):"success"===n_.kind?Q("title.updated"):"error"===n_.kind?Q("title.failed"):Q("title.generate"),iC=(0,r.jsxs)("div",{id:"workspace-file-view",className:"workspace-file-view",children:[(0,r.jsx)("div",{className:"workspace-file-tabs",children:(0,r.jsx)(lT,{tabs:ro,activeTabId:rc??"",onSelectTab:ru,onCloseTab:rO})}),(0,r.jsx)("div",{className:"workspace-file-content",children:rY?.filePath?(0,r.jsx)(lN,{filePath:rY.filePath,cwd:rg??void 0,sourceSessionId:rY.sourceSessionId,gitRefreshKey:eB,initialDisplayMode:rY.initialDisplayMode,onMentionLines:rm,onAtMention:rh,onOpenFile:e=>r_(e,te(e),{sourceSessionId:rY.sourceSessionId})}):(0,r.jsx)("div",{className:"workspace-file-empty",children:Q("files.noneOpen")})})]}),iN=(0,r.jsx)(cp,{open:"resource"===tr.activeView,sessionId:ev?.id??null,activeTab:ta,onTabChange:ts,usage:ec}),iI=(0,r.jsx)(cZ,{open:"efficiency"===tr.activeView,sessionId:ev?.id??null,activeTab:tl,onTabChange:to}),iT=(0,r.jsx)(dL,{title:ip.process,data:nZ,onOpenFile:rD}),iM=ev?ev.path?ev.path:nI?.sessionId===ev.id&&nI.sessionFile?nI.sessionFile:null:null,i$=(0,r.jsx)(dZ,{title:ip.sidechat,sessionId:ev?.id??null,sessionPath:iM,sessionName:ev?.name,historyStore:tu,flights:tp,sessionCensus:tf,visible:"sidechat"===tr.activeView}),iR=rq?(0,r.jsx)(dE,{activeView:tr.activeView,onViewChange:e=>n3(e),viewLabels:ip,sessionId:ev?.id??null,sessionPath:iM,sessionName:ev?.name,sessionCwd:ev?.cwd??rB??void 0,liveSubagents:nM,processSlot:iT,fileSlot:iC,sideChatSlot:i$,resourceSlot:t??iN,efficiencySlot:iI,visible:!0,onClose:()=>ti({type:"select-view",view:"chat"}),onReturnFocus:tN}):null,iE=e??iR,iL=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ea,{selectedSessionId:ey?.id??ev?.id??null,optimisticSession:ey??ev,onSelectSession:rI,onNewSession:rT,initialSessionId:rf,skipInitialProjectSelection:null!==J.requestedCwd,onInitialRestoreDone:rP,refreshKey:e_,onSessionDeleted:rF,selectedCwd:ev?.cwd??eL??null,onCwdChange:rC,onBackgroundTaskDone:ex,loungePanel:(0,r.jsx)(ug,{lounge:ef,usage:ec,loungeOpen:eu,onOpenLounge:en?()=>nd(!1):void 0}),loungeActive:eu,onLoungeActiveChange:tI}),(0,r.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[eu?null:(0,r.jsx)(ui,{usage:ec,onOpen:()=>{ts("usage"),n3("resource",!1)},onRelogin:re}),(0,r.jsx)(uW,{}),(0,r.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{n0(null),ti({type:"close-layer"}),en&&nd(!1),eJ(!0)},title:Q("common.settings"),style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,background:"none",border:"1px solid var(--border)",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.borderColor="var(--text-dim)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21h-4v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3v-4h.09A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.12.39.33.74.6 1 .3.28.69.42 1.1.4h.09v4h-.09A1.7 1.7 0 0 0 19.4 15Z"})]}),Q("common.settings")]})]})]}),iz=tH&&tU&&tU.requestId===tH.requestId&&tU.deploymentCompleted?tU:null,iA=iz?.cleanup??null,iW=iz&&!tH?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:null};let t=`${e.completedCount}/${e.totalCount} 완료`,n=`${Math.round(e.elapsedSeconds)}초 경과`;return"running"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 중",detail:`${t} \xb7 ${n} \xb7 현재 ${e.currentTarget??"대상 선택 중"}`,dismissible:!1,autoHideMs:null}:"failed"===e.status?{tone:"warning",title:"업데이트 완료 \xb7 산출물 정리 실패",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건 \xb7 실패 ${e.failureCount}건. 업데이트 자체는 성공했고 실패 증거는 보존했습니다.`,dismissible:!0,autoHideMs:sC(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:sC(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sC(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sC(e.status)}}(iA):null;return(0,r.jsxs)(r.Fragment,{children:[t$?(0,r.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,r.jsxs)("div",{className:"server-restart-card",children:[(0,r.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,r.jsx)("strong",{children:Q("restart.title")}),(0,r.jsx)("span",{children:Q(tA?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:tj,className:"workspace-shell","data-active-view":tr.activeView,"data-deck-mode":td.deck,"data-deck-visible":rq,"data-chat-wide":e$?"true":void 0,children:[(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${no.drawer?" is-open":""}${t2?"":" sidebar-mobile-pending"}${t7?" sidebar-mode-shift":""}`,onClick:()=>{nd(!1),tN()}}),(0,r.jsx)("div",{ref:nm.panelRef,id:"session-sidebar",className:`sidebar-container${no.laidOut?" sidebar-open":" sidebar-closed"}${t2?"":" sidebar-mobile-pending"}${t7?" sidebar-mode-shift":""}${nm.isResizing?" sidebar-resizing":""}`,"aria-hidden":en&&!no.presented,inert:en&&!no.presented,style:{"--sidebar-width":`${nm.width}px`},children:iL}),no.laidOut&&(0,r.jsx)("div",{...nm.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${nm.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${Q("layout.resizeSidebar")}: ${Q("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":tr.activeView,"aria-hidden":no.drawer,inert:no.drawer,children:[(0,r.jsxs)("div",{ref:nx,className:"workspace-header-stack",children:[iW&&tH&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":iW.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:iW.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:iW.detail}),iW.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tB(sM(tH.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tP&&!(iW&&tH)&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":"positive",role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:Q("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:Q("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tD(!1),"aria-label":Q("restart.returnedDismiss"),children:Q("i18n.close")})]}),(0,r.jsx)(dv,{variant:"banner",locale:Z,...et}),(0,r.jsxs)("header",{className:"workspace-header-seam",children:[(0,r.jsx)(s.r,{ref:nc,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:rl,"aria-controls":"session-sidebar","aria-expanded":no.presented,title:no.presented?Q("sidebar.hide"):Q("sidebar.show"),"aria-label":no.presented?Q("sidebar.hide"):Q("sidebar.show"),children:no.presented?(0,r.jsx)(l.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}):(0,r.jsx)(l.In,{size:"18px",svg:(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})})}),(0,r.jsxs)("div",{className:"workspace-session-identity",title:r4,children:[(0,r.jsx)("strong",{children:rQ}),(0,r.jsx)("span",{"aria-live":"polite",children:r6})]}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===n_.kind?n_.message:""}),rU&&e0?.requiresTrust&&!e0.trusted&&(0,r.jsxs)(s.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{tn(e0.error?Q("trust.applyFailed",{error:e0.error}):null),n0(null),ti({type:"close-layer"}),e3(!0),e0.pending&&e4(e=>e+1)},title:Q("grant"===e0.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":Q("grant"===e0.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),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:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),!en&&(0,r.jsx)("span",{children:Q("trust.resourcesNotLoaded")})]}),rU&&ix&&(0,r.jsxs)(s.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:rs,"aria-expanded":"session"===nQ,title:iv??Q("session.title"),"aria-label":ib?`${iv}. ${ib}`:iv??void 0,children:[(0,r.jsx)("span",{className:"workspace-context-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"workspace-context-meter-fill","data-level":ig.level,style:{inlineSize:`${ig.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":ig.level,children:ix})]}),U?(0,r.jsx)(s.r,{asChild:!0,className:"workspace-header-action",variant:"ghost",size:"small",children:(0,r.jsx)("a",{href:`/${iu}`,"data-office-link":"chat",title:nz("office.toChatTitle"),children:nz("office.toChat")})}):(0,r.jsx)(s.r,{asChild:!0,className:"workspace-header-action",variant:"ghost",size:"small",children:(0,r.jsxs)("a",{href:`/office${iu}`,target:"_blank",rel:"noopener","data-office-link":"office",title:nz("office.toOfficeTitle"),"aria-label":`${nz("office.toOffice")} (${nz("office.newTab")})`,children:[nz("office.toOffice"),(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:"M14 4h6v6"}),(0,r.jsx)("path",{d:"M20 4 11 13"}),(0,r.jsx)("path",{d:"M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"})]})]})}),rU&&!U&&(0,r.jsx)(o.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:ih,onPressedChange:n9,"aria-controls":"workspace-auxiliary-panel",title:"ko"===Z?"보조 패널":"Auxiliary panel",children:im}),(0,r.jsxs)(d.k.Root,{open:n4,onOpenChange:e=>n5(e),placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(d.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===Z?"더 보기":"More","aria-label":"ko"===Z?"더 보기":"More",children:(0,r.jsx)(l.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"5",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"1"})]})})})}),(0,r.jsx)(d.k.Positioner,{children:(0,r.jsx)(d.k.Content,{"aria-label":"ko"===Z?"세션 및 환경 메뉴":"Session and environment menu",children:(0,r.jsxs)(d.k.ScrollArea,{children:[(0,r.jsxs)(d.k.Group,{children:[(0,r.jsx)(d.k.GroupLabel,{children:"ko"===Z?"세션":"Session"}),(0,r.jsx)(d.k.Item,{onClick:rs,children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("session.title")})})}),(0,r.jsx)(d.k.Item,{onClick:rH,disabled:!ev,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:Q("history.label")}),!ev&&(0,r.jsx)(d.k.ItemDescription,{children:Q("history.unsaved")})]})}),(0,r.jsx)(d.k.Item,{onClick:()=>void rA(),disabled:null!==iw||"naming"===n_.kind,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:iS}),ik&&(0,r.jsx)(d.k.ItemDescription,{children:ik})]})}),(0,r.jsx)(d.k.Item,{onClick:()=>ra("branches"),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("i18n.branches")})})}),(0,r.jsx)(d.k.Item,{onClick:()=>ra("system"),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("system.label")})})})]}),(0,r.jsxs)(d.k.Group,{children:[(0,r.jsx)(d.k.GroupLabel,{children:"ko"===Z?"환경":"Environment"}),(0,r.jsx)(dv,{variant:"menu",locale:Z,...et}),(0,r.jsx)(d.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();Y({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("light"===G?"theme.light":"dark"===G?"theme.dark":"theme.auto")})})}),ee.map(e=>(0,r.jsx)(d.k.Item,{role:"menuitemradio","aria-checked":Z===e.id,onClick:()=>X(e.id),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:e.label})})},e.id)),(0,r.jsx)(d.k.Item,{onClick:()=>{n0(null),ti({type:"close-layer"}),en&&nd(!1),eJ(!0)},children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:Q("common.settings")})})})]})]})})})]})]}),nQ&&n1&&(0,r.jsxs)("div",{style:{position:"fixed",top:n1.top,left:n1.left,width:n1.width,maxHeight:`calc(100dvh - ${n1.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===nQ&&(0,r.jsx)("div",{className:"workspace-top-panel","aria-label":Q("i18n.branches"),children:(0,r.jsx)(c1,{tree:nv.sessionId===(ev?.id??null)?nv.tree:[],activeLeafId:nv.sessionId===(ev?.id??null)?nv.leafId:null,onLeafChange:nj,hasSession:!!ev})}),"system"===nQ&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:nS?(0,r.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:nS}):""===nS?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Q("system.empty")}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Q("system.load")})}),"session"===nQ&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:nI?(L=nI.totalActiveMs??0,z=[...nI.sessionName?[{label:Q("session.name"),value:nI.sessionName,copyField:null}]:[],{label:Q("session.file"),value:nI.sessionFile??Q("session.inMemory"),copyField:"file"},{label:Q("session.id"),value:nI.sessionId,copyField:"id"},...L>0?[{label:Q("session.totalActive"),value:(e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`})(L),copyField:null}]:[]],P=[[Q("session.user"),nI.userMessages.toLocaleString(Z)],[Q("session.assistant"),nI.assistantMessages.toLocaleString(Z)],[Q("session.toolCalls"),nI.toolCalls.toLocaleString(Z)],[Q("session.toolResults"),nI.toolResults.toLocaleString(Z)],[Q("session.total"),nI.totalMessages.toLocaleString(Z)]],F=[[Q("session.input"),nI.tokens.input.toLocaleString(Z)],[Q("session.output"),nI.tokens.output.toLocaleString(Z)],...nI.tokens.cacheRead>0?[[Q("session.cacheRead"),nI.tokens.cacheRead.toLocaleString(Z)]]:[],...nI.tokens.cacheWrite>0?[[Q("session.cacheWrite"),nI.tokens.cacheWrite.toLocaleString(Z)]]:[],[Q("session.total"),nI.tokens.total.toLocaleString(Z)]],_=nJ??nI.contextUsage,D=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),O=[...nI.cost>0?[[Q("session.cost"),`$${nI.cost.toFixed(4)}`]]:[],..._?.contextWindow?[[Q("session.context"),`${null!==_.tokens?D(_.tokens):"?"} / ${D(_.contextWindow)}${null!==_.percent?` \xb7 ${_.percent.toFixed(1)}%`:""}`]]:[],...nI.tokens.cacheRead+nI.tokens.cacheWrite>0&&nI.tokens.cacheRead+nI.tokens.cacheWrite+nI.tokens.input>0?[[Q("session.cacheHitRate"),`${(nI.tokens.cacheRead/(nI.tokens.cacheRead+nI.tokens.cacheWrite+nI.tokens.input)*100).toFixed(1)}%`]]:[]],H=(e,t,n="left",i=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:i?"max-content max-content":"auto minmax(0, 1fr)",columnGap:i?14:12,rowGap:4,justifyContent:i?"start":void 0},children:t.map(([t,a])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:a})]},`${e}:${t}`))})]}),B=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:Q("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:z.map(e=>{var t,n;let i;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?(t=e.copyField,n=e.value,i=nU===t,(0,r.jsx)("button",{type:"button",title:i?Q("session.copied"):Q("file"===t?"session.copyFile":"session.copyId"),onClick:()=>nV(t,n),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:i?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=i?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:i?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})):null})]},`session-info:${e.label}`)})})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:en?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:en?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[B,H(Q("session.messages"),P),H(Q("session.tokens"),[...F,...O],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Q("session.load")})})]})]}),(0,r.jsxs)("div",{className:`chat-content-layout${U?` ${uT().page}`:""}`,"data-office-pane":U?io:void 0,children:[r9&&"floor"===io?(0,r.jsx)(uC.t,{roster:r9,selected:it,onSelect:nL.select,view:nL.view,onViewChange:nL.setView}):null,(0,r.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-lounge-open":eu?"true":void 0,inert:id||void 0,children:[rU?(0,r.jsx)(s7,{session:ev,newSessionCwd:rB,initialSessionData:ek,transitioning:null!==ey,onAgentEnd:rL,onAttentionNeeded:rz,onSessionCreated:rR,onSessionForked:rW,modelsRefreshKey:eq,chatInputRef:ng,onBranchDataChange:nw,onSystemPromptChange:nN,onSessionStatsChange:nB,onSessionStatsPanelOpen:rs,onContextUsageChange:nY,onSubagentsChange:n$,onMainIdentityChange:nE,onOpenWorkspaceView:r3,onProcessLogChange:nX,onOpenFile:rD,transcriptReplacement:ic?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iE}):ii&&ir?(0,r.jsx)(uR,{participant:ii,recipient:ir,sessionId:ev?.id??null,cwd:ev?.cwd??rB??void 0,onBackToMain:()=>nL.select(uE.h7),onOpenFile:rD},ii.key):null,onComposerFocusChange:tT,onSessionBusyChange:tv,onWaitingChange:ty,onAttentionChange:nF,soundEnabled:er,onSoundToggle:ei,playCueSound:es,preloadCueSound:el,unlockAudio:eo,jumpRequest:eN,onJumpHandled:eM},eO):ic?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iE}):"validating"===eA?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:Q("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd})]}):"error"===eA?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--danger)"},children:Q("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eP})]}):rV?rg?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:Q("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:Q("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),Q("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),Q("workspace.addModels")]})]})]}):null,eh?(0,r.jsx)(uj,{lounge:ef,visible:eu,onBack:()=>tI(!1)}):null]}),"pinned"===td.deck&&rq&&!U&&(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:iE})]}),r9&&io?(0,r.jsx)(uS.FC,{roster:r9,selected:it,onSelect:e=>{eu&&tI(!1),nL.select(e)},pane:io,onShowFloor:()=>{eu&&tI(!1),nL.setPane("floor")},selectionGone:nL.selected!==it}):null]}),"command-palette"===tr.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(ti({type:"close-layer"}),tN())},children:(0,r.jsxs)("div",{ref:tC,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:tQ,"aria-label":"ko"===Z?"명령 팔레트":"Command palette",children:[(0,r.jsxs)("header",{children:[(0,r.jsx)("strong",{children:"ko"===Z?"명령 팔레트":"Command palette"}),(0,r.jsx)("kbd",{children:"Ctrl K"})]}),(0,r.jsx)(la,{t:Q,onPick:(e,t)=>{ti({type:"close-layer"}),n3("chat",!1),eT.current+=1,eI({id:eT.current,sessionId:e.id,entryId:t.entryId}),rI(e)}}),(0,r.jsxs)("div",{className:"workspace-command-list",children:[c.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>n3(e,!0),children:[(0,r.jsx)("span",{children:ip[e]}),(0,r.jsx)("small",{children:tr.activeView===e?"ko"===Z?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{ts(e),n3("resource",!1)},children:[(0,r.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,r.jsx)("small",{children:ip.resource})]},e)),(0,r.jsxs)("button",{type:"button",onClick:rl,children:[(0,r.jsx)("span",{children:no.presented?Q("sidebar.hide"):Q("sidebar.show")}),(0,r.jsx)("small",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:eE,children:(0,r.jsx)("span",{children:Q(e$?"palette.wideChatOff":"palette.wideChatOn")})}),(0,r.jsx)("button",{type:"button",onClick:()=>{ti({type:"close-layer"}),eJ(!0)},children:(0,r.jsx)("span",{children:Q("common.settings")})})]})]})})]}),eV&&(0,r.jsx)(df,{cwd:rK,sessionId:ev?.id??null,onClose:()=>{eJ(!1),e4(e=>e+1),tN()},onModelsChanged:()=>eK(e=>e+1),onReloaded:()=>eH(e=>e+1)}),null!==eG&&(0,r.jsx)(oE,{cwd:rK,onClose:rt,onModelsChanged:()=>eK(e=>e+1),relogin:{target:eG,outcome:eZ,onLoginSucceeded:rr}}),e6&&rK&&(0,r.jsx)(db,{cwd:rK,busy:e7,scheduled:e0?.pending==="grant",error:tt,onCancel:()=>{e7||(e3(!1),tN())},onConfirm:()=>void rG("grant"),onCancelSchedule:()=>void rG("cancel")})]})}},69575:(e,t,n)=>{Promise.resolve().then(n.bind(n,32321)),Promise.resolve().then(n.bind(n,92176))},98795:e=>{e.exports={root:"SearchableSelect_root__FMhaH",trigger:"SearchableSelect_trigger__eqMdt",value:"SearchableSelect_value__eJ2RU",placeholder:"SearchableSelect_placeholder__Hkg33",chevron:"SearchableSelect_chevron__DSTnM",popover:"SearchableSelect_popover__5VxMd",searchWrap:"SearchableSelect_searchWrap__IoKKk",searchIcon:"SearchableSelect_searchIcon__A6f0C",search:"SearchableSelect_search__W_1al",options:"SearchableSelect_options__tjHyi",option:"SearchableSelect_option__LRRH9",optionCopy:"SearchableSelect_optionCopy__W87H8",optionLabel:"SearchableSelect_optionLabel__G7jIg",optionDescription:"SearchableSelect_optionDescription__cE_cC",check:"SearchableSelect_check__1Likw",empty:"SearchableSelect_empty__vZzXQ"}}}]);