cuelo 0.6.8 → 0.7.0

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 (66) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +14 -14
  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/sessions/search/route.js +1 -1
  26. package/.next/server/app/api/updates/route.js +1 -1
  27. package/.next/server/app/index.html +1 -1
  28. package/.next/server/app/index.rsc +4 -4
  29. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  30. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  31. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  32. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  33. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  34. package/.next/server/app/page.js +6 -6
  35. package/.next/server/app/page_client-reference-manifest.js +1 -1
  36. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  37. package/.next/server/app/recover.html +1 -1
  38. package/.next/server/app/recover.rsc +2 -2
  39. package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
  40. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  41. package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
  42. package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
  43. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  44. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  45. package/.next/server/app-paths-manifest.json +14 -14
  46. package/.next/server/chunks/6429.js +2 -2
  47. package/.next/server/middleware-build-manifest.js +1 -1
  48. package/.next/server/pages/404.html +1 -1
  49. package/.next/server/pages/500.html +1 -1
  50. package/.next/server/server-reference-manifest.json +1 -1
  51. package/.next/static/chunks/app/{layout-50d78c1f0e021377.js → layout-89b7963cbc4da94d.js} +1 -1
  52. package/.next/static/chunks/app/page-042cc56cc090bf73.js +22 -0
  53. package/.next/trace +105 -105
  54. package/.next/trace-build +1 -1
  55. package/README.md +12 -7
  56. package/Tools/CUELO_Setup/files/native-runtime-patch.js +5 -5
  57. package/Tools/OMP_Global_Config/agent/extensions/jev-runtime.ts +55 -13
  58. package/Tools/OMP_Global_Config/agent/extensions/lib/maker-routing.ts +57 -12
  59. package/Tools/OMP_Global_Config/agent/extensions/lib/routing-ledger.ts +36 -7
  60. package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +504 -54
  61. package/bin/prepare-runtime.js +37 -6
  62. package/install.mjs +3 -1
  63. package/package.json +8 -7
  64. package/.next/static/chunks/app/page-4c2544dfbb3d1f9a.js +0 -22
  65. /package/.next/static/{hPKzLPSEaHxrT4rE0H1XO → JfkwRK2BKBsxwumh964am}/_buildManifest.js +0 -0
  66. /package/.next/static/{hPKzLPSEaHxrT4rE0H1XO → JfkwRK2BKBsxwumh964am}/_ssgManifest.js +0 -0
@@ -1,22 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2730:(e,t,n)=>{"use strict";function r(e,t,n,i={}){let s=n[e]?.[t]??n.en?.[t];return void 0===s?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(s,i)}function i(e,t,n=new Date){let r=(e instanceof Date?e:new Date(e)).getTime()-n.getTime(),s=Math.abs(r),[a,o]=s<6e4?["second",1e3]:s<36e5?["minute",6e4]:s<864e5?["hour",36e5]:["day",864e5],l=Math.round(r/o);return new Intl.RelativeTimeFormat(t,{numeric:"always"}).format(l,a)}n.d(t,{fw:()=>i,u0:()=>r})},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"}},13481:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>dB});var r=n(95155),i=n(12115),s=n(73321),a=n(16871),o=n(81886),l=n(68890),c=n(66919);let d=["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(d.map(e=>[e,!0]));function g(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function f(e,t){switch(t.type){case"select-view":return{activeView:g(t.view),transientLayer:null};case"open-layer":return{activeView:g(e.activeView),transientLayer:t.layer};case"toggle-layer":return{activeView:g(e.activeView),transientLayer:e.transientLayer===t.layer?null:t.layer};case"close-layer":return{activeView:g(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 T(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=T(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 N(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(T(e.key),e.order);let r=[...e],i=new Set(e.map(T));for(let e of t){let t=T(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(T(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 R=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function M(e){let t=e.match(R);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var E=n(92176);let $=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let A=L("(max-width: 640px)"),P=L($);function F(){return!1}function z(){return(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,F)}var W=n(47650);async function D(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 O(){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 B(){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 _({onCancel:e,onSelect:t,busy:n=!1,error:s}){let{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(""),[g,f]=(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 D(e),n=t.path??e??"/";d(n),p(t.parentPath??null),m(n),f(t.directories??[]),v(t.drives??null)}catch(e){y(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),j()},[j]);let S=h.trim()!==c,C=!!c&&!S&&!n,T=!!u||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,W.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":a("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:a("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:a("i18n.close"),"aria-label":a("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=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||!T,title:a("directoryPicker.goToParent"),"aria-label":a("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:a("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value: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:a("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!h.trim()?"default":"pointer",opacity:w||!h.trim()?.6:1},children:a("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("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)(B,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noDrives")})}):g.length>0?g.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)(O,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:a("directoryPicker.noSubdirectories")}),(b||s)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:b??s})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:a("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!C,title:a(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:a(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}function H({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:s}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:'"Plus Jakarta Sans", Geist, ui-sans-serif, system-ui, sans-serif',fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...s},children:e})]})}var U=n(2730);let q={ko:{"lounge.tab":"단톡방","lounge.title":"단톡방","lounge.roomSwitch":"단톡방 켜기","lounge.roomOn":"켜짐","lounge.roomOff":"꺼짐","lounge.roomOffHint":"방이 꺼져 있어요. 켜기 전에는 아무도 호출되지 않아요.","lounge.members":"멤버","lounge.membersCount":"{active}/{total}명 참여","lounge.participate":"{name} 참여","lounge.state.off":"쉬는 중","lounge.state.idle":"대기","lounge.state.reading":"보는 중","lounge.state.speaking":"말하는 중","lounge.state.working":"일하는 중","lounge.state.offline":"오프라인","lounge.usage.weekly":"주간","lounge.usage.weeklyTier":"주간 \xb7 {tier}","lounge.usage.none":"사용량 보고 없음","lounge.usage.loading":"사용량 확인 중","lounge.usage.blocked":"차단","lounge.usage.spent":"소진","lounge.usage.resets":"{when} 리셋","lounge.account.change":"계정 설정","lounge.account.for":"{name}의 단톡방 계정","lounge.account.choose":"단톡방 계정을 고르세요","lounge.account.missing":"연결 끊김 \xb7 ID {id}","lounge.account.hint":"단톡방 계정은 이 방에서만 써요. 작업 세션의 계정은 바뀌지 않아요.","lounge.account.required":"계정을 고르면 사용량이 보여요","lounge.settings":"방 설정","lounge.pace":"대화 속도","lounge.pace.slow":"느리게","lounge.pace.normal":"보통","lounge.pace.active":"활발","lounge.sleep":"자동 잠들기","lounge.sleepMinutes":"{minutes}분","lounge.autoTalk":"먼저 말 걸기","lounge.autoTalkHint":"조용할 때 멤버가 먼저 한마디 해요. 속도 간격마다 한 번, 잠들면 멈춰요.","lounge.asleep":"잠든 상태예요. 메시지를 보내면 깨어나요.","lounge.sleepAt":"{time}에 잠들어요","lounge.calls":"최근 {window} 호출 {used}/{limit}","lounge.perTurn":"메시지당 최대 {limit}번 응답","lounge.open":"대화 보기","lounge.back":"작업으로","lounge.connecting":"연결하는 중…","lounge.reconnecting":"연결이 끊겨 다시 연결하는 중이에요.","lounge.loadFailed":"단톡방을 불러오지 못했어요: {error}","lounge.actionFailed":"요청을 처리하지 못했어요: {error}","lounge.roomOffBanner":"방이 꺼져 있어 메시지를 보낼 수 없어요.","lounge.turnOn":"방 켜기","lounge.empty":"아직 대화가 없어요. 첫 메시지를 보내 보세요.","lounge.you":"나","lounge.placeholder":"메시지 보내기 \xb7 @로 멘션","lounge.placeholderOff":"방을 켜면 대화할 수 있어요","lounge.composer":"단톡방 메시지","lounge.send":"보내기","lounge.stop":"중단","lounge.speaking":"{name} 입력 중…","lounge.queued":"다음: {names}","lounge.reply":"답장","lounge.replyTo":"{name}에게 답장","lounge.cancelReply":"답장 취소","lounge.react":"반응 추가","lounge.reaction":"{emoji} {count}명","lounge.missingMessage":"이전 메시지","lounge.mentionList":"멘션할 멤버","lounge.messages":"단톡방 대화","lounge.textLimit":"{count}/{max}자"},en:{"lounge.tab":"Lounge","lounge.title":"Lounge","lounge.roomSwitch":"Turn on lounge","lounge.roomOn":"On","lounge.roomOff":"Off","lounge.roomOffHint":"The room is off. Nobody is called until you turn it on.","lounge.members":"Members","lounge.membersCount":"{active}/{total} joined","lounge.participate":"{name} joins","lounge.state.off":"Resting","lounge.state.idle":"Idle","lounge.state.reading":"Reading","lounge.state.speaking":"Speaking","lounge.state.working":"Working","lounge.state.offline":"Offline","lounge.usage.weekly":"Weekly","lounge.usage.weeklyTier":"Weekly \xb7 {tier}","lounge.usage.none":"No usage reported","lounge.usage.loading":"Checking usage","lounge.usage.blocked":"Blocked","lounge.usage.spent":"Used up","lounge.usage.resets":"Resets {when}","lounge.account.change":"Account","lounge.account.for":"Lounge account for {name}","lounge.account.choose":"Choose a lounge account","lounge.account.missing":"Disconnected \xb7 ID {id}","lounge.account.hint":"Lounge accounts are used only in this room. Work session accounts stay unchanged.","lounge.account.required":"Choose an account to see usage","lounge.settings":"Room settings","lounge.pace":"Pace","lounge.pace.slow":"Slow","lounge.pace.normal":"Normal","lounge.pace.active":"Lively","lounge.sleep":"Fall asleep after","lounge.sleepMinutes":"{minutes} min","lounge.autoTalk":"Start conversations","lounge.autoTalkHint":"When it is quiet, a member speaks first — once per pace interval, never while asleep.","lounge.asleep":"Asleep. Send a message to wake the room.","lounge.sleepAt":"Falls asleep at {time}","lounge.calls":"Calls in last {window}: {used}/{limit}","lounge.perTurn":"Up to {limit} replies per message","lounge.open":"Open chat","lounge.back":"Back to work","lounge.connecting":"Connecting…","lounge.reconnecting":"Connection lost. Reconnecting.","lounge.loadFailed":"Could not load the lounge: {error}","lounge.actionFailed":"Request failed: {error}","lounge.roomOffBanner":"The room is off, so messages cannot be sent.","lounge.turnOn":"Turn on","lounge.empty":"No messages yet. Send the first one.","lounge.you":"You","lounge.placeholder":"Message \xb7 @ to mention","lounge.placeholderOff":"Turn the room on to chat","lounge.composer":"Lounge message","lounge.send":"Send","lounge.stop":"Stop","lounge.speaking":"{name} is typing…","lounge.queued":"Next: {names}","lounge.reply":"Reply","lounge.replyTo":"Replying to {name}","lounge.cancelReply":"Cancel reply","lounge.react":"Add reaction","lounge.reaction":"{emoji} {count}","lounge.missingMessage":"Earlier message","lounge.mentionList":"Members to mention","lounge.messages":"Lounge conversation","lounge.textLimit":"{count}/{max}"},"zh-CN":{"lounge.tab":"群聊","lounge.title":"群聊","lounge.roomSwitch":"开启群聊","lounge.roomOn":"已开启","lounge.roomOff":"已关闭","lounge.roomOffHint":"群聊已关闭。开启前不会调用任何成员。","lounge.members":"成员","lounge.membersCount":"{active}/{total} 人参与","lounge.participate":"{name} 参与","lounge.state.off":"休息中","lounge.state.idle":"待命","lounge.state.reading":"正在看","lounge.state.speaking":"正在发言","lounge.state.working":"工作中","lounge.state.offline":"离线","lounge.usage.weekly":"每周","lounge.usage.weeklyTier":"每周 \xb7 {tier}","lounge.usage.none":"无用量报告","lounge.usage.loading":"正在确认用量","lounge.usage.blocked":"已阻止","lounge.usage.spent":"已用尽","lounge.usage.resets":"{when} 重置","lounge.account.change":"账号设置","lounge.account.for":"{name} 的群聊账号","lounge.account.choose":"请选择群聊账号","lounge.account.missing":"已断开 \xb7 ID {id}","lounge.account.hint":"群聊账号仅用于本群聊,工作会话的账号不会改变。","lounge.account.required":"选择账号后显示用量","lounge.settings":"群聊设置","lounge.pace":"对话节奏","lounge.pace.slow":"慢","lounge.pace.normal":"普通","lounge.pace.active":"活跃","lounge.sleep":"自动休眠","lounge.sleepMinutes":"{minutes} 分钟","lounge.autoTalk":"主动开口","lounge.autoTalkHint":"安静时由成员先说一句。每个节奏间隔一次,休眠后停止。","lounge.asleep":"已休眠。发送消息即可唤醒。","lounge.sleepAt":"{time} 休眠","lounge.calls":"最近 {window} 调用 {used}/{limit}","lounge.perTurn":"每条消息最多 {limit} 次回复","lounge.open":"查看对话","lounge.back":"返回工作","lounge.connecting":"正在连接…","lounge.reconnecting":"连接已断开,正在重新连接。","lounge.loadFailed":"无法加载群聊:{error}","lounge.actionFailed":"请求失败:{error}","lounge.roomOffBanner":"群聊已关闭,无法发送消息。","lounge.turnOn":"开启","lounge.empty":"还没有消息。发送第一条吧。","lounge.you":"我","lounge.placeholder":"发送消息 \xb7 用 @ 提及","lounge.placeholderOff":"开启群聊后即可对话","lounge.composer":"群聊消息","lounge.send":"发送","lounge.stop":"停止","lounge.speaking":"{name} 正在输入…","lounge.queued":"接下来:{names}","lounge.reply":"回复","lounge.replyTo":"回复 {name}","lounge.cancelReply":"取消回复","lounge.react":"添加表情","lounge.reaction":"{emoji} {count} 人","lounge.missingMessage":"之前的消息","lounge.mentionList":"可提及的成员","lounge.messages":"群聊对话","lounge.textLimit":"{count}/{max}"}};function V(){let{locale:e}=(0,E.s)();return{lt:(0,i.useCallback)((t,n)=>(0,U.u0)(e,t,q,n),[e]),locale:e}}function K(e,t){let n=/^([^(]+)\(([^)]+)\)$/.exec(e.trim());return n?"ko"===t?n[2]:n[1]:e}let J="omp-web:unread-session-ids",G="omp-web:pinned-session-ids",Y="omp-web:removed-projects";function Z(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 X(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function Q({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 ee({open:e,children:t,style:n}){let[s,a]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(a(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>a(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),s)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"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 et="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function en(){let[e,t]=(0,i.useState)(!1),[n,s]=(0,i.useState)(!1),a=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),s=(0,i.useRef)(null),a=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);a.current=0;let n=4*e.length,i=()=>{a.current+=1;let t=Math.floor(a.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:et[Math.floor(Math.random()*et.length)]).join("")),a.current<n?s.current=requestAnimationFrame(i):r(e)};return s.current=requestAnimationFrame(i),()=>{s.current&&cancelAnimationFrame(s.current)}},[e,t]),n}(e?"0.6.8/18.4.4":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),s(!0),setTimeout(()=>s(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,i.useCallback)(()=>{a.current&&clearTimeout(a.current);let t=!e;l(t),t&&(a.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:c,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)(H,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",letterSpacing:"-0.01em"}:void 0})})}async function er(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 ei({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:s,initialSessionId:a,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,loungePanel:m,loungeActive:g=!1,onLoungeActiveChange:f}){let x,{lt:v}=V(),{t:b,locale:y}=(0,E.s)(),w=z(),[R,M]=(0,i.useState)([]),$=t&&!R.some(e=>e.id===t.id)?[t,...R]:R,[L,A]=(0,i.useState)(!0),[P,F]=(0,i.useState)(null),[W,D]=(0,i.useState)(null),[O,B]=(0,i.useState)(""),[H,U]=(0,i.useState)(""),[q,K]=(0,i.useState)("projects"),[et,ea]=(0,i.useState)(()=>new Set),[ed,eu]=(0,i.useState)(()=>new Set),[eh,em]=(0,i.useState)(null),[eg,ef]=(0,i.useState)(null),[ex,ev]=(0,i.useState)({version:1,projects:[]}),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(!1),[ej,eS]=(0,i.useState)(!1),[eC,eT]=(0,i.useState)(null),[eI,eN]=(0,i.useState)(""),[eR,eM]=(0,i.useState)(!1),[eE,e$]=(0,i.useState)(null),[eL,eA]=(0,i.useState)(""),[eP,eF]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(null),[eD,eO]=(0,i.useState)(!1),[eB,e_]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(!1),[eK,eJ]=(0,i.useState)(""),[eG,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(null),e1=(0,i.useRef)(null),e2=(0,i.useRef)(null),e8=(0,i.useRef)(null),e4=(0,i.useRef)(!1),e5=(0,i.useRef)(!1),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(()=>new Set),[te,tt]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(J);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}})()),[tn,tr]=(0,i.useState)(()=>new Set),ti=(0,i.useRef)(new Set),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(null);(0,i.useEffect)(()=>{tr(function(){try{let e=window.localStorage.getItem(G);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 to=(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}`);ev(await e.json())}catch{ev({version:1,projects:[]})}finally{ey(!0)}},[]);(0,i.useEffect)(()=>{to()},[to,c]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(Y)}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 er(n.map(e=>({key:T(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(Y)}catch{}await to()})()},[to]);let tl=(0,i.useCallback)(async e=>{if(e5.current)throw Error("Project update in progress");e5.current=!0,eM(!0);try{await er(e),await to()}finally{e5.current=!1,eM(!1)}},[to]);(0,i.useEffect)(()=>{eC&&e8.current?.select()},[eC]);let tc=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&A(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();M(r.sessions),ts.current||e9(new Set(r.runningSessionIds??[])),F(null),e||(e3(!0),ta.current&&clearTimeout(ta.current),ta.current=setTimeout(()=>e3(!1),2e3))}catch(e){F(String(e))}finally{e&&A(!1)}},[]),td=(0,i.useCallback)(e=>{tt(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tr(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),d?.(e),tc()},[tc,d]),[tu,tp]=(0,i.useState)(null),[th,tm]=(0,i.useState)(!1),[tg,tf]=(0,i.useState)(null),tx=(0,i.useCallback)(()=>{th||(tp(null),tf(null))},[th]),tv=(0,i.useCallback)(async e=>{tm(!0),tf(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&&(ts.current=!0,e9(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(tt(n),tr(n),t))d?.(e)}(await tc(),tm(!1),r.length>0)?tf(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tp(null)},[tc,d,b]),[tb,ty]=(0,i.useState)(0),tw=(0,i.useCallback)(()=>{ty(e=>e+1),tc()},[tc]),tk=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tk.current;tk.current=!0,tc(e,!e)},[tc,c]),(0,i.useEffect)(()=>{try{K(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 tj=(0,i.useCallback)(e=>{K(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==q)return;let e=()=>{"visible"===document.visibilityState&&tc(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tc,q]),(0,i.useEffect)(()=>{try{0===te.size?window.localStorage.removeItem(J):window.localStorage.setItem(J,JSON.stringify([...te]))}catch{}},[te]),(0,i.useEffect)(()=>{try{0===tn.size?window.localStorage.removeItem(G):window.localStorage.setItem(G,JSON.stringify([...tn]))}catch{}},[tn]);let tS=(0,i.useCallback)(e=>{tr(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;ts.current=!0,e9(new Set(r.runningSessionIds??[]))}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[]),(0,i.useEffect)(()=>{let t=ti.current,n=[...t].filter(t=>!e7.has(t)&&t!==e),r=[...e7].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tt(e=>{let t=new Set(e);return e7.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!R.some(t=>t.id===e));(n.length>0||i)&&tc(!1,!0),n.length>0&&h?.(),ti.current=e7},[e7,e,R,tc,h]),(0,i.useEffect)(()=>{e&&tt(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&&B(e.home)}).catch(()=>{})},[]);let tC=(0,i.useRef)(!1),tT=(0,i.useCallback)(e=>{if(!e)return null;if(eB&&eB.forCwd===e||eB?.worktrees.some(t=>t.path===e))return eB.projectRoot;let t=$.find(t=>t.cwd===e);return t?.projectRoot??e},[eB,$]),tI=(0,i.useRef)(null);(0,i.useEffect)(()=>{tI.current!==W&&(tI.current=W,p?.(W,tT(W)))},[W,p,tT]);let tN=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tN.current&&(tN.current=u,D(u))},[u]);let[tR,tM]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!W)return void e_(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(W)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void e_(null);e_({forCwd:W,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||e_(null)}),()=>{e=!0}},[W,tR,c]),(0,i.useEffect)(()=>{if(0!==R.length&&!o&&null===W){if(a&&!tC.current){tC.current=!0;let e=R.find(e=>e.id===a);if(e){D(e.cwd),n(e,!0);return}l?.()}if(!eb)return;let e=new Map(ex.projects.map(e=>[e.key,e])),t=N(R.length>0?I(R):[],ex.projects).filter(t=>!e.get(T(t))?.hidden);t.length>0&&D(t[0])}},[R,W,a,o,n,l,ex,eb]);let tE=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eD){eO(!0),eW(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 eW(n.error??b("workspace.unable"));let r=n.cwd??t,i=T(r),s=ex.projects.find(e=>e.key===i);if(s?.hidden===!0)try{await tl([{key:i,path:r,hidden:!1}])}catch{}D(r),eF(!1)}catch{eW(b("workspace.unable"))}finally{eO(!1)}}},[tl,eD,ex.projects,b]),t$=(0,i.useCallback)(()=>{eF(!0),eW(null)},[]),tL=(0,i.useCallback)(async()=>{let e=eK.trim();if(e&&!eZ&&eB){eX(!0),eY(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eB.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eY(n.error??`HTTP ${t.status}`);eV(!1),eJ(""),eU(!1),e_(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),D(n.path),tM(e=>e+1)}catch(e){eY(e instanceof Error?e.message:String(e))}finally{eX(!1)}}},[eK,eZ,eB]),tA=(0,i.useCallback)(async(e,t)=>{if(eB&&!eZ){eX(!0),eY(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eB.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e0(e);eY(r.error??`HTTP ${n.status}`);return}e0(null),W===e&&D(eB.projectRoot),tM(e=>e+1)}catch(e){eY(e instanceof Error?e.message:String(e))}finally{eX(!1)}}},[eB,eZ,W]);(0,i.useEffect)(()=>{let e=e=>{e1.current&&!e1.current.contains(e.target)&&(ef(null),eU(!1),eV(!1),eJ(""),eY(null),e0(null),eA(""),em(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tP=(0,i.useCallback)(e=>{e.cwd&&D(e.cwd),n(e)},[n]),tF=(0,i.useCallback)((e=W)=>{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)}`;D(e),s?.(t,e)},[W,s]),[tz,tW]=(0,i.useState)(!1),[tD,tO]=(0,i.useState)(null),tB=(0,i.useCallback)(async()=>{tW(!0),tO(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}`);tF(t.cwd)}catch(e){tO(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tW(!1)}},[tF,b]),t_=(0,i.useCallback)(e=>{eu(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),tH=tT(W),tU=null===tH?null:T(tH),tq=(0,i.useMemo)(()=>new Map(ex.projects.map(e=>[e.key,e])),[ex.projects]),tV=I($);if(null!==tH){let e=T(tH);tV.some(t=>T(t)===e)||tV.unshift(tH)}let tK=N(tV,ex.projects),tJ=tK.filter(e=>ew||!tq.get(T(e))?.hidden),tG=tK.some(e=>tq.get(T(e))?.hidden),tY=()=>{ef(null),eU(!1),eV(!1),eJ(""),eY(null),e0(null),eA("")},tZ=async(e,t)=>{tY();try{await tl([{key:T(e),path:e,hidden:t}]),t&&tU&&tU===T(e)&&D(null),t||tK.some(t=>T(t)!==T(e)&&tq.get(T(t))?.hidden)||ek(!1)}catch{}},tX=async e=>{if(e4.current){e4.current=!1,eT(null);return}let t=eI.trim();if(t===(tq.get(T(e))?.alias??""))return void eT(null);e$(null);try{await tl([{key:T(e),path:e,alias:t||null}]),eT(null)}catch{e$(b("sidebar.projectUpdateFailed"))}},tQ=async(e,t)=>{if(H)return;let n=tJ.indexOf(e),r=n+t;if(n<0||r<0||r>=tJ.length)return;let i=new Set(tJ),s=tK.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),a=[...tK],o=s[n],l=s[r];[a[o],a[l]]=[a[l],a[o]],tY();try{await tl(a.map((e,t)=>({key:T(e),path:e,order:t})))}catch{}},t0=new Map;for(let e of $){let t=e.projectRoot??e.cwd;if(!t)continue;let n=T(t),r=t0.get(n);r?r.push(e):t0.set(n,[e])}let t1=(0,i.useMemo)(()=>{let e=new Map;for(let t of $){let n=t.projectRoot??t.cwd;if(!n)continue;let r=T(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),e7.has(t.id)&&i.running++,te.has(t.id)&&i.unread++}return e},[$,e7,te]),t2=H.trim().toLowerCase(),t8=H.length>0,t4=tJ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=T(e),r=tq.get(n),i=r?.alias??t,s=(t0.get(n)??[]).slice().sort((e,t)=>{let n=Number(tn.has(t.id))-Number(tn.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t2)return[{project:e,key:n,name:i,sessions:s,hidden:r?.hidden===!0}];let a=i.toLowerCase().includes(t2)||t.toLowerCase().includes(t2),o=s.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t2));return a||0!==o.length?[{project:e,key:n,name:i,sessions:a?s:o,hidden:r?.hidden===!0}]:[]}),t5=[],t6=[];for(let e of t4){let t=e.key===tU||(t1.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?t6.push(e):t5.push(e)}let t3={running:0,unread:0};for(let e of t6){let t=t1.get(e.key);t&&(t3.running+=t.running,t3.unread+=t.unread)}let t7=t8||ej,t9=[...t5.map(e=>({kind:"project",group:e})),...t6.length>0?[{kind:"temporary"}]:[],...t7?t6.map(e=>({kind:"project",group:e})):[]],ne=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))}(t9.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nt=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",s=new Set,a="Pinned"){let o=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)}),l=o.filter(e=>s.has(e.id)),c=[],d=new Map,u=0;for(let e of o){if(s.has(e.id))continue;if(t.has(e.id)){c.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=d.get(r);i?i.push(e):d.set(r,[e])}let p=[];for(let e of(l.length>0&&p.push({key:"pinned",label:a,running:!1,sessions:l}),c.length>0&&p.push({key:"priority",label:i,running:!0,sessions:c}),[...d.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,i,s]=e.split("-").map(Number),a=new Date(r,i-1,s),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(a.getFullYear(),a.getMonth(),a.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(a):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(a)}(e,n,r),running:!1,sessions:d.get(e)??[]});return p})($,e7,new Date,y,b("navigator.priority"),tn,b("sidebar.pinned")),[y,tn,e7,$,b]),nn=!!(eB?.isGit&&eB.isTopLevel&&W&&tH===eB.projectRoot),nr=eB?.worktrees.find(e=>e.path===W)??eB?.worktrees.find(e=>e.isMain),ni=(eB?.worktrees.length??0)>=8,ns=ni&&eL.trim()?(eB?.worktrees??[]).filter(e=>(e.branch??X(e.path,O)).toLowerCase().includes(eL.trim().toLowerCase())):eB?.worktrees??[],na=(()=>{if(!tu)return[];let e="project"===tu.kind?t0.get(T(tu.project))??[]:nt.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),no=na.filter(e=>!e7.has(e.id)),nl=e=>{let t=new Set;for(let n of e)n.transient||e7.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nc=void 0!==m&&g;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eP&&(0,r.jsx)(_,{busy:eD,error:ez,onCancel:()=>{eF(!1),eW(null)},onSelect:e=>void tE(e)}),tu&&(0,r.jsx)(es,{scope:tu,eligible:no.length,runningExcluded:na.length-no.length,busy:th,error:tg,onCancel:tx,onConfirm:()=>void tv(no)}),(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)(en,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>tF(),disabled:!W,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:W?"var(--text-muted)":"var(--text-dim)",cursor:W?"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:W?b("sidebar.newSessionTitle",{path:W}):b("sidebar.selectProject"),"aria-label":W?b("sidebar.newSessionTitle",{path:W}):b("sidebar.selectProject"),onMouseEnter:e=>{W&&(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=W?"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${e6?" is-success":""}`,onClick:()=>tc(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:e6?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${e6?"rgba(74,222,128,0.4)":"var(--border)"}`,color:e6?"#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=>{e6||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e6||(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:e6?(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"})]})})]})]})}),(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=!nc&&q===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:()=>{tj(e),nc&&f?.(!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":nc,"aria-controls":"navigator-lounge-panel","data-navigator-mode":"lounge",onClick:()=>f?.(!nc),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:nc?"var(--bg-selected)":"transparent",color:nc?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:nc?600:500,whiteSpace:"nowrap"},children:v("lounge.tab")})]}),!nc&&"projects"===q&&(0,r.jsx)("button",{type:"button",onClick:()=>ek(e=>!e),disabled:!tG,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":ew,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:ew?"var(--bg-selected)":"transparent",color:ew?"var(--accent)":"var(--text-dim)",cursor:tG?"pointer":"default",opacity:tG?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"}),!ew&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nc&&"projects"===q&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:t$,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"})]})})]}),nc&&m,!nc&&"projects"===q&&(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:H,onChange:e=>U(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),U(""),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}})]}),!nc&&"projects"===q&&(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||!eb)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),P&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:P}),eE&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eE}),!L&&eb&&!P&&0===t4.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t2?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&eb&&!P&&t9.map(t=>{let n,i,s;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":t7,title:b("sidebar.temporaryProjects"),onClick:()=>eS(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:t7?"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:t6.length}),ep(t3,b)]})},"navigator-temporary-projects");let{project:a,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===tU,p=ne.has(l.toLowerCase())&&X((i=Math.max((n=a.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),O)||null,h=!ed.has(a)&&!t2,m=et.has(a),g=eC===a,f=tJ.indexOf(a),x=eR||t8||f<=0,v=eR||t8||f>=tJ.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?c:c.slice(0,5)),k=c.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:eg===a?e1:void 0,onMouseEnter:()=>em(a),onMouseLeave:()=>em(e=>e===a&&eg!==a?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t_(a),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),g?(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:e8,value:eI,onChange:e=>eN(e.target.value),onBlur:()=>void tX(a),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e4.current=!0,eT(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:()=>D(a),title:a,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),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}),ep(t1.get(o),b)]}),(0,r.jsx)("button",{type:"button",onClick:()=>tF(a),title:b("sidebar.newSessionTitle",{path:a}),"aria-label":b("sidebar.newSessionTitle",{path:a}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||eh===a?1:0,pointerEvents:w||eh===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>em(a),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{ef(eg===a?null:a),eU(!1),eV(!1),eY(null),u||D(a)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":eg===a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:eg===a?"var(--bg-selected)":"transparent",color:u&&nr&&!nr.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eh===a||eg===a?1:0,pointerEvents:w||eh===a||eg===a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>em(a),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(ee,{open:eg===a,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[nn&&eB&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eU(e=>!e),title:nr?b("sidebar.switchWorktreeTitle",{path:nr.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eH,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eH?"1px solid var(--border)":"none",background:eH?"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)(ee,{open:eH,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:[ni&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eL,onChange:e=>eA(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eA(""),eU(!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:[ns.map(e=>{let t=e.path===W||e.isMain&&!eB.worktrees.some(e=>e.path===W);return eQ===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 tA(e.path,!0),disabled:eZ,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:()=>e0(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:()=>{D(e.path),eU(!1),eY(null),eA("")},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)(Q,{text:e.branch??X(e.path,O),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 tA(e.path,!1),disabled:eZ,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)}),ni&&0===ns.length&&eL.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eq?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:e2,value:eK,onChange:e=>{eJ(e.target.value),eY(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tL()),"Escape"===e.key&&(eV(!1),eJ(""),eY(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 tL(),disabled:eZ||!eK.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:eZ||!eK.trim()?"not-allowed":"pointer",opacity:eZ||!eK.trim()?.65:1},children:eZ?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eV(!1),eJ(""),eY(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(),eV(!0),eY(null),setTimeout(()=>e2.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")})]}),eG&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eG})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eR,onClick:()=>{let e;return e=tq.get(T(a))?.alias??"",void(e4.current=!1,e$(null),eN(e),eT(a),tY())},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:eR?"default":"pointer",textAlign:"left",fontSize:11,opacity:eR?.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(tq.get(T(a))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t8?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void tQ(a,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:t8?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void tQ(a,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eR,onClick:()=>void tZ(a,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eR?"default":"pointer",textAlign:"left",fontSize:11,opacity:eR?.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"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(s=0===nl(t0.get(o)??[])||th,(0,r.jsxs)("button",{type:"button",disabled:s,onClick:()=>{tY(),tf(null),tp({kind:"project",project:a,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",textAlign:"left",fontSize:11,opacity:s?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.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:e7,unreadSessionIds:te,pinnedSessionIds:tn,onSelectSession:tP,onTogglePinnedSession:tS,onRenamed:tc,onSessionDeleted:td,onSessionArchived:tw,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ea(e=>{let t=new Set(e);return t.has(a)?t.delete(a):t.add(a),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},a)})]}),!nc&&(0,r.jsx)(el,{refreshKey:tb,selectedSessionId:e,onSelectSession:tP,onRestored:tw}),!nc&&"priority"===q&&(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")}),P&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:P}),!L&&!P&&(x=nl(nt.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:tz,onClick:()=>void tB(),title:b("sidebar.newScratchSessionTitle"),style:Z(tz,w),children:b("sidebar.newScratchSession")}),nt.length>0&&(0,r.jsx)("button",{type:"button",disabled:0===x||th,onClick:()=>{tf(null),tp({kind:"priority"})},style:Z(0===x||th,w),children:b("sidebar.clearPriorityList")})]})),tD&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tD}),!L&&!P&&0===nt.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!P&&nt.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:e7.has(t.id),unread:te.has(t.id),pinned:tn.has(t.id),onSelect:tP,onTogglePin:tS},t.id))]},t.key))]})]})}function es({scope:e,eligible:t,runningExcluded:n,busy:s,error:a,onCancel:o,onConfirm:l}){let{t:c}=(0,E.s)(),d=s||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(s);h.current=s;let m=(0,i.useRef)(o);return m.current=o,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{s||e.target!==e.currentTarget||o()},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:c("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?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:a})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:s,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:s?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":s,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(s?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ea({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function eo({session:e,selected:t,running:n,unread:i,pinned:s,onSelect:a,onTogglePin:o}){let{t:l}=(0,E.s)(),c=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),d=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>a(e),title:`${c}
2
- ${e.cwd}
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:c}),n&&(0,r.jsx)(ed,{}),!n&&i&&(0,r.jsx)(eu,{})]}),(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:d})]}),(0,r.jsx)("button",{type:"button","aria-pressed":s,"aria-label":l(s?"sidebar.unpin":"sidebar.pin"),title:l(s?"sidebar.unpin":"sidebar.pin"),onClick:()=>o(e.id),style:{width:30,border:"none",background:"transparent",color:s?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(ea,{filled:s})})]})}function el({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:s}){let{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(!1),[c,d]=(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||d(n.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,i.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),s(t)}catch{}},[s]);return 0!==c.length||o?(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>l(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:o?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),a("sidebar.archived")," (",c.length,")"]}),o&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===c.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:a("sidebar.noArchivedSessions")}),c.map(e=>{let i=M(e.firstMessage)??e.firstMessage,s=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:a("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:a("sidebar.restore")})]},e.id)})]})]}):null}function ec({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:o,onRenamed:l,onSessionDeleted:c,onTogglePinnedSession:d,onSessionArchived:u,depth:p}){let[h,m]=(0,i.useState)(!1),g=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)(eh,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:s.has(e.session.id),isPinned:a.has(e.session.id),onClick:()=>o(e.session),onTogglePin:()=>d(e.session.id),onRenamed:l,onDeleted:e=>c?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:g,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),g&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ec,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:s,pinnedSessionIds:a,onSelectSession:o,onTogglePinnedSession:d,onRenamed:l,onSessionDeleted:c,onSessionArchived:u,depth:p+1},e.session.id))})]})}function ed(){let{t:e}=(0,E.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 eu(){let{t:e}=(0,E.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 ep(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 eh({session:e,isSelected:t,isRunning:n,isUnread:s,isPinned:a,onClick:o,onTogglePin:l,onRenamed:c,onDeleted:d,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:g}){let{t:f}=(0,E.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,T]=(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 N=M(e.firstMessage)??e.firstMessage,R=e.name||N.slice(0,50)||e.id.slice(0,12),$=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||N.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,N,e.id]),L=(0,i.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==R&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[w,e.id,e.name,c,R]),A=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),T(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),d?.(e.id)}catch{T(!1)}}},[e.id,e.transient,d]),P=(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]),F=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?A():S(!0)},[A]),z=(0,i.useCallback)(e=>{e.stopPropagation(),A()},[A]),W=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),D=(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:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${s?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:o,onContextMenu:j||b?void 0:D,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:f("sidebar.deleteSession",{title:R.slice(0,22)+(R.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:z,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"})]}),f("sidebar.delete")]}),(0,r.jsx)("button",{onClick:W,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:f("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(),o()},"aria-current":t?"page":void 0,title:R,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:R}),n&&(0,r.jsx)(ed,{}),!n&&s&&(0,r.jsx)(eu,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:f("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(),g?.()},title:f(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(),l?.()},title:f(a?"sidebar.unpin":"sidebar.pin"),"aria-label":f(a?"sidebar.unpin":"sidebar.pin"),"aria-pressed":a,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:a?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||a?1:0,pointerEvents:x||a?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(ea,{filled:a})}),(0,r.jsx)("button",{onClick:$,title:f("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:P,title:f("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:F,title:f("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 em=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eg=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,ef=/\x1B\[([0-9;]*)m/g,ex=/\x1B_pi:c\x07/g,ev=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eb=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function ey(e){return e.replace(ex,"").replace(em,"")}function ew(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 ek(e,t){let n=ew(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function ej(e){return ew(e)[0]?.char}function eS(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(ex,""),i=ey(e).trimEnd();if(t.test(i))continue;let s=e,a=ej(s);("│"===a||"┃"===a)&&" "===ej(s=ek(s,0))&&(s=ek(s,0));let o=function(e){let t=ew(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),l=o>=0?ew(s)[o]?.char:void 0;("│"===l||"┃"===l)&&(s=ek(s,o)),n.push(function(e){let t=e;for(;;){let e=ew(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===ey(n[0]).trim();)n.shift();for(;n.length>0&&""===ey(n[n.length-1]).trim();)n.pop();return n.length?n:e}function eC(e){let t,n=[],r={},i=0;for(ef.lastIndex=0;null!==(t=ef.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=ev[r-30];else if(r>=90&&r<=97)n.color=eb[r-90];else if(r>=40&&r<=47)n.backgroundColor=ev[r-40];else if(r>=100&&r<=107)n.backgroundColor=eb[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,s,a]=[t[e+2],t[e+3],t[e+4]];[i,s,a].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${s}, ${a})`:n.backgroundColor=`rgb(${i}, ${s}, ${a})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return ev[e];if(e>=8&&e<16)return eb[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 eT={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:""},eI={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eN={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"},eR={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 eM(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eE(e){return null!==(eN[eM(e)]??null)}function e$(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eL(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 eP(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eL(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 eF(e){return e.filter(e=>"toolCall"===e.type).length}function ez(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 eW(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let s of i)"toolCall"===s.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};return"generate_image"===e.toolName||("write"===e.toolName?"xd://generate_image"===n.path:"read"===e.toolName&&"string"==typeof n.path&&eE(n.path))}(s,t.get(s.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:s.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let eD=new Map,eO=new Map,eB="command",e_="autolearn-saved";function eH(e){return"custom"===e.role&&(e.customType===eB||e.customType===e_&&!1!==e.display)}let eU="local-command:";function eq(e){return e?.startsWith(eU)===!0}function eV(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],s=[];for(let n=0;n<e.length;n++){let a=n<t.length;!(r.has(e[n])||a&&eq(t[n]))&&(i.push(e[n]),a&&s.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=s.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=s.length&&s.splice(t,0,e.entryId)}return{messages:i,entryIds:s}}function eK(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let eJ={create:!0,update:!0};function eG(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function eY(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 eZ(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 eX(e){try{return decodeURIComponent(e)}catch{return e}}function eQ(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e0(e){let t=eQ(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){s.length>0&&".."!==s[s.length-1]?s.pop():i||n||r||s.push(e);continue}s.push(e)}let a=s.join("/");return n?a:r?`//${a}`:i?`/${a}`:a}function e1(e,t,n=t){let r,i,s,a,o;if(!e)return null;let l=e.split("#",1)[0].split("?",1)[0].trim();if(!l)return null;let c=null,d=null,u=eX(l),p=u.startsWith("\\\\"),h=eQ(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:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=eX(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("/")?(c=h,d="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(c=`${eQ(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let g=e0(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&n&&(r=e0(g).replace(/\/+$/,""),i=e0(n).replace(/\/+$/,""),a=(s=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(a===(o=s?i.toLowerCase():i)||a.startsWith(`${o}/`)))?null:g}function e2(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),e4=n(7644),e5=n(32316);function e6(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e3(e){return e6(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function e7(e){let t=e6(e).replace(/\/+$/,"");return t.split("/").pop()??t}function e9(e,t){if(!t)return e;let n=e6(e),r=e6(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var te=n(88374),tt=n(63280),tn=n(94764),tr=n(63835),ti=n(54152),ts=n(84678),ta=n(98164);let to={...tn.j,attributes:{...tn.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...tn.j.strip||[],"iframe","object","style","form"]};function tl(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,a=null,o=new Map;for(let e=0;e<n.length;e++){var l;let t=n[e];if(a){r.push(t),RegExp(`</${a}\\s*>`,"i").test(t)&&(a=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},s=0,r.push(t);continue}if(i){r.push(t);continue}let d=t.match(/<(code|pre|script|style)\b/i);if(d){let e=d[1].toLowerCase(),n=t.slice((d.index??0)+d[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(a=e),s=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){s=0,r.push(t);continue}if(s||t.includes("`")){s=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,s),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>td(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],i=m[2].trimEnd();if(i&&!i.includes("$$")){let s=tc(n,e+1,t,o);if(s){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<s.index;i++)r.push(td(n[i],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.index;continue}}}let g=t.match(/^([ \t]{0,3})\$\$\s*$/);if(g){let t=g[1],i=tc(n,e+1,t,o);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let s=e+1;s<i.index;s++)r.push(td(n[s],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((l=t,/^\s{0,3}\[[^\]]+\]:/.test(l)||/]\s*\(/.test(l)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(l)||/\b(?:https?|file|mailto):/i.test(l)||/\b[A-Za-z]:\\/.test(l)?l:l.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function tc(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var s,a,o,l;let t=e[i];if(s=t,""===(a=n)?/^ {0,3}\$\$\s*$/.test(s):s.startsWith(a)&&/^\$\$\s*$/.test(s.slice(a.length)))return{index:i,content:"",glued:!1};if(o=t,/^ {0,3}(`{3,}|~{3,})/.test(o)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(o)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(o)||/^ {0,3}>/.test(o)||/<(code|pre|script|style)\b/i.test(o)||(l=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(l)))return r.set(n,i),null;let c=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!==c)return{index:i,content:c,glued:!0}}return r.set(n,e.length),null}function td(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 tu={singleTilde:!1},tp=[[ti.A,["yaml"]],[ts.A,tu],ta.A],th=[[ti.A,["yaml"]],[ts.A,tu],ta.A],tm=[tt.A,[tr.A,to],[te.A,{throwOnError:!1,strict:!1}]],tg=[tt.A,[tr.A,to],[te.A,{throwOnError:!1,strict:!1}]],tf="pi-theme",tx=["light","dark","auto"],tv={preference:"auto",theme:"light"},tb="omp-theme",ty=null,tw=0,tk=new Set,tj=null,tS=!1;function tC(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tT(e){return"auto"===e?tC():e}let tI="--omp-md-";function tN(e){let t=document.documentElement,n=ty?.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(tI)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(tI)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tb,e)}catch{}}function tR(){if(tj)return tj;let e=function(){try{let e=localStorage.getItem(tf);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tb);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=tT(e);return tN(t),tj={preference:e,theme:t}}function tM(e,t,n){if(tN(t),n)try{localStorage.setItem(tf,e)}catch{}tj={preference:e,theme:t},tk.forEach(e=>e())}function tE(){let e=tR();if("auto"!==e.preference)return;let t=tC();t!==e.theme&&tM("auto",t,!1)}function t$(e){return tk.add(e),tR(),tS||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tE),window.addEventListener("focus",tE),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tE()}),tS=!0),tE(),()=>{tk.delete(e)}}function tL(){return tR()}function tA(){return tv}async function tP(e){let t=++tw,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===tw){ty=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(ty))}catch{}tN(tR().theme)}}function tF(e){let t=(0,i.useSyncExternalStore)(t$,tL,tA);(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=()=>{tM(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,a=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(a,window.innerHeight-a));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${a}px)`,`circle(${o}px at ${s}px ${a}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=tR().preference,r=tx.indexOf(t),tx[(r+1)%tx.length]),e)},[n]),s=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:s,isDark:"dark"===t.theme}}function tz(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()}}function tW({code:e,isStreaming:t,defaultPreview:s=!1}){let{isDark:a}=tF(),{t:o}=(0,E.s)(),[l,c]=(0,i.useState)(s),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),m=`${a?"dark":"light"}
4
- ${e}`,g=l&&!t;(0,i.useEffect)(()=>{if(!g)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:a?"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)}`,s=await r.render(i,e);t||u({key:m,status:"ready",svg:s.svg})})().catch(()=>{t||u({key:m,status:"error"})}),()=>{t=!0}},[e,m,a,g]);let f=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>c(e=>!e),disabled:t,title:t?o("i18n.previewAfterStreaming"):g?o("i18n.showMermaidSource"):o("i18n.previewMermaid"),className:["markdown-code-action",g?"is-active":""].filter(Boolean).join(" "),children:g?o("i18n.source"):o("i18n.preview")}),[t,g,o]);if(!g)return(0,r.jsx)(tO,{code:e,lang:"mermaid",headerAction:f,isStreaming:t});let x=d?.key===m&&"error"===d.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:o("i18n.invalidMermaid")}):d?.key!==m||"ready"!==d.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":o("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!p&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:o("i18n.openMermaidViewer"),"aria-label":o("i18n.openMermaidViewer"),onClick:()=>h(!0),dangerouslySetInnerHTML:{__html:d.svg}}),p&&(0,r.jsx)(tD,{svg:d.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"}),f]}),x]})}function tD({svg:e,onClose:t}){let{t:n}=(0,E.s)(),s=(0,i.useRef)(null),[a,o]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:s,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:a<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*a),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:a>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>o(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*a}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tO=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:s}){let{isDark:a}=tF(),{t:o}=(0,E.s)(),[l,c]=(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:()=>{tz(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),s?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(e8.A,{language:t||"text",style:a?e4.xJ:e4.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",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 tB({children:e,className:t,isStreaming:n,cwd:s,onOpenFile:a}){let o=(0,i.useMemo)(()=>tl(e),[e]),l=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let s=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===s?(0,r.jsx)(tW,{code:a.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(tO,{code:a.replace(/\n$/,""),lang:s,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=a?e1(e,s):null;return i&&a?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),a(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?e1(e,s):null,a=i?`/api/files/${e3(i)}?type=read`:e;return(0,r.jsx)("img",{src:a,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[s,n,a]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(e5.oz,{remarkPlugins:tp,rehypePlugins:tm,components:l,children:o})})}let t_=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,tH=/(?:\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 tU(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let tq={hideThinkingBlock:!1},tV=new Set,tK=tq,tJ=0;function tG(e){return tV.add(e),()=>{tV.delete(e)}}function tY(){return tK}function tZ(){return tq}async function tX(e){let t=++tJ,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!==tJ||i.hideThinkingBlock!==tK.hideThinkingBlock&&(tK={hideThinkingBlock:!0===i.hideThinkingBlock},tV.forEach(e=>e()))}function tQ(){return(0,i.useSyncExternalStore)(tG,tY,tZ)}let t0="/api/sidecars/resource";function t1(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},n=e=>{let n=t[e];return"number"==typeof n&&Number.isFinite(n)?n:null},r=n("usedFraction");if(null!==r&&r>=1)return!0;let i=n("remainingFraction");if(null!==i&&i<=0)return!0;let s=n("used"),a=n("limit");if(null!==s&&null!==a&&s>=a)return!0;let o=n("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==s&&s>=100}let t2=[{alias:"RIN(린)",file:"rin.webp"},{alias:"MIO(미오)",file:"mio.webp"},{alias:"NOVA(노바)",file:"nova.webp",provider:"opencode-go"},{alias:"YUKI(유키)",file:"yuki.webp",provider:"openai-codex"},{alias:"ISANA(이사나)",file:"isana.webp",provider:"b-ai"},{alias:"SHION(시온)",file:"shion.webp",provider:"web6"},{alias:"HIKARI(히카리)",file:"hikari.webp",provider:"google-antigravity"}],t8=[{seed:3,alias:t2[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:t2[4].alias,provider:"b-ai",model:"deepseek-v4.1-flash",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:t2[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:t2[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:t2[2].alias,provider:"opencode-go",model:"muse-spark-1.3-contributor",voice:"번뜩이는 발상\xb7즉흥적 시제품\xb7낙천적 재도전",summonExample:"노바 불러와",switchExample:"노바로 교체해"},{seed:6,alias:t2[6].alias,provider:"google-antigravity",model:"gemini-3.8-flash",voice:"빠른 관찰\xb7톡 쏘는 한마디\xb7장난스러운 여유",summonExample:"히카리 불러와",switchExample:"히카리로 교체해"},{seed:5,alias:t2[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],t4=t8.filter(e=>null!==e.switchExample),t5=t2.filter(e=>!("provider"in e)).length,t6=new Map(t2.flatMap((e,t)=>"provider"in e?[[e.provider,t]]:[])),t3=new Map([...t6].map(([e,t])=>[e,{seed:t,alias:t2[t].alias}]));function t7(e){return t2[e%t2.length].alias}function t9(e){return`/avatars/${t2[e%t2.length].file}`}function ne(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function nt(e){return({"openai-codex":"OpenAI Codex",anthropic:"Anthropic","google-gemini":"Google Gemini","github-copilot":"GitHub Copilot","opencode-go":"OpenCode Go",devin:"Devin","b-ai":"B.AI",web6:"WEB6"})[e]??e.replace(/(^|-)(\w)/g,(e,t,n)=>`${t?" ":""}${n.toUpperCase()}`)}function nn(e){let t=new Map;return e.map(e=>{var n;let r=e.metadata?.email,i=e.metadata?.accountId,s="string"==typeof r&&r.length>0?r:"string"==typeof i?i:"",a=s.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return ne(e);let n=e.slice(t+1),r=n.lastIndexOf("."),i=r<0?n:n.slice(0,r),s=r<0?"":n.slice(r);return`${ne(e.slice(0,t))}@${0===i.length?"":`${i[0]}•••`}${s}`}(s):"",o=(n=e.provider,t6.get(n)??-1);if(o>=0)return{seed:o,alias:t2[o].alias,masked:a,raw:s};let l=t.get(e.provider)??0;t.set(e.provider,l+1);let c=l%t5,d=l<t5?t2[c].alias:`${t2[c].alias}${l+1}`;return{seed:c,alias:d,masked:a,raw:s}})}class nr extends Error{constructor(e,t,n,r){super(e,r),this.kind=t,this.status=n,this.name="ResourceClientError",this.code=r?.code,this.outcomeUnknown=r?.outcomeUnknown}}function ni(e,t){return`${t0}${e}${t?"?refresh=1":""}`}function ns(e,t,n=!1){return e instanceof nr?e:t?new nr("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new nr("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new nr(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function na(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function no(e,t){let n,r=t.fetchImpl??fetch,i=new AbortController,s=!1,a=()=>i.abort(t.signal?.reason);t.signal?.aborted?a():t.signal?.addEventListener("abort",a,{once:!0}),null!=t.timeoutMs&&(n=setTimeout(()=>{s=!0,i.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,n=await r(e,{signal:i.signal});try{t=await n.json()}catch(e){throw new nr("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",n.status,{cause:e})}let s=t&&"object"==typeof t?t:null,a="string"==typeof s?.error?s.error:null;if(!n.ok||a)throw new nr(a??`HTTP ${n.status}`,"http",n.status,{code:"string"==typeof s?.code?s.code:void 0,outcomeUnknown:s?.outcomeUnknown===!0});return t}catch(e){throw ns(e,s,i.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",a)}}let nl="google-antigravity",nc=`${nl}:google:`;function nd(e){if(e.provider!==nl||!Array.isArray(e.limits))return e;let t=e.limits.filter(e=>"string"==typeof e.id&&e.id.startsWith(nc));return t.length===e.limits.length?e:{...e,limits:t}}async function nu(e={}){try{let t=await no(ni("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new nr("사용량 응답 형식이 올바르지 않습니다.","invalid-response");let n=t.reports.map(nd);return{status:"fresh",data:n.every((e,n)=>e===t.reports[n])?t:{...t,reports:n},error:null}}catch(t){return na(e.previous,ns(t,!1))}}async function np(e,t={}){if(!e)return na(void 0,new nr("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await no(`/api/agent/${encodeURIComponent(e)}/account`,t),r=n?.state==="resolved"||n?.state==="unresolved"||n?.state==="not-running"||n?.state==="unsupported";if(!n||n.sessionId!==e||"number"!=typeof n.observedAt||!r||!Array.isArray(n.resetRecommendations))throw new nr("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return na(void 0,ns(e,!1))}}async function nh(e={}){try{let t=await no(ni("/models",!0===e.refresh),{...e,timeoutMs:e.timeoutMs??12e4});if(!t||!Array.isArray(t.models)||!Array.isArray(t.agents)||!Array.isArray(t.daily))throw new nr("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return na(e.previous,ns(t,!1))}}async function nm(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new nr("credential id가 올바르지 않습니다.","invalid-response");let r=await no(`${t0}/credential/${e}/${t?"enable":"disable"}`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,t)=>(n.fetchImpl??fetch)(e,{...t,method:"POST"})});if(!r||!0!==r.ok||r.credentialId!==e||!t!==r.disabled)throw new nr("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function ng(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new nr("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new nr("credit id가 올바르지 않습니다.","invalid-response");let r=await no(`${t0}/credential/${e}/reset`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,r)=>{let i=new Headers(r?.headers);return i.set("Content-Type","application/json"),(n.fetchImpl??fetch)(e,{...r,method:"POST",headers:i,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!r||"boolean"!=typeof r.ok||r.credentialId!==e||r.creditId!==t||"string"!=typeof r.code||r.ok!==("reset"===r.code))throw new nr("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function nf(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let nx={faces:new Map,pins:new Map},nv=[],nb=nx,ny=null,nw=new Map,nk=new Set;function nj(e){return nk.add(e),()=>{nk.delete(e)}}function nS(e){nb=e,nk.forEach(e=>e())}function nC(e){return Number.isSafeInteger(e)&&e>0}function nT(e,t){return`${e}:${t}`}function nI(e,t,n){if(!t)return null;if(nC(n)){let e=nb.faces.get(nT(t,n));if(e)return e}let r=e?nb.pins.get(e):void 0;if(r&&r.provider===t){let e=nb.faces.get(nT(t,r.credentialId));if(e)return e}return t3.get(t)??null}function nN(e,t,n){let r=!!t&&!nC(n)&&!!e;return(0,i.useEffect)(()=>{r&&e&&t&&function(e,t){let n=Date.now(),r=nb.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,s=nw.get(i);void 0!==s&&n-s<3e4||(nw.set(i,n),np(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!nC(i))return;let s=new Map(nb.pins);s.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),nS({faces:nb.faces,pins:s})}).catch(()=>{}))}(e,t)},[r,e,t]),(0,i.useSyncExternalStore)(nj,()=>nI(e,t,n),()=>null)}function nR({seed:e,size:t,provider:n}){let[s,a]=(0,i.useState)(!1),[o,l]=(0,i.useState)(!1);return s?(0,r.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:t7(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(),l(!0)},"aria-label":t7(e),children:(0,r.jsx)("img",{className:"account-avatar",src:t9(e),width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>a(!0)})}),o&&(0,r.jsx)(nM,{seed:e,provider:n,onClose:()=>l(!1)})]})}function nM({seed:e,provider:t,onClose:n}){let{t:s}=(0,E.s)(),a=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let o=t7(e);return(0,W.createPortal)((0,r.jsxs)("dialog",{ref:a,className:"account-avatar-dialog","aria-label":o,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:t9(e),width:256,height:256,alt:o,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:o}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:nt(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:s("i18n.close")})]}),document.body)}function nE(e){let t,n=[],r=null,i=0,s=0,a=0,o=0,l=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){l=[],c=[];return}let e=Math.max(l.length,c.length);for(let t=0;t<e;t++){let e=l[t]?{lineNo:l[t].lineNo,text:l[t].text,type:"removed"}:d(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();r.rows.push({type:"line",left:e,right:n})}l=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(a>0||o>0)){if(d.startsWith("--- ")){u(),t=n$(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:n$(d.slice(4)),rows:[]},n.push(r);continue}}let e=d.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),s=Number(e[3]),a=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:d});continue}if(!r)continue;if(d.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:d});continue}let p=d[0],h=d.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:s++,text:h,type:"context"}}),a>0&&a--,o>0&&o--):"-"===p?(l.push({lineNo:i++,text:h}),a>0&&a--):"+"===p?(c.push({lineNo:s++,text:h}),o>0&&o--):""!==d&&(u(),r.rows.push({type:"hunk",text:d}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function n$(e){return e.split(" ")[0].trim()}function nL({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,s="blocked"===e.status;return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":n?"is-abandoned":s?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":s?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,s&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let nA="/icons/catppuccin";function nP({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${nA}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${nA}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function nF({size:e=14,open:t=!1}){return(0,r.jsx)(nP,{name:t?"_folder_open":"_folder",size:e})}function nz({size:e=14}){return(0,r.jsx)(nP,{name:"_file",size:e})}let nW={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",markdown:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function nD(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)(nP,{name:i,size:t});let s=nW[n.split(".").pop()??""];return s?(0,r.jsx)(nP,{name:s,size:t}):(0,r.jsx)(nz,{size:t})}function nO({files:e,onOpenFile:t}){let{t:n}=(0,E.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=e7(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:[nD(i,12),(0,r.jsx)("span",{children:i})]},e)})})}class nB extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let n_={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},nH={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},nU={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function nq(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&&nH[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&nU[r]?"text":null}let nV={".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 nK(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?nV[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 nJ(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function nG(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}),n+=i.size,r+=i.text.length))}}return t}async function nY(e){let t,n=nq(e);if(!n)throw new nB("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new nB("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await n4(e);else{try{t=await e.text()}catch(e){throw new nB("read_failed",e instanceof Error?e.message:String(e))}n5(t)}return{name:e.name,mimeType:n_[n],size:e.size,text:t}}function nZ(e,t){let n=nG(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=`${n6}${JSON.stringify(r)}${n3}
5
- ${n7}${e}${n9}`;return n.forEach((e,t)=>{i+=re(t,e),i+=e.text,i+=rt(t)}),i}function nX(e){let t;if(!e.startsWith(n6))return null;let n=e.indexOf("\n");if(n<0)return null;let r=e.slice(0,n);if(!r.endsWith(n3))return null;try{t=JSON.parse(r.slice(n6.length,-n3.length))}catch{return null}if(!function(e){if(!e||"object"!=typeof e||!Number.isSafeInteger(e.userMessageLength)||(e.userMessageLength??-1)<0||!Array.isArray(e.documents)||0===e.documents.length||e.documents.length>3)return!1;let t=0,n=0;for(let r of e.documents){if(!r||"object"!=typeof r||"string"!=typeof r.name||0===r.name.length||"text/markdown"!==r.mimeType&&"text/plain"!==r.mimeType&&"application/pdf"!==r.mimeType||!Number.isSafeInteger(r.size)||(r.size??-1)<0||(r.size??0)>8388608||!Number.isSafeInteger(r.textLength)||(r.textLength??-1)<0||(r.textLength??0)>12e4)return!1;t+=r.size??0,n+=r.textLength??0}return t<=0x1000000&&n<=24e4}(t))return null;let i=n+1;if(!e.startsWith(n7,i))return null;let s=(i+=n7.length)+t.userMessageLength;if(s>e.length)return null;let a=e.slice(i,s);if(i=s,!e.startsWith(n9,i))return null;i+=n9.length;let o=[];for(let n=0;n<t.documents.length;n+=1){let r=t.documents[n],s=re(n,r);if(!e.startsWith(s,i))return null;let a=(i+=s.length)+r.textLength;if(a>e.length)return null;let l=e.slice(i,a);i=a;let c=rt(n);if(!e.startsWith(c,i))return null;i+=c.length,o.push({name:r.name,mimeType:r.mimeType,size:r.size,text:l})}return i===e.length?{message:a,documents:o}:null}function nQ(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:`${(e/1048576).toFixed(1)} MB`}let n0="\n[transcript truncated to fit the attachment limit]",n1="File saved at: ";function n2(e){return"application/pdf"===e.mimeType?"pdf":"text/markdown"===e.mimeType?"markdown":e.text.startsWith(n1)?nK({name:e.name,type:""})?"audio":"file":"text"}async function n8(e,t){let n=new FormData;n.append("file",e,e.name),t&&n.append("sessionId",t);let r=await fetch("/api/attachments",{method:"POST",body:n}),i=await r.json().catch(()=>null);if(!r.ok||"string"!=typeof i?.path||"number"!=typeof i.size||"string"!=typeof i.mimeType)throw Error("string"==typeof i?.error?i.error:`HTTP ${r.status}`);return{path:i.path,size:i.size,mimeType:i.mimeType,..."string"==typeof i.transcript?{transcript:i.transcript}:{},..."string"==typeof i.transcriptError?{transcriptError:i.transcriptError}:{}}}async function n4(e){let t;try{t=await fetch("/api/document-text",{method:"POST",headers:{"Content-Type":"application/pdf"},body:e})}catch(e){throw new nB("read_failed",e instanceof Error?e.message:String(e))}let n=await t.json().catch(()=>null);if(!t.ok){var r;throw new nB("string"==typeof n?.code&&("unsupported"===(r=n.code)||"file_too_large"===r||"text_too_large"===r||"too_many_pages"===r||"no_extractable_text"===r||"password_protected"===r||"invalid_pdf"===r||"read_failed"===r)?n.code:"invalid_pdf","string"==typeof n?.error?n.error:`Unable to read ${e.name}`)}if("string"!=typeof n?.text)throw new nB("invalid_pdf",`Unable to read ${e.name}`);return n5(n.text),n.text}function n5(e){if(e.length>12e4)throw new nB("text_too_large","Document exceeds the extracted text limit")}let n6="\x3c!-- omp-web-document-context-v1:",n3=" --\x3e",n7="User message:\n",n9="\n\nAttached documents (locally extracted text supplied by the user):\n";function re(e,t){return`
6
- --- Begin attached document ${e+1}: ${JSON.stringify(t.name)} (${t.mimeType}, ${t.size} bytes) ---
7
- `}function rt(e){return`
8
- --- End attached document ${e+1} ---`}let rn=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function rr(e){let t=0,n=0;for(let r of e)rn.test(r)?t++:n++;return t+n/4}let ri=new Map;function rs({children:e,className:t,...n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(tB,{className:t,...n,children:e});if(!a){var l;return(0,r.jsxs)("button",{onClick:()=>o(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",s("i18n.largeMessageReveal",{size:(l=e.length)>=1e6?`${(l/1e6).toFixed(1)} MB`:l>=1e3?`${Math.round(l/1e3)} KB`:`${l} B`})]})}return(0,r.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:12,lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:e})})}let ra=null,ro=null,rl=null;function rc(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=(ra??=new Intl.DateTimeFormat([],{hour:"2-digit",minute:"2-digit"})).format(t);if(r)return i;let s=t.getFullYear()!==n.getFullYear()?(rl??=new Intl.DateTimeFormat([],{month:"short",day:"numeric",year:"numeric"})).format(t):(ro??=new Intl.DateTimeFormat([],{month:"short",day:"numeric"})).format(t);return`${s} ${i}`}let rd=(0,i.memo)(function({message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:s,onOpenFile:a,entryId:o,onFork:l,forking:c,onNavigate:d,prevAssistantEntryId:u,onEditContent:p,showTimestamp:h,prevTimestamp:m,sessionId:g,writtenFiles:f}){return"user"===e.role?(0,r.jsx)(ru,{message:e,cwd:s,onOpenFile:a,entryId:o,onFork:l,forking:c,onNavigate:d,prevAssistantEntryId:u,onEditContent:p}):"assistant"===e.role?(0,r.jsx)(rp,{message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:s,onOpenFile:a,showTimestamp:h,prevTimestamp:m,sessionId:g,entryId:o,writtenFiles:f}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(rL,{message:e}):(0,r.jsx)(rF,{message:e,cwd:s,onOpenFile:a}):"bashExecution"===e.role?(0,r.jsx)(rD,{message:e,sessionId:g}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.entryId===t.entryId&&e.onFork===t.onFork&&e.forking===t.forking&&e.onNavigate===t.onNavigate&&e.prevAssistantEntryId===t.prevAssistantEntryId&&e.onEditContent===t.onEditContent&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.sessionId===t.sessionId);function ru({message:e,cwd:t,onOpenFile:n,entryId:s,onFork:a,forking:o,onNavigate:l,prevAssistantEntryId:c,onEditContent:d}){let{t:u}=(0,E.s)(),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),f="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),x=nX(f),v=x?.message??f,b=x?.documents??[],y="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),w=rc(e.timestamp),k=!!s&&!!a,j=!!c&&!!l;return(0,r.jsxs)("div",{className:"message-user",style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsxs)("div",{className:"message-user-bubble",style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--accent-line)",borderRadius:"var(--seed-radius-r3)",padding:"8px 12px",fontSize:14,lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:[y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!v},children:y.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t)})}),b.length>0&&(0,r.jsx)("div",{role:"list","aria-label":u("chat.attachments"),style:{display:"flex",flexDirection:"column",gap:5,marginBottom:8*!!v},children:b.map((e,t)=>{var n;return(0,r.jsxs)("div",{role:"listitem",style:{display:"flex",alignItems:"center",gap:7,minWidth:0,padding:"5px 7px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"color-mix(in srgb, var(--user-bg) 70%, var(--bg-panel))"},children:[nD(e.name,14),(0,r.jsx)("span",{title:e.name,style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:[(n=n2(e),"pdf"===n?"PDF":"markdown"===n?"Markdown":"audio"===n?u("chat.attachKindAudio"):"file"===n?u("chat.attachKindFile"):"Text")," \xb7 ",nQ(e.size)]})]},`${e.name}-${t}`)})}),v&&(0,r.jsx)(rs,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:v})]})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!p,pointerEvents:p?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{tz(function(e){let t=nX(e);if(!t)return e;let n=t.documents.map(e=>e.name).join(", ");return t.message.trim()?`${t.message}
9
-
10
- Attached: ${n}`:`Attached: ${n}`}(f)).then(()=>{g(!0),setTimeout(()=>g(!1),1500)})},title:u("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:m?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{m||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{m||(e.currentTarget.style.color="var(--text-dim)")},children:[m?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),m?u("i18n.copied"):u("i18n.copy")]})}),(k||j)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:p||o?1:0,pointerEvents:p||o?"auto":"none",transition:"opacity 0.12s"},children:[j&&(0,r.jsxs)("button",{onClick:()=>{l(c),d?.(e)},title:u("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),u("i18n.editFromHere")]}),k&&(0,r.jsxs)("button",{onClick:()=>{a(s)},disabled:o,title:o?u("i18n.creatingSession"):u("i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:o?"var(--accent)":"var(--text-dim)",cursor:o?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{o||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),o?u("i18n.creating"):u("i18n.newSession")]})]}),w&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:w})]})]})}function rp({message:e,isStreaming:t,toolResults:n,modelNames:s,cwd:a,onOpenFile:o,showTimestamp:l,prevTimestamp:c,sessionId:d,entryId:u,writtenFiles:p}){var h;let m,{t:g}=(0,E.s)(),{hideThinkingBlock:f}=tQ(),x=l?rc(e.timestamp):null,v=nN(d,e.provider,e.credentialId),b=s?.[`${e.provider}:${e.model}`]??s?.[e.model]??e.model,y=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!eL(e,{isStreaming:t,hideThinking:f})),[e.content,t,f]),w=(0,i.useMemo)(()=>y.map(({block:e})=>e),[y]),k=eA(e,{isStreaming:t}),[j,S]=(0,i.useState)(!1),[C,T]=(0,i.useState)(!1),[I,N]=(0,i.useState)(!1),R=(0,i.useRef)(null),[M,$]=(0,i.useState)(null),L=(0,i.useRef)(y);L.current=y;let A=(0,i.useRef)(new Map),P=(0,i.useMemo)(()=>{if(!t)return A.current=new Map,0;let e=new Map,n=0;for(let{block:t,originalIndex:r}of y){let i="text"===t.type?t.text:"thinking"===t.type?t.thinking:"toolCall"===t.type?JSON.stringify(t.input??{})??"":null;if(null===i)continue;let s=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return rr(t);let i=e.tokens,s=e.text.length;return s>0&&s<t.length&&(n=e.text.charCodeAt(s-1))>=55296&&n<=56319&&(r=t.charCodeAt(s))>=56320&&r<=57343&&(i-=1/4,s--),i+rr(t.slice(s))}(A.current.get(r),i);e.set(r,{text:i,tokens:s}),n+=s}return A.current=e,n},[y,t]),F=(0,i.useRef)(P);F.current=P;let z=(0,i.useRef)(new Map),[W,D]=(0,i.useState)(new Map),O=(0,i.useMemo)(()=>{if(!e.timestamp||!c)return;let t=Math.round((e.timestamp-c)/1e3);return t>0?t:void 0},[e.timestamp,c]),B=(0,i.useMemo)(()=>{let t=new Map;if(!n||!e.timestamp)return t;for(let[r,i]of n)if(i.timestamp&&e.timestamp){let n=Math.round((i.timestamp-e.timestamp)/1e3);n>0&&t.set(r,n)}return t},[n,e.timestamp]),_=w.filter(e=>"text"===e.type).map(e=>e.text).join("\n");return((0,i.useEffect)(()=>{if(!t){let e=new Date().getTime();D(t=>{let n=new Map(t);for(let[t,r]of z.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),R.current=null,$(null);return}let e=setInterval(()=>{let e=L.current,t=Date.now();e.forEach(({originalIndex:e})=>{z.current.has(e)||z.current.set(e,t)}),D(n=>{let r=!1,i=new Map(n);for(let n=0;n<e.length-1;n++){let s=e[n].originalIndex,a=e[n+1].originalIndex;if(!i.has(s)&&z.current.has(s)){let e=z.current.get(s),n=z.current.get(a)??t;i.set(s,Math.round((n-e)/1e3)),r=!0}}return r?i:n});let n=F.current;if(0===n)return;null===R.current&&(R.current=t);let r=(t-R.current)/1e3;r>.5&&$(n/r)},300);return()=>clearInterval(e)},[t]),0!==w.length||t||k)?(0,r.jsxs)("div",{className:`message-assistant${t?" is-streaming":""}`,style:{marginBottom:16},onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),children:[(0,r.jsx)("div",{className:"message-assistant-role",style:{fontSize:11,color:"var(--text-dim)",marginBottom:2,display:"flex",alignItems:"center",gap:9,...v?{minHeight:40}:null},children:e.provider&&(0,r.jsxs)(r.Fragment,{children:[v&&(0,r.jsx)(nR,{seed:v.seed,size:40,provider:e.provider}),v&&(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:v.alias}),(0,r.jsx)("span",{children:`${nt(e.provider)} \xb7 ${b}`})]})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:y.map(({block:e,originalIndex:i})=>(0,r.jsx)(rh,{block:e,toolResults:n,isStreaming:t,streamingDuration:W.get(i)??("thinking"===e.type?O:void 0),toolCallDurations:B,cwd:a,onOpenFile:o,sessionId:d,entryId:u,blockIndex:i},`${u??"stream"}-${i}`))}),k&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(w.length>0),padding:"7px 10px",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",background:"var(--danger-soft)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",k]}),p&&p.length>0&&(0,r.jsx)(nO,{files:p,onOpenFile:o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,r.jsx)("button",{type:"button",onClick:()=>N(e=>!e),onFocus:()=>S(!0),onBlur:()=>S(!1),"aria-expanded":I,title:g("i18n.messageUsageTitle"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:I?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:j||I?1:0,pointerEvents:j||I?"auto":"none",transition:"opacity 0.12s, color 0.12s"},children:I?(h=e.usage,m=[],h.input&&m.push(`${h.input.toLocaleString()} in`),h.output&&m.push(`${h.output.toLocaleString()} out`),h.cacheRead&&m.push(`${h.cacheRead.toLocaleString()} cache R`),h.cacheWrite&&m.push(`${h.cacheWrite.toLocaleString()} cache W`),h.cost?.total&&m.push(`$${h.cost.total.toFixed(4)}`),m.join(" \xb7 ")):g("i18n.messageUsage")}),t&&Math.round(P)>0&&(0,r.jsx)("button",{type:"button",onClick:()=>N(e=>!e),"aria-expanded":I,title:g("i18n.estimatedTokens"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:I?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:I?`~${Math.round(P)}${null!==M?` \xb7 ${M.toFixed(1)} t/s`:""}`:g("i18n.messageUsage")}),_&&!t&&(0,r.jsxs)("button",{onClick:()=>{tz(_).then(()=>{T(!0),setTimeout(()=>T(!1),1500)})},title:g("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:C?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!j,pointerEvents:j?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{C||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{C||(e.currentTarget.style.color="var(--text-dim)")},children:[C?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),g(C?"i18n.copied":"i18n.copy")]}),x&&!t&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:x})]})]}):null}function rh({block:e,toolResults:t,isStreaming:n,streamingDuration:i,toolCallDurations:s,cwd:a,onOpenFile:o,sessionId:l,entryId:c,blockIndex:d}){if("text"===e.type)return(0,r.jsx)(rx,{block:e,isStreaming:n,cwd:a,onOpenFile:o});if("thinking"===e.type)return(0,r.jsx)(rv,{block:e,duration:i,sessionId:l,entryId:c,blockIndex:d});if("toolCall"===e.type){let n=t?.get(e.toolCallId),i=s?.get(e.toolCallId);return(0,r.jsx)(rb,{block:e,result:n,duration:i})}if("image"===e.type)return"image"===e.type&&"toolImage"in e?l?(0,r.jsx)(rg,{sessionId:l,toolCallId:e.toolImage.toolCallId}):null:(0,r.jsx)(rm,{block:e});return null}function rm({block:e}){let t=rW(e);return t?(0,r.jsx)("img",{src:t,alt:"",style:{maxWidth:"100%",maxHeight:420,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}}):null}function rg({sessionId:e,toolCallId:t}){let{t:n}=(0,E.s)(),[s,a]=(0,i.useState)(()=>eD.get(`${e}
11
- ${t}`)),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{if(void 0!==s)return;let n=!0;return(function(e,t){let n=`${e}
12
- ${t}`,r=eD.get(n);if(void 0!==r)return Promise.resolve(r);let i=eO.get(n);if(i)return i;let s=fetch(ez(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,s),s})(e,t).then(e=>{n&&a(e)}),()=>{n=!1}},[s,e,t]),!s)return null;let u=Array.from({length:s},(e,t)=>t).filter(e=>!c.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:()=>l(i),children:(0,r.jsx)("img",{src:ez(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(i))})},i)),null!==o&&(0,r.jsx)(rf,{src:ez(e,t,o),onClose:()=>l(null)})]})}function rf({src:e,onClose:t}){let{t:n}=(0,E.s)(),s=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,W.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"tool-image-dialog",onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:[(0,r.jsx)("img",{className:"tool-image-full",src:e,alt:"",draggable:!1}),(0,r.jsx)("button",{type:"button",className:"tool-image-close",onClick:t,children:n("i18n.close")})]}),document.body)}function rx({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(rs,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rv({block:e,duration:t,sessionId:n,entryId:s,blockIndex:a}){let{t:o}=(0,E.s)(),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){c(null),u(!1),h(null);return}let t=!1;return n&&s?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=ri.get(r);if(i)return ri.delete(r),ri.set(r,i),i;let s=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw ri.delete(r),e});if(ri.set(r,s),ri.size>100){let e=ri.keys().next().value;e&&ri.delete(e)}return s})(n,s,a).then(e=>{t||c(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(o("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,a,s,n,o]);let m=e.deferred?l:e.thinking,g="string"==typeof m&&m.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":o("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:d?(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):g?(0,r.jsx)(tB,{className:"markdown-thinking-body",children:m}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&g&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function rb({block:e,result:t,duration:n}){let s,a=e.toolName.toLowerCase(),o="edit"===a||a.startsWith("edit_")||a.endsWith(".edit")||a.endsWith("_edit")||a.includes("str_replace")||a.includes("replace_editor"),[l,c]=(0,i.useState)(o),d=JSON.stringify(e.input,null,2),u="todo"===a||a.endsWith(".todo")||a.endsWith("_todo"),p="bash"===a||a.startsWith("bash ")||a.endsWith(".bash")||a.endsWith("_bash"),h=t&&!t.isError?function(e){let t=e.details;if(!rE(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(t):null,m=u?"unknown"===(s=e2(e,t)).kind||0===s.phases.length?null:s.phases:null,g=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,f=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,x=null!==f&&("(no output)"===f.trim()||""===f.trim()),v=t?.isError??!1;if(p)return(0,r.jsx)(rC,{command:rE(e.input)&&"string"==typeof e.input.command?e.input.command:"",output:f??"",pending:!t,isError:v,duration:n,local:a.includes("(local)")});if(u&&m)return(0,r.jsx)(rS,{phases:m});let b=!!(m||h),y=function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.length)return"";let i=e.toolName.toLowerCase();if(t=i,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(0,120);if("file_path"in n)return String(n.file_path).slice(0,120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let s=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==s)return String(s).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,m);return(0,r.jsxs)("div",{className:`tool-call-card${v?" is-error":" is-success"}`,style:{borderRadius:7,overflow:"hidden",fontSize:12,border:v?"1px solid var(--danger-line)":"1px solid var(--success-line)",background:v?"var(--danger-soft)":"var(--success-soft)"},children:[(0,r.jsxs)("button",{className:"tool-call-header",onClick:()=>c(e=>!e),"aria-expanded":l,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)(rk,{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}),g&&(0,r.jsxs)("span",{title:`${g.added} lines added, ${g.removed} lines removed`,"aria-label":`${g.added} lines added, ${g.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:["+",g.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",g.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:l?"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:l?560:260,overflowY:"auto",overflowX:"hidden",borderTop:"1px solid var(--success-line)"},children:(0,r.jsx)(rT,{diff:h})}),t&&v&&(0,r.jsx)(r$,{text:f??"",isEmpty:x,isError:!0}),l&&!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:d}),l&&t&&!b&&!v&&(0,r.jsx)(r$,{text:f??"",isEmpty:x,isError:!1})]})}let ry={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 rw(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function rk({toolName:e,isError:t}){let n,i=(n=e.trim().toLowerCase()).includes("str_replace")||n.includes("replace_editor")||rw(n,"edit")?"edit":rw(n,"read")||rw(n,"cat")?"read":rw(n,"write")||rw(n,"save")?"write":rw(n,"glob")||rw(n,"find")?"glob":rw(n,"grep")||rw(n,"search")?"grep":rw(n,"bash")||rw(n,"shell")||rw(n,"exec")?"bash":rw(n,"todo")?"todo":rw(n,"eval")?"eval":rw(n,"task")||rw(n,"agent")?"task":rw(n,"browser")||rw(n,"web_search")||rw(n,"fetch")?"browser":rw(n,"image")||rw(n,"inspect_image")?"image":"generic",s=t?"var(--danger)":ry[i];return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":i,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:s},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)(rj,{kind:i})})})}function rj({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 rS({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)(nL,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function rC({command:e,output:t,pending:n,isError:i,duration:s,local:a}){let{isDark:o}=tF(),{t:l}=(0,E.s)(),c=eS(t.split(/\r?\n/)),d=1===c.length&&""===c[0]?[]:c,u=n?l("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:o?e4.xJ:e4.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "}),a&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsxs)("div",{className:"shell-output-divider",children:[(0,r.jsx)("span",{className:"shell-output-label",children:"Output"}),u&&(0,r.jsx)("span",{className:`shell-output-status${i?" is-error":n?" is-pending":""}`,children:u})]}),(0,r.jsxs)("div",{className:"shell-output-body","aria-live":n?"polite":void 0,children:[0===d.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:l("i18n.noOutput")}),d.map((e,t)=>{let n=ey(e).trimStart(),s=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${s}`.trim(),children:[eC(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":l("chat.runningCommand"),children:"▋"})]})]}),void 0!==s&&(0,r.jsxs)("div",{className:"shell-output-footer",children:[s,"s"]})]})}function rT({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(rI,{text:e.text})})}function rI({text:e}){let{t}=(0,E.s)(),n=(0,i.useMemo)(()=>nE(e),[e]);if(!n)return(0,r.jsx)(rM,{text:e});let s=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[s&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(rN,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(rN,{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)(rR,{cell:e.left,side:"left"}),(0,r.jsx)(rR,{cell:e.right,side:"right"})]},t))})]},n))})}function rN({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 rR({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:s,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function rM({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 rE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r$({text:e,isEmpty:t,isError:n}){let{t:i}=(0,E.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 rL({message:e}){let{t}=(0,E.s)(),n=rz(e.content),s=(0,i.useMemo)(()=>{let e,t,r,i,s;return e=[],t=[],r=n.match(tH),i=r?.[1]??"",s=r?.index===void 0?n:n.slice(0,r.index),i.replace(t_,(n,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):t.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:t}},[n]),a=rc(e.timestamp),o=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!==o&&(0,r.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:tU(o)})}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:a})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),s.body?(0,r.jsx)(tB,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(rA,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function rA({readFiles:e,modifiedFiles:t}){let{t:n}=(0,E.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)(rP,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(rP,{title:n("i18n.readFiles"),files:e})]})}function rP({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 rF({message:e,cwd:t,onOpenFile:n}){var s;let a,{t:o}=(0,E.s)(),l=!1===e.display,[c,d]=(0,i.useState)(!l),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),g=rz(e.content),f="string"==typeof(s=e.content)?[]:s.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=rc(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:l?"var(--bg-subtle)":"var(--bg)",opacity:l&&!c?.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}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),c?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[f.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!g},children:f.map((e,t)=>{let n=rW(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})}),g?(0,r.jsx)(tB,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:g}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:g?(a=g.replace(/\s+/g," ").trim())?a.length>140?`${a.slice(0,140)}...`:a:"Show extension message":o("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:[g||v?(0,r.jsx)("button",{onClick:()=>{tz(g||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:o(h?"i18n.copied":"i18n.copy")}):null,(x||l)&&(0,r.jsx)("button",{onClick:()=>{l?d(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(l?c?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(l&&c||!l&&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 rz(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rW(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 rD({message:e,sessionId:t}){let[n,s]=(0,i.useState)(null),[a,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(null),d=!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 g(){if(p){o(!0),c(null);try{let e=await fetch(p),t=await e.json();t.success?s(t.data?.output??""):c(t.error??"failed")}catch(e){c(String(e))}finally{o(!1)}}}let f=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:f,input:{command:e.command}},v=d?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:f,content:m?[{type:"text",text:m}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rb,{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:g,disabled:a,style:{background:"none",border:"none",color:"var(--accent)",cursor:a?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:a?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),l&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",l,")"]})]})]})}let rO="cuelo-chat-search",rB="cuelo-chat-search-active";function r_(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 rH({open:e,onClose:t,containerRef:n,index:s,renderedStart:a,renderedEnd:o,contentKey:l,onReveal:c,onProgrammaticScroll:d,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[m,g]=(0,i.useState)(""),[f,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)(f);k.current=f;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)(()=>()=>{r_(rO,[]),r_(rB,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){r_(rO,[]),r_(rB,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),i=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let s=(e.textContent??"").toLowerCase(),a=n.get(i);a||(a=[],n.set(i,a));for(let n=s.indexOf(t);-1!==n;n=s.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),a.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,i){let s=[];if(!t)return s;for(let a=0;a<e.length;a++){let o=a>=r&&a<i?n.get(a)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[a],t);for(let e=0;e<o;e++)s.push({item:a,k:e})}return s}(s,w,n,a,o);j.current=r;let i=eZ(r,k.current);b(e=>e.index===i&&e.total===r.length?e:{index:i,total:r.length});let l=[];for(let t of e.values())for(let e of t)l.push(e);if(r_(rO,l),i<0){r_(rB,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=a&&u.item<o,m=S.current,g=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){r_(rB,[]),g&&c(u.item);return}let f=e.get(u.item)?.[u.k];if(r_(rB,f?[f]:[]),g)if(d(),f){let e,n;e=f.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,s,a,o,l,f,n,c,d]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=eZ(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let T=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=>g(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:T}),(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 rU({questions:e,containerRef:t,layoutKey:n,onJump:s,label:a}){let o=(0,i.useRef)(null),[l,c]=(0,i.useState)(-1),[d,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=d&&e.length>=2;(0,i.useEffect)(()=>{let n=t.current;if(!n||!p)return;let r=0,i=null,s=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,s=0,a=i.length-1,o=i.length-1;for(;s<=a;){let e=s+a>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(o=e,a=e-1):s=e+1}let l=o>=0?Number(i[o].dataset.chatItem):-1,d=-1;for(let t of e){if(t.item>l)break;d=t.item}c(d)},a=()=>{r||(r=requestAnimationFrame(s))};return r=requestAnimationFrame(s),n.addEventListener("scroll",a,{passive:!0}),()=>{n.removeEventListener("scroll",a),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,i.useEffect)(()=>{let e=o.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)},[l]);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));o.current?.querySelectorAll("button")[r]?.focus()},[h]);if(!p)return null;let g=e.some(e=>e.item===l)?l:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":a,children:(0,r.jsx)("div",{ref:o,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(rq,{question:e,position:t,count:h,active:e.item===l,focusable:e.item===g,onJump:s,onMoveFocus:m},e.item))})})}let rq=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:s,onJump:a,onMoveFocus:o}){let l=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,r.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:s?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${l}`,title:l,onClick:()=>a(e.item),onKeyDown:e=>o(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function rV({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})]})}function rK({stalled:e,t}){return e?(0,r.jsx)(rV,{label:t("chat.stallLabel"),tone:"warning",children:t("chat.stallMessage")}):null}let rJ={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function rG({compaction:e,t}){let[n,s]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;s(Date.now());let t=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let a=Math.max(0,Math.floor((n-e.startedAt)/1e3)),o=e.reason&&!0===rJ[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(rV,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:a}),o?` \xb7 ${o}`:""]})}function rY({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 rZ=n(39092),rX=n.n(rZ);let rQ=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],r0={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},r1=["approval","choice","done","failed","blocked","working"],r2={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},r8={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function r4(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function r5(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(r2,e)?e:null}function r6(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:s,ko:a}=i;if("string"!=typeof e||""===e)continue;let o=r5(s);if(null===o)continue;let l=t+e.replace(/^\/+/,""),c=n.get(o);c?c.push(l):n.set(o,[l]),"string"==typeof a&&""!==a.trim()&&r.set(l,a.trim())}return{files:n,lines:r}}function r3(e,t,n){if(!t||!Object.hasOwn(r0,t))return null;let r=r0[t];return e.get(r)?.get(n)??null}async function r7(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return function(e){let t=new Map;if("object"!=typeof e||null===e)return t;let{characters:n}=e;if(!Array.isArray(n))return t;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:r,stickers:i,captions:s}=e;if("string"!=typeof n||""===n)continue;let a=r6(r,"/audio/completion/"),o=r6(i,"/stickers/"),l=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=r5(e);if(null===i)continue;let s=t.get(i);s?s.push(r.trim()):t.set(i,[r.trim()])}return t}(s),c=new Map;for(let e of r1){let t=a.files.get(e)??[],n=new Map;for(let e of t){let t=a.lines.get(e);void 0!==t&&n.set(e,t)}c.set(e,{voices:t,stickers:o.files.get(e)??[],lines:n,captions:l.get(e)??[]})}t.set(n,c)}return t}(await t.json())}catch{return new Map}}function r9(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,s=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&s>=r?s+1:s]}function ie(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 it=["01","02","03"];function ir(e,t,n){if(!e||"streaming"===t||!rQ.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),s=r9(it.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>(function(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),0x1000193);return(t>>>0)/0x100000000})(n));return s?{src:s,alt:r2[r]}:null}let ii=new Map,is=(0,i.createContext)(ii);function ia({utterances:e,children:t}){return(0,r.jsx)(is.Provider,{value:e,children:t})}function io({turnIndex:e,turnEntryId:t,sessionId:n,cwd:s,onOpenFile:a}){let o=(0,i.useContext)(is).get(e);return o&&0!==o.length?(0,r.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:o.map(e=>(0,r.jsx)(il,{utterance:e,sessionId:n,cwd:s,onOpenFile:a},e.key))}):null}function il({utterance:e,sessionId:t,cwd:n,onOpenFile:s}){let a=nN(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),u=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=u.current;e&&!o&&d(e.scrollHeight>e.clientHeight+1)},[e.text,o]);let p=e.text.trim().length>0,h=e.label?.trim(),m=a?.alias??h??nt(e.provider),g=a?.alias.split("(",1)[0]?.trim(),f=a&&h&&h!==a.alias&&h!==g?`작업 \xb7 ${h}`:null,x=ir(a?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...a?{minHeight:40}:null},children:[a&&(0,r.jsx)(nR,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),f&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:f})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(tB,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:s,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(c||o)&&(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,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:o?"접기":"더보기"}),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)(rX(),{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 ic=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function id(e,t,n,r){if("string"!=typeof n)return[];let i=ic.exec(n),s=i?.[1],a=i?.[2];return s&&a?[{toolCallId:e,...t?{name:t}:{},alias:s,model:a,batchSize:r}]:[]}function iu(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(...id(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(...id(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function ip(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 ih=/^agent:\/\/([^/?#]+)\/?$/i;function im(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?ih.exec(e.path):null,s=i?.[1],a=e.content;if(!s||"string"!=typeof a)continue;let o=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:s,message:a,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return n}let ig=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function ix(e){if(!e)return null;let t=/^\s*TASK_GUARD\s*:\s*$/im.exec(e),n=e;if(t){let r=t.index+t[0].length;"\r"===e[r]&&(r+=1),"\n"===e[r]&&(r+=1);let i=r;for(;r<e.length;){let t=e.indexOf("\n",r),n=-1===t?e.length:t,s=n>r&&"\r"===e[n-1]?n-1:n;if(!ig.test(e.slice(r,s)))break;i=s,r=-1===t?e.length:t+1}let s=t[0].length-t[0].trimStart().length;n=`${e.slice(0,t.index+s)}${e.slice(i)}`}let r=[...n.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===r.length&&r[0]&&r[0]===r[0].trim()&&/[가-힣]/u.test(r[0])?r[0]:null}class iv extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function ib(e){try{return await e.json()}catch{throw new iv("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function iy(e){return!!e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.bytes&&"number"==typeof e.modified&&(null===e.messages||"number"==typeof e.messages)&&(void 0===e.taskTitle||"string"==typeof e.taskTitle)&&"string"==typeof e.firstTask}function iw(e){return!!e&&"object"==typeof e&&"string"==typeof e.role&&("message"===e.kind||"custom"===e.kind)&&"string"==typeof e.text&&(null===e.at||"number"==typeof e.at)}function ik(e){return!!e&&"object"==typeof e&&!!("id"in e&&"string"==typeof e.id)&&!!("index"in e&&"number"==typeof e.index)&&!!("agent"in e&&"string"==typeof e.agent)&&!!("agentSource"in e&&("bundled"===e.agentSource||"user"===e.agentSource||"project"===e.agentSource))&&!!("status"in e&&("pending"===e.status||"running"===e.status||"completed"===e.status||"failed"===e.status||"aborted"===e.status||"unknown"===e.status))&&!!("lastUpdate"in e&&"number"==typeof e.lastUpdate)&&!0}function ij(e){return!!e&&"object"==typeof e&&(!("id"in e)||void 0===e.id||"string"==typeof e.id)&&(!("type"in e)||void 0===e.type||"string"==typeof e.type)&&(!("message"in e)||void 0===e.message||null!==e.message&&"object"==typeof e.message)}function iS(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let n=async(t,n,r)=>{let i;try{i=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new iv(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let s=await ib(i);if(!i.ok)throw new iv("http",function(e,t){if(e&&"object"==typeof e&&"error"in e){let t=e.error;if("string"==typeof t&&t)return t}return t}(s,`HTTP ${i.status}`),i.status);return{response:i,body:s}};return{async getLiveSnapshots(e,t){let{body:r}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!r||"object"!=typeof r)throw new iv("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new iv("http",r.error);if(!0!==r.running)return{runtime:"detached",subagents:[]};let i=r.state?.subagents;if(void 0!==i&&(!Array.isArray(i)||!i.every(ik)))throw new iv("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:i??[]}},async getLiveTranscript(e,t,r,i){let{body:s}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:r}),signal:i},"live-unreachable");if(!s||"object"!=typeof s)throw new iv("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof s.error&&s.error)throw new iv("http",s.error);if(!0!==s.success||!s.data||"object"!=typeof s.data)throw new iv("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let a=s.data;if(!Array.isArray(a.entries)||!a.entries.every(ij)||"number"!=typeof a.fromByte||"number"!=typeof a.nextByte||"boolean"!=typeof a.reset)throw new iv("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:a.fromByte,nextByte:a.nextByte,reset:a.reset,entries:a.entries}},async getArchive(e,r){let i=`${t}/archive?session=${encodeURIComponent(e)}`,{body:s}=await n(i,{method:"GET",signal:r},"sidecar-unreachable");if(!s||"object"!=typeof s||"string"!=typeof s.sessionId||"string"!=typeof s.dir||"boolean"!=typeof s.found||!Array.isArray(s.subagents)||!s.subagents.every(iy))throw new iv("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:s.sessionId,dir:s.dir,found:s.found,subagents:s.subagents,...!0===s.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,r,i=400,s){let a=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(r)}&limit=${encodeURIComponent(String(i))}`,{body:o}=await n(a,{method:"GET",signal:s},"sidecar-unreachable");if(!o||"object"!=typeof o||"string"!=typeof o.sessionId||"string"!=typeof o.name||"number"!=typeof o.bytes||"boolean"!=typeof o.truncated||!Array.isArray(o.entries)||!o.entries.every(iw))throw new iv("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}function iC(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:n}}function iT(e){return"pending"===e||"running"===e}let iI=new Map;function iN(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function iR(e){return e instanceof iv&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function iM(e,{sessionId:t,client:n,enabled:r}){let[s,a]=(0,i.useState)(iI),o=(0,i.useRef)(new Map),l=(0,i.useRef)(e);l.current=e;let c=(0,i.useCallback)(()=>{let e=o.current;a(t=>{let n=!1,r=new Map;for(let[i,s]of e){let e=t.get(i),a=e&&e.entries===s.collected&&e.state===s.state?e:{state:s.state,entries:s.collected};a!==e&&(n=!0),r.set(i,a)}return r.size!==t.size&&(n=!0),n?r:t})},[]),d=e.map(e=>`${e.key}|${iN(e)}`).join("\n");return(0,i.useEffect)(()=>{if(!r)return;let e=!1,i=!1,s=null,a=o.current,d=new Set(l.current.map(e=>e.key));for(let e of[...a.keys()])d.has(e)||a.delete(e);for(let e of l.current){let t=iN(e);a.get(e.key)?.signature!==t&&a.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(r,i,s,a)=>{if(!r.archiveName){i.state={kind:"empty",source:"live",note:a};return}try{let o=await n.getArchiveTranscript(t,r.archiveName,400,s);if(e)return;0===i.collected.length&&(i.collected=o.entries.flatMap((e,t)=>{let n=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:n,message:e.message}]:e.irc?[{id:n,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),i.state=0===o.entries.length?{kind:"empty",source:"archive",note:a}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:a}}catch(n){if(e||s.aborted)return;let t=iR(n);i.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(r,i)=>{let s=a.get(r.key);if(s){if(!r.liveId)return void await u(r,s,i);try{var o,l;let a=await n.getLiveTranscript(t,r.liveId,s.nextByte,i);if(e)return;let c=(o=a.entries,l=a.fromByte,o.flatMap((e,t)=>{let n=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:n,message:iC(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:n,irc:{from:"string"==typeof t.from?t.from:void 0,message:"string"==typeof t.message?t.message:void 0}}]}return[]}));a.reset||0===a.fromByte?s.collected=c:c.length>0&&(s.collected=[...s.collected,...c]),s.nextByte=a.nextByte,s.collected.length>0?("ready-live"!==s.state.kind||s.state.entries!==s.collected)&&(s.state={kind:"ready-live",entries:s.collected}):await u(r,s,i)}catch(t){if(e||i.aborted)return;if(r.archiveName){let e=iR(t);await u(r,s,i,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=iR(t);s.state="unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message}}}}},h=async()=>{if(e||i||"u">typeof document&&"visible"!==document.visibilityState)return;i=!0;let t=new AbortController;s=t;try{for(let e of l.current)await p(e,t.signal)}finally{i=!1}e||c()};h();let m=l.current.some(e=>iT(e.status))?setInterval(()=>void h(),3e3):void 0,g=()=>{"visible"===document.visibilityState&&h()};return document.addEventListener("visibilitychange",g),()=>{e=!0,s?.abort(),clearInterval(m),document.removeEventListener("visibilitychange",g)}},[n,r,c,t,d]),s}let iE=["greeting","utterance","message","text"],i$=function(e){let t=(0,i.useMemo)(()=>iS(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let s of n.subagents){if(t.has(s.name))continue;let n=[...i].reverse().find(e=>e.name===s.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},s="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,a="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==s||void 0!==a)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==s?{resolvedModel:s,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==a?{retryFailure:{attempt:0,errorMessage:a}}:{}}),i}(s,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),s="string"==typeof t.task?ic.exec(t.task):null,a=s?.[1],o=s?.[2],l=i.find(e=>e.name===t.id)??(a&&o?r.requests.find(e=>e.alias===a&&e.model===o):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!l)return[];let c=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:l,sends:c}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),s=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),a=iM(s,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&s.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:s}=e,a="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",o="failed"===a,l=s?.model.split("/",1)[0]?.trim()||void 0,c=o&&l?l:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=r.indexOf("/");if(i>0)return r.slice(0,i);let s=t?.model.trim()??"",a=s.indexOf("/");return a>0?s.slice(0,a):n?.trim()||void 0}(i,s,n),d=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,n)=>{var r;let g;if("irc"in t){let{from:n,message:r,truncated:s}=t.irc;if(s||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let s=e.sends[t];if(s.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(s.send,i.id)&&s.send.from===n){h=s.turnIndex,m=t+1;break}}return}if("assistant"!==t.message.role)return;let f=t.message.provider||c;if(!f||o&&l&&f!==l)return;let x=((g=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?g: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",...iE]){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))||(o?t.message.errorMessage?.trim()??"":"");0!==x.length&&p.push({key:`${i.id}:${n}`,turnIndex:h,speakerId:u,provider:f,credentialId:t.message.credentialId,accountSessionId:null,label:o&&s?s.alias:d,text:x,status:a})}),0===p.length&&"settled"!==a&&c){let e=o?i.progress?.retryFailure?.errorMessage?.trim():void 0;p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:c,accountSessionId:null,label:o&&s?s.alias:d,text:e||"",status:a})}return p})(t,a.get(t.snapshot.id),e.sessionProvider)),[r,a,e.sessionProvider])},iL="web6",iA=[],iP=[],iF=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let s=`${t}?sessionId=${encodeURIComponent(i)}`,a=await e(s,{signal:r});if(!a.ok)throw Error(`HTTP ${a.status}`);let o=await a.json(),l=o&&"object"==typeof o&&"consults"in o?o.consults:null;if(!Array.isArray(l))throw Error("consults 배열이 아니다");return l.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:s,text:a,error:o}=e;return{sessionId:t,startedAt:n,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof s&&""!==s?s:void 0,text:"string"==typeof a&&""!==a?a:void 0,error:"string"==typeof o&&""!==o?o:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(iP),s=(0,i.useRef)(""),a=e.sessionId??"",o=a.length>0;return(0,i.useEffect)(()=>{if(!o){s.current="",r(iP);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(a,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===s.current)return;s.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,o,a]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return iA;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 iA;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let s=t.error??"";0!==s.trim().length&&i.push({key:`${iL}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${iL}:${t.conversationId??"unknown"}`,text:s,status:"failed"})}return i.length>0?i:iA})(n,e.messages,a),[n,e.messages,a])},iz=(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"})]}),iW=(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?iz:iW})})})}let iO={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0},iB={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},i_=(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"})]}),iH=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function iU({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:s}=(0,E.s)(),a=function(e,t,n){let{locale:r}=(0,E.s)(),[s,a]=(0,i.useState)("idle"),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,i.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,y.current?.close(),y.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let n=b.current;b.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),a(e),p(null),f(!1)},[]),S=(0,i.useCallback)((e,t)=>{l(e),d(t??null),j("error")},[j]),C=(0,i.useCallback)(async()=>{let i,s=k.current+1;k.current=s,l(null),d(null),f(!0),a("connecting");let o=e;if(!o&&t){try{o=await t()}catch{o=void 0}if(k.current!==s)return}if(!o){k.current===s&&(f(!1),S("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===s&&(f(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==s){for(let e of i.getTracks())e.stop();return}v.current=i;try{let e,t,l=new RTCPeerConnection;for(let e of(x.current=l,i.getTracks()))l.addTrack(e,i);let d=document.createElement("audio");if(d.autoplay=!0,b.current=d,l.ontrack=e=>{let[t]=e.streams;t&&(d.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await function(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(s),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},s=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}(l),k.current!==s)return;let h=l.localDescription?.sdp;if(!h)throw Error("The browser produced no offer SDP.");let m=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,sdp:h,locale:r})}),g=await m.json().catch(()=>({})),v="",j="";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&&(v=g.callId),"sdp"in g&&"string"==typeof g.sdp&&(j=g.sdp)),!m.ok||!v||!j){if(k.current===s){var c,u;f(!1),S((c=m.status,u=e,401===c||"live-auth"===u?"auth":502===c||"live-upstream"===u?"upstream":"failed"),t)}return}if(k.current!==s)return void fetch(`/api/live/call/${encodeURIComponent(v)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:j}),k.current!==s){l.close(),fetch(`/api/live/call/${encodeURIComponent(v)}`,{method:"DELETE"}).catch(()=>{});return}w.current=v;let C=new EventSource(`/api/live/events?callId=${encodeURIComponent(v)}`);y.current=C,C.onmessage=e=>{let t;if(k.current===s){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;"string"==typeof t.state&&(r=t.state,!0===iO[r])&&a(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text&&(p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&n&&Promise.resolve().then(()=>n(o)).catch(()=>{}));return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},C.onerror=()=>{k.current===s&&w.current&&S("failed")},a("live")}catch(e){k.current===s&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===s&&f(!1)}},[e,t,n,r,S]),T=(0,i.useCallback)(()=>{if("idle"===s||"closed"===s||"error"===s){g||C();return}j("idle")},[g,s,C,j]);return(0,i.useEffect)(()=>()=>j("closed"),[j]),{state:s,failure:o,detail:c,transcript:u,supported:h,toggle:T}}(e,t,n),o="connecting"===a.state||"live"===a.state||"working"===a.state,l="connecting"===a.state?"chat.liveConnecting":"working"===a.state?"chat.liveWorking":"live"===a.state?"chat.liveOn":null,c=s(o?"chat.liveStop":"chat.liveStart"),d=!1===a.supported?iB.unsupported:a.failure?iB[a.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,r.jsxs)("div",{role:"group","aria-label":s("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6},children:[d&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a.detail??void 0,children:s(d)}),l&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap"},children:s(l)}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:a.toggle,disabled:!a.supported||!u,"aria-pressed":o,title:p?s(p):c,"aria-label":p?s(p):c,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:o?iH:i_})})]})}let iq={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 iV({sessionId:e}){let{t}=(0,E.s)(),[n,s]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void s(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let a=Array.isArray(i.handles)?i.handles:[],o=a.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==o,s(o)}catch{}},a=async()=>{await i(),t||(n=window.setTimeout(()=>void a(),r?5e3:3e4))};return a(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:iq,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}function iK(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let iJ=new Map,iG="ompweb-drafts-for-reload-v1",iY=!1;function iZ(){if(iY||"u"<typeof sessionStorage)return;iY=!0;let e=sessionStorage.getItem(iG);if(e){sessionStorage.removeItem(iG);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)&&iJ.set(e[0],iQ(t))}}catch{}}}function iX(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(iG,JSON.stringify([...iJ.entries()].map(([e,t])=>[e,iQ(t)]))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function iQ(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function i0(e){return!e.value&&0===e.images.length&&0===e.documents.length}function i1(e){iZ();let t=iJ.get(e);return t?iQ(t):null}function i2(e,t){(iZ(),i0(t))?iJ.delete(e):iJ.set(e,iQ(t))}function i8(e){iJ.delete(e)}function i4(e,t,n,r,i,s=[]){let a=[...t??[],...r].filter(iK).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=nG([...i??[],...s]);return{value:e.trim()?n.trim()?`${e}
13
-
14
- ${n}`:e:n,images:a,documents:o}}function i5(e,t,n){if(e===t)return n?iQ(n):i1(t);let r=i1(e),i=n&&!i0(n)?iQ(n):r??(n?iQ(n):null),s=i1(t);if(i8(e),!i)return s;let a=s?i4(s.value,s.images,i.value,i.images,s.documents,i.documents):i;return i2(t,a),iQ(a)}function i6(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 i3(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function i7(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 i9="omp-web:model-picks";function se(){try{let e=JSON.parse(window.localStorage.getItem(i9)??"{}");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 st(e,t,n,r,i={}){let s=i.gap??8,a=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*a)),c=Math.max(0,e-s-a),d=Math.max(0,n-t-s-a),u="above"===o?c:d,p="above"===o?d:c,h=u>=r||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(r,h?u:p))}}function sn(e,t,n){return Math.min(e*t,n)}function sr(e,t,n){let{viewportFraction:r,cap:s,gap:a,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,i.useState)({side:c??"above",maxHeight:s}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),d=st(i.top,i.bottom,n,sn(n,r,s),{gap:a,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,s,a,o,l,c,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]),d}var si=n(14755);async function ss(e,t,n,r,i,s,a){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await a?.()??[],c=[...sv,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(s&&(!c||"builtin"===c.source))return i(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return i(`/${o} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}let sa=["off","default","full"],so={off:"none",default:"default",full:"full"},sl=si.IN.join(" \xb7 "),sc=si.C1.filter(e=>!si.IN.includes(e)).join(" \xb7 ");function sd(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let su=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),sp=0,sh={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function sm(e,t){return su.compare(e.name||e.modelId,t.name||t.modelId)||su.compare(e.provider,t.provider)||su.compare(e.modelId,t.modelId)}let sg=["auto","off","minimal","low","medium","high","xhigh","max"],sf=["low","medium","high","xhigh"],sx={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},sv=[{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"}],sb=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],sy={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},sw={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function sk(e,t,n){let r=e.name.toLowerCase(),i=sj(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function sj(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function sS(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function sC(e){return{data:e.data,mimeType:e.mimeType}}function sT(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function sI(e){return(e??[]).filter(iK).slice(0,10).map(sT)}function sN(e){return nG(e).map(e=>{let t=n2(e);return{...e,id:++sp,status:"ready",..."audio"===t||"file"===t?{stored:t}:{}}})}function sR(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sM({kind:e,text:t,onRemove:n,removeLabel:i}){let s=nX(t),a=s?[s.message,s.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):t;return(0,r.jsxs)("div",{title:a,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:"var(--seed-radius-full)",border:`1px solid ${"steer"===e?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===e?"var(--accent)":"var(--text-dim)"},children:e}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),n&&(0,r.jsx)("button",{type:"button",onClick:n,title:i,"aria-label":i,style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,color:"var(--text-dim)",background:"transparent",border:"none",borderRadius:"var(--radius-control)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},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",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]})}function sE({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 s$({error:e}){return e?(0,r.jsx)(sE,{tone:"error",title:"Model error",body:e}):null}function sL({warnings:e}){return e&&0!==e.length?(0,r.jsx)(sE,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sA=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:s,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:g,mainPresetActiveAlias:f,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:T,thinkingLevel:I,effectiveThinkingLevel:N,thinkingCeiling:R,onThinkingLevelChange:M,availableThinkingLevels:$,thinkingLevelMap:L,retryInfo:A,queuedMessages:P,inputHistory:F=[],onRecallQueue:W,onRemoveQueuedMessage:D,slashCommands:O,slashCommandsLoading:B,onLoadSlashCommands:_,onBuiltinCommand:H,soundEnabled:U,onSoundToggle:q,onAudioUnlock:V,onPromptWithStreamingBehavior:K,draftKey:J,cwd:G,sessionId:Y,onEnsureSession:Z,onLiveTranscriptPersisted:X},Q){let ee,et,en,er,ei,es,{t:ea}=(0,E.s)(),eo=z(),[el,ec]=(0,i.useState)(()=>J?i1(J)?.value??"":""),[ed,eu]=(0,i.useState)(!1),[ep,eh]=(0,i.useState)(null),[em,eg]=(0,i.useState)(""),[ef,ex]=(0,i.useState)({});(0,i.useEffect)(()=>{ed&&ex(se())},[ed]);let[ev,eb]=(0,i.useState)(!1),[ey,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(!1),[eT,eI]=(0,i.useState)(null),[eN,eR]=(0,i.useState)(!1),[eM,eE]=(0,i.useState)(()=>J?sI(i1(J)?.images):[]),[e$,eL]=(0,i.useState)(()=>J?sN(i1(J)?.documents):[]),[eA,eP]=(0,i.useState)(null),eF=(0,i.useMemo)(()=>e$.filter(e=>"ready"===e.status),[e$]),ez=e$.some(e=>"ready"!==e.status),eW=el.trimStart(),eD=0===eM.length&&0===e$.length&&eW.startsWith("!"),eO=eD&&eW.startsWith("!!"),[eB,e_]=(0,i.useState)(!1),[eH,eU]=(0,i.useState)(0),[eq,eV]=(0,i.useState)(null),[eK,eJ]=(0,i.useState)(!1),[eG,eY]=(0,i.useState)(0),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(0),[e1,e2]=(0,i.useState)(null),[e8,e4]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=G&&e3?.cwd===G?e3.values:{},te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),ti=(0,i.useRef)(null),ts=(0,i.useRef)(null),ta=(0,i.useRef)(null),to=(0,i.useRef)(null),tl=(0,i.useRef)(null),tc=(0,i.useRef)(null),td=(0,i.useRef)(null),tu=(0,i.useRef)(!1),tp=(0,i.useRef)(0),th=(0,i.useRef)(!1),tm=(0,i.useRef)([]),tg=(0,i.useRef)([]),tf=(0,i.useRef)([]),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(J),ty=(0,i.useRef)(el),tw=(0,i.useRef)(eM),tk=(0,i.useRef)(0),tj=(0,i.useRef)(e$);ty.current=el,tw.current=eM,tj.current=e$,(0,i.useImperativeHandle)(Q,()=>({insertIfEmpty(e){let t=te.current;(t?t.value:el).trim()||(ty.current=e,ec(e),eV(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=te.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:el,tw.current.length,tk.current,tj.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"),nX(t)?.message??t),s=sI("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return iK(r)?[r]:[]})),a=sN((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),nX(n)?.documents??[]));ty.current=i,tw.current=s,tj.current=a,ec(i),eV(null),eX(!1),eE(e=>(e.forEach(sR),s)),eL(a),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tb.current!==e)return void i5(e,t);let n={value:ty.current,images:tw.current.map(sC),documents:tj.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))},r=i5(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);if(tb.current=t,i)return;let s=sI(r.images),a=sN(r.documents),o=r.value;ty.current=o,tw.current=s,tj.current=a,ec(o),eE(e=>(e.forEach(sR),s)),eL(a),eV(null),eX(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tb.current,s=r??i,a=s===i,o=!a&&s?i1(s):null,l=i4(e,t,a?ty.current:o?.value??"",a?tw.current.map(sC):o?.images??[],n,a?tj.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r})):o?.documents??[]);if(s&&i2(s,l),!a)return;let c=t?.length?[...sI(t).slice(0,Math.max(0,10-tw.current.length)),...tw.current].slice(0,10):tw.current,d=sN(l.documents);ty.current=l.value,tw.current=c,tj.current=d,ec(l.value),eV(null),eX(!1),t?.length&&eE(e=>{let n=Math.max(0,10-e.length),r=sI(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tw.current=i,i}),eL(d),requestAnimationFrame(()=>{let e=te.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=te.current;if(!t)return void ec(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),s=t.value.slice(r),a=i.length>0&&!i.endsWith(" ")?" ":"",o=i+a+e+s;ty.current=o,ec(o),eV(null),requestAnimationFrame(()=>{if(!t)return;let r=n+a.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tN(e)}}));let tS=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tw.current.length-tk.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eP(ea("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:nQ(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eP(ea("chat.attachImageLimit",{count:10})),i.length){tk.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)})));eE(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(sR);let r=[...t,...n];return tw.current=r,r})}finally{tk.current-=i.length}}},[ea]),tC=(0,i.useCallback)(async e=>{for(let t of e){let e=nq(t);if(!e)continue;if(tj.current.length>=3){eP(ea("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eP(ea("chat.attachTooLarge",{name:t.name,limit:nQ(8388608)}));continue}if(tj.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eP(ea("chat.attachTotalTooLarge",{limit:nQ(0x1000000)}));continue}let n={id:++sp,name:t.name,mimeType:n_[e],size:t.size,text:"",status:"extracting"},r=[...tj.current,n];tj.current=r,eL(r);try{let e=await nY(t);if(tj.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new nB("text_too_large","Total extracted text exceeds 240000 characters");let r=tj.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tj.current=r,eL(r)}catch(i){let e=tj.current.some(e=>e.id===n.id),r=tj.current.filter(e=>e.id!==n.id);if(tj.current=r,eL(r),!e)continue;i instanceof nB?"text_too_large"===i.code?eP(ea("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eP(ea("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eP(ea("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eP(ea("chat.attachPasswordProtected",{name:t.name})):eP(ea("chat.attachExtractFailed",{name:t.name})):eP(ea("chat.attachExtractFailed",{name:t.name}))}}},[ea]),tT=(0,i.useCallback)((e,t)=>{if(!tj.current.some(t=>t.id===e))return!1;let n=t?tj.current.map(n=>n.id===e?t:n):tj.current.filter(t=>t.id!==e);return tj.current=n,eL(n),!0},[]),tI=(0,i.useCallback)(async(e,t)=>{for(let n of e){if(tj.current.length>=3){eP(ea("chat.attachLimit",{count:3}));continue}if(n.size>0x1900000){eP(ea("chat.attachStoredTooLarge",{name:n.name,limit:nQ(0x1900000)}));continue}let e={id:++sp,name:n.name,mimeType:"text/plain",size:n.size,text:"",status:"audio"===t?"transcribing":"extracting",sourceSize:n.size},r=[...tj.current,e];tj.current=r,eL(r);let i=(t,n)=>{let r=tj.current.filter(t=>t.id!==e.id);return t<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+t<=24e4&&r.reduce((e,t)=>e+t.size,0)+n<=0x1000000};if("file"===t&&n.size<=8388608){let t=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?nJ("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?nJ("utf-16be",t.subarray(2)):t.includes(0)?null:nJ("utf-8",t)??nJ("euc-kr",t)},()=>null);if(null!==t&&i(t.length,n.size)){tT(e.id,{...e,text:t,status:"ready"});continue}}let s={...e,stored:t,status:"audio"===t?"transcribing":"uploading"};if(tT(e.id,s))try{let r=await n8(n,Y),a=tj.current.filter(t=>t.id!==e.id).reduce((e,t)=>e+t.text.length,0),o=function(e,t=12e4){let n=`${n1}${e.path}
15
- (${e.mimeType}, ${e.size} bytes) Open it with a tool when its contents are needed.`;if(void 0!==e.transcript){let r=`${n}
16
-
17
- Transcript of the audio (speech-to-text by Gemini; may contain recognition errors):
18
- `,i=r+e.transcript;return i.length<=t?i:r+e.transcript.slice(0,Math.max(0,t-r.length-n0.length))+n0}return e.transcriptError?`${n}
19
- The audio could not be transcribed: ${e.transcriptError}`:n}(r,Math.min(12e4,24e4-a)),l=new TextEncoder().encode(o).byteLength;if(!i(o.length,l)){tT(e.id,null)&&eP(ea("chat.attachTotalTooLarge",{limit:nQ(0x1000000)}));continue}let c="audio"===t&&void 0===r.transcript;tT(e.id,{...s,text:o,size:l,status:"ready",transcriptFailed:c})&&c&&eP(ea("chat.attachTranscribeFailedNotice",{name:n.name,error:r.transcriptError??""}))}catch(t){tT(e.id,null)&&eP(ea("chat.attachUploadFailed",{name:n.name,error:t instanceof Error?t.message:String(t)}))}}},[tT,Y,ea]),tN=(0,i.useCallback)(async e=>{eP(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let s of e)s.type.startsWith("image/")?t.push(s):null!==nq(s)?n.push(s):nK(s)?r.push(s):i.push(s);return{images:t,documents:n,audio:r,files:i}}(e);await Promise.all([tS(t),tC(n),tI(r,"audio"),tI(i,"file")])},[tC,tI,tS]),tR=(0,i.useCallback)(e=>{eE(t=>{let n=[...t],[r]=n.splice(e,1);return r&&sR(r),tw.current=n,n})},[]),tM=(0,i.useCallback)(e=>{let t=tj.current.filter(t=>t.id!==e);tj.current=t,eL(t)},[]),tE=(0,i.useCallback)(()=>{tw.current=[],eE(e=>(e.forEach(sR),[]))},[]),t$=(0,i.useCallback)(()=>{tj.current=[],eL([])},[]),tL=(0,i.useCallback)(()=>{ty.current="",ec(""),eV(null),eX(!1),J&&i8(J),tb.current&&tb.current!==J&&i8(tb.current),tE(),t$(),eP(null),te.current&&(te.current.style.height="auto")},[t$,tE,J]);(0,i.useEffect)(()=>{J&&tb.current===J&&i2(J,{value:el,images:eM.map(sC),documents:eF.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))})},[eM,J,eF,el]),(0,i.useEffect)(()=>{let e=tb.current;if(e===J)return;e&&i2(e,{value:ty.current,images:tw.current.map(sC),documents:tj.current.filter(e=>"ready"===e.status).map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,text:r}))});let t=J?i1(J):null;tb.current=J;let n=t?.value??"",r=sI(t?.images),i=sN(t?.documents);ty.current=n,tw.current=r,tj.current=i,ec(n),eV(null),eX(!1),eE(e=>(e.forEach(sR),r)),eL(i)},[J]),(0,i.useEffect)(()=>{let e=te.current;e&&(e.style.height="auto",el&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[el]),(0,i.useEffect)(()=>()=>{tw.current.forEach(sR)},[]);let tA=(0,i.useCallback)(async()=>{let t=el.trim(),n=eW.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if((r||eM.length||eF.length)&&!o&&!ez){if(V?.(),r.startsWith("/")){await ss(r,O,H,t=>e(t,eM.length?eM:void 0,eF.length?eF:void 0),eP,!!(eM.length||eF.length),_)&&tL();return}tL(),e(r,eM.length?eM:void 0,eF.length?eF:void 0)}},[el,eW,eM,eF,ez,o,H,O,_,e,tL,V]),tP=eW.startsWith("/")&&!/\s/.test(eW.slice(1))?eW.slice(1).toLowerCase():null,tF=(()=>{if(null===tP)return[];let e=[...o?[]:sv,...O??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=sj(e,ea).toLowerCase();return t.includes(tP)||n.includes(tP)}).sort((e,t)=>{let n=sk(e,tP,ea)-sk(t,tP,ea);return 0!==n?n:sw[e.source]-sw[t.source]||su.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:tz,groups:tW}=(ee=0,{commands:(et=sb.map(e=>{let t=tF.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!sS(e,e9)),...t.filter(e=>sS(e,e9))]:t;return{source:e,items:n.map(e=>({command:e,index:ee++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:et}),tD=1===tF.length?ea(tP?"chat.match":"chat.command"):ea(tP?"chat.matches":"chat.commands",{count:tF.length}),tO=!!el.trim(),tB=!ez&&(tO||eM.length>0||eF.length>0),t_=(0,i.useCallback)((e,t)=>{if(!G)return void eV(null);let n=t??e.length;eV(i6(e.slice(0,n)))},[G]),tH=eq?.query??null,tq=i.useMemo(()=>null!==tH&&e1&&e1.cwd===G?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:i7(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:i7(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||i3(e.entry.path)-i3(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(e1.entries,tH):[],[tH,e1,G]),tV=!!(tH&&e1?.truncated&&e1.cwd===G);(0,i.useEffect)(()=>{if(!tV||!G||!tH)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(G)}&q=${encodeURIComponent(tH)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e6({cwd:G,query:tH,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tV,tH,G]);let tK=tV&&null!==e5&&e5.cwd===G&&e5.query===tH,tJ=tK?e5.matches:tq,tG=null===eq?null:`${eq.start}:${+!!eq.quoted}:${eq.query}`;(0,i.useEffect)(()=>{if(null===tG){eJ(!1),eY(0);return}eJ(!0),eY(0)},[tG]);let tY=null!==eq,tZ=sr(tc,eZ,{viewportFraction:.44,cap:360}),tX=sr(tc,eB,{viewportFraction:.56,cap:460}),tQ=sr(tc,eK,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!tY||!G)return;let e=tx.current;e&&e.cwd===G&&Date.now()-e.fetchedAt<1e4||tv.current===G||(tv.current=G,e4(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(G)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{e2({cwd:G,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)=>i3(e.path)-i3(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tx.current={cwd:G,fetchedAt:Date.now()}}).catch(()=>{tx.current=null}).finally(()=>{tv.current=null,e4(!1)}))},[tY,G]);let t0=(0,i.useCallback)(e=>{if(!eq)return;let t=te.current,n=t?.selectionStart??el.length,r=el.slice(0,eq.start),i=el.slice(n);eq.quoted&&i.startsWith('"')&&(i=i.slice(1));let s=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eq.quoted),a=r+s.text+i,o=r.length+s.cursorOffset;ec(a),eV(i6(a.slice(0,o))),requestAnimationFrame(()=>{let e=te.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[eq,el]);(0,i.useEffect)(()=>{eG>=tJ.length&&eY(Math.max(0,tJ.length-1))},[tJ.length,eG]),(0,i.useEffect)(()=>{tg.current.length=tJ.length},[tJ.length]),(0,i.useEffect)(()=>{eK&&tg.current[eG]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eG,eK]),(0,i.useEffect)(()=>{eQ>=F.length&&e0(Math.max(0,F.length-1))},[F.length,eQ]),(0,i.useEffect)(()=>{tf.current.length=F.length},[F.length]),(0,i.useEffect)(()=>{eZ&&tf.current[eQ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eQ,eZ]);let t1=(0,i.useCallback)(e=>{ty.current=e,ec(e),eX(!1),e0(0),eV(null),requestAnimationFrame(()=>{let t=te.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),t2=(0,i.useCallback)(e=>{let t=`/${e.name} `;ty.current=t,ec(t),e_(!1),eU(0),requestAnimationFrame(()=>{let e=te.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),t8=(0,i.useCallback)(async e=>{let t=el.trim(),r=eW.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,a=ez||!i&&0===eM.length&&0===eF.length?null:{message:i,images:eM.length?eM:void 0,documents:eF.length?eF:void 0};if(!a)return;V?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await ss(i,O,H,e=>{if(!K)throw Error("Cannot queue this command while the session is busy.");K(e,o,a.images,a.documents)},eP,!!(a.images?.length||a.documents?.length),_)&&tL();return}tL(),"steer"===e&&n?n(a.message,a.images,a.documents):"followup"===e&&s&&s(a.message,a.images,a.documents)},[el,eW,eM,eF,ez,O,_,H,K,n,s,tL,V]),t5=(0,i.useCallback)(e=>{let t=tz.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eH-1);if("right"===e)return Math.min(t,eH+1);let n=tm.current[eH];if(!n)return"down"===e?Math.min(t,eH+1):Math.max(0,eH-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,s=r.top+r.height/2,a=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===eH)continue;let t=tm.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-s;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<o&&(a=n,o=c)}return a>=0?a:"down"===e?Math.min(t,eH+1):Math.max(0,eH-1)},[tz.length,eH]),t6=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tp.current<100,a=tu.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(a||i)){i&&e.preventDefault();return}if(eZ&&!a){if("ArrowDown"===e.key){e.preventDefault(),e0(e=>Math.min(Math.max(0,F.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e0(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eX(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&F[eQ]){e.preventDefault(),t1(F[eQ]);return}}if(eB&&null!==tP){if("ArrowDown"===e.key){e.preventDefault(),eU(t5("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eU(t5("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eU(t5("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eU(t5("left"));return}if("Escape"===e.key){e.preventDefault(),e_(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&tz[eH]){e.preventDefault(),t2(tz[eH]);return}}if(eK&&null!==eq&&!a){if("ArrowDown"===e.key){e.preventDefault(),eY(e=>Math.min(Math.max(0,tJ.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eY(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eJ(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&tJ[eG]){e.preventDefault(),t0(tJ[eG]);return}}if("ArrowUp"===e.key&&!a&&!o&&F.length>0&&0===el.trim().length){e.preventDefault(),e_(!1),eJ(!1),e0(F.length-1),eX(!0);return}if("Escape"===e.key&&!a&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(n||s)?t8(n?"steer":"followup"):tA())},[o,n,s,t,eB,tP,tz,eH,t2,t8,tA,t5,eK,eq,tJ,eG,t0,eZ,F,eQ,t1,el]),t3=(0,i.useCallback)(()=>{let e=te.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),t7=(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(),tN(t))},[tN]);(0,i.useEffect)(()=>{if(null===tP){e_(!1),eU(0),th.current=!1;return}e_(!0),eU(0),!th.current&&_&&(th.current=!0,Promise.resolve(_()).catch(()=>{th.current=!1}))},[tP,_]),(0,i.useEffect)(()=>{if(!eB||!G)return;let e=!1;return e7({cwd:G,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(G)}`).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;e7({cwd:G,values:n})}).catch(()=>{e||e7({cwd:G,values:{}})}),()=>{e=!0}},[eB,G]),(0,i.useEffect)(()=>{eH>=tz.length&&eU(Math.max(0,tz.length-1))},[tz.length,eH]),(0,i.useEffect)(()=>{tm.current.length=tz.length},[tz.length]),(0,i.useEffect)(()=>{eB&&tm.current[eH]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eH,eB]);let ne=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(sm):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(sm),nt=f??null,nn=t4.find(e=>e.alias===nt)?.provider??null,nr=nn?ne.filter(e=>e.provider===nn):ne,ni=(en=em.trim().toLocaleLowerCase())?nr.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(en)):nr,ns=nr.length>8,na=[];for(let e of ni){let t=na.find(t=>t.provider===e.provider);t?t.options.push(e):na.push({provider:e.provider,options:[e]})}let no=nn?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nl=l?no.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,nc=em.trim()?[]:nr.map((e,t)=>{var n,r;return{option:e,order:t,count:ef[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})),nd=(e,t,n)=>{let i=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(eu(!1),eg(""),!i||c){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}(se(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(i9,JSON.stringify(r))}catch{}ex(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:ea("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nu=l?ne.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,np=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nh=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:ea("chat.compacted")} ${tU(S.tokensBefore)} -> ${tU(S.estimatedTokensAfter)} tokens (${ea("chat.tokensSaved",{saved:tU(np)})})`:null,nm=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},ng=(()=>{let e=I??"auto";if("auto"===e){let e=R?`auto ≤ ${nm(R)??R}`:"auto",t=N&&(L?.[N]??N);return t?`${e} (${t})`:e}return L?L[e]??e:e})(),nf=e=>!$||$.includes(e),nx=[{level:"auto",ceiling:null},...sf.filter(nf).map(e=>({level:"auto",ceiling:e})),...sg.filter(e=>"auto"!==e&&nf(e)).map(e=>({level:e,ceiling:null}))],nv=Object.entries(so).find(([,e])=>e===(C??"default"))?.[0]??"default";return(0,i.useEffect)(()=>{let e=e=>{tt.current&&!tt.current.contains(e.target)&&tn.current&&!tn.current.contains(e.target)&&(eu(!1),eg("")),tr.current&&!tr.current.contains(e.target)&&ti.current&&!ti.current.contains(e.target)&&eb(!1),ts.current&&!ts.current.contains(e.target)&&ej(!1),ta.current&&!ta.current.contains(e.target)&&eC(!1),to.current&&!to.current.contains(e.target)&&eR(!1),!tl.current||tl.current.contains(e.target)||te.current?.contains(e.target)||eX(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eo||eR(!1)},[eo]),(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:td,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tN(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)(s$,{error:p}),(0,r.jsx)(sL,{warnings:h}),(P?.steering.length??0)+(P?.followUp.length??0)>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:ea("chat.queued",{count:(P?.steering.length??0)+(P?.followUp.length??0)})}),W&&(0,r.jsxs)("button",{onClick:W,title:ea("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"})]}),ea("chat.recall")]})]}),P?.steering.map((e,t)=>(0,r.jsx)(sM,{kind:"steer",text:e,removeLabel:ea("chat.queueRemove"),onRemove:D?()=>D("steering",e):void 0},`steer-${t}`)),P?.followUp.map((e,t)=>(0,r.jsx)(sM,{kind:"follow-up",text:e,removeLabel:ea("chat.queueRemove"),onRemove:D?()=>D("followUp",e):void 0},`followup-${t}`))]}),A&&(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"})]}),ea("chat.retrying",{attempt:A.attempt,max:A.maxAttempts}),A.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",A.errorMessage]})]}),nh&&(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"})}),nh]}),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}),eA&&(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:eA}),(0,r.jsx)("button",{type:"button",onClick:()=>eP(null),"aria-label":ea("i18n.close"),title:ea("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"})]})})]}),(eM.length>0||e$.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":ea("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eM.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":ea("chat.removeImage",{index:t+1}),onClick:()=>tR(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}`)),e$.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status?(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"}}):nD(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?ea("chat.attachKindAudio"):"file"===e.stored?ea("chat.attachKindFile"):sh[e.mimeType]," \xb7 ",nQ(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${ea("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${ea("chat.attachUploading")}`:"","transcribing"===e.status?` \xb7 ${ea("chat.attachTranscribing")}`:"",e.transcriptFailed&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${ea("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>tM(e.id),"aria-label":ea("chat.removeAttachment",{name:e.name}),title:ea("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))]}),(0,r.jsxs)("div",{ref:tc,style:{position:"relative",minWidth:0},children:[eZ&&F.length>0&&(0,r.jsxs)("div",{ref:tl,style:{position:"absolute",left:0,right:0,...sd(tZ.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:tZ.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,tZ.maxHeight-31),overflowY:"auto",padding:4},children:F.map((e,t)=>{let n=t===eQ;return(0,r.jsxs)("button",{ref:e=>{tf.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t1(e)},onMouseEnter:()=>e0(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}`)})})]}),eB&&null!==tP&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...sd(tX.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:tX.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:B?ea("chat.loadingCommands"):ea("chat.slashCommands",{label:tD})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ea("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,tX.maxHeight-34),overflowY:"auto",padding:10},children:B||0!==tF.length?tW.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:ea(sy[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===eH,i=sS(e,e9);return(0,r.jsxs)("button",{ref:e=>{tm.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t2(e)},onMouseEnter:()=>eU(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:ea("chat.dormant")})]}),sj(e,ea)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:sj(e,ea)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ea("chat.noCommands")})})]}),eK&&null!==eq&&(er=e8&&(!e1||e1.cwd!==G),ei=1===tJ.length?ea("chat.match"):ea("chat.matches",{count:tJ.length}),es=e1?.truncated&&!tK?eq.query?ea("chat.searchingAll"):ea("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...sd(tQ.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:tQ.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:er?ea("chat.loadingFiles"):ea("chat.files",{label:ei,hint:es})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ea("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,tQ.maxHeight-34),overflowY:"auto",padding:4},children:er||0!==tJ.length?tJ.map((e,t)=>{let n=t===eG,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tg.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t0(e)},onMouseEnter:()=>eY(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)(nF,{size:14}):nD(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:s}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tV&&!tK?ea("chat.searching"):ea("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eD?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eD?"var(--tool-bg)":o&&(n||s)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:te,value:el,onChange:e=>{ty.current=e.target.value,ec(e.target.value),eX(!1),t_(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;t_(t.value,t.selectionStart)},onKeyDown:t6,onCompositionStart:()=>{tu.current=!0},onCompositionEnd:e=>{tu.current=!1,tp.current=Date.now();let t=e.currentTarget;t_(t.value,t.selectionStart)},onInput:t3,onPaste:t7,placeholder:o&&(n||s)?ea("chat.steerPlaceholder"):o?ea("chat.agentPlaceholder"):ea("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"}}),o?(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:()=>t8("steer"),disabled:!tB,title:ez?ea("chat.attachExtractingWait"):ea("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tB?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:tB?"var(--warning)":"var(--text-dim)",cursor:tB?"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"})]}),ea("chat.steer")]}),s&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>t8("followup"),disabled:!tB,title:ez?ea("chat.attachExtractingWait"):ea("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tB?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:tB?"var(--accent-hover)":"var(--text-dim)",cursor:tB?"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"})]}),ea("chat.followUp")]})]}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:tA,disabled:!tB,"aria-busy":ez||void 0,title:ez?ea("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:tB?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:tB?"var(--accent-hover)":"var(--text-dim)",cursor:tB?"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"})]}),ea("chat.send")]})]})]}),eD&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eO?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ea("chat.shell")," \xb7 ",eO?ea("chat.outputLocal"):ea("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:eo?"1 1 0%":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eM.length||e$.length?" is-active":""}`,onClick:()=>td.current?.click(),title:ea("chat.attachFile"),"aria-label":ea("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:eM.length||e$.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=eM.length||e$.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eM.length||e$.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"})]})}),g&&t4.length>0&&(0,r.jsxs)("div",{ref:tr,style:{position:"relative",flexShrink:+!!eo,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eo?"composer-icon-button":"composer-chip"}${ev?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ew({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eu(!1),eg(""),eb(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":ev,onKeyDown:e=>{"Escape"===e.key&&ev&&(e.stopPropagation(),eb(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:ev?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ev?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:ea("chat.mainPreset"),"aria-label":ea("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"})}),eo?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ea("chat.mainPreset")})]}),ev&&ey&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=st(ey.top,ey.bottom,e,sn(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ey.top+6}:{top:ey.bottom+6},s=eo?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ey.left,width:"max-content",minWidth:ey.width};return(0,r.jsx)("div",{ref:ti,role:"menu","aria-label":ea("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eb(!1),tr.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:t4.map(e=>{let t=e.alias===nt;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eb(!1),g({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},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:t9(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)})})})})()]}),(ne.length>0||nu||p)&&m&&(0,r.jsxs)("div",{ref:tt,style:{position:"relative",flex:eo?"1 1 0%":void 0,minWidth:0},children:[(0,r.jsxs)("button",{className:`composer-chip${ed?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eh({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eu(e=>(e&&eg(""),!e))},disabled:o||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eo?"flex-start":void 0,padding:eo?"8px 10px":"8px 12px",height:32,width:eo?"100%":void 0,maxWidth:eo?"100%":220,overflow:"hidden",background:ed?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ed?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":ne.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:nu??(ne.length>0?"Select model":"No models")})]}),ed&&ep&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=st(ep.top,ep.bottom,e,sn(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ep.top+6}:{top:ep.bottom+6},s=eo?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ep.left,width:"max-content",minWidth:ep.width};return(0,r.jsxs)("div",{ref:tn,style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[ns&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:em,onChange:e=>eg(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eg(""),eu(!1))},placeholder:ea("chat.filterModels"),"aria-label":ea("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eo,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:[nc.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:ea("chat.frequentModels")}),nc.map(({option:e,count:t})=>nd(e,"frequent",t))]}),no.length>0&&!em.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nc.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:ea("chat.modelRoles")}),no.map(e=>{let t=nl?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{eu(!1),eg(""),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:ea("chat.allModels")})]}),0===na.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:em.trim()?ea("chat.noMatchingModels"):"No available models"}):na.map((e,t)=>(0,r.jsxs)("div",{children:[na.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=>nd(e,"all"))]},e.provider))]})]})})()]}),M&&(0,r.jsxs)("div",{ref:ta,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eo?"composer-icon-button":"composer-chip"}${eS?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eI({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eu(!1),eg(""),eb(!1),eC(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eS,onKeyDown:e=>{"Escape"===e.key&&eS&&(e.stopPropagation(),eC(!1))},title:ea("chat.changeReasoning",{level:ng}),"aria-label":ea("chat.changeReasoning",{level:ng}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eo?0:"8px 12px",height:32,background:eS?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eS?"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"})]}),eo?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ng})]}),eS&&eT&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=st(eT.top,eT.bottom,e,sn(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eT.top+6}:{top:eT.bottom+6},s=eo?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eT.left,width:"max-content",minWidth:Math.max(180,eT.width)};return(0,r.jsx)("div",{role:"menu","aria-label":ea("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eC(!1),ta.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...s,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nx.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(R??null)===t),i=t??e,s="auto"===e&&null===t?null:nm(i),a=t?`auto ≤ ${s??t}`:s??e,o=t?ea("chat.thinkingAutoCapped",{level:s??t}):ea(sx[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eC(!1),M(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[a,null!==s&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}),(0,r.jsx)(iV,{sessionId:Y})]}),(0,r.jsxs)("div",{ref:to,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eo?4:2},children:[eo?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eN?" is-active":""}`,title:ea("chat.moreControls"),"aria-label":ea("chat.moreControls"),"aria-expanded":eN,onClick:()=>{eu(!1),eg(""),eR(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(a.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eN?void 0:ea("chat.moreControls"),"aria-label":ea("chat.moreControls"),"aria-expanded":eN,onClick:()=>{eu(!1),eg(""),eR(e=>!e)},children:ea("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":ea("chat.moreControls"),style:{display:eN?"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:[!o&&T&&(0,r.jsxs)("div",{ref:ts,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${ek?" is-active":""}`,onClick:()=>!o&&ej(e=>!e),disabled:o,title:ea("chat.changeToolPreset")+`: ${nv}`,"aria-label":ea("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:ek?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ek?"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:nv})]}),ek&&(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:sa.map(e=>{let t=so[e],n=(C??"default")===t,i="off"===e?ea("chat.noTools"):"default"===e?ea("chat.builtInTools",{tools:sl}):ea("chat.allBuiltInTools",{tools:`${sl} + ${sc}`});return(0,r.jsxs)("button",{onClick:()=>{ej(!1),n||T(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)})})]}),!o&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!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:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||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?ea("chat.stopCompaction"):ea("chat.compactContext"),"aria-label":k?ea("chat.stopCompaction"):ea("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:ea("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:ea("chat.compact")})]})})}),eN&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:ea("chat.collapseControls"),"aria-label":ea("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ej(!1),eC(!1),eR(!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"})]})})]}),o&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:ea("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"})}),ea("chat.stop")]}),(0,r.jsx)(iU,{sessionId:Y,onEnsureSession:Z,onTranscriptPersisted:X}),void 0!==q&&(0,r.jsx)(iD,{soundEnabled:U??!0,onToggle:q})]})]})]})]})});function sP({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=ey(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:eC(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function sF({phases:e}){let{t}=(0,E.s)(),[n,s]=(0,i.useState)(!1),[a,o]=(0,i.useState)(!1),{currentPhase:l,activeTask:c,remaining:d,completed:u,total:p,percent:h}=function(e){let t=0,n=0,r=null,i=null,s=null;for(let a of e)for(let e of a.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:a,task:e}):"blocked"===e.status?s||(s={phase:a,task:e}):i||(i={phase:a,task:e}))}let a=r??i??s,o=t+n;return{currentPhase:a?.phase??null,activeTask:a?.task??null,remaining:n,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}(e);if(0===p)return null;let m=0===d;return(0,r.jsxs)("div",{className:`todo-strip${m?" is-done":""}`,children:[(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":n,onClick:()=>s(e=>!e),children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:m?"✓":"›"}),l&&(0,r.jsx)("span",{className:"todo-strip-phase",children:l.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:m?t("todo.allDone",{count:u}):c?.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:d})})]}),n&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,n)=>{let i=t.tasks.filter(e=>a||"completed"!==e.status);return 0===i.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,r.jsx)(nL,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":a,onClick:()=>o(e=>!e),children:t(a?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sz(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function sW(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 sD(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}}class sO extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function sB(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 sO(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let s_="ompweb-update-client-id",sH="ompweb-update-resume-intent-v2",sU="ompweb-update-return-v1",sq="cuelo-restart-return-v1",sV="ompweb:update-wake";function sK(e){return null===e||"running"===e?null:"failed"===e?3e4:8e3}function sJ(){let e=sessionStorage.getItem(s_);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(s_,t),t}function sG(){let e=sessionStorage.getItem(sU);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 sY(e){let t=sG();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(sU,JSON.stringify(n))}catch{}return n}async function sZ(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:sJ(),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 sX(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=sG();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(sU,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sessionStorage.removeItem(sH);let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sV,{detail:{sessionId:e.sessionId}}))}function sQ(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 s0(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function s1(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 s2(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(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 s8(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function s4(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!eq(r??void 0))return{message:e[n],entryId:r}}return null}let s5=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class s6 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 s3(e){return new Promise(t=>setTimeout(t,e))}function s7(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function s9(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:s7(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:s7(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=s7(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function ae(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 at(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(ae).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function an(e){return"user"===e.role?`user:${at(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 ar(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 ai(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}let as={count:50,end:null};function aa(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),s=r-i;return{startIndex:s,endIndex:r,hasMore:s>0,hasLater:r<n}}function ao(e,t,n){let{startIndex:r,endIndex:i}=aa(e,n);if(t>=r&&t<i)return n;let s=Math.max(0,t-10),a=Math.max(t+1,s+50);return a>=e?{count:e-s,end:null}:{count:a-s,end:a}}function al({sticker:e,text:t,tag:n,followRef:s}){let a=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!s||s.current)&&a.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:a,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:r2[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(rX(),{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 ac(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=(nX(t)?.message??t).trim();return n.length>0?n:null}function ad(e){return`omp-cues:${e}`}function au(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(ad(e),JSON.stringify(n.slice(-200)))}catch{}}let ap=[];function ah(e){return`omp-web:interrupted-dismissed:${e}`}let am=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:s,messageCwd:a,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:g,main:f,process:x,startIndex:v,endIndex:b,sentinelRef:y,laterSentinelRef:w,flashItem:k,t:j,onProcessLogChange:S,cues:C,cueFollowRef:T}){(0,i.useEffect)(()=>{S({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:s,cwd:a,sessionId:g})},[S,x,e,t,n,s,a,g]);let I=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let s=new Map,a=new Map;for(let e of t){let t=a.get(e.anchorIdx);for(let o of(t||(t=new Set,a.set(e.anchorIdx,t)),e.entries)){let e=n[o.idx];if(e?.role!=="assistant")continue;let a=Math.max(0,(o.blocks?i.get(o.idx):void 0)??o.afterMainIndex??-1),l=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=eG(i.action);if(!0===eJ[e]){let t={kind:"skill",action:e,name:eG(i.name)};n(JSON.stringify(t),t)}continue}let s=eG(i.memory),a=i.skill,o=a?{action:eG(a.action),name:eG(a.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:s,skill:o}),{kind:"lesson",memory:s.length>160?`${s.slice(0,160)}…`:s,...o?{skill:o}:{}})}}(o.blocks??e.content??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=s.get(a);n?n.push(t):s.set(a,[t])})}}return s}(f,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return j("chat.savedSkill",{action:e.action,name:e.name});let t=j("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${j("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:e_,content:[j("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[f,x,e,n,j]),N=v>0,R=b<f.length,M=(i,f={})=>{let x=f.messageOverride??e[i],v=i-1;for(;v>=0&&eq(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=f.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&&d&&i===e.length-1&&(w=!1)}return void 0!==f.showTimestamp&&(w=f.showTimestamp),(0,r.jsx)(rd,{message:x,toolResults:n,modelNames:s,cwd:a,onOpenFile:o,entryId:t[i],onFork:l||c||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:g,writtenFiles:f.writtenFiles},`${y}-view-${i}`)},E=(t,n)=>{let i=f[t],s="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":s?"":void 0,className:k===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[N&&(0,r.jsx)("div",{ref:y,className:"py-3 text-center text-xs text-text-muted",children:j("chat.loadEarlier",{count:v})}),f.slice(v,b).map((s,l)=>{let c=v+l,d="message"===s.kind?s.anchorIdx??s.idx:s.anchorIdx,u=f[c+1],p=u?"message"===u.kind?u.anchorIdx??u.idx:u.anchorIdx:null,h=u?u.idx:1/0,m=C.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=s.idx&&r<h}).map(e=>(0,r.jsx)(al,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:T},`cue-${e.id}`)),x=p!==d,b=I.get(c),y=b?(0,r.jsx)(rd,{message:b,cwd:a,onOpenFile:o},`saved-lessons-${c}`):null,w=x?(0,r.jsx)(io,{turnIndex:d,turnEntryId:t[d],sessionId:g,cwd:a,onOpenFile:o}):null;if("message"===s.kind)return(0,r.jsxs)(i.Fragment,{children:[E(c,M(s.idx)),y,w,m]},`message-${s.idx}`);let k=function(e,t,n){let r=new Set,i=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t,n;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(n=e.toLowerCase())||n.startsWith("edit_")||n.endsWith(".edit")||n.endsWith("_edit")||n.includes("str_replace")||n.includes("replace_editor")}(s.toolName))continue;let e=t?.get(s.toolCallId);if(!e||e.isError)continue;let a=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(s.input);if(!a||!/^[a-zA-Z]:[\\/]/.test(a)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(a))continue;let o=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,s=i(e),a=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(s),l=s.startsWith("//");if(o||l)n=s;else if(s.startsWith("/")){let e=a?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??a?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!a)return null;n=`${a}/${s}`}return e0(n)}(a,n);o&&(r.has(o)||(r.add(o),i.push({filePath:o})))}return i}(s.precedingBlocks,n,a);return(0,r.jsxs)(i.Fragment,{children:[E(c,M(s.idx,{keyPrefix:`answer-${s.runIndex}`,messageOverride:e$(e[s.idx],s.blocks),writtenFiles:k})),y,w,m]},`answer-${s.idx}-${s.runIndex}`)}),R&&(0,r.jsx)("div",{ref:w,className:"py-3 text-center text-xs text-text-muted",children:j("chat.loadLater",{count:f.length-b})})]})});function ag({session:e,newSessionCwd:t,initialSessionData:s,transitioning:a=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:g,onSessionStatsPanelOpen:f,onContextUsageChange:x,onSubagentsChange:b,onProcessLogChange:y,onOpenFile:w,transcriptReplacement:k,onComposerFocusChange:j,onSessionBusyChange:S,onWaitingChange:C,onAttentionChange:T,soundEnabled:I=!0,onSoundToggle:N,playCueSound:R=async()=>({sticker:null,text:null}),preloadCueSound:M,unlockAudio:$,jumpRequest:L=null,onJumpHandled:A}){var P,F;let z,D,O,{t:B}=(0,E.s)(),_=(0,i.useRef)(R);_.current=R;let U=(0,i.useRef)(null),q=(0,i.useRef)(M);q.current=M;let V=(0,i.useRef)(null),[K,J]=(0,i.useState)([]),G=(0,i.useRef)(K);G.current=K;let Y=(0,i.useRef)(0),Z=(0,i.useRef)([]),X=(0,i.useRef)([]),Q=(0,i.useRef)(null),ee=(0,i.useRef)(0),et=(0,i.useRef)(-1),en=(0,i.useRef)(-1),er=(0,i.useCallback)(()=>{let e=Q.current?.current;return e?{sessionId:e,turn:ee.current}:null},[]),ei=(0,i.useCallback)(e=>Q.current?.current===e.sessionId&&ee.current===e.turn,[]),es=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;Y.current=Math.max(Y.current+1,Date.now());let i={id:Y.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},s="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};J(e=>{let t=[...e,s];return null!==s.anchorEntryId&&au(n.sessionId,t),t})},[]),ea=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ei(n)&&("working"!==t||en.current!==n.turn);i()&&_.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&es(e,t,n,r)}).catch(()=>{})},[ei,es]),eo=(0,i.useCallback)(async(e,t,n)=>{let r=nI(e,t,n);if(r||!t)return r?.alias??null;let i=V.current;if(i&&i.sessionId===e&&i.provider===t)return i.alias;try{let{data:n}=await np(e),r=n?.state==="resolved"&&n.provider===t?n.credentialId:void 0,i=nI(e,t,r)?.alias??null;return i&&(V.current={sessionId:e,provider:t,alias:i},q.current?.(i)),i}catch{return null}},[]),el=(0,i.useCallback)((e,t,n,r,i)=>{let s=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=ie(e[n]),s=0;for(let t=r;t<=n;t++)ie(e[t])===i&&(s+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:s}}}(Z.current,X.current);eo(t.sessionId,n,r).then(a=>{console.info(`[cue] tag=${e} alias=${a} provider=${n} credentialId=${r} source=${i} session=${t.sessionId} turn=${t.turn}`),ea(a,e,t,s)})},[ea,eo]),[ec,ed]=(0,i.useState)(0),eu=(0,i.useRef)([]),ep=(0,i.useCallback)(e=>{if(ee.current+=1,null!==r4(e.outcome)){let t=e.sessionId;eu.current.push({completion:e,trigger:t?{sessionId:t,turn:ee.current}:null}),ed(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eu.current.splice(0)){let n=r4(e.outcome),r="neutral"===n?null:n;t?el(r,t,e.provider,e.credentialId,"completion"):_.current(null,r).catch(()=>{})}},[ec,el]);let eh=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:em,error:eg,messages:ef,entryIds:ex,streamState:ev,agentRunning:eb,bashRunning:ew,pendingBash:ek,modelNames:ej,modelList:eS,modelError:eC,modelScopeWarnings:eT,modelThinkingLevels:eI,modelThinkingLevelMaps:eN,modelRoles:eR,toolPreset:eM,thinkingLevel:eE,effectiveThinkingLevel:eL,thinkingCeiling:ez,retryInfo:eD,contextUsage:eO,forkingEntryId:e_,isCompacting:eJ,compaction:eG,compactError:eZ,compactResult:eX,displayModel:eQ,modelSwitching:e0,sessionStats:e1,runStalled:e8,runStateKnown:e4,slashCommands:e5,slashCommandsLoading:e6,queuedMessages:e3,subagents:e7,todoPhases:e9,notices:te,extensionDialog:tt,extensionResponse:tn,extensionCustomUi:tr,extensionStatuses:ti,extensionWidgets:ts,respondToExtensionUi:ta,sendExtensionCustomInput:to,isAutoModelSelection:tl,agentPhase:tc,isNew:td,autoFollowPaused:tu,resumeAutoFollow:tp,pauseAutoFollow:th,goalStatus:tm,sessionIdRef:tg,messagesEndRef:tf,scrollContainerRef:tx,handleSend:tv,handleAbort:tb,handleFork:ty,handleNavigate:tw,handleModelChange:tk,handleRoleModelChange:tj,handleMainPresetChange:tS,newSessionAccount:tC,handleCompact:tT,handleSteer:tI,handleFollowUp:tN,handlePromptWithStreamingBehavior:tR,handleAbortCompaction:tM,handleRecallQueue:tE,handleRemoveQueuedMessage:t$,handleBuiltinSlashCommand:tL,handleToolPresetChange:tA,handleThinkingLevelChange:tP,loadSlashCommands:tF,ensureNewSession:tz,refreshLiveTranscript:tW}=function(e){let{session:t,newSessionCwd:r,initialData:s,onAgentEnd:a,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,g=s&&s.sessionId===t?.id?s:null,[f,x]=(0,i.useState)(g),[v,b]=(0,i.useState)(!m&&!g),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(g?.leafId??null),[S,C]=(0,i.useState)(g?.context.messages??[]),[T,I]=(0,i.useState)(g?.context.entryIds??[]),[N,R]=(0,i.useReducer)(sQ,{isStreaming:!1,streamingMessage:null}),[M,E]=(0,i.useState)(!1),[$,L]=(0,i.useState)(!1),[A,P]=(0,i.useState)(null),[F,z]=(0,i.useState)({}),[W,D]=(0,i.useState)([]),[O,B]=(0,i.useState)(null),[_,H]=(0,i.useState)([]),[U,q]=(0,i.useState)({}),[V,K]=(0,i.useState)({}),[J,G]=(0,i.useState)([]),[Y,Z]=(0,i.useState)(null),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)("default"),[ei,es]=(0,i.useState)(()=>{let e=g?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ea,eo]=(0,i.useState)(),[el,ec]=(0,i.useState)(null),[ed,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(g?.contextUsage??null),[em,eg]=(0,i.useState)(null),[ef,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(!1),[eC,eT]=(0,i.useState)(!1),[eI,eN]=(0,i.useState)(null),[eR,eM]=(0,i.useState)(null),[eE,e$]=(0,i.useState)(null),eL=(0,i.useRef)(null),[eA,eP]=(0,i.useState)(!1),eF=(0,i.useRef)(!1),ez=(0,i.useRef)(0),[eW,eD]=(0,i.useState)(!1),[eO,e_]=(0,i.useState)(null),[eH,eK]=(0,i.useState)([]),[eJ,eG]=(0,i.useState)(!1),[eY,eZ]=(0,i.useReducer)(s9,{visible:[],pending:[]}),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(null),[e2,e8]=(0,i.useState)(null),e4=(0,i.useRef)(null),[e5,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)([]),[e9,te]=(0,i.useState)([]),[tt,tn]=(0,i.useState)({steering:[],followUp:[]}),[tr,ti]=(0,i.useState)([]),[ts,ta]=(0,i.useState)(null),to=(0,i.useRef)(null),tl=(0,i.useRef)(null),tc=(0,i.useRef)(null),td=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(0),th=(0,i.useRef)(!1),tm=(0,i.useRef)(t?.id??null),tg=(0,i.useRef)(g?.leafId??null),tf=(0,i.useRef)(S),tx=(0,i.useRef)(T);tf.current=S,tx.current=T;let tv=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tb=(0,i.useRef)(!1),ty=(0,i.useRef)(!1),tw=(0,i.useRef)(!1),tk=(0,i.useRef)(-1),tj=(0,i.useRef)("unknown"),tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tT=(0,i.useRef)(0),tI=(0,i.useRef)(!1),tN=(0,i.useRef)(0),tR=(0,i.useRef)(null),tM=(0,i.useRef)(null),tE=(0,i.useRef)(null),t$=(0,i.useRef)(!1),tL=(0,i.useRef)(!0),[tA,tP]=(0,i.useState)(!1),[tF,tz]=(0,i.useState)(null),tW=(0,i.useRef)(void 0),tD=(0,i.useRef)(0),tO=(0,i.useRef)(0),tB=(0,i.useRef)(()=>{}),t_=(0,i.useRef)(null),tH=(0,i.useRef)(null),tU=(0,i.useRef)(null),tq=(0,i.useRef)(!1),tV=(0,i.useRef)(null),tK=(0,i.useRef)(null),tJ=(0,i.useRef)(null),tG=(0,i.useRef)(null),tY=(0,i.useRef)(!1);tY.current=e.transitioning??!1;let tZ=(0,i.useRef)(Date.now()),tX=(0,i.useRef)(0),tQ=(0,i.useRef)(0),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(Promise.resolve()),t8=e.setToolPreset??er,t4=ev??f?.context.model??ew??null,t5=m?Y??ee:t4,t6=(0,i.useMemo)(()=>{if(eX)return{...eX,totalActiveMs:f?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,s=0,a=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(s+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;a+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,n+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:f?.filePath||void 0,sessionId:tm.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:a,toolResults:s,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:f?.totalActiveMs,...ep?{contextUsage:ep}:{}}},[S,eX,ep,f?.filePath,f?.totalActiveMs,t?.id,t?.name]),t3=(0,i.useRef)(0),t7=(0,i.useCallback)((e,t)=>{e&&tm.current===e&&Array.isArray(t)&&(t3.current+=1,ta(n=>n?.sid===e&&s1(n.phases,t)?n:{sid:e,phases:t}))},[]),t9=(0,i.useCallback)((e,t,n)=>{tm.current===e&&t3.current===n&&Array.isArray(t)&&ta(n=>n?.sid===e&&s1(n.phases,t)?n:{sid:e,phases:t})},[]),ne=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tf.current):e;tf.current=t,C(t)},[]),nt=(0,i.useCallback)(e=>{tx.current=e,I(e)},[]),nn=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let s=r??null;if(!s){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),ne([]),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);s=await r.json()}if(tm.current!==e)return null;x(s),j(s.leafId),tg.current=s.leafId??null;let a=eV(s.context.messages,s.context.entryIds??[],tv.current.sessionId===e?tv.current.outputs:[]);if(ne(a.messages),nt(a.entryIds),eh(s.contextUsage??null),eb(e=>t1.current?e:null),w(null),es(s.context.configuredThinkingLevel??s.context.thinkingLevel??"off"),eo(s.context.thinkingLevel),ec(s.context.thinkingCeiling??null),i=!0,t&&b(!1),!n)return null;try{let t=t3.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tm.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&eh(i.contextUsage??null),void 0!==i.systemPrompt&&eg(i.systemPrompt??null),void 0!==i.thinkingLevel&&(es(i.configuredThinkingLevel??i.thinkingLevel),eo(i.thinkingLevel)),void 0!==i.thinkingCeiling&&ec(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&e7(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&te(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tn(s0(i.queuedMessages)),void 0!==i.subagents&&ti(e=>s2(e,i.subagents??[])),t9(e,i.todoPhases,t)):r.running||tn({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)}},[t9,nt,ne]),nr=(0,i.useCallback)(e=>{let t=t2.current.then(async()=>{tm.current===e&&await nn(e)});return t2.current=t.catch(()=>{}),t},[nn]),ni=(0,i.useCallback)(async(e,t)=>{try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let r=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,i=await fetch(r);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();tg.current=t;let a=eV(s.context.messages,s.context.entryIds??[],tv.current.sessionId===e?tv.current.outputs:[]);ne(a.messages),nt(a.entryIds),eh(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nt,ne]),ns=(0,i.useCallback)(async e=>{try{let t=await sB(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));t8(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[t8]),na=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tm.current;m&&r&&n&&!tq.current&&(tq.current=!0,l?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,l]),no=(0,i.useCallback)(async()=>{if(tm.current||!m||!r)return tm.current;if(tU.current)return tU.current;let e=(async()=>{let e=tV.current,t=tJ.current,n=tK.current;e&&ek(e);let i=(0,si.xG)(en),s=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",toolNames:i,...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{},...e&&null!==n?{oauthPosition:n}:{}})});if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json(),o=a.sessionId;tm.current=o;let l=tG.current;return null!==l&&await sB(o,{type:"set_thinking_ceiling",ceiling:l}),a.model&&tV.current===e&&(ek(a.model),e||et(a.model)),a.thinkingLevel&&tJ.current===t&&(es(a.configuredThinkingLevel??a.thinkingLevel),eo(a.thinkingLevel)),o})();tU.current=e;try{return await e}finally{tU.current=null}},[m,r,en]),nl=(0,i.useCallback)(async()=>{let e=tm.current??await no();if(!e)return eK([]),[];eG(!0);try{let t=await sB(e,{type:"get_commands"}),n=t?.commands??[];return eK(n),n}catch(e){return console.error("Failed to load slash commands:",e),eK([]),[]}finally{eG(!1)}},[no]),nc=(0,i.useCallback)(()=>{tp.current+=1,th.current=!1,tu.current&&(clearTimeout(tu.current),tu.current=null)},[]),nd=(0,i.useCallback)(()=>{to.current?.close(),to.current=null,tl.current=null,tc.current=null},[]),nu=(0,i.useCallback)(()=>{td.current?.close(),td.current=null},[]),np=(0,i.useCallback)(e=>{"update_maintenance"===e.type||(ez.current=Date.now(),eF.current&&(eF.current=!1,eP(!1)))},[]),nh=(0,i.useCallback)(e=>{nu();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);td.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);np(n),"session_snapshot"===n.type?tR.current?.(n):"agent_start"===n.type&&tM.current?.(e)}catch{}}},[nu,np]),nm=(0,i.useCallback)(e=>{nd();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);to.current=t,tl.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(s),tc.current?.source===t&&(tc.current.pending=!1),n({status:e,source:t}))},s=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);np(t),"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tR.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),to.current===t&&(tb.current||th.current))){to.current=null,tl.current=null,tc.current=null;let t=tp.current;setTimeout(()=>{t===tp.current&&!to.current&&(tb.current||th.current)&&nm(e)},1e3)}}});return tc.current={source:t,promise:n,pending:!0},n},[nd,np]),ng=(0,i.useCallback)(async e=>{let t=to.current;if(t&&tl.current===e){if(t.readyState===EventSource.OPEN)return;let e=tc.current;if(e?.source===t&&e.pending&&(await e.promise,to.current===t&&t.readyState===EventSource.OPEN))return}let n=await nm(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw to.current===n.source&&(to.current=null),tl.current===e&&(tl.current=null),tc.current?.source===n.source&&(tc.current=null),n.source.close(),new s6(n.status)},[nm]),nf=(0,i.useCallback)(async(e,t)=>{let n=e4.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tm.current,i=e=>{e4.current=e,e8(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await sB(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),e1(t=>t?.id===e.id?null:t)},[]),nx=(0,i.useCallback)(async(e,t)=>{let n=tm.current;if(n)try{await sB(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nv=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eZ({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),nb=(0,i.useCallback)(e=>{let t={role:"custom",customType:eB,content:ey(e).trim(),display:!0,timestamp:Date.now()},n=tv.current,r=tm.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tx.current.slice(0,tf.current.length),s=null;for(let e=i.length-1;e>=0;e--)if(!eq(i[e])){s=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eU}${n.seq}`,baseEntryId:s,message:t}),ne(e=>[...e,t])},[ne]),ny=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e1(e=>e?.id===t.id?null:e),e4.current?.id===t.id&&(e4.current=null,e8(null));return}switch(sW(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e1(t);break;case"notify":nv({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":e7(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":te(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":e6(e=>t.closed?e?.id===t.id?null:e:t)}},[nv,o,e.chatInputRef]),nw=(0,i.useCallback)(()=>{let e=tb.current;return tb.current=!1,E(!1),e_(null),eu(null),R({type:"end"}),e},[]),nk=(0,i.useCallback)(()=>{tj.current="unknown",tS.current=null;let e=s4(tf.current,tx.current);tC.current=e?{entryId:e.entryId,key:an(e.message)}:null,tT.current+=1},[]),nj=(0,i.useCallback)(()=>{let e=tj.current,t=tS.current;if("unknown"===e){let n=s4(tf.current,tx.current),r=n?.message,i=tC.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:an(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=s8(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tm.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nS=(0,i.useCallback)(e=>{let t=nj();if("unknown"!==t.outcome||!e)return void a?.(t);let n=tT.current;e.catch(()=>void 0).then(()=>{let e=tm.current===t.sessionId&&tT.current===n;a?.(e?nj():t)})},[a,nj]),nC=(0,i.useCallback)((e,t)=>tk.current!==e&&(tk.current=e,nS(t),!0),[nS]),nT=(0,i.useCallback)(e=>{nc(),th.current=!0;let t=tp.current,n=async()=>{if(t===tp.current&&tm.current===e&&th.current)try{let r=t3.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(t!==tp.current||tm.current!==e||!th.current)return;let a=s.state;if(ti(e=>s2(e,a?.subagents??[])),t9(e,a?.todoPhases,r),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isHandoffRunning)){th.current=!1,tu.current=null,ty.current=!!a?.isStreaming,tw.current=!!a?.isPromptRunning,tb.current=!0,E(!0),e_(a?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(s.running&&a?.isCompacting){eT(!0),tu.current=setTimeout(()=>void n(),600);return}if(s.running&&(a?.subagents?.length??0)>0){tu.current=setTimeout(()=>void n(),1e3);return}th.current=!1,tu.current=null,nd()}catch{if(t!==tp.current||tm.current!==e||!th.current)return;tu.current=setTimeout(()=>void n(),600)}};tu.current=setTimeout(()=>void n(),3e4)},[t9,nc,nd]),nI=(0,i.useCallback)(async(e=tm.current,t=tX.current)=>{if(tX.current===t)try{e&&await nn(e)}finally{if(tX.current!==t)return;let n=tw.current,r=ty.current;tw.current=!1,ty.current=!1,t0.current=null;let i=nw();n?nC(t):r&&i&&nS(),e&&nT(e)}},[nn,nS,nC,nT,nw]),nN=(0,i.useCallback)(async(e,t)=>{await s3(800);let n=Date.now();for(;tb.current&&Date.now()-n<2e4;){if(void 0!==t&&tX.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 nI(e,t)}}catch{}await s3(600)}},[nI]),nR=(0,i.useCallback)(async e=>{let t=tN.current+1;for(tN.current=t;tI.current&&tN.current===t&&tm.current===e;){await s3(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 nn(e),tN.current!==t||tm.current!==e)return;tI.current=!1,L(!1),P(null);return}catch{}}},[nn]),nM=(0,i.useCallback)(async e=>{if(!tb.current)return;let t=tX.current;try{let n=t3.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(tX.current!==t)return;let s=i.state;if(eT(s?.isCompacting??!1),tn(s0(s?.queuedMessages)),s?.contextUsage!==void 0&&eh(s.contextUsage??null),ti(e=>s2(e,s?.subagents??[])),t9(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isCompacting||s.isHandoffRunning)||!tb.current)return;s&&(void 0!==s.systemPrompt&&eg(s.systemPrompt??null),void 0!==s.extensionStatuses&&e7(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&te(s.extensionWidgets??[])),await nI(e,t)}catch{}},[t9,nI]),nE=(0,i.useCallback)(async e=>{let t=await nn(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tm.current===e&&!tb.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(ty.current=!!n.isStreaming,tw.current=!!n.isPromptRunning,tb.current=!0,E(!0),e_(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nm(e),!n.isStreaming&&n.isPromptRunning&&nN(e),!0)},[nm,nn,nN]),n$=(0,i.useCallback)(async(e,t=tX.current)=>{let n=tQ.current+1;tQ.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==tQ.current||tm.current!==e||tX.current!==t)return;i.state?.contextUsage!==void 0&&eh(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eC){eL.current=null,e$(null);return}e$(e=>e??{startedAt:Date.now(),reason:eL.current})},[eC]),(0,i.useEffect)(()=>{if(!M){eF.current=!1,eP(!1);return}ez.current=Date.now();let e=setInterval(()=>{var e,t,n;!eF.current&&(e=tb.current,t=ez.current,n=Date.now(),e&&n-t>=18e4)&&(eF.current=!0,eP(!0))},1e4);return()=>clearInterval(e)},[M]),(0,i.useEffect)(()=>{if(!M&&!eC)return;let e=()=>{let e=tm.current;e&&n$(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[M,eC,n$]),(0,i.useEffect)(()=>{if(!M)return;let e=()=>{let e=tm.current;e&&nM(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)}},[M,nM]),(0,i.useEffect)(()=>{if(M)return;let e=()=>{let e=tm.current;e&&!tb.current&&nE(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tm.current,n=e.detail?.sessionId;t&&n===t&&!tb.current&&nE(t).then(e=>{e||tm.current!==t||tb.current||nn(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(sV,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sV,n)}},[M,nE,nn]),tM.current=e=>{if(tm.current!==e||tb.current||to.current||tE.current)return;let t=nE(e).then(async t=>{t||tm.current!==e||tb.current||await nn(e)}).catch(()=>{}).finally(()=>{tE.current===t&&(tE.current=null)});tE.current=t},(0,i.useEffect)(()=>{tb.current=M},[M]),tR.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let s=e.context.messages,a=new Map;for(let e of s){let t=an(e);a.set(t,(a.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=an(e),n=a.get(t)??0;n>0&&a.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=an(e),n=a.get(t)??0;return 0===n||(a.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...s,...l],entryIds:[...e.context.entryIds]}}(e,tm.current,tg.current,tf.current,tx.current);if(!t)break;tg.current=t.entryId;let n=eV(t.messages,t.entryIds,tv.current.sessionId===tm.current?tv.current.outputs:[]);ne(n.messages),nt(n.entryIds);break}case"agent_start":{let e=!tb.current;nc(),e&&nk(),ty.current=!0,tb.current=!0,E(!0),e_({kind:"waiting_model"}),R({type:"start"});break}case"agent_end":if(!tb.current)break;if(e_(null),eu(null),R({type:"end"}),tm.current){nn(tm.current);let e=t3.current;fetch(`/api/agent/${encodeURIComponent(tm.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&eh(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eg(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&e7(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&te(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&ti(e=>s2(e,t.state?.subagents??[])),tm.current&&t9(tm.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tz(t.state.goal??null),tn(s0(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tz(e.status??null);break;case"agent_settled":{let e=ty.current;if(ty.current=!1,!e||tw.current)break;let t=tm.current,n=nw();eT(!1);let r=t?nn(t):void 0;t&&nT(t),n&&nS(r);break}case"prompt_done":{let e=tX.current,t=tw.current;tw.current=!1,t0.current=null;let n=tk.current!==e;if(!t&&!n)break;let r=tm.current;nC(e,r?nn(r):void 0),!ty.current&&(nw(),r&&nT(r))}break;case"prompt_error":tj.current="failed",nv({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tj.current="failed",nv({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tb.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&R({type:"update",message:iC(t)}),e_(null);break}case"message_end":{if(!tb.current)break;let t=e.message;if(t?.role==="assistant"&&(tS.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tj.current=s8(t)),t&&"user"===t.role){let e=iC(t),n=at(e),r=t0.current;t0.current=null,ne(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&at(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else t&&ne(e=>[...e,iC(t)]);let n=tm.current;n&&n$(n),R({type:"reset"}),e_({kind:"waiting_model"});break}case"todo_changed":t7(tm.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;e_(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;e_(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";ti(n=>{let r=n.find(e=>e.id===t.id);return s2(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()};ti(e=>s2(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};ti(e=>s2(e,[r]));break}case"queue_update":tn({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eu({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eu(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eL.current=e.reason;let t=e.reason;e$(e=>e?{...e,reason:t}:e)}eT(!0),eN(null),eM(null);break;case"auto_compaction_end":case"compaction_end":if(eT(!1),e.errorMessage)eN(e.errorMessage),eM(null);else if(!e.aborted){eM(ar(e.result,e.reason??"auto"));let t=tm.current;t&&(nn(t),n$(t))}break;case"extension_ui_request":ny(e)}},[nv,t7,t9,nc,ny,nn,nS,nC,n$,nk,nT,nw,nt,ne]);let nL=(0,i.useCallback)(async(n,i,s)=>{let a=n.trim();if(!a&&!i?.length&&!s?.length||tb.current||tI.current||t1.current)return;let o=nZ(n,s??[]),l=!i?.length&&!s?.length&&a.startsWith("/");if(!i?.length&&!s?.length&&a.startsWith("!")){let e=a.startsWith("!!"),t=(e?a.slice(2):a.slice(1)).trim();if(!t)return;await tW.current?.(t,e);return}nk();let c=tX.current+1;nc(),tw.current=!0;let d=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...o.trim()?[{type:"text",text:o}]:[],...d]:o,timestamp:Date.now()};ne(e=>[...e,u]),t0.current=at(u),tX.current=c,tb.current=!0,E(!0),e_(l?{kind:"running_command"}:{kind:"waiting_model"}),R({type:"start"}),tB.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,g=!1;try{if(m&&r){let e=tm.current??await tU.current,t=e??await no();t&&(h=t,Y&&(ek(Y),e&&await sB(t,{type:"set_model",provider:Y.provider,modelId:Y.modelId})),await ng(t),g=!0,await sB(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),na(1,n))}else t&&(h=t.id,await ng(t.id),g=!0,await sB(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}));l&&h&&nN(h,c)}catch(o){console.error("Failed to send message:",o);let r=o instanceof sO&&"update_draining"===o.code&&!1===o.accepted;if(!(!g||o instanceof sO&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return void nN(h,c);tw.current=!1,tb.current=!1,nd();let a=t0.current;a&&ne(e=>{let t=e[e.length-1];return t?.role==="user"&&at(t)===a?e.slice(0,-1):e}),nv({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,ai(i),s,t?.id??h??void 0),t0.current=null,E(!1),e_(null),R({type:"end"})}},[m,r,Y,t,no,ng,na,nN,nv,nc,nd,e.chatInputRef,nk,ne]);tW.current=(0,i.useCallback)(async(n,r)=>{if(tb.current||tI.current)return;let i=`${r?"!!":"!"}${n}`;tI.current=!0,tB.current(!0),P({command:n,excludeFromContext:r}),L(!0);try{let e=tm.current??t?.id??await no();if(!e)throw Error("Unable to create a session for the shell command");await sB(e,{type:"bash",command:n,excludeFromContext:r}),await nn(e),na(1,i)}catch(t){console.error("Failed to execute shell command:",t),nv({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tI.current=!1,P(null),L(!1)}},[nv,no,nn,e.chatInputRef,na,t]);let nA=(0,i.useCallback)(async()=>{let e=tm.current;if(e){if(tI.current){try{await sB(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sB(e,{type:"abort"}),tj.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nP=(0,i.useCallback)(async e=>{if(tI.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tm.current;if(!t)return{forked:!1,error:"No active session to fork"};ex(e??null);try{let{cancelled:n,newSessionId:r}=await sB(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(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{ex(null)}},[c]),nF=(0,i.useCallback)(async e=>{if(tI.current)return;let t=tm.current;t&&(sB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await ni(t,e))},[ni]),nz=(0,i.useCallback)(async e=>{if(tI.current)return;j(e);let t=tm.current;t&&(await ni(t,e),e&&sB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[ni]),nW=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=tV.current?.provider===e;tV.current=n,r||(tK.current=null,Q(null)),Z(n),ek(n);let i=tm.current??await tU.current;if(!i)return;try{await sB(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tm.current;if(n&&!t1.current){t1.current=!0,eb({provider:e,modelId:t}),eS(!0);try{await sB(n,{type:"set_model",provider:e,modelId:t}),t1.current=!1,await nn(n)}catch(e){console.error("Failed to set model:",e),t1.current=!1,eb(ev),nv({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nn(n)}finally{t1.current=!1,eS(!1)}}},[nv,ev,m,nn,Z]),nD=(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(t1.current)return!1;t1.current=!0,eS(!0);let e=tV.current,s=tK.current,a=tJ.current;try{tV.current=t,tK.current=n??null,tJ.current="auto";let e=tm.current??await tU.current;return e&&await sB(e,r),Z(t),Q(n??null),ek(t),es("auto"),eo(void 0),e&&await nn(e),!0}catch(n){console.error("Failed to apply Main preset:",n),tV.current=e,tK.current=s,tJ.current=a,nv({type:"error",message:i(n)});let t=tm.current;return t&&await nn(t),!1}finally{t1.current=!1,eS(!1)}}let s=tm.current;if(!s||t1.current)return!1;t1.current=!0,eb(t),eS(!0);try{return await sB(s,r),await nn(s),!0}catch(e){return console.error("Failed to apply Main preset:",e),eb(ev),nv({type:"error",message:i(e)}),await nn(s),!1}finally{t1.current=!1,eS(!1)}},[nv,ev,ea,m,nn,Z,ei]),nO=(0,i.useCallback)(async e=>{let t=J.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;tJ.current=t??null,es(t??"auto"),eo(void 0),tV.current=e,tK.current=null,Q(null),Z(e),ek(e)}let r=tm.current??(m?await tU.current:null);if(r)try{await sB(r,{type:"set_role_model",role:e}),m||eb({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,J,Z]),nB=(0,i.useCallback)(async()=>{let e=tm.current;if(e&&!eC){eL.current="manual",eT(!0),eN(null),eM(null);try{let t=await sB(e,{type:"compact"});eM(ar(t,"manual")),await nn(e,!0)}catch(e){eN(e instanceof Error?e.message:String(e)),eM(null)}finally{eT(!1)}}},[eC,nn]),n_=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",s=await fetch(i,e?{signal:e}:void 0);if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();z(a.models),B(a.modelError??null),H(a.modelScopeWarnings??[]),q(a.thinkingLevels??{}),K(a.thinkingLevelMaps??{}),G(a.roles??[]);let o=a.modelList??[];if(D(o),m&&!tm.current){let e=(a.defaultModel?o.find(e=>e.id===a.defaultModel?.modelId&&e.provider===a.defaultModel?.provider):void 0)??o[0];et(e?{provider:e.provider,modelId:e.id}:null);let t=e&&a.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===tJ.current&&es(t??"auto")}},[m,r,t?.cwd]),nH=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=tm.current??await no(),a=e=>(e.handled&&(e.error?nv({type:"error",message:e.error}):"openSessionStats"!==e.action&&nv({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||eC)return a({handled:!0,error:"No active session to compact"});eL.current="manual",eT(!0),eN(null),eM(null);let e=await sB(s,{type:"compact",...i?{customInstructions:i}:{}});return eM(ar(e,"manual")),await nn(s,!0)&&na(),a({handled:!0,message:"Compacted context"})}case"reload":if(!s)return a({handled:!0,error:"No active session to reload"});return await sB(s,{type:"reload"}),await Promise.all([nn(s,!1,!0),ns(s),nl(),n_()]),a({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return a({handled:!0,error:"No active session to name"});if(!i)return a({handled:!0,error:"Usage: /name <name>"});return await sB(s,{type:"set_session_name",name:i}),await nn(s)&&na(),a({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return a({handled:!0,error:"No active session"});let e=await sB(s,{type:"get_session_stats"});return e&&eQ(e),h?.(),a({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return a({handled:!0,error:"No active session"});let e=await sB(s,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return a({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),a({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!s)return a({handled:!0,error:"No active session to fork"});let e=await nP();if(!e.forked)return a({handled:!0,error:e.error??"Fork failed"});return a({handled:!0,message:"Forked a new session"})}case"goal":{if(!s)return a({handled:!0,error:"No active session"});let e=await sB(s,{type:"goal",args:i});if(tz(e?.status??null),e?.error)return a({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nb(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nv({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return a({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!s)return a({handled:!0,error:"No active session"});if(tb.current||tI.current)return a({handled:!0,error:"Cannot hand off while the session is busy"});tb.current=!0,E(!0),e_({kind:"running_command"});try{await ng(s);let e=await sB(s,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return a({handled:!0,error:"Handoff cancelled"});return await nn(s,!0)&&na(),a({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tb.current=!1,E(!1),e_(null),tm.current===s&&nT(s)}default:{if(!s)return a({handled:!0,error:"No active session"});let t=await sB(s,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nb(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return a({handled:!0,message:"Command completed"})}}}catch(e){return a({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eT(!1)}},[nv,nb,ng,no,nP,eC,n_,nn,nl,ns,na,h,nT]),nU=(0,i.useCallback)(async(t,n,r)=>{let i=tm.current;if(!i){nv({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ai(n),r);return}let s=nZ(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sB(i,{type:"steer",message:s,...a?.length?{images:a}:{}})}catch(s){console.error("Failed to steer:",s),nv({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,ai(n),r,i)}},[nv,e.chatInputRef]),nq=(0,i.useCallback)(async(t,n,r,i)=>{let s=tm.current;if(!s){nv({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ai(r),i);return}let a=nZ(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sB(s,{type:"prompt",message:a,streamingBehavior:n,...o?.length?{images:o}:{}})}catch(n){console.error("Failed to queue prompt:",n),nv({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,ai(r),i,s)}},[nv,e.chatInputRef]),nV=(0,i.useCallback)(async(t,n,r)=>{let i=tm.current;if(!i){nv({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,ai(n),r);return}let s=nZ(t,r??[]),a=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await sB(i,{type:"follow_up",message:s,...a?.length?{images:a}:{}})}catch(s){console.error("Failed to follow up:",s),nv({type:"error",message:s instanceof Error?s.message:String(s)}),e.chatInputRef?.current?.restoreSubmission?.(t,ai(n),r,i)}},[nv,e.chatInputRef]),nK=(0,i.useCallback)(async()=>{let e=tm.current;if(e)try{await sB(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nJ=(0,i.useCallback)(async()=>{let t=tm.current;if(t)try{var n;let r=await sB(t,{type:"clear_queue"});tn({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),nv({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nv]),nG=(0,i.useCallback)(async(e,t)=>{let n=tm.current;if(n)try{let r=await sB(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tn(n=>{let r=n[e].indexOf(t);return r<0?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nv({type:"error",message:"Failed to remove queued message"})}},[nv]),nY=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==el;es(e),ec(n),m&&!tm.current&&(tJ.current=e,tG.current=n),eo(void 0);let i=tm.current??await tU.current;if(i)try{r&&await sB(i,{type:"set_thinking_ceiling",ceiling:n}),await sB(i,{type:"set_thinking_level",level:e}),await nn(i)}catch(e){console.error("Failed to set thinking level:",e),nv({type:"error",message:"Failed to set thinking level"}),await nn(i)}},[m,nn,nv,el]),nX=(0,i.useCallback)(async e=>{let t=(0,si.xG)(e);t8(e);let n=tm.current??await tU.current;if(n)try{await sB(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[t8]),nQ=(0,i.useCallback)(e=>{tL.current=e,tP(t=>!e===t?t:!e)},[]);tB.current=nQ;let n0=(0,i.useCallback)((e="smooth")=>{tO.current=Date.now()+700,t_.current?.scrollIntoView({behavior:e})},[]),n1=(0,i.useCallback)(()=>{tD.current=0,nQ(!0),n0("smooth")},[n0,nQ]),n2=(0,i.useCallback)(()=>{tD.current=0,nQ(!1)},[nQ]),n8=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!s5.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tD.current=Date.now()+1200)},[]),n4=(0,i.useCallback)(()=>{if(!tb.current&&!tI.current)return;let e=tH.current;if(!e)return;let t=Date.now()<=tD.current;!t&&Date.now()<tO.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?nQ(!0):t&&nQ(!1))},[nQ]);return(0,i.useEffect)(()=>(tm.current=t?.id??null,tv.current.sessionId!==tm.current&&(tv.current={sessionId:tm.current,outputs:[],seq:0}),t&&nn(t.id,!g,!0,g).then(e=>{if(tm.current!==t.id)return;nh(t.id),e?.running&&(ns(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(ty.current=!!e.state.isStreaming,tw.current=!!e.state.isPromptRunning,tb.current=!0,E(!0),e_(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nm(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nN(t.id)),e.state?.isBashRunning&&(tI.current=!0,L(!0),nR(t.id)),(e.state?.subagents?.length??0)>0&&nm(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eT(n.isCompacting),void 0!==n.contextUsage&&eh(n.contextUsage??null),void 0!==n.systemPrompt&&eg(n.systemPrompt??null),void 0!==n.thinkingLevel&&(es(n.configuredThinkingLevel??n.thinkingLevel),eo(n.thinkingLevel)),void 0!==n.thinkingCeiling&&ec(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&e7(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&te(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tn(s0(n.queuedMessages)),void 0!==n.subagents&&ti(e=>s2(e,n.subagents??[])),void 0!==n.goal&&tz(n.goal??null)),e&&eD(!0)}),()=>{tN.current+=1,nc(),nd(),nu()}),[t?.id]),(0,i.useEffect)(()=>{p?.(em)},[em,p]),(0,i.useEffect)(()=>{u&&u(f?.tree??[],k,nz)},[f?.tree,k,nz,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",n8),()=>{window.removeEventListener("keydown",n8)}),[n8]),(0,i.useEffect)(()=>{let e=tH.current;if(e)return e.addEventListener("pointerdown",n8,{passive:!0}),e.addEventListener("wheel",n8,{passive:!0}),e.addEventListener("touchstart",n8,{passive:!0}),e.addEventListener("scroll",n4,{passive:!0}),()=>{e.removeEventListener("pointerdown",n8),e.removeEventListener("wheel",n8),e.removeEventListener("touchstart",n8),e.removeEventListener("scroll",n4)}},[S.length,v,n4,n8]),(0,i.useEffect)(()=>{if(tY.current||!M&&!$||!tL.current)return;let e=tH.current;if(!e)return;let t=requestAnimationFrame(()=>{tO.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[M,$,S.length,N.streamingMessage,eO,A,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!t$.current){t$.current=!0,n0("instant");return}if(!tY.current&&tL.current){let e=Date.now()-tZ.current<1500;n0(tb.current||tI.current||e?"instant":"smooth")}}},[S.length,M,$,n0,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n_(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n_,d]),(0,i.useEffect)(()=>{if(!eR)return;let e=setTimeout(()=>eM(null),6e3);return()=>clearTimeout(e)},[eR]),(0,i.useEffect)(()=>{if(0===eY.visible.length)return;let e=eY.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eZ({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eY.visible[0])return;let t=setTimeout(()=>{eZ({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eY.visible]),(0,i.useEffect)(()=>{eQ(null)},[S.length,ep?.tokens,ep?.percent,ep?.contextWindow]),{data:f,loading:v,error:y,activeLeafId:k,messages:S,entryIds:T,streamState:N,agentRunning:M,modelNames:F,modelList:W,modelError:O,modelScopeWarnings:_,modelThinkingLevels:U,modelThinkingLevelMaps:V,modelRoles:J,newSessionModel:Y,toolPreset:en,thinkingLevel:ei,effectiveThinkingLevel:ea,thinkingCeiling:el,retryInfo:ed,contextUsage:ep,systemPrompt:em,forkingEntryId:ef,isCompacting:eC,compaction:eE,compactError:eI,compactResult:eR,currentModel:t4,displayModel:t5,modelSwitching:ej,sessionStats:t6,runStalled:eA,runStateKnown:eW,slashCommands:eH,slashCommandsLoading:eJ,queuedMessages:tt,subagents:tr,todoPhases:ts&&ts.sid===tm.current?ts.phases:null,notices:eY.visible,extensionDialog:e0,extensionResponse:e2,extensionCustomUi:e5,extensionStatuses:e3,extensionWidgets:e9,respondToExtensionUi:nf,sendExtensionCustomInput:nx,isAutoModelSelection:m&&null===Y,agentPhase:eO,isNew:m,autoFollowPaused:tA,resumeAutoFollow:n1,pauseAutoFollow:n2,goalStatus:tF,sessionIdRef:tm,eventSourceRef:to,messagesEndRef:t_,scrollContainerRef:tH,handleSend:nL,handleAbort:nA,handleFork:nP,handleNavigate:nF,handleModelChange:nW,handleRoleModelChange:nO,handleMainPresetChange:nD,newSessionAccount:X,handleCompact:nB,handleSteer:nU,handleFollowUp:nV,handlePromptWithStreamingBehavior:nq,handleAbortCompaction:nK,handleRecallQueue:nJ,handleRemoveQueuedMessage:nG,handleBuiltinSlashCommand:nH,handleToolPresetChange:nX,handleThinkingLevelChange:nY,loadTools:ns,loadSlashCommands:nl,ensureNewSession:no,refreshLiveTranscript:nr,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:E,setForkingEntryId:ex,bashRunning:$,pendingBash:A,handleAgentEventRef:tR}}({session:e,newSessionCwd:t,initialData:s,transitioning:a,onAgentEnd:ep,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:f}),tD=nN(e?.id,eQ?.provider,void 0),tO=tD?.alias;(0,i.useEffect)(()=>{tO&&q.current?.(tO)},[tO]);let tB=(0,i.useMemo)(()=>{if(!eQ)return null;let e=td?tC:t4.find(e=>e.alias===tD?.alias)?.oauthPosition;return t4.find(t=>t.provider===eQ.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[eQ,td,tC,tD]),t_=eb||ew,tH=e?.id;Z.current=ef,X.current=ex,Q.current=tg;let tU=(0,i.useRef)(!0);tU.current=!tu;let tq=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eb&&!tq.current&&(ee.current+=1),tq.current=eb},[eb]),(0,i.useEffect)(()=>()=>{ee.current+=1},[]),(0,i.useEffect)(()=>{J(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(ad(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[]}}(tH),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===tH)])},[tH]),(0,i.useEffect)(()=>{let e=tg.current;e&&G.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&J(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let s=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let s=0;for(let a=i;a<r;a++)if(ie(t[a])===e.identity&&(s+=1)===e.occurrence)return{kind:"entry",entryId:n[a]};return null}(i.intent,ef,ex);if(null===s){r.push(i);continue}n=!0,"drop"!==s.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===s.entryId)||r.push({id:i.id,anchorEntryId:s.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(au(e,r),r):t})},[ef,ex,tg]);let tV=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tg.current,t=tV.current;if(tV.current=e?{sessionId:e,entryIds:ex}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let s=e.length;s<i;s++){let e=n[s];"assistant"===e.role&&"web6"===e.provider&&"ChatGPT 6PRO"===e.model&&r.push(t[s])}return r}(t.entryIds,ex,ef),r=er();if(0===n.length||!r)return;let i=nI(e,"web6",void 0)?.alias??null;for(let e of n)G.current.some(t=>t.anchorEntryId===e)||ea(i,"done",r,{kind:"entry",entryId:e})},[ex,ef,tg,er,ea]);let tK=eb&&tc?.kind==="running_tools"&&tc.tools.length>0&&tc.tools.every(e=>"wait"===e.name),tJ=em||a,{hideThinkingBlock:tG}=(P=t??e?.cwd??null,z=tQ(),(0,i.useEffect)(()=>{tX(P).catch(()=>{})},[P]),z),tY=(0,i.useMemo)(()=>({hideThinking:tG}),[tG]);(0,i.useEffect)(()=>{if(!tt||U.current===tt.id)return;U.current=tt.id;let e=er();if(e){var t;en.current=e.turn,el("select"===(t=tt.method)||"ask"===t?"choice":"approval",e,eQ?.provider,void 0,"dialog:session-model")}},[tt,eQ?.provider,er,el]),(0,i.useEffect)(()=>(v=t_?tb:null,()=>void(v=null)),[t_,tb]),(0,i.useEffect)(()=>{S?.(t_)},[S,t_]),(0,i.useEffect)(()=>()=>S?.(!1),[S]),(0,i.useEffect)(()=>{C?.(tK)},[tK,C]),(0,i.useEffect)(()=>()=>C?.(!1),[C]),(0,i.useEffect)(()=>{T?.(null!==tt)},[T,tt]),(0,i.useEffect)(()=>()=>T?.(!1),[T]);let{main:tZ,process:t0}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],s=-1,a=null,o=(e,t,n)=>{if(0===t.length)return;let s=(a&&a.anchorIdx===e||(a={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(a)),a),o=r.length-1;for(let e of t)s.entries.push({...e,afterMainIndex:o});s.messageCount+=t.length,s.toolCallCount+=n},l=eW(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:s,idx:e,runIndex:n,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){o(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),s=i.idx,r.push(i);continue}if(eH(t)){r.push(void 0!==i.anchorIdx||s<0?i:{...i,anchorIdx:s});continue}if("assistant"!==t.role){"toolResult"!==t.role&&o(s,[{idx:i.idx}],0);continue}let a=eP(t,n),c=!1;for(let e of a){if("answer"===e.kind){d(i.idx,e.blocks),c=!0;continue}o(s,[{idx:i.idx,blocks:e.blocks}],eF(e.blocks)),l.collect(i.idx,e.blocks)}!c&&eA(t,n)&&d(i.idx,[])}return u(),{main:r,process:i}})(ef,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(eK(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!eK(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let s=i,a=s+1;for(;a<e.length&&!eK(e[a]);)a+=1;if((t.sessionBusy||t.isStreaming)&&a===e.length&&s===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,s+1,a)){for(let e=s;e<a;e++)r.push({kind:"message",idx:e});i=a;continue}for(let n of(r.push({kind:"message",idx:s}),function(e,t,n,r){let i=[],s=[],a=0,o=[],l=0,c=0,d=eW(e.slice(t+1,n)),u=()=>{0!==s.length&&(i.push({kind:"process",anchorIdx:t,idx:s[0].idx,groupIndex:c++,entries:s,messageCount:s.length,toolCallCount:a,turnHasAnswer:!1}),s=[],a=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(n),precedingBlocks:o}),o=[]};for(let l=t+1;l<n;l++){let n=e[l];if("assistant"!==n.role){if(eH(n)){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&s.push({idx:l});continue}let c=eP(n,r),h=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){p(l,e.blocks);continue}for(let t of(s.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),a+=eF(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eA(n,r)&&p(l,[])}u();let h=d.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,s,a,{hideThinking:t.hideThinking})))r.push(n);i=a}return r}(ef,{sessionBusy:t_,isStreaming:ev.isStreaming,hideThinking:tY.hideThinking}),tY),[ef,t_,ev.isStreaming,tY]),[t1,t2]=(0,i.useState)(as),{startIndex:t8,endIndex:t5,hasLater:t6}=aa(tZ.length,t1),t3=null!==t1.end&&t6,t7=(0,i.useRef)(tZ.length);t7.current=tZ.length;let t9=(0,i.useRef)(null),ne=(0,i.useRef)(null),nt=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==t1.end&&t1.end>=tZ.length&&t2(e=>({count:e.count,end:null}))},[t1.end,tZ.length]),(0,i.useEffect)(()=>{let e=t9.current,t=tx.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nt.current=t.scrollHeight-t.scrollTop,t2(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[t1,tZ.length,tx]),(0,i.useEffect)(()=>{if(null==nt.current)return;let e=tx.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nt.current),nt.current=null}},[t1.count,tx]),(0,i.useEffect)(()=>{let e=ne.current,t=tx.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&t2(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=aa(e,t),s=i+n;return s>=e?{count:e-r,end:null}:{count:s-r,end:s}})(t7.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[t1,tZ.length,tx]);let[nn,nr]=(0,i.useState)(null),[ni,ns]=(0,i.useState)(0),na=(0,i.useRef)(null),no=(0,i.useCallback)(e=>{th(),na.current=e,nr(null),t2(t=>ao(t7.current,e,t)),ns(e=>e+1)},[th]);(0,i.useLayoutEffect)(()=>{let e=na.current,t=tx.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;na.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,nr(e)},[ni,t1,tZ,tx]),(0,i.useEffect)(()=>{if(null===nn)return;let e=setTimeout(()=>nr(null),1800);return()=>clearTimeout(e)},[nn]);let nl=(0,i.useCallback)(()=>{(0,W.flushSync)(()=>t2(as));let e=tx.current;e&&(e.scrollTop=e.scrollHeight)},[tx]),nc=(0,i.useCallback)(()=>{t3&&nl(),tp()},[t3,nl,tp]),nd=(0,i.useRef)(null),[nu,nh]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!L||nd.current===L.id||L.sessionId!==e?.id||em||0===ef.length)return;nd.current=L.id,A?.(L.id);let t=ex.indexOf(L.entryId);if(t<0)return void nh(!0);let n=0;for(let e=0;e<tZ.length;e++){let r=tZ[e].idx;if(r>t||(n=e,r===t))break}no(n)},[L,e?.id,em,ef.length,ex,tZ,no,A]),(0,i.useEffect)(()=>{if(!nu)return;let e=setTimeout(()=>nh(!1),6e3);return()=>clearTimeout(e)},[nu]);let[nm,ng]=(0,i.useState)(!1),[nf,nx]=(0,i.useState)(0),nv=(0,i.useMemo)(()=>nm?tZ.map(e=>(function(e,t){if("answer"===e.kind)return eY(e.blocks);let n=t[e.idx];return n&&"content"in n?eY(n.content):""})(e,ef).toLowerCase()):ap,[nm,tZ,ef]),nb=(0,i.useCallback)(e=>{th(),t2(t=>ao(t7.current,e,t))},[th]),ny=(0,i.useCallback)(()=>ng(!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=tx.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(),ng(!0),nx(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tx]);let nw=(0,i.useMemo)(()=>{let e=[];return tZ.forEach((t,n)=>{if("message"!==t.kind)return;let r=ac(ef[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[tZ,ef]),nk=`${t8}:${t5}`,nj=ex.length>0?ex[ex.length-1]:null,[nS,nC]=(0,i.useState)(null),nT=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nT.current||!e4||em||!e?.id||(nT.current=!0,t_||!nj||!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)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(ef)||function(e){try{return window.localStorage.getItem(ah(e))}catch{return null}}(e.id)!==nj&&nC(nj))},[e4,em,e?.id,t_,nj,ef]);let nR=(0,i.useCallback)(()=>{e?.id&&nS&&function(e,t){try{window.localStorage.setItem(ah(e),t)}catch{}}(e.id,nS),nC(null)},[e?.id,nS]),nM=null!==nS&&nS===nj&&!t_&&!t3,nE=e1?[e1.sessionId,e1.sessionFile??"",e1.sessionName??"",e1.userMessages,e1.assistantMessages,e1.toolCalls,e1.toolResults,e1.totalMessages,e1.tokens.input,e1.tokens.output,e1.tokens.cacheRead,e1.tokens.cacheWrite,e1.tokens.total,e1.cost??0,e1.totalActiveMs??0].join("|"):null,n$=(0,i.useRef)(e1);n$.current=e1,(0,i.useEffect)(()=>{g?.(n$.current)},[nE,g]),(0,i.useEffect)(()=>()=>{g?.(null)},[g]);let nL=eO?`${eO.percent??"null"}|${eO.contextWindow}|${eO.tokens??"null"}`:null,nA=(0,i.useRef)(eO);nA.current=eO,(0,i.useEffect)(()=>{x?.(nA.current)},[nL,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(e7)},[b,e7]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:nP,handleDragEnter:nF,handleDragOver:nz,handleDragLeave:nW,handleDrop:nD}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:s,handleDragOver:a,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t_||p?.current?.addAttachments(e)},[t_,p])),nO=(0,i.useMemo)(()=>{let e=new Map;for(let t of ef)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ef]),nB=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ef.length-1;n>=0;n-=1){let r=ac(ef[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ef]),n_=(0,i.useMemo)(()=>(function(e,t,n=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=e2(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)})(ef,nO,e9),[ef,nO,e9]),nH=(0,i.useMemo)(()=>ip(ev.streamingMessage).join("|"),[ev.streamingMessage]),nU=(0,i.useMemo)(()=>JSON.stringify(iu(ev.streamingMessage)),[ev.streamingMessage]),nq=(0,i.useMemo)(()=>JSON.stringify(im(ev.streamingMessage)),[ev.streamingMessage]),nV=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let s=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),a=[],o=new Map,l=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){l=n;continue}let i=ip(r),c=im(r,s);if(0===i.length&&0===c.length||l<0)continue;let d=iu(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),a.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.length>0||i.length>0){let s=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){s=t;break}if(s>=0){let e=o.get(s);e||(e={index:s,entryId:t[s],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(s,e),a.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!d.has(e.toolCallId))]}}return a.sort((e,t)=>e.index-t.index)})(ef,ex,nH.length>0?nH.split("|"):[],JSON.parse(nU),JSON.parse(nq)),[ef,ex,nH,nU,nq]),nK=e?.id??tg.current??void 0,nJ=(D=i$(F=(0,i.useMemo)(()=>({sessionId:nK,sessionProvider:eQ?.provider,turns:nV,messages:ef,subagents:e7}),[nK,eQ?.provider,nV,ef,e7])),O=iF(F),(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}([...D,...O])),[D,O])),nG=td&&0===ef.length&&!ev.isStreaming&&!t_,nY=e?.cwd??t??void 0,nX=eQ?eI[`${eQ.provider}:${eQ.modelId}`]??null:null,nQ=eQ?eN[`${eQ.provider}:${eQ.modelId}`]??null:null,n0=(0,i.useRef)(null),n1=(0,i.useRef)(null),n2=(0,i.useCallback)(()=>{n0.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(j?.(n2),()=>j?.(null)),[n2,j]),(0,i.useLayoutEffect)(()=>{let e=n1.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tx.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tx.current;if(!i)return;let s=n-i.clientHeight;n=i.clientHeight,s<=0||i.scrollHeight-i.scrollTop-i.clientHeight-s<=1&&(i.scrollTop+=s)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[em,tx]);let n8=(0,i.useCallback)((...e)=>(null!==t1.end&&nl(),tv(...e)),[tv,t1.end,nl]),n4=(0,r.jsx)("div",{ref:n0,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(sA,{ref:p,sessionId:e?.id??tg.current??void 0,onEnsureSession:td&&t?tz:void 0,onLiveTranscriptPersisted:tW,onSend:n8,onAbort:tb,onSteer:eb?tI:void 0,onFollowUp:eb?tN:void 0,onPromptWithStreamingBehavior:eb?tR:void 0,isStreaming:t_,model:eQ,isAutoModelSelection:tl,modelNames:ej,modelList:eS,modelError:eC,modelScopeWarnings:eT,onModelChange:tk,onMainPresetChange:e||td?tS:void 0,mainPresetActiveAlias:tB,modelRoles:eR,onRoleModelChange:tj,modelSwitching:e0,onCompact:e||td?tT:void 0,onAbortCompaction:tM,isCompacting:eJ,compactError:eZ,compactResult:eX,toolPreset:eM,onToolPresetChange:e||td?tA:void 0,thinkingLevel:eE,effectiveThinkingLevel:eL,thinkingCeiling:ez,onThinkingLevelChange:e||td?tP:void 0,availableThinkingLevels:nX,thinkingLevelMap:nQ,retryInfo:eD,queuedMessages:e3,inputHistory:nB,onRecallQueue:tE,onRemoveQueuedMessage:t$,slashCommands:e5,slashCommandsLoading:e6,onLoadSlashCommands:tF,onBuiltinCommand:tL,soundEnabled:I,onSoundToggle:N,onAudioUnlock:$,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),n5=ev.streamingMessage,n6=(0,i.useMemo)(()=>n5?eP(n5,{isStreaming:!0}):[],[n5]),n3=(0,i.useMemo)(()=>n6.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[n6]),n7=(0,i.useMemo)(()=>n6.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[n6]),n9=n5?.role==="assistant"?n5:null,re=eb&&(tc?.kind==="running_tools"||(n9?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rt=n9?.provider??eQ?.provider,rn=n9?.credentialId,rr=n9?.provider?`stream:${n9.provider}/${n9.model}`:`session-model:${eQ?.provider}/${eQ?.modelId}`;(0,i.useEffect)(()=>{if(!re)return;let e=er();e&&et.current!==e.turn&&en.current!==e.turn&&(et.current=e.turn,el("working",e,rt,rn,rr))},[re,rt,rn,rr,er,el]);let[ri,rs]=(0,i.useState)(null),ra=(0,i.useCallback)(e=>{rs(e)},[]),ro=(0,i.useMemo)(()=>ek?{role:"bashExecution",command:ek.command,output:"",excludeFromContext:ek.excludeFromContext}:null,[ek]),rl=(0,i.useMemo)(()=>{let e=[eb&&!n5&&tc?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}(tc,B):null,ew&&!ek?B("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eb,n5,tc,ew,ek,B]);(0,i.useEffect)(()=>{if(!ri)return void y?.(null);let e=[],t=[],n=0;if(n5&&n7.length>0){let r=ri.messages.length+e.length;for(let i of(e.push(n5),n7))t.push({idx:r,blocks:i}),n+=eF(i)}if(ro&&(t.push({idx:ri.messages.length+e.length}),e.push(ro)),0===t.length)return void y?.(rl?{...ri,status:rl}:ri);let r=-1;for(let e=ri.messages.length-1;e>=0;e--)if(eK(ri.messages[e])){r=e;break}let i=ri.groups.slice(),s=i.length>0?i[i.length-1]:void 0;s&&s.anchorIdx===r?i[i.length-1]={...s,entries:[...s.entries,...t],messageCount:s.messageCount+t.length,toolCallCount:s.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),y?.({...ri,groups:i,messages:[...ri.messages,...e],status:rl})},[ri,n7,n5,ro,rl,y]),(0,i.useEffect)(()=>()=>y?.(null),[y]);let rc=ts.filter(e=>"belowEditor"!==e.placement),ru=ts.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":tJ,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nF,onDragOver:nz,onDragLeave:nW,onDrop:nD,children:[tJ?(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,nP&&!t_&&(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")})}),tr&&(0,r.jsx)(aw,{request:tr,onInput:to}),nG&&!k?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto px-4 py-8",children:(0,r.jsxs)("div",{className:"w-full max-w-[820px]",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)(H,{})}),(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.6.8"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.4.4"]})]})]})]}),(0,r.jsx)(av,{notices:te,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:k}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!k,style:{display:k?"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)(rH,{open:nm,onClose:ny,containerRef:tx,index:nv,renderedStart:t8,renderedEnd:t5,contentKey:ef,onReveal:nb,onProgrammaticScroll:th,focusRequest:nf,t:B}),nu&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:B("chat.jumpMissing")}),(0,r.jsx)(av,{notices:te,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tx,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)(ax,{widgets:rc}),(0,r.jsx)(ia,{utterances:nJ,children:(0,r.jsx)(am,{messages:ef,entryIds:ex,toolResultsMap:nO,modelNames:ej,messageCwd:nY,onOpenFile:w,sessionBusy:t_,isNew:td,isStreaming:ev.isStreaming,handleFork:ty,forkingEntryId:e_,handleNavigate:tw,handleEditContent:eh,sessionId:e?.id??tg.current??void 0,main:tZ,process:t0,startIndex:t8,endIndex:t5,sentinelRef:t9,laterSentinelRef:ne,flashItem:nn,t:B,cues:K,cueFollowRef:tU,onProcessLogChange:ra})}),!t3&&ev.isStreaming&&ev.streamingMessage&&n3.length>0&&(0,r.jsx)(rd,{message:e$(ev.streamingMessage,n3),sessionId:e?.id??tg.current??void 0,isStreaming:!0,modelNames:ej,cwd:nY,onOpenFile:w}),nM&&(0,r.jsx)(rY,{onDismiss:nR,t:B}),(0,r.jsx)("div",{ref:tf})]})})}),(0,r.jsx)(rU,{questions:nw,containerRef:tx,layoutKey:nk,onJump:no,label:B("chat.questionRail")}),(t_&&tu||t3)&&(0,r.jsxs)("button",{type:"button",onClick:nc,"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:n1,className:"relative chat-composer-dock",children:[tt&&(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)(ay,{request:tt,onRespond:ta,onActivity:e=>void to(e,"activity"),delivery:tn})})}),(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(rK,{stalled:e8&&eb,t:B}),(0,r.jsx)(rG,{compaction:eG,t:B}),(0,r.jsx)(af,{goal:tm,t:B}),(0,r.jsx)(ax,{widgets:ru}),n_&&(0,r.jsx)(sF,{phases:n_})]})}),n4,(0,r.jsx)(sP,{statuses:ti})]})]})}function af({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:tU(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:tU(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 ax({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 av({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let s="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function ab({focusKey:e,label:t,labelledBy:n,maxBlockSize:s="min(56dvh, 620px)",onCancel:a,delivery:o,children:l}){let{t:c}=(0,E.s)(),d=(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&&!d.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=d.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:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:a?e=>{"Escape"===e.key&&(e.stopPropagation(),a())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:s},children:[o?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function ay({request:e,onRespond:t,onActivity:n,delivery:s}){let{t:a}=(0,E.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,i.useState)({}),[u,p]=(0,i.useState)({}),[h,m]=(0,i.useState)(""),g=(0,i.useRef)(0),f=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-g.current<1e3||(g.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{if(l("editor"===e.method?e.prefill??"":""),m(""),p({}),"ask"!==e.method)return void d({});let t={};for(let n of e.questions)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];d(t)},[e]);let x=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("ask"===e.method){let n=e.questions.every(e=>(c[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:(c[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})})})};return(0,r.jsx)(ab,{focusKey:e.id,label:a("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:a("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:a("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let s=c[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=s.includes(n),o=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(f(),d(t=>{let i=t[e]??[],s=r?i.includes(n)?i.filter(e=>e!==n):[...i,n]:[n];return{...t,[e]:s}}))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:u[t.id]??"",onChange:e=>{f(),p(n=>({...n,[t.id]:e.target.value}))},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:a("chat.customAnswer"),"aria-label":a("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:a("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:a("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||s?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&s?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&s?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&s?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:s?.status==="sending"?a("chat.responseSending"):a("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(ab,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:a("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(tB,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:h,onChange:e=>m(e.target.value),placeholder:a("chat.planFeedback"),"aria-label":a("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:h.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:a("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:a("chat.approvePlan")})]})]})]})}):(0,r.jsx)(ab,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:s,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:a("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(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:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&x()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:a("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:x,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:a("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:x,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:a("chat.submit")}):null]})]})})}function aw({request:e,onInput:t}){let{t:n}=(0,E.s)(),s=(0,i.useRef)(null),a=(0,i.useRef)(!1),o=eS(e.lines);return(0,i.useEffect)(()=>{s.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||s.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:s,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eI[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":" ":eT[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(a.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{a.current=!0},onCompositionEnd:n=>{a.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var s;return(0,r.jsxs)(i.Fragment,{children:[(s=`line-${t}`,eC(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${s}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function ak({onPick:e,t}){let[n,s]=(0,i.useState)(""),[a,o]=(0,i.useState)({kind:"idle"}),l=(0,i.useRef)(null),c=n.trim();(0,i.useEffect)(()=>{if(c.length<2)return void o({kind:"idle"});let e=new AbortController;o({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);o({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||o({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[c]);let d=e=>{let t=l.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===a.kind?a.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>s(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),d(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}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===a.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===a.kind&&t("palette.searching"),"error"===a.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,i)=>{let s=u.sessions[n.sessionId],a=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!s,onClick:()=>s&&e(s,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:s?s.name?.trim()||s.firstMessage?.trim()||s.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,a)}),n.snippet.slice(a)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var aj=n(50640),aS=n(73620);let aC=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function aT(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 aI=["tags","categories","keywords","tag","category"];function aN({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,s=aI.find(t=>Array.isArray(e[t])),a=s?e[s].map(aT).filter(Boolean):[],o=n.filter(([e])=>e!==s&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),a.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:a.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.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=aT(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 aR={source:"Source",preview:"Preview",diff:"Diff"},aM={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},aE={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 a$(){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 aL(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function aA(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=aL(n.startContainer),i=aL(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),a=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(a))return null;if(s<a){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((i=e).dataset.lineNumber))}}}return s>a?null:{startLine:s,endLine:a}}function aP({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,s)=>{let a=e.children??[],o=a[0]?.properties?.className,l=Array.isArray(o)&&o.includes("react-syntax-highlighter-line-number"),c=l?a[0]:null,d=l?a.slice(1):a;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":s+1,style:{display:"flex",minWidth:"100%"},children:[c&&(0,aj.Ay)({node:c,stylesheet:t,useInlineStyles:n,key:`source-line-number-${s}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:d.map((e,r)=>(0,aj.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${s}-${r}`}))})]},`source-line-${s}`)})}function aF(e,t,n,r={}){let i=e3(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function az({filePath:e,sourceSessionId:t}){let{t:n}=(0,E.s)();return(0,r.jsx)("a",{href:aF(e,"download",t),download:e7(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 aW(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function aD({patch:e}){let t,{t:n}=(0,E.s)(),i=(t=nE(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let s=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),a=new Set;for(let e of s)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)a.add(t);let o=[],l=0;for(;l<i.length;)if(a.has(l)){let e=[];for(;l<i.length&&a.has(l);)e.push(i[l]),l++;o.push({hidden:!1,lines:e})}else{let e=0;for(;l<i.length&&!a.has(l);)e++,l++;o.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...aM},children:o.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:aE,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function aO({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(0),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),f=(0,i.useRef)(null),x=e7(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),u(null),h(null),g(null),o(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(aF(e,"watch",n));return f.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}c(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),f.current=null}},[e,n]);let v=aF(e,"read",n,l?{v:l}:void 0),b=null!=d?aW(d):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:e9(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:x||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,r.jsx)("span",{children:b}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(az,{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:()=>g("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function aB({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(0),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),f=(0,i.useRef)(null),x=e7(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),u(null),h(null),g(null),o(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(aF(e,"watch",n));return f.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}h(null),g(null),c(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),f.current=null}},[e,n]);let v=aF(e,"read",n,l?{v:l}: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:e9(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!=d&&(0,r.jsx)("span",{children:aW(d)}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]}),(0,r.jsx)(az,{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:()=>g("Failed to load audio"),style:{width:"100%"}},v)]})})]})}function a_({filePath:e,cwd:t,sourceSessionId:n}){let{t:s}=(0,E.s)(),[a,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(0),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),g=eM(e),f="pdf"===g,x=f?aF(e,"read",n,l?{v:l}:void 0):aF(e,"preview",n,l?{v:l}:void 0);return(0,i.useEffect)(()=>{c(0),u(null),h(null),o(!1),m.current&&(m.current.close(),m.current=null),fetch(aF(e,"meta",n)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!f&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(aF(e,"watch",n));return m.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!f&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),c(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),m.current=null}},[e,f,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:e9(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===g?"docx preview":"pdf"}),null!=d&&(0,r.jsx)("span",{children:aW(d)}),(0,r.jsx)(az,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:f?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:e7(e)}),style:{width:"100%",height:"100%",border:"none",background:f?"var(--bg)":"#eef1f5"}},x)})]})}function aH({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:o,initialDisplayMode:l}){let c;return eE(e)?(0,r.jsx)(aO,{filePath:e,cwd:t,sourceSessionId:n}):null!==(eR[eM(e)]??null)?(0,r.jsx)(aB,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(c=eM(e))||"docx"===c?c:null)?(0,r.jsx)(a_,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(aU,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:a,gitRefreshKey:o,initialDisplayMode:l})}function aU({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:s,onMentionLines:a,onAtMention:o,gitRefreshKey:l,initialDisplayMode:c}){let d,u,{isDark:p}=tF(),{t:h}=(0,E.s)(),[m,g]=(0,i.useState)(null),[f,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"),[T,I]=(0,i.useState)(!1),[N,R]=(0,i.useState)(!1),M=(0,i.useRef)(null),$=(0,i.useRef)(0),L=(0,i.useRef)(null),[A,P]=(0,i.useState)(null),F=(0,i.useCallback)(e=>fetch(aF(e,"read",n)).then(e=>e.json()).then(e=>e.error?(j(e.error),null):(j(null),g(e),e)).catch(e=>(j(String(e)),null)),[n]),z=(0,i.useCallback)(async e=>{let n=++$.current;if(b(!0),!t){x(null),b(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(n!==$.current)return;x(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch{n===$.current&&x(null)}finally{n===$.current&&b(!1)}},[t]);(0,i.useEffect)(()=>{w(!0),j(null),g(null),x(null),C("source"),I(!1),R(!1),M.current&&(M.current.close(),M.current=null),F(e).finally(()=>w(!1));let t=new EventSource(aF(e,"watch",n));return M.current=t,t.addEventListener("connected",()=>{R(!0)}),t.addEventListener("change",()=>{F(e),z(e)}),t.addEventListener("error",()=>{R(!1)}),t.onerror=()=>{R(!1)},()=>{t.close(),M.current=null}},[e,F,z,n]),(0,i.useEffect)(()=>{z(e)},[z,e,l]),(0,i.useEffect)(()=>{(m?.language==="markdown"||m?.language==="html")&&"diff"!==c&&C("preview")},[m?.language,c]);let W=f?.supported===!0&&"string"==typeof f.patch,D=W&&"deleted"===f.status;(0,i.useEffect)(()=>{W||"diff"!==S||C("source")},[S,W]),(0,i.useEffect)(()=>{D&&M.current&&(M.current.close(),M.current=null,R(!1))},[D]);let O=(0,i.useRef)(!1);(0,i.useEffect)(()=>{O.current=!1},[e]),(0,i.useEffect)(()=>{"diff"===c&&W&&!O.current&&(O.current=!0,C("diff"))},[c,W]);let B=(0,i.useMemo)(()=>m?.language==="markdown"?tl(m.content):"",[m]),_=(0,i.useMemo)(()=>m?.language==="markdown"?function(e){let t=function(e){let t=aC.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,aS.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;P(a&&"source"===S&&e?aA(e,window.getSelection()):null)};if(e(),a&&"source"===S)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[m?.content,S,a]);let H=(0,i.useCallback)(n=>{a&&n&&a(e9(e,t),n.startLine,n.endLine)},[t,e,a]);if((0,i.useEffect)(()=>{if(!a||"source"!==S)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=L.current,r=n?aA(n,window.getSelection()):null;r&&(e.preventDefault(),H(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[S,H,a]),y||"diff"===c&&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&&!D)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:k});if(!m&&!D)return null;let U=m?.language??"text",q=m?.content??"",V="html"===U,K="markdown"===U,J=(u=(d=e6(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===u?"/":2===u&&/^[a-zA-Z]:\//.test(d)?d.slice(0,3):d.slice(0,u),G=q.split("\n"),Y=D?"diff":S,Z=D?["diff"]:["source",...V||K?["preview"]:[],...W?["diff"]:[]],X=D?h("files.deleted"):`${U} \xb7 ${G.length} lines \xb7 ${aW(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:e9(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:X,children:X}),!D&&(0,r.jsx)("span",{title:N?h("i18n.liveSync"):h("i18n.notWatching"),"aria-label":N?h("i18n.liveSync"):h("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:N?"#4ade80":"var(--border)",boxShadow:N?"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:aR[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(o||a)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{A&&a?H(A):o?.(e9(e,t),!1)},title:A&&a?`${h("i18n.mentionSelectedLines")} (L${A.startLine}${A.startLine!==A.endLine?`-L${A.endLine}`:""})`:h("files.insertPath"),"aria-label":h("files.mention"),disabled:!o&&!a,className:"file-viewer-icon-button",children:(0,r.jsx)(a$,{})}),"source"===Y&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:()=>I(e=>!e),title:T?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-label":T?h("i18n.disableWrap"):h("i18n.enableWrap"),"aria-pressed":T,className:"file-viewer-icon-button",style:{background:T?"var(--bg-selected)":"transparent",color:T?"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"})]})})})]}),!D&&(0,r.jsx)(az,{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&&W?(0,r.jsx)(aD,{patch:f.patch}):V&&"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")}):K&&"preview"===Y?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[_?.data&&(0,r.jsx)(aN,{data:_.data}),(0,r.jsx)(e5.oz,{remarkPlugins:th,rehypePlugins:tg,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,r.jsx)(tW,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tO,{code:s.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let a=s?e1(e,J,t??J):null;return a&&s?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),s(a))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...s}){delete s.node;let a="string"==typeof e?e1(e,J,t??J):null,o=a?aF(a,"read",n):e;return(0,r.jsx)("img",{src:o,alt:i??"",loading:"lazy",...s})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:B})]}):(0,r.jsx)(e8.A,{className:T?"file-source-view is-wrapped":"file-source-view",language:"text"===U?"plaintext":U,style:p?e4.xJ:e4.vs,showLineNumbers:!0,lineNumberStyle:{...aE},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...aM,width:T?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:T?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(aP,{...e,wrapLines:T}),wrapLongLines:T,children:q})})]})}function aq({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:s}){let{t:a,locale:o}=(0,E.s)(),[l,c]=(0,i.useState)(null);return(0,r.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===o?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,r.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),s(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:nD(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),s(e.id)},onMouseEnter:()=>c(e.id),onMouseLeave:()=>c(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:l===e.id?"var(--bg-hover)":"transparent",border:"none",color:l===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:a("i18n.close"),"aria-label":`${a("i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let aV=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],aK=new Set(aV);function aJ(e){return void 0!==e&&aK.has(e)}function aG(e){if(!e)return[...aV];let t=new Set(e);return aV.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function aY(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return aJ(n)?n:"inherit"}function aZ(e,t){let n=e.lastIndexOf(":"),r=aJ(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var aX=n(98795),aQ=n.n(aX);function a0(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function a1({value:e,options:t,onChange:n,disabled:s=!1,placeholder:a="Select…",searchPlaceholder:o="Search options…",noResultsLabel:l="No matching options",ariaLabel:c,className:d,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),g=(0,i.useRef)([]),[f,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=a0(v.trim());return e?t.filter(t=>a0(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!f)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[f]),(0,i.useEffect)(()=>{f?requestAnimationFrame(()=>m.current?.focus()):b("")},[f]),(0,i.useEffect)(()=>{if(!f)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,f,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{f&&g.current[y]?.scrollIntoView({block:"nearest"})},[y,f]);let{side:C,maxHeight:T}=sr(p,f,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),I=e=>{e.disabled||(n(e.value),x(!1))},N=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:`${aQ().root}${d?` ${d}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:aQ().trigger,disabled:s,"aria-label":c,"aria-haspopup":"listbox","aria-expanded":f,"aria-controls":f?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?aQ().value:aQ().placeholder,children:j?.label??(e||a)}),(0,r.jsx)("svg",{className:aQ().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),f&&(0,r.jsxs)("div",{className:aQ().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:T}:{top:"calc(100% + 5px)",maxHeight:T},"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:aQ().searchWrap,children:[(0,r.jsxs)("svg",{className:aQ().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:aQ().search,value:v,placeholder:o,"aria-label":o,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(),N(1);else if("ArrowUp"===e.key)e.preventDefault(),N(-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:aQ().options,role:"listbox","aria-label":c,style:{maxHeight:Math.max(0,T-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{g.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:aQ().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:aQ().optionCopy,children:[(0,r.jsx)("span",{className:aQ().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:aQ().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:aQ().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:aQ().empty,children:l})})]})]})}let a2=["global","project"];function a8(e){return`${e.provider}/${e.id}`}function a4({cwd:e,onRolesChanged:t}){let{t:n}=(0,E.s)(),[s,a]=(0,i.useState)([]),[o,l]=(0,i.useState)([]),[c,d]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){a([]),l([]),d({}),m(!1);return}m(!0),f(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let s=await r.json();if(s.error)throw Error(s.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();a(s.roles??[]),l(o.modelList??[]),d(o.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;f(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),f(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);a(s.roles??[]),t?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>s.filter(e=>!e.hidden),[s]);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")})]}),(0,r.jsxs)("div",{style:{display:"flex",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",border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:a2.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-dim)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),g&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:g}),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}`:aZ(e.selector??"","inherit"),i=aY(e.selector),s=aG(c[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]);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",alignItems:"center",gap:10},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}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:n(`roles.source.${e.source}`)})]}),(0,r.jsx)(a1,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:1,minWidth:160},onChange:t=>{if(!t)return void y(e.role,null);let n=o.find(e=>a8(e)===t),r=n?c[`${n.provider}:${n.id}`]:void 0,i=aY(e.selector),s=aG(r).includes(i)?i:"inherit";y(e.role,aZ(t,s))},options:[{value:"",label:n("roles.unset")},...o.map(e=>({value:a8(e),label:`${e.name} — ${e.provider}`,searchText:a8(e)})),...t&&!o.some(e=>a8(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:s.map(s=>{let a=i===s;return(0,r.jsx)("button",{type:"button","aria-pressed":a,disabled:x===e.role,title:"inherit"===s?n("roles.thinkingInherit"):s,onClick:()=>{a||y(e.role,aZ(t,s))},style:{padding:"3px 7px",border:`1px solid ${a?"var(--accent)":"var(--border)"}`,borderRadius:4,background:a?"var(--bg-selected)":"transparent",color:a?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:a?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:s},s)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function a5(e){window.open(e,"_blank","noopener,noreferrer")}var a6=n(67381),a3=n(64433),a7=n(70350),a9=n(88195),oe=n(9312),ot=n(87275),on=n(22008),or=n(95476),oi=n(35029),os=n(14489),oa=n(78728),oo=n(19872),ol=n(7751),oc=n(92526),od=n(48238),ou=n(57794),op=n(41098),oh=n(84604),om=n(15315),og=n(74278),of=n(55457),ox=n(71437),ov=n(29167),ob=n(97283),oy=n(34166),ow=n(33889),ok=n(85486),oj=n(74068),oS=n(83546),oC=n(83709);let oT={anthropic:{Icon:a6.A,hasColor:!1},openai:{Icon:a3.A,hasColor:!1},"openai-codex":{Icon:a3.A,hasColor:!1},google:{Icon:a7.A,hasColor:!0},"google-vertex":{Icon:a7.A,hasColor:!0},"ant-ling":{Icon:ow.A,hasColor:!0},deepseek:{Icon:a9.A,hasColor:!0},groq:{Icon:oe.A,hasColor:!1},mistral:{Icon:ot.A,hasColor:!0},moonshotai:{Icon:on.A,hasColor:!1},"moonshotai-cn":{Icon:on.A,hasColor:!1},moonshot:{Icon:on.A,hasColor:!1},minimax:{Icon:or.A,hasColor:!0},"minimax-cn":{Icon:or.A,hasColor:!0},fireworks:{Icon:oi.A,hasColor:!0},huggingface:{Icon:os.A,hasColor:!0},cerebras:{Icon:oa.A,hasColor:!0},openrouter:{Icon:oo.A,hasColor:!1},xai:{Icon:ol.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:oc.A,hasColor:!0},"cloudflare-workers-ai":{Icon:oc.A,hasColor:!0},"vercel-ai-gateway":{Icon:od.A,hasColor:!1},"github-copilot":{Icon:ou.A,hasColor:!1},"amazon-bedrock":{Icon:op.A,hasColor:!0},"azure-openai-responses":{Icon:oh.A,hasColor:!0},"kimi-coding":{Icon:om.A,hasColor:!0},nvidia:{Icon:ok.A,hasColor:!0},opencode:{Icon:oj.A,hasColor:!1},"opencode-go":{Icon:oj.A,hasColor:!1},qwen:{Icon:og.A,hasColor:!0},xiaomi:{Icon:oS.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oS.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oS.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oS.A,hasColor:!1},zai:{Icon:oC.A,hasColor:!1},"zai-coding-cn":{Icon:oC.A,hasColor:!1},zhipu:{Icon:of.A,hasColor:!0},cohere:{Icon:ox.A,hasColor:!0},perplexity:{Icon:ov.A,hasColor:!0},together:{Icon:ob.A,hasColor:!0},grok:{Icon:oy.A,hasColor:!1}},oI=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function oN({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 oR={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:{...oR,fontFamily:i?"var(--font-mono)":"inherit"}})}function oE({value:e,onChange:t,placeholder:n,mono:s,onKeyDown:a,autoComplete:o="off",spellCheck:l=!1,style:c}){let[d,u]=(0,i.useState)(!1),{t:p}=(0,E.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:d?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:a,placeholder:n,style:{...oR,paddingRight:34,fontFamily:s?"var(--font-mono)":"inherit"},autoComplete:o,spellCheck:l}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(d?"i18n.hideDetails":"i18n.showDetails"),title:p(d?"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:d?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function o$({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:oR})}function oL({value:e,onChange:t,options:n,required:i}){let{t:s}=(0,E.s)();return(0,r.jsx)(a1,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${s("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function oA({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 oP({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 oF({name:e,provider:t,onChange:n,onRename:s,onDelete:a,onAddModels:o}){let{t:l}=(0,E.s)(),[c,d]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[g,f]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>d(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(""),f([])},[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"}),f([]);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),T=C.filter(e=>!w.has(e.id)).map(e=>e.id),I=g.filter(e=>!w.has(e)).length,N=T.length>0&&T.every(e=>g.includes(e)),R=!N&&T.some(e=>g.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=R)},[R]),(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)(oP,{children:l("i18n.provider")}),(0,r.jsx)("button",{onClick:a,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:l("i18n.delete")})]}),(0,r.jsxs)(oN,{label:l("i18n.providerName"),children:[(0,r.jsx)(oM,{value:c,onChange:d,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,r.jsx)("button",{onClick:()=>s(c.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:l("i18n.rename")})]}),(0,r.jsx)(oN,{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)(oN,{label:"API Key",children:[(0,r.jsx)(oE,{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)(oN,{label:"API",children:(0,r.jsx)(oL,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:oI,required:!0})}),(0,r.jsxs)(oN,{label:"Headers",children:[(0,r.jsx)(oB,{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?l("models.discoveryFetching"):l("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:l("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":l("models.discoveryFilter"),style:{...oR,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:T.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:N,disabled:0===T.length,onChange:()=>{let e=new Set(T);f(t=>N?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...T])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),l("models.discoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=g.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 f(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:l("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?l("models.discoveryShowing",{shown:C.length,total:S.length}):l("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(g),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(o(t),f([]))},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?l("models.discoveryAddSelectedCount",{count:I}):l("models.discoveryAddSelected")})]})]})]})]})}let oz=["off","minimal","low","medium","high","xhigh","max"],oW={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oD({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:oz.map(e=>{let t=n[e],s=e in n?null===t?"null":"string":"omit",a="string"==typeof t?t:"",o=oW[e],l={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--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:o,flexShrink:0,opacity:"null"===s?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===s?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===s?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...l,..."omit"===s?c:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...l,borderLeft:"1px solid var(--border)",..."null"===s?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===s?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,a||e),style:{...l,..."string"===s?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:a,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==s&&i(e,a||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===s?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===s?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oO={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oB({headers:e,onChange:t}){let[n,s]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),a=(0,i.useRef)(n.length),o=e=>{s(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},l=(e,t)=>{o(n.map(n=>n.id===e?{...n,...t}:n))},c={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=>l(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...oR,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>l(e.id,{value:t.target.value}),placeholder:"value",style:{...oR,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void o(n.filter(e=>e.id!==t))},style:c,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>s(e=>[...e,{id:a.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function o_({providerName:e,provider:t,model:n,onChange:s,onDelete:a}){let[o,l]=(0,i.useState)({phase:"idle"}),{t:c}=(0,E.s)(),[d,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>s({...n,[e]:t}),g=(()=>{if("idle"===o.phase)return null;if("testing"===o.phase)return c("i18n.testingModel");let e=[void 0!==o.latencyMs?`${o.latencyMs}ms`:null,void 0!==o.status?`HTTP ${o.status}`:null].filter(Boolean);return"success"===o.phase?[c("i18n.connected"),...e,o.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,o.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{l({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 f=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==o.phase){l({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 l({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});l({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,o.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===d.phase)return;let i=++p.current;u({phase:"loading"});try{let a=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&a.set("baseUrl",t.baseUrl.trim());let o=await fetch(`/api/models-config/catalog?${a}`),l=await o.json();if(i!==p.current)return;if(!o.ok||l.error||!l.recommendation)return void u({phase:"error",message:l.error??`HTTP ${o.status}`});let c=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},s=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s=!0,r+=1);s&&(n.cost=i)}return{model:n,appliedCount:r}}(n,l.recommendation.preset);c.appliedCount>0&&(h.current=n,s(c.model)),u({phase:"success",recommendation:l.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[d.phase,n,s,t.baseUrl,e]),v=(()=>{if("success"!==d.phase)return null;let{recommendation:t,appliedCount:n}=d,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?c("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?c("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):c("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),b="error"===d.phase?d.message:v,y="error"===d.phase?"#ef4444":"success"===d.phase&&"unreliable"===d.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)(oP,{children:c("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[g&&(0,r.jsx)("span",{title:g,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===o.phase?"#fecaca":"success"===o.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===o.phase?"#fee2e2":"success"===o.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:g}),(0,r.jsxs)("button",{onClick:f,disabled:!n.id.trim()||"testing"===o.phase,title:c("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===o.phase?"#16a34a":"none",border:`1px solid ${"success"===o.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===o.phase?"#fff":n.id.trim()&&"testing"!==o.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==o.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===o.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"===o.phase?c("i18n.checking"):"success"===o.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)("button",{onClick:a,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(oN,{label:"ID *",children:(0,r.jsx)(oM,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(oN,{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"===d.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==d.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==d.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===d.phase?c("models.catalogFilling"):c("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:c("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,s(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsx)(oN,{label:"API override",children:(0,r.jsx)(oL,{value:n.api??"",onChange:e=>m("api",e||void 0),options:oI})}),(0,r.jsxs)(oN,{label:"Headers",children:[(0,r.jsx)(oB,{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)(oA,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(oA,{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)(oA,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oO}};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)(oA,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>s({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(oP,{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)(oD,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(oN,{label:"Context window (tokens)",children:(0,r.jsx)(o$,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(oN,{label:"Max output tokens",children:(0,r.jsx)(o$,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(oP,{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)(oN,{label:e,children:(0,r.jsx)(o$,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void s({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}function oH({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)({phase:"idle"}),{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(""),c=(0,i.useRef)(null),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===n.phase||"prompt"===n.phase)&&setTimeout(()=>d.current?.focus(),50)},[n.phase]),(0,i.useEffect)(()=>{s({phase:"idle"}),l(""),c.current?.close(),c.current=null},[e.id]),(0,i.useEffect)(()=>()=>{c.current?.close()},[]);let u=(0,i.useCallback)(()=>{c.current?.close(),s({phase:"connecting"}),l("");let n=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);c.current=n,n.onmessage=e=>{let r=JSON.parse(e.data);"auth"===r.type?(s({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),a5(r.url)):"device_code"===r.type?(s({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),a5(r.verificationUri)):"prompt_request"===r.type?s({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?s({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?s({phase:"progress",message:r.message}):"success"===r.type?(n.close(),s({phase:"success"}),t()):"error"===r.type?(n.close(),s({phase:"error",message:r.message})):"cancelled"===r.type&&(n.close(),s({phase:"idle"}))},n.onerror=()=>{n.close(),s(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,t]),p=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),s({phase:"idle"}),t()},[e.id,t]),h=(0,i.useCallback)(async(t,n)=>{if(n.trim()){s({phase:"progress",message:"Verifying…"});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.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));s({phase:"error",message:e.error??`Server error ${r.status}`});return}l("")}catch(e){s({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[e.id]),m=(0,i.useCallback)(async(t,n)=>{s({phase:"progress",message:"Continuing…"});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})});if(!r.ok){let e=await r.json().catch(()=>({}));s({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){s({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id]),g="connecting"===n.phase||"progress"===n.phase||"auth"===n.phase||"device_code"===n.phase||"prompt"===n.phase||"select"===n.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)(oP,{children:a("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:a(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:a("i18n.openingBrowser")}),"select"===n.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:n.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:n.options.map(e=>(0,r.jsx)("button",{onClick:()=>m(n.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"===n.phase||"prompt"===n.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"===n.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":n.message}),"auth"===n.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:n.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:d,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(n.token,o)},placeholder:"auth"===n.phase?"http://localhost:1455/auth/callback?code=…":n.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:()=>h(n.token,o),disabled:!o.trim(),style:{padding:"6px 12px",background:o.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:o.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:o.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:a("i18n.submit")})]})]}),"device_code"===n.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:n.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:n.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:n.verificationUri}),n.expiresInSeconds?` Expires in ${Math.ceil(n.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:n.message}),"success"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:a("i18n.connectedSuccessfully")}),"error"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:n.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:g?(0,r.jsx)("button",{onClick:()=>{c.current?.close(),s({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:a("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:u,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:a(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:a("i18n.disconnect")})]})})]})}function oU({provider:e,onRefresh:t}){let[n,s]=(0,i.useState)(""),[a,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,E.s)();(0,i.useEffect)(()=>{s(""),u(null),h(!1)},[e.id]);let g=(0,i.useCallback)(async()=>{if(n.trim()){o(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(s(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{o(!1)}}},[n,e.id,t]),f=(0,i.useCallback)(async()=>{c(!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{c(!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)(oP,{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)(oN,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(oE,{value:n,onChange:s,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&g()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:g,disabled:a||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:a||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":a?"i18n.saving":"i18n.save")]})]})}),d&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:d}),e.configured&&(0,r.jsx)("button",{onClick:f,disabled:l,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:l?"not-allowed":"pointer",fontSize:12},children:m(l?"i18n.removing":"i18n.disconnect")})]})}function oq({id:e,size:t}){let n=oT[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 oV({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:s,onAddCustom:a,onClose:o}){let[l,c]=(0,i.useState)(""),{t:d}=(0,E.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=l.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))),g=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),f=h.length+m.length+ +!!g,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&&o()},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:l,onChange:e=>c(e.target.value),onKeyDown:e=>{"Escape"===e.key&&o()},placeholder:d("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===f?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:d("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{a(),o()},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:d("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*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(oq,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{s(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(oq,{id:e.id,size:28})]},e.id))]})})]})})}function oK({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:s}){let a=z(),{t:o}=(0,E.s)(),[l,c]=(0,i.useState)({providers:{}}),[d,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(!1),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)({type:"roles"}),[y,w]=(0,i.useState)([]),[k,j]=(0,i.useState)([]),[S,C]=(0,i.useState)(!1),T=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>w(e.providers)).catch(()=>{})},[]),I=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>j(e.providers)).catch(()=>{})},[]),N=(0,i.useCallback)(()=>{T(),I()},[T,I]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{c(e.providers?e:{...e,providers:{}})}).catch(()=>c({providers:{}})).finally(()=>u(!1)),N()},[N]);let R=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;l.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),b({type:"provider",name:e})},[l.providers]),M=(0,i.useCallback)((e,t)=>{c(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),$=(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)})}),b(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),L=(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 b(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 b({type:"model",providerName:e,index:n}),t})},[]),P=(0,i.useCallback)((e,t)=>{c(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],s=new Set(i.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),F=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),W=(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}}}}),b({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{h(!0),g(null),x(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}),t=await e.json();!e.ok||t.error?g(t.error??`HTTP ${e.status}`):(x(!0),s?.(),setTimeout(()=>x(!1),2e3))}catch(e){g(String(e))}finally{h(!1)}},[l,s]),O=Object.entries(l.providers??{}),B=y.filter(e=>e.loggedIn),_=k.filter(e=>e.configured),H=(()=>{if(!v)return null;if("roles"===v.type)return(0,r.jsx)(a4,{cwd:e??null,onRolesChanged:s});if("oauth"===v.type){let e=y.find(e=>e.id===v.providerId);return e?(0,r.jsx)(oH,{provider:e,onRefresh:N},e.id):null}if("apikey"===v.type){let e=k.find(e=>e.id===v.providerId);return e?(0,r.jsx)(oU,{provider:e,onRefresh:N},e.id):null}if("provider"===v.type){let e=l.providers?.[v.name];return e?(0,r.jsx)(oF,{name:v.name,provider:e,onChange:e=>M(v.name,e),onRename:e=>$(v.name,e),onDelete:()=>L(v.name),onAddModels:e=>P(v.name,e)},v.name):null}let t=l.providers?.[v.providerName],n=t?.models?.[v.index];return n?(0,r.jsx)(o_,{providerName:v.providerName,provider:t,model:n,onChange:e=>F(v.providerName,v.index,e),onDelete:()=>W(v.providerName,v.index)},`${v.providerName}-${v.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()},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: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,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: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.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.jsxs)("div",{onClick:()=>b({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:v?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{v?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{v?.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)"}}),B.map(e=>{let t=v?.type==="oauth"&&v.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>b({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(oq,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),_.map(e=>{let t=v?.type==="apikey"&&v.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>b({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(oq,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(B.length>0||_.length>0)&&O.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):O.map(([e,t])=>{let n=v?.type==="provider"&&v.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>b({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=v?.type==="model"&&v.providerName===e&&v.index===n;return(0,r.jsxs)("div",{onClick:()=>b({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:()=>C(!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:d?null:H??(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:[m&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:m}),(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:p||f,style:{position:"relative",padding:"6px 16px",minWidth:92,background:f?"#16a34a":p?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:f?"#fff":p?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:p||f?"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:f?"saved-pop 0.45s ease":void 0},children:[f&&(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:f?o("i18n.saved"):p?o("i18n.saving"):o("i18n.save")})]})]})]})}),S&&(0,r.jsx)(oV,{oauthProviders:y,apiKeyProviders:k,onSelectOAuth:e=>b({type:"oauth",providerId:e}),onSelectApiKey:e=>b({type:"apikey",providerId:e}),onAddCustom:R,onClose:()=>C(!1)})]})}function oJ(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oG(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function oY(e){let t=oG(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function oZ(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function oX(e){return e?e.slice(0,8):"unknown"}function oQ({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,E.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 o0({skill:e,cwd:t,onToggle:n,toggling:i,saveError:s,updateStatus:a,checkingUpdate:o,updating:l,updateError:c,onCheckUpdate:d,onUpdate:u}){let{t:p}=(0,E.s)(),h=oG(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 oJ(e)}(e.filePath)}),(0,r.jsx)(oQ,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),s&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:s})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:oX(a?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)("button",{onClick:d,disabled:o||l,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11},children:p("i18n.check")}),a?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:oX(a.latestVersion)}),(o||a&&"update-available"!==a.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:o?"var(--accent)":a?.state==="up-to-date"?"#16a34a":a?.state==="error"?"#ef4444":"var(--text-dim)"},children:o?p("i18n.checking"):a?.state==="up-to-date"?p("i18n.upToDate"):a?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):a?.message||p("i18n.checkFailed")}),a?.state==="update-available"&&(0,r.jsx)("button",{onClick:u,disabled:l||o,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11,fontWeight:600},children:p(l?"i18n.updating":"i18n.update")})]}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:c})]}),(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 o1({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:s}){let{t:a}=(0,E.s)(),[o,l]=(0,i.useState)(""),[c,d]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[g,f]=(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),d([]);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);d(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{f(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),s()}catch(e){v(String(e))}finally{f(null)}},[s,w,e]),T="global"===w?"~/.claude/skills/":`${oJ(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:a("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(o)},placeholder:a("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)("button",{onClick:()=>S(o),disabled:u||!o.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||!o.trim()?"not-allowed":"pointer",opacity:u||!o.trim()?.5:1,flexShrink:0},children:u?a("i18n.searching"):a("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:a("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",T]})]}),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})]}),c.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=g===e.package,s=e.package.indexOf("@"),o=s>-1?e.package.slice(0,s):e.package,l=s>-1?e.package.slice(s+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(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:o}),(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!==g,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:n||i||null!==g?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${a("i18n.installed")}`:i?a("i18n.installing"):a("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function o2({cwd:e,onClose:t,embedded:n=!1}){let s=z(),{t:a}=(0,E.s)(),[o,l]=(0,i.useState)([]),[c,d]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[g,f]=(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,T]=(0,i.useState)(!1),[I,N]=(0,i.useState)(null),[R,M]=(0,i.useState)(null),[$,L]=(0,i.useState)(!0),[A,P]=(0,i.useState)({}),F=(0,i.useCallback)(async()=>{d(!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(l(r),L(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&P(t=>({...t,[oY(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{d(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),M(null),F()},[e]);let W=(0,i.useCallback)(async t=>{let n=(t?[t]:o.filter(e=>!!e.install)).map(oZ).filter(e=>!!e);if(0!==n.length){M(null),S(e=>new Set([...e,...n])),t||T(!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){M(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||T(!1)}}},[e,o]),D=(0,i.useCallback)(async t=>{if(!t.install)return;let n=oZ(t);N(n),M(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 F();let s=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){M(e instanceof Error?e.message:String(e))}finally{N(null)}},[e,F]),O=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;f(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}`);l(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&P(t=>({...t,[oY(e)]:!0}))}catch(e){v(String(e))}finally{f(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),B=o.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":s?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":s?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:a("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:oJ(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"})]}),!$&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:a("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:s?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:s?"100%":210,maxHeight:s?"40vh":void 0,borderRight:s?"none":"1px solid var(--border)",borderBottom:s?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:a("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===o.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:a("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===oG(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===oG(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===oG(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===oG(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===oG(e)}]){let r=o.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:s?"var(--border)":"var(--accent)",boxShadow:s?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:s?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=oZ(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:a("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),s=n.filter(e=>e.disableModelInvocation),o=A[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),s.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>P(t=>({...t,[e]:!o})),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:o?"▾":"▸"}),a("i18n.dormant")," (",s.length,")"]}),o&&s.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),a("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(o1,{cwd:e,projectResourcesLoaded:$,installedPackages:{global:new Set(o.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(o.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{F()}}):c?null:B?(0,r.jsx)(o0,{skill:B,cwd:e,onToggle:O,toggling:g.has(B.filePath),saveError:x,updateStatus:oZ(B)?w[oZ(B)]:void 0,checkingUpdate:!!oZ(B)&&j.has(oZ(B)),updating:I===oZ(B),updateError:R,onCheckUpdate:()=>void W(B),onUpdate:()=>void D(B)},B.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:a("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.some(e=>!!e.install)&&(0,r.jsx)("button",{onClick:()=>void W(),disabled:C||null!==I,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:C||null!==I?"not-allowed":"pointer",opacity:C||null!==I?.5:1,fontSize:12},children:C?a("i18n.checking"):a("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?a("i18n.update"):a("i18n.updates")]})]}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:a("i18n.close")})]})]})})}function o8(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function o4(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function o5(e){return`${e.scope}\0${e.source}`}function o6(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 o3(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 o7(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function o9({pkg:e}){let{t}=(0,E.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 le({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 lt(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 ln({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 lr({value:e,projectResourcesLoaded:t,onChange:n}){let{t:i}=(0,E.s)();return(0,r.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(s=>{let a=e===s,o="project"===s&&!t;return(0,r.jsx)("button",{onClick:()=>{o||n(s)},disabled:o,title:o?i("trust.projectScopeUnavailable"):void 0,style:{width:76,border:"none",borderRight:"global"===s?"1px solid var(--border)":"none",background:a?"var(--bg-selected)":"none",color:a?"var(--text)":"var(--text-muted)",cursor:o?"not-allowed":"pointer",opacity:o?.45:1,fontSize:12},children:s},s)})})}function li({cwd:e,source:t,scope:n,projectResourcesLoaded:s,busy:a,actionError:o,onSourceChange:l,onScopeChange:c,onInstall:d}){let{t:u}=(0,E.s)(),p=(0,i.useRef)(null);return(0,i.useEffect)(()=>{p.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:u("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"]})]}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===n?`${o8(e)}/.omp/plugins`:"~/.omp/plugins"})]}),(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:p,value:t,onChange:e=>l(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=o4(t);n!==t&&(e.preventDefault(),l(n))},onBlur:e=>l(o4(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()&&!a&&d()}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(lr,{value:n,projectResourcesLoaded:s,onChange:c}),(0,r.jsx)("button",{type:"button",onClick:d,disabled:a||!t.trim(),style:{...lt(a||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:u(a?"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:()=>l(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))})]}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:o})]})}function ls({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:s,sessionId:a,onAction:o,onReloadSession:l}){let{t:c}=(0,E.s)(),d=o5(e),u=n?.endsWith(d)??!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)(ln,{enabled:h,loading:u||p,onToggle:()=>o(e.disabled?"enable":"disable",e),label:c(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(le,{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:c("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:c("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:()=>o("update",e),disabled:u||p,style:lt(u||p),children:c(n===`update:${d}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:l,disabled:!a||p||u,style:lt(!a||p||u),title:c(a?"i18n.reloadSession":"i18n.openSessionToReload"),children:c(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>o("remove",e),disabled:u||p,style:lt(u||p,!0),children:c(n===`remove:${d}`?"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:c("i18n.status")}),(0,r.jsx)("div",{style:{color:o7(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:o3(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??c("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:o6(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?o8(e.installedPath):c("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:o8(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:c("i18n.resolvedResources")}),(0,r.jsx)(o9,{pkg:e})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:s}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function la({cwd:e,sessionId:t,onClose:n,onReloaded:s,embedded:a=!1}){let o=z(),{t:l}=(0,E.s)(),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)("global"),[j,S]=(0,i.useState)(null),[C,T]=(0,i.useState)(null),[I,N]=(0,i.useState)(null),R=(0,i.useMemo)(()=>c?.packages??[],[c?.packages]),M=R.find(e=>o5(e)===g)??null,$=c?.projectResourcesLoaded??!0,L=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:R.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[R]),A=(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}`);d(n),v(e=>0===n.packages.length||e),f(e=>e&&n.packages.some(t=>o5(t)===e)?e:n.packages[0]?o5(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{A()},[A]);let P=(0,i.useCallback)(async(t,n)=>{let r=o5(n);S(`${t}:${r}`),T(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}`);d(i),"remove"===t?(f(i.packages[0]?o5(i.packages[0]):null),0===i.packages.length&&v(!0),N("Package removed.")):N({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t])}catch(e){T(e instanceof Error?e.message:String(e))}finally{S(null)}},[e]),F=(0,i.useCallback)(async()=>{let t=o4(b).trim();if(!t)return;y(t);let n=`${w}\0${t}`;S(`install:${n}`),T(null),N(null);try{var r;let i,s,a=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:w,cwd:e})}),o=await a.json();if(!a.ok||o.error)throw Error(o.error??`HTTP ${a.status}`);d(o);let l=(r=o.packages,s=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${s}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));f(l?o5(l):n),v(!1),y(""),N("Package installed.")}catch(e){T(e instanceof Error?e.message:String(e))}finally{S(null)}},[e,w,b]),W=(0,i.useCallback)(async()=>{if(t){S("reload"),T(null),N(null);try{await sB(t,{type:"reload"}),s?.(),await A(),N("Session reloaded.")}catch(e){T(e instanceof Error?e.message:String(e))}finally{S(null)}}},[A,s,t]),D=j?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:a?"relative":"fixed",inset:a?void 0:0,width:"100%",height:"100%",zIndex:a?void 0:1e3,background:a?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{a||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:a?"100%":o?"calc(100vw - 16px)":860,maxWidth:a?"none":"calc(100vw - 16px)",height:a?"100%":o?"calc(100dvh - 16px)":"76vh",maxHeight:a?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:a?"none":"1px solid var(--border)",borderRadius:8*!a,display:"flex",flexDirection:"column",boxShadow:a?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o8(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"})]}),!$&&(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:l("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:o?"100%":245,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"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===R.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):L.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=o5(e),n=!x&&g===t;return(0,r.jsxs)("div",{onClick:()=>{f(t),v(!1),T(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:o7(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:o6(e,l)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:o3(e,l)})]})]},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),T(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"})]}),l("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(li,{cwd:e,source:b,scope:w,projectResourcesLoaded:$,busy:D,actionError:C,onSourceChange:y,onScopeChange:k,onInstall:F}):u?null:M?(0,r.jsx)(ls,{pkg:M,cwd:e,busyKey:j,actionError:C,actionMessage:I,sessionId:t,onAction:P,onReloadSession:W},o5(M)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("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:c?.diagnostics.length?(0,r.jsxs)("span",{title:c.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:c.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[c.diagnostics.length," diagnostic",1===c.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:c?`${c.totals.extensions} ext \xb7 ${c.totals.skills} skills \xb7 ${c.totals.prompts} prompts \xb7 ${c.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void A(),disabled:u||null!==j,style:lt(u||null!==j),children:l("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:lt(!1),children:l("i18n.close")})]})]})})}var lo=n(13004),ll=n.n(lo);function lc(){let[e,t]=(0,i.useState)(null),[n,s]=(0,i.useState)(null),[a,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,g]=(0,i.useState)(""),f=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),s(null)}catch(e){s(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{f()},[f]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),o(null),c(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 o(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==m)return void o("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),g(""),c(`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&&c(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")&&c("The stored password was removed and password access is off.")},[x]);if(!e)return(0,r.jsx)("div",{className:ll().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!d&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:ll().scrollContent,children:[(0,r.jsxs)("header",{className:ll().contentHeader,children:[(0,r.jsx)("h2",{className:ll().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:ll().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:ll().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."]}),l&&(0,r.jsx)("div",{className:ll().reloadNotice,children:(0,r.jsx)("span",{children:l})})]}),(0,r.jsxs)("div",{className:ll().settingsBody,children:[(0,r.jsxs)("section",{className:ll().group,children:[(0,r.jsx)("h3",{className:ll().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:ll().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ll().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:ll().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:ll().settingDescription,children:"Set a password below before turning this on."}),a&&(0,r.jsx)("div",{className:ll().error,children:a})]}),(0,r.jsx)("div",{className:ll().settingControl,children:(0,r.jsx)("button",{type:"button",className:ll().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:d||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,r.jsxs)("section",{className:ll().group,children:[(0,r.jsx)("h3",{className:ll().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:ll().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ll().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:ll().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:ll().settingControl,children:(0,r.jsx)("input",{className:ll().textInput,type:"password",autoComplete:"new-password",value:p,disabled:d||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:ll().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ll().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:ll().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:ll().settingControl,children:(0,r.jsx)("input",{className:ll().textInput,type:"password",autoComplete:"new-password",value:m,disabled:d||w,onChange:e=>g(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,r.jsxs)("div",{className:ll().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:ll().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:ll().dangerButton,disabled:d,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:ll().primaryButton,disabled:!k,onClick:()=>void v(),children:d?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:ll().group,children:[(0,r.jsx)("h3",{className:ll().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:ll().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ll().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:ll().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:ll().settingControl,children:(0,r.jsx)("a",{className:ll().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:ll().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ll().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:ll().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:ll().settingControl})]})]})]})]})}function ld({cwd:e}){let{t}=(0,E.s)(),[n,s]=(0,i.useState)(null),[a,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),v=(0,i.useRef)(new Map);(0,i.useEffect)(()=>{f&&d!==f&&(v.current.get(f)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[d,n,f]);let b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let i=e?`?include=${encodeURIComponent(e)}`:"",a=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),l=await a.json();if(n!==b.current||r.signal.aborted)return;if(!a.ok||!l.projects)throw Error(l.error??`HTTP ${a.status}`);let c=l.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=l.projects,s(l.projects),o(null),c&&g({cwd:c.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;o(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!==d||null!==l)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)}},[d,l,n,S,j]);let C=(0,i.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),c(null),x(e),g(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),i=await r.json();if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);let a=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=a,s(a),"cancel"===n?g({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||g({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:ll().empty,children:[a?t("trust.loadFailed",{error:a}):"…",a&&(0,r.jsx)("button",{type:"button",className:ll().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let T=null!==d;return(0,r.jsxs)("div",{className:ll().scrollContent,children:[(0,r.jsxs)("header",{className:ll().contentHeader,children:[(0,r.jsx)("h2",{className:ll().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:ll().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:ll().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:T,onClick:()=>void j(),children:t("trust.refresh")}),a&&(0,r.jsx)("div",{className:ll().error,role:"alert",children:t("trust.loadFailed",{error:a})})]})]}),(0,r.jsx)("div",{className:ll().settingsBody,children:(0,r.jsxs)("section",{className:ll().group,children:[0===n.length&&(0,r.jsx)("div",{className:ll().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=d===e.cwd,s=l?.cwd===e.cwd?l:null,a=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),o=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,r.jsxs)("div",{className:ll().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:ll().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:ll().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:ll().settingDescription,style:{fontWeight:600},children:a})]}),(0,r.jsx)("code",{className:ll().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:ll().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:ll().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:ll().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),s&&(0,r.jsx)("div",{className:ll().settingDescription,style:{color:"var(--text)"},children:"revoke"===s.action?t("trust.confirmRevoke"):s.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:ll().saveState,children:m.text})]}),o&&(0,r.jsx)("div",{className:ll().error,role:"alert",children:o})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:ll().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:s?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:ll().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{c(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===s.action?ll().dangerButton:ll().primaryButton,disabled:T,onClick:()=>void C(e.cwd,s.action),children:"revoke"===s.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:ll().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:ll().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:T,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,r.jsx)("button",{type:"button",className:ll().primaryButton,disabled:T,onClick:()=>c({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:ll().dangerButton,disabled:T,onClick:()=>c({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let lu=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이다"}}}'),lp=[{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"}],lh={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"})]}),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 lm({kind:e}){return(0,r.jsx)("svg",{className:ll().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:lh[e]??lh.tools})}function lg({field:e,busy:t,onSave:n}){let[s,a]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{a("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let o="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:ll().textInput,type:"secret"===e.type?"password":"text",value:s,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>a(e.target.value),onBlur:()=>{s!==o&&("secret"!==e.type||s.length>0)&&n(s)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function lf({field:e,busy:t,onSave:n}){let s=JSON.stringify(e.value??{},null,2),[a,o]=(0,i.useState)(s),[l,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{o(s),c(null)},[s]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:ll().jsonEditor,style:{minHeight:92},value:a,disabled:t,onChange:e=>o(e.target.value),onBlur:()=>{if(a!==s)try{n(JSON.parse(a)),c(null)}catch(e){c(e instanceof Error?e.message:String(e))}}}),l&&(0,r.jsx)("div",{className:ll().error,children:l})]})}function lx({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],s=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let s=[...i];[s[e],s[r]]=[s[r],s[e]],n(s)};return(0,r.jsx)("div",{className:ll().multiSelect,children:e.options?.map(a=>{let o=i.indexOf(a.value);return(0,r.jsxs)("span",{className:ll().choice,"data-selected":o>=0,title:a.description,children:[(0,r.jsx)("button",{type:"button",className:ll().choiceToggle,disabled:t,onClick:()=>{let e;return e=a.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:a.label}),e.ordered&&o>=0&&(0,r.jsxs)("span",{className:ll().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===o,onClick:()=>s(o,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||o===i.length-1,onClick:()=>s(o,1),children:"→"})]})]},a.value)})})}function lv({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:ll().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(a1,{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)(lx,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(lf,{field:e,busy:t,onSave:n}):(0,r.jsx)(lg,{field:e,busy:t,onSave:n})}function lb({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:ll().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:ll().settingLabel,children:e.label}),(0,r.jsx)("div",{className:ll().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:ll().error,children:n})]}),(0,r.jsx)("div",{className:ll().settingControl,children:(0,r.jsx)(lv,{field:e,busy:t,onSave:i})})]})}function ly({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:ll().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:ll().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:ll().themePreviewPanel,children:[(0,r.jsx)("div",{className:ll().themePreviewLine}),(0,r.jsx)("div",{className:ll().themePreviewLine})]})]})}let lw='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',lk=new Set(["hideThinkingBlock"]);function lj({cwd:e,sessionId:t,initialSection:n="models",onClose:s,onModelsChanged:a,onReloaded:o}){let[l,c]=(0,i.useState)(n),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[f,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:T,setPreference:I}=tF(),{locale:N,t:R}=(0,E.s)(),M=(0,i.useRef)(null),$=e=>"ko"===N?lu.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),g(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){g(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{let e=M.current;if(!e)return;(Array.from(e.querySelectorAll(lw)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(lw)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],s=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),s.focus()):t.shiftKey||r!==s&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let A=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await tP(e),await L()):lk.has(t.path)?await tX(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]),P=(0,i.useMemo)(()=>new Map(d?.fields.map(e=>[e.path,e.value])??[]),[d?.fields]),F=(0,i.useMemo)(()=>d?.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,P))??[],[d?.fields,P]),z=l.startsWith("settings:")?l.slice(9):null,W=(0,i.useMemo)(()=>{let e=f.trim().toLowerCase();return e?F.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):z?F.filter(e=>e.tab===z&&("appearance"!==z||"Theme"!==e.group)):[]},[z,f,F]),D=(0,i.useCallback)(()=>{a?.(),s()},[s,a]),O=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sB(t,{type:"reload"}),j(!1),o?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[o,t]),B=d?.tabs.find(e=>e.id===z),_=f.trim()?`${$("Search")} \xb7 ${W.length}`:B?.label??$("Settings"),H=(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:ll().group,children:[(0,r.jsx)("h3",{className:ll().groupTitle,children:t}),n.map(e=>(0,r.jsx)(lb,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void A(e,t)},e.path))]},t):null}),U=()=>p?(0,r.jsx)("div",{className:ll().empty,children:$("Loading omp settings…")}):m||!d?(0,r.jsx)("div",{className:ll().empty,children:m??$("Settings unavailable")}):(0,r.jsxs)("div",{className:ll().scrollContent,children:[(0,r.jsxs)("header",{className:ll().contentHeader,children:[(0,r.jsx)("h2",{className:ll().contentTitle,children:_}),(0,r.jsx)("p",{className:ll().contentDescription,children:$(f.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:ll().reloadNotice,children:[(0,r.jsx)("span",{children:$("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void O(),disabled:S,children:$(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:ll().settingsBody,children:W.length?H(W,B?.groups??[]):(0,r.jsx)("div",{className:ll().empty,children:$("No settings match this search.")})})]});return(0,r.jsx)("div",{className:ll().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&D()},children:(0,r.jsxs)("div",{ref:M,tabIndex:-1,className:ll().window,role:"dialog","aria-modal":"true","aria-label":$("Settings"),children:[(0,r.jsxs)("aside",{className:ll().sidebar,children:[(0,r.jsxs)("div",{className:ll().brand,children:[(0,r.jsx)("div",{className:ll().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:ll().title,children:$("Settings")}),(0,r.jsx)("code",{className:ll().context,title:e??$("Global configuration"),children:e??$("Global configuration")})]}),(0,r.jsxs)("div",{className:ll().searchWrap,children:[(0,r.jsxs)("svg",{className:ll().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:ll().search,value:f,"aria-label":$("Search /settings"),placeholder:$("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:ll().nav,children:[(0,r.jsx)("div",{className:ll().navLabel,children:$("Configuration")}),lp.map(t=>{let n=t.labelKey?R(t.labelKey):$(t.label);return(0,r.jsxs)("button",{type:"button",className:ll().navButton,"data-active":!f&&l===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${$("requires a project")}`:n,onClick:()=>{x(""),c(t.id)},children:[(0,r.jsx)(lm,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:ll().navLabel,children:$("OMP settings")}),d?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:ll().navButton,"data-active":!f&&z===e.id,onClick:()=>{x(""),c(`settings:${e.id}`)},children:[(0,r.jsx)(lm,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:ll().closeRail,children:(0,r.jsxs)("button",{type:"button",className:ll().closeButton,onClick:D,children:[(0,r.jsx)("span",{children:$("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:ll().content,children:f.trim()?U():"models"===l?(0,r.jsx)(oK,{cwd:e,embedded:!0,onClose:D,onModelsChanged:a}):"themes"===l?d?(0,r.jsxs)("div",{className:ll().scrollContent,children:[(0,r.jsxs)("header",{className:ll().contentHeader,children:[(0,r.jsx)("h2",{className:ll().contentTitle,children:$("Themes")}),(0,r.jsxs)("p",{className:ll().contentDescription,children:[$("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"}),$(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:ll().settingsBody,children:[(0,r.jsx)("div",{className:ll().themeGrid,children:["dark","light"].map(e=>{let t=d.fields.find(t=>t.path===`theme.${e}`),n=d.theme.palettes[e];return(0,r.jsxs)("div",{className:ll().themeCard,children:[(0,r.jsx)(ly,{mode:e,palette:n}),(0,r.jsxs)("div",{className:ll().themeCardBody,children:[(0,r.jsxs)("div",{className:ll().themeCardHeader,children:[(0,r.jsxs)("span",{className:ll().themeSlot,children:[e,$(" mapping")]}),T===e&&(0,r.jsx)("span",{className:ll().themeActive,children:$("Active on web")})]}),(0,r.jsx)(a1,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void A(t,e)}),T!==e&&(0,r.jsxs)("button",{type:"button",className:ll().closeButton,style:{marginTop:8},onClick:()=>I(e),children:[$("Preview "),e]})]})]},e)})}),H(d.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,r.jsx)("div",{className:ll().empty,children:p?$("Loading themes…"):m??$("Themes unavailable")}):"skills"===l&&e?(0,r.jsx)(o2,{cwd:e,embedded:!0,onClose:D}):"plugins"===l&&e?(0,r.jsx)(la,{cwd:e,sessionId:t,embedded:!0,onClose:D,onReloaded:o}):"mcp"===l?(0,r.jsx)(lS,{cwd:e,sessionId:t,onReloaded:o}):"access"===l?(0,r.jsx)(lc,{}):"trust"===l?(0,r.jsx)(ld,{cwd:e}):U()})]})})}function lS({cwd:e,sessionId:t,onReloaded:n}){let[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)("user"),[c,d]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);a(r),f(null)}catch(e){f(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=s?"user"===o?s.user:s.project:null,j=k?.servers[c]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{a(t=>{if(!t)return t;let n={..."user"===o?t.user:t.project,servers:e};return"user"===o?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),f(null);try{let t,n=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===c?{...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:o,servers:n})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await w()}catch(e){f(e instanceof Error?e.message:String(e))}finally{v(!1)}}},T=async r=>{y(`${o}:${r.name}`),f(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",s=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,name:r.name,enabled:!r.enabled})}),a=await s.json();if(!s.ok||a.error)throw Error(a.error??`HTTP ${s.status}`);await w(),t&&(await sB(t,{type:"reload"}),n?.())}catch(e){f(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:ll().scrollContent,children:[(0,r.jsxs)("header",{className:ll().contentHeader,children:[(0,r.jsx)("h2",{className:ll().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:ll().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:ll().settingsBody,children:s?(0,r.jsxs)("div",{className:ll().mcpLayout,children:[(0,r.jsxs)("aside",{className:ll().mcpList,children:[(0,r.jsxs)("div",{className:ll().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:ll().scopeButton,"data-active":"user"===o,onClick:()=>{l("user"),d(0)},children:["User \xb7 ",s.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:ll().scopeButton,"data-active":"project"===o,disabled:!s.project,onClick:()=>{l("project"),d(0)},children:["Project \xb7 ",s.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:ll().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:ll().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${o}:${e.name}`;return(0,r.jsxs)("div",{className:ll().serverRow,"data-active":c===t,children:[(0,r.jsxs)("button",{type:"button",className:ll().serverSelect,title:e.source?.path,onClick:()=>d(t),children:[(0,r.jsx)("span",{className:ll().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:ll().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:ll().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:ll().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 T(e),children:b===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:ll().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:ll().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),d(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:ll().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:ll().editorHeader,children:[(0,r.jsx)("input",{className:ll().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:ll().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==c)),d(Math.max(0,c-1)))},children:"Delete"})]}),!1===j.editable&&(0,r.jsxs)("div",{className:ll().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:ll().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:ll().editorActions,children:[(0,r.jsxs)("div",{children:[g&&(0,r.jsx)("div",{className:ll().error,children:g}),(0,r.jsx)("div",{className:ll().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:ll().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:ll().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:ll().empty,children:g??"Loading MCP configuration…"})})]})}let lC="cuelo-notification-prompt-dismissed";function lT({variant:e,locale:t,permission:n,dismissed:i,request:s,dismiss:a}){let o="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":o?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:o?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,children:o?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,"aria-label":o?"알림 권한 안내 닫기":"Dismiss notification prompt",children:o?"닫기":"Dismiss"})]}):(0,r.jsx)(c.k.Item,{disabled:"denied"===n,onClick:"default"===n?s:void 0,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:"default"===n?o?"알림 켜기":"Enable notifications":o?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(c.k.ItemDescription,{children:o?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function lI({cwd:e,busy:t,scheduled:n,error:s,onCancel:a,onConfirm:o,onCancelSchedule:l}){let{t:c}=(0,E.s)(),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{d.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:5,cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||a()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:c(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:c(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:s})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c("trust.cancelSchedule")}),(0,r.jsx)("button",{ref:d,type:"button",onClick:a,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c(n?"trust.close":"trust.cancel")}),!n&&(0,r.jsx)("button",{type:"button",onClick:o,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:c(t?"trust.trusting":"trust.trustProject")})]})]})})}var lN=n(55681),lR=n(54265);let lM={kind:"loading"};function lE(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":iT(e.status)?"var(--accent)":"var(--success)"}function l$(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let lL={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function lA(e){return e.lastUpdate||e.progress?.durationMs||0}function lP(){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 lF({sessionId:e,sessionCwd:t,record:n,client:s,visible:a,onBack:o}){let l=(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]),c=(0,i.useRef)(null),d=iM(l,{sessionId:e,client:s,enabled:a}).get(n.key)?.state??lM;(0,i.useEffect)(()=>{if(!a||"ready-live"!==d.kind&&"ready-archive"!==d.kind)return;let e=requestAnimationFrame(()=>{let e=c.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[d,a]);let u="ready-live"===d.kind?d.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:o,"aria-label":"Subagent 목록으로 돌아가기",title:"목록",style:lP(),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:l$(n)})]}),n.live&&(0,r.jsx)("span",{style:{color:lE(n.live),fontFamily:"var(--font-mono)",fontSize:9.5},children:n.live.status})]}),(0,r.jsxs)("div",{ref:c,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===d.kind&&(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===d.kind&&d.entries.flatMap((e,n)=>{if(!("message"in e))return[];let i=d.entries[n-1];return[(0,r.jsx)(rd,{message:e.message,toolResults:p,cwd:t,showTimestamp:!0,prevTimestamp:i&&"message"in i?i.message.timestamp:void 0},e.id)]}),"ready-archive"===d.kind&&(0,r.jsxs)(r.Fragment,{children:[d.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:d.note}),d.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),d.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"===d.kind&&(0,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[d.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:d.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===d.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:d.message}),"error"===d.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:d.message})]})]})}function lz({record:e,onSelect:t}){let n,i,s,a,o,l,c,d,u=e.live,p=e.archive,h=(n=e.live,i=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,s=[n?.assignment,n?.progress?.assignment,n?.task].map(ix).find(e=>null!==e)??(i?.taskTitle?.trim()||null),a=n?.progress?.lastIntent?.trim()||"",o=n?.progress?.currentTool?.trim()||"",{title:s??"담당 업무 미확인",stage:a&&o?`${a} \xb7 ${o}`:a||(o?`${o} 실행 중`:null),explicitTitle:null!==s}),m=u?.id||p?.name||"Subagent",g=l$(e),f=(l=e.live,(d=(c=(l?.agent||l?.progress?.agent||"").trim()).toLowerCase().split(/[-_.:/\s]+/).filter(Boolean).join(" "))?{kind:"known",agent:c,source:l?.agentSource??"bundled",label:d}:{kind:"unknown"}),x=function(e){let t=e.live?.progress,n="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,i="string"==typeof r?.thinkingLevel?r.thinkingLevel.trim():"";if(n)return{model:n,modelShort:n.split("/").pop()||n,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:i||null};let s="string"==typeof r?.model?r.model.trim():"";return{model:s||null,modelShort:s?s.split("/").pop()||s:null,modelIsFallback:!!s&&r?.modelIsFallback===!0,effort:i||null}}(e),v=x.modelShort??"모델 미확인",b=x.effort??"추론 미확인",y="known"===f.kind?f.label:"역할 미확인";return(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:t,"data-identity":e.identity,title:`${m}
20
- ${x.model??"모델 미확인"} \xb7 ${b}
21
- ${h.title}${h.stage?`
22
- 현재 단계: ${h.stage}`:""}`,"aria-label":`${y} ${m}, 업무 ${h.title}${h.stage?`, 현재 단계 ${h.stage}`:""}, ${u?u.status:p?.status??"미확인"}, 모델 ${x.model??"미확인"}, 추론 ${b}`,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"===f.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":f.agent,title:`${f.agent} \xb7 ${lL[f.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),f.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:h.title})]}),u?(0,r.jsx)("span",{style:{color:lE(u),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:u.status}):p?(0,r.jsx)("span",{style:{color:"failed"===p.status?"var(--danger)":"aborted"===p.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:p.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),h.stage&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${h.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 ",h.stage]}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":x.model?x.effort?"both":"model":x.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[v,x.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",b]})]}),(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:m}),(0,r.jsx)("span",{children:g})]}),(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:[u?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",u.progress.toolCount]}),(0,r.jsxs)("span",{children:[u.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}분`}(u.progress.durationMs)})]}),p&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===p.messages?"메시지 수 미확인":`메시지 ${p.messages}`}),(0,r.jsxs)("span",{children:[(p.bytes/1024).toFixed(+(p.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)}일 전`}(p.modified)})]})]})]})}function lW({title:e,sessionId:t,sessionPath:n,sessionCwd:s,liveSubagents:a,client:o,visible:l=!0,onClose:c,onReturnFocus:d}){let u=(0,i.useMemo)(()=>o??iS(),[o]),[p,h]=(0,i.useState)([]),[m,g]=(0,i.useState)({kind:"loading"}),[f,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([]),g({kind:"loading"}),x({kind:"loading"}),b(!1),w(null)},[t]),(0,i.useEffect)(()=>{if(!l||!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,s]=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),g(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=iR(i.reason);g("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===s.status)b(!0===s.value.listTruncated),x(s.value.subagents.length>0?{kind:"ready",data:s.value.subagents}:{kind:"empty",data:[]});else{let e=iR(s.reason);x("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};i();let s=setInterval(()=>void i(),3e3),a=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",a),()=>{e=!0,r?.abort(),clearInterval(s),document.removeEventListener("visibilitychange",a)}},[k,u,t,l]);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,s]=lA(i)>=lA(e)?[i,e]:[e,i];n.set(i.id,{...t,assignment:t.assignment??s.assignment,description:t.description??s.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(a,p),[a,p]),C="ready"===f.kind||"empty"===f.kind?f.data:[],T=(0,i.useMemo)(()=>(function(e,t){let n=new Map(t.map(e=>[e.name,e])),r=new Set,i=e.map(e=>{let t=(function(e){let t=[];if(e.sessionFile){let n=e.sessionFile.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"");n&&t.push({name:n,match:"session-file"})}return t.some(t=>t.name===e.id)||t.push({name:e.id,match:"name"}),t})(e).find(e=>n.has(e.name)&&!r.has(e.name)),i=t?n.get(t.name):void 0;return i&&r.add(i.name),{key:`live:${e.id}`,identity:i?"live-archive":"live",live:e,...i&&t?{archive:i,archiveMatch:t.match}:{}}});for(let e of t)r.has(e.name)||i.push({key:`archive:${e.name}`,identity:"archive",archive:e});return i})(S,C),[C,S]),I=y?T.find(e=>e.key===y)??null:null;if((0,i.useEffect)(()=>{y&&!I&&w(null)},[I,y]),I&&t)return(0,r.jsx)(lF,{sessionId:t,sessionCwd:s,record:I,client:u,visible:l,onBack:()=>w(null)});let N=0===T.length&&"loading"===m.kind&&"loading"===f.kind,R=0===T.length&&("empty"===m.kind||0===a.length)&&"empty"===f.kind;return(0,r.jsxs)("section",{"aria-label":"Subagent 기록","data-state":N?"loading":R?"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:lP(),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"})})}),c&&(0,r.jsx)("button",{type:"button",onClick:()=>{c?.(),d?.()},"aria-label":"Subagent 기록 닫기",title:"닫기",style:lP(),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?N?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):R?(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:T.map(e=>(0,r.jsx)(lz,{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:"세션을 선택한 뒤 다시 시도하세요."}),!N&&"loading"===m.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!N&&"loading"===f.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"===f.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:f.message}),"error"===f.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:f.message}),v&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let lD=["process","efficiency","subagents","files","resource","sidechat"];function lO({activeView:e,onViewChange:t,viewLabels:n,sessionId:i,sessionPath:s,sessionName:l,sessionCwd:c,liveSubagents:d,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:m,resourceSlot:g,efficiencySlot:f,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)(lN.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)(lN.J.List,{"aria-label":"보조 패널 보기",children:[lD.map(e=>{let t="subagents"===e?d.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(lN.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)(lR.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,r.jsx)(lN.J.Indicator,{})]}),v&&(0,r.jsx)(a.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{v?.(),b?.()},"aria-label":"보조 패널 닫기",children:(0,r.jsx)(o.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)(lN.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(lN.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:f}),(0,r.jsx)(lN.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(lW,{title:n.subagents,sessionId:i,sessionPath:s,sessionCwd:c,liveSubagents:d,client:u,visible:x&&"subagents"===e})}),(0,r.jsx)(lN.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,r.jsx)(lN.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:m}),(0,r.jsx)(lN.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:g})]})})}function lB({title:e,data:t,onOpenFile:n}){let{t:s}=(0,E.s)(),o=t?.groups??[],[l,c]=(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:o.length>0?`${o.length} ${s(1===o.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===o.length?(0,r.jsx)("p",{className:"process-log-empty",children:s("process.empty")}):o.map((e,i)=>{let o=l.has(e.anchorIdx),d=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} ${s(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${s(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(a.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!o,onClick:()=>c(t=>{let n=new Set(t);return n.has(e.anchorIdx)?n.delete(e.anchorIdx):n.add(e.anchorIdx),n}),title:o?s("chat.expandProcess"):s("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:d??s("chat.processDetails")}),(0,r.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!o&&(0,r.jsx)("div",{className:"process-log-entries",children:e.entries.map((i,s)=>{let a=t?.messages[i.idx];return a?(0,r.jsx)(rd,{message:i.blocks?e$(a,i.blocks,{omitUsage:!0}):a,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[i.idx],sessionId:t?.sessionId,showTimestamp:!1},`process-${e.anchorIdx}-${s}`):null})})]},`turn-${e.anchorIdx}-${i}`)})]})]})}let l_=6,lH="omp-btw-log:",lU="omp-btw-log-index";function lq(e){return e.trim().toLowerCase()}function lV(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function lK(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 lJ(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function lG(e,t={}){let n=t.now??Date.now,r=new Map,i=new Set,s=!1,a=[],o=t=>{if(e)try{e.removeItem(t)}catch{}},l=e=>{r.delete(e),i.delete(e),o(lH+e)},c=()=>{let e=new Set,t=[];for(let n of(a.sort((e,t)=>t.updatedAt-e.updatedAt),a))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):l(n.id));a=t},d=()=>{if(!s){if(s=!0,e)try{let t=e.getItem(lU),n=t?JSON.parse(t):[];Array.isArray(n)&&(a=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:lq(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{a=[]}c()}},u=e=>{d();for(let t=a.length-1;t>=0;t-=1){if(a[t].id===e)continue;let[n]=a.splice(t,1);return l(n.id),!0}return!1},p=t=>{if(e){try{e.setItem(lU,JSON.stringify(a));return}catch(e){if(!lJ(e)||!u(t))return}try{e.setItem(lU,JSON.stringify(a))}catch{}}},h=t=>{let n=lq(t);if(!n)return[];if(i.has(n))return lV(r.get(n)??[]);if(e)try{let t=e.getItem(lH+n);if(t){let e=JSON.parse(t),i=lK(e?.entries);return r.set(n,i),lV(i)}}catch{}return lV(r.get(n)??[])},m=e=>{let t=lq(e);t&&(d(),a=a.filter(e=>e.id!==t),l(t),p(null))};return{read:h,append:(t,s)=>((t,s)=>{let o=lq(t);if(!o)return[];let l=lK(s),h=n();if(r.set(o,lV(l)),d(),(a=a.filter(e=>e.id!==o)).unshift({id:o,updatedAt:h}),c(),p(o),!e)return lV(l);let m=JSON.stringify({updatedAt:h,entries:l});try{return e.setItem(lH+o,m),i.delete(o),lV(l)}catch(e){if(!lJ(e)||!u(o))return i.add(o),lV(l)}p(o);try{e.setItem(lH+o,m),i.delete(o)}catch{i.add(o)}return lV(l)})(t,[...h(t),s]),history:(e,t=l_)=>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;d();let i=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=lq(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);i.set(t,Number.isFinite(n)?n:0)}let s=r?lq(r):null,l=n();for(let e of[...a])if(e.id!==s){if(!i.has(e.id)){m(e.id);continue}l-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 c=[];try{for(let t=0;t<e.length;t+=1){let n=e.key(t);if(!n?.startsWith(lH))continue;let r=lq(n.slice(lH.length));i.has(r)||r===s||c.push(n)}}catch{return}for(let e of c)o(e)}}}function lY(){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 lZ extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function lX(e){let t;try{t=JSON.parse(e)}catch{throw new lZ("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new lZ("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new lZ("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class lQ{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()?[lX(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[lX(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function l0(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 l1(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 l2({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 l8({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)(tB,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function l4({identity:e,status:t,utteranceKey:n,children:i}){let s=nN(e?.sessionId,e?.provider,e?.credentialId),a=ir(s?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[s&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(nR,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:s.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[i,a&&(0,r.jsx)("img",{src:a.src,alt:a.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function l5({title:e,sessionId:t,sessionPath:n,sessionName:s,historyStore:a,flights:o,sessionCensus:l,client:c,visible:d=!0,onClose:u,onReturnFocus:p}){let h,m,g=(0,i.useMemo)(()=>c??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(-l_)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new lZ("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new lZ("http",await l0(r),r.status);if(!r.body)throw new lZ("stream","사이드채팅 스트림을 열 수 없습니다.");let i=r.body.getReader(),s=new lQ,a="",o=null,l=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)a+=t.v;else if("done"===t.t)a=t.v||a;else if("m"===t.t)o=t.v;else throw new lZ("server",t.v)};try{for(;;){let e=await i.read();if(e.done)break;l(s.push(e.value))}l(s.finish())}catch(e){if(n.signal?.aborted||e instanceof lZ)throw e;throw new lZ("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{i.releaseLock()}if(!a)throw new lZ("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:a,model:o}}}}(),[c]),f=t?.toLowerCase()??null,[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)({}),w=f??"",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),[T,I]=(0,i.useState)({}),[N,R]=(0,i.useState)({}),[M,E]=(0,i.useState)({}),[$,L]=(0,i.useState)(null),[A,P]=(0,i.useState)(null),[F,z]=(0,i.useState)({}),[W,D]=(0,i.useState)({}),[O,B]=(0,i.useState)({}),_=(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)}})),H=(0,i.useRef)(!0),U=(0,i.useRef)(f),q=(0,i.useRef)(d),V=(0,i.useRef)(null),K=(0,i.useRef)(!1),J=(0,i.useRef)(0),G=(0,i.useRef)(null);U.current=f,q.current=d,(0,i.useEffect)(()=>(H.current=!0,()=>{H.current=!1}),[]),(0,i.useEffect)(()=>{v(f?a.read(f):[])},[a,f]),(0,i.useEffect)(()=>{if(L(null),!f)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(f)}?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:f}:null)}).catch(()=>{e&&L(null)}),()=>{e=!1}},[f]),(0,i.useEffect)(()=>{if(!f)return;let e=()=>{if(!H.current||U.current!==f)return;let e=o.takeOutcome(f);if(e){if("aborted"===e.kind)R(t=>({...t,[f]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)I(t=>({...t,[f]:[...t[f]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),y(t=>(t[f]??"").trim()?t:{...t,[f]:e.question});else if(e.model){let t=e.model;E(e=>({...e,[f]:t}))}v(a.read(f))}else null===o.read(f)&&v(a.read(f));C(e=>e+1)},t=o.subscribe(f,e);return e(),t},[o,a,f]),(0,i.useEffect)(()=>{l&&a.cleanup(l,f)},[a,f,l]),(0,i.useEffect)(()=>{d&&V.current?.focus()},[d,f]),(0,i.useEffect)(()=>{if(!d)return;let e=requestAnimationFrame(()=>{let e=G.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,f,x.length,d]);let Y=async e=>{if(!f||!n){let e=f??"";R(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=o.begin(f,e);if(!t)return;let{signal:r}=t.controller;R(e=>{let t={...e};return delete t[f],t});try{let t=await g.ask({sessionPath:n,question:e,history:a.history(f),signal:r,onEvent:e=>o.ingest(f,e)});a.append(f,{q:e,a:t.text,at:Date.now()}),o.finish(f,{kind:"done",model:t.model})}catch(n){let t=o.read(f)?.text??"";if(r.aborted){let n=!1;t&&(a.append(f,{q:e,a:t,at:Date.now()}),n=!0),o.finish(f,{kind:"aborted",saved:n})}else{let r=n instanceof lZ?n.kind:"unknown",i=n instanceof Error?n.message:String(n);o.finish(f,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:i})}}finally{H.current&&q.current&&V.current?.focus()}},Z=async(e,t,n)=>{if(!f)return;let r=`${f}:${t}`;if(_.current.claim(r)){D(e=>({...e,[r]:"sending"})),B(e=>{let t={...e};return delete t[r],t});try{var i,s;let t,a=await fetch(`/api/agent/${encodeURIComponent(f)}`,{cache:"no-store"}),o=null;try{o=await a.json()}catch{}if(!a.ok){if(o&&"object"==typeof o&&"error"in o&&"string"==typeof o.error)throw Error(o.error);throw Error(`HTTP ${a.status}`)}let l=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}(o);if(null===l)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let c=(i=e.q,s=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",i,"","[사이드채팅 답변]",s,...t?["","[추가 지시]",t]:[]].join("\n"));await sB(f,{type:l?"steer":"prompt",message:c}),_.current.markSent(r),D(e=>({...e,[r]:"sent"}))}catch(e){_.current.release(r),D(e=>{let t={...e};return delete t[r],t}),B(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},X=()=>{if(f&&null!==o.read(f))return void o.abort(f);let e=k.trim();e&&(j(w,""),Y(e))},Q=T[f??""]??[],ee=N[f??""],et=f?o.read(f):null,en=x.length>0||Q.length>0||null!==et,er=et?.model??M[f??""],ei=!f||!n,es=null!==et,ea=!es&&!ei&&k.trim().length>0,eo=!f||es,el=$?.sessionId===f?$:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==et,"data-state":f&&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:[s||f?.slice(0,8)||"세션 없음",er?` \xb7 ${er}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{f&&null===o.read(f)&&(a.clear(f),v([]),I(e=>{let t={...e};return delete t[f],t}),R(e=>({...e,[f]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:eo,style:l1(eo),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...l1(),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:[f&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,i=`${f}:${n}`,s=W[i],a=A===i;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(l2,{children:e.q}),(0,r.jsx)(l4,{identity:el,status:"settled",utteranceKey:n,children:(0,r.jsx)(l8,{children:e.a})}),"sent"===s?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!a&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>P(i),style:{...l1(),alignSelf:"flex-start"},children:"메인에 보내기"}),a&&(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:F[i]??"",onChange:e=>z(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,F[i]??""),disabled:"sending"===s,style:l1("sending"===s),children:"sending"===s?"보내는 중…":"메인으로 전송"}),"sending"!==s&&(0,r.jsx)("button",{type:"button",onClick:()=>P(null),style:l1(),children:"취소"})]})]}),O[i]&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:O[i]})]})]},n)}),Q.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(l2,{children:e.question}),(0,r.jsxs)(l4,{identity:el,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(l8,{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)(l2,{children:et.question}),(0,r.jsx)(l4,{identity:el,status:"streaming",utteranceKey:`stream:${et.question}`,children:(0,r.jsx)(l8,{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:V,id:"side-chat-question",rows:4,value:k,onChange:e=>j(w,e.target.value),onCompositionStart:()=>{K.current=!0},onCompositionEnd:()=>{K.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(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}es||(e.preventDefault(),X())},disabled:es||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?"세션 파일이 준비되면 질문할 수 있습니다.":es?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!es&&!ea,style:l1(!es&&!ea),children:es?"중단":"전송"})]})]})]})}function l6(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 l3="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 l7(...e){return e.filter(Boolean).join(" ")}function l9(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),s=n%60;return r>0?`${r}d ${i}h 후 리셋`:i>0?`${i}h ${s}m 후 리셋`:`${s}m 후 리셋`}function ce(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),s=Math.floor(r%1440/60),a=r%60;return i>0?`${i}d ${s}h 후 만료`:s>0?`${s}h ${a}m 후 만료`:`${a}m 후 만료`}function ct(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 cn(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function cr(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 ci(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function cs(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function ca(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function co({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 cl({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 cc(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 cd({limit:e,now:t,detailed:n}){let i="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,s=Math.max(0,Math.min(100,100*i)),a=Math.round(100*i),o=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),s=100*r,a=Math.max(0,100-s);if(!n.durationMs){let e=i/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?a/e:a}}let o=Math.min(n.durationMs,Math.max(0,n.durationMs-i)),l=n.durationMs>432e5,c=l?864e5:36e5,d=n.durationMs/c,u=i/c,p=o/n.durationMs*100;return{burnOnly:!1,unit:l?"하루":"시간",partial:u<1,burn:u>=1?a/u:a,pacePct:p,deltaPct:s-p,nominal:100/d}}(e,t),l=e.daySlot,c=l?.usedPct==null||null==l.baselinePct?null:Math.max(0,Math.min(l.baselinePct,100)),d=null==c?null:Math.max(c,Math.min(100*i,100)),u=o?.pacePct==null?null:Math.min(o.pacePct,99.6),p=a>=90,h=o?.deltaPct!=null&&o.deltaPct>=.5?o.deltaPct:null,m=l?"unknown"===l.quality||null==l.usedPct?"구간 사용 — 기록 부족":"approx"===l.quality?`구간 사용 ≈${l.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${l.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:l7("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[a,"%"]})]}),(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":a,children:[(0,r.jsx)("div",{className:l7("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${s}%`}}),null!=c&&null!=d&&d>c?(0,r.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${c}%`,width:`${d-c}%`,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:l9(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:[o?.pacePct!=null?(0,r.jsx)(co,{label:"페이스",value:`${o.pacePct.toFixed(1)}%`}):null,o?(0,r.jsx)(co,{label:o.partial?"남은 한도":`앞으로 ${o.unit}`,value:`${o.burn.toFixed(1)}%`}):null,o?.nominal!=null?(0,r.jsx)(co,{label:"균등 배분 기준",value:`${o.nominal.toFixed(1)}%/${"하루"===o.unit?"일":"시간"} \xb7 계산값`}):null,l?(0,r.jsx)(co,{label:"구간",value:`${cc(l.slotStart)} ~ ${cc(l.slotEnd)} \xb7 ${l.slotIndex+1}/${l.slotCount}`}):null,l?(0,r.jsx)(co,{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??"?"} 전 표본`}(l)}):null]}):null]})}let cu={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function cp({confirmId:e,pending:t,primaryRef:n,summary:i,onConfirm:s,onCancel:a}){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(),a())},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:l7(l3,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:s,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:l3,disabled:t,onClick:a,children:"취소"})]})]})}function ch({report:e,brokerOk:t,now:n,active:s,identity:a,recommendation:o,pendingAction:l,feedback:c,onToggle:d,onReset:u}){let p=e.metadata??{},h=a??nn([e])[0],m=e.credentialId,g=Number.isSafeInteger(m)&&m>0,f=e.accountRole,x="usage-only"===f?"사용량":"control-only"===f?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,b=s?"active":e.disabled?"off":v?"auto-blocked":"idle",y="toggle"===l?"전환 중…":"reset"===l?"리셋 사용 중…":g?s?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${l9(e.autoBlockedUntilMs,n)}`:"control-only"===f?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===f?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,i.useId)(),k=(0,i.useId)(),[j,S]=(0,i.useState)(!1),[C,T]=(0,i.useState)(!1),[I,N]=(0,i.useState)(null),R=(0,i.useRef)(null),M=(0,i.useRef)(null),E=(0,i.useRef)(!1),$=(0,i.useRef)(!1),L="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,A=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),P=A?.id??null,F=ce(A?.expiresAt??null,n),z=L?.availableCount,W=L&&"unavailable"!==L.state?"empty"===L.state||0===z?"없음":`${z??L.credits.length}개${F?` \xb7 ${F}`:""}`:"확인 불가",D=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=>cu[e]).filter(e=>void 0!==e))];return r.length?`${r.join("\xb7")} 한도만`:null}(e),O=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let n="number"==typeof e.naturalResetAt?l9(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=ce(e.expiresAt??null,t),r="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${n&&"만료됨"!==n?n:"곧 만료"}됩니다.${r}`}(o,n),B=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&L?.state==="available"&&0!==z&&null!=P;(0,i.useLayoutEffect)(()=>{if(I)return void M.current?.focus();if(E.current){var e;E.current=!1,e=R.current,e?.focus()}},[I]),(0,i.useEffect)(()=>{"reset"!==l&&(e.disabled||!t||L?.state!=="available")&&(E.current=!1,N(null))},[t,l,e.disabled,L?.state]);let _=async()=>{if(I&&!$.current){$.current=!0;try{await u(e,I.creditId)}finally{$.current=!1,E.current=!0,N(null)}}},H=(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=l?"pending":s?"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":s?"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)(nR,{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:`${nt(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:l?"status":void 0,children:y}),null!=H&&H-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${l9(H,n).replace(/ 후 리셋$/,"")}`}):null]})]}),g?(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:l7(l3,"resource-account-switch min-w-[3.25rem]"),disabled:null!=l||!t,"aria-label":`${h.alias} 계정 사용 설정`,"aria-checked":!e.disabled,"aria-busy":null!=l||void 0,title:t?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{E.current=!1,N(null),d(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(t1)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,c?(0,r.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===c.tone?"alert":"status",children:c.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:()=>T(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(cd,{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||T(!1)},children:j?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?I?(0,r.jsx)(cp,{confirmId:w,pending:"reset"===l,primaryRef:M,summary:I.summary,onConfirm:()=>{_()},onCancel:()=>{E.current=!0,N(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===z?"empty":"reset"===l?"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:l7("font-mono text-xs tabular-nums text-text",o?.reason==="expiring-credit"&&"text-warning"),children:W})]}),D?(0,r.jsx)("span",{className:"text-xs text-text-muted",children:D}):null,B?(0,r.jsx)("button",{ref:R,type:"button",className:l7(l3,"ml-auto flex-none"),disabled:null!=l,onClick:()=>{P&&N({creditId:P,summary:W})},children:"리셋 사용"}):t&&e.disabled&&L?.state==="available"?(0,r.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),O?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:O}):null]}):null]})}function cm({state:e,loading:t,accountState:n,pendingActions:i,feedbackByCredential:s,onToggle:a,onReset:o}){let l=l6(1e4),c=e.data,d=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,u=nn(c?.reports??[]),p=null==d?-1:c?.reports.findIndex(e=>e.credentialId===d)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cl,{state:e,loading:t,subject:"사용량"}),c?.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"}),"페이스"]})]}),c&&0===c.reports.length?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,c?.reports.map((e,t)=>{let d=e.credentialId;return(0,r.jsx)(ch,{report:e,brokerOk:!0===c.brokerOk,now:l,active:t===p,identity:u[t],recommendation:null==d?void 0:n?.resetRecommendations.find(e=>e.credentialId===d),pendingAction:null==d?null:i.get(d)??null,feedback:null==d?void 0:s.get(d),onToggle:a,onReset:o},`${e.provider}:${d??e.metadata?.accountId??e.metadata?.email??t}`)})]})}function cg({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:[ct(e.cost)," \xb7 ",ci(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)(co,{label:"요청",value:cn(e.requests)}),(0,r.jsx)(co,{label:"요청당",value:ct(e.costPerRequest)}),(0,r.jsx)(co,{label:"토큰/요청",value:cr(e.tokensPerRequest)}),(0,r.jsx)(co,{label:"출력/요청",value:cr(e.outputPerRequest)}),(0,r.jsx)(co,{label:"캐시율",value:ci(e.cacheRate,1)}),(0,r.jsx)(co,{label:"TTFT",value:cs(e.avgTtft)})]})]})}function cf({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:[ct(e.cost)," \xb7 ",ci(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)(co,{label:"요청",value:cn(e.requests)}),(0,r.jsx)(co,{label:"요청당",value:ct(e.costPerRequest)}),(0,r.jsx)(co,{label:"토큰/요청",value:cr(e.tokensPerRequest)})]})]})}function cx({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:ca(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:ct(e.cost)})]})}function cv({state:e,loading:t}){let n=e.data;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cl,{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)(co,{label:"요청",value:cn(n.overall.requests)}),(0,r.jsx)(co,{label:"비용",value:ct(n.overall.cost)}),(0,r.jsx)(co,{label:"토큰",value:cr(n.overall.tokens)}),(0,r.jsx)(co,{label:"캐시율",value:ci(n.overall.cacheRate,1)}),(0,r.jsx)(co,{label:"캐시 절감",value:ci(n.overall.cacheSavings,1)}),(0,r.jsx)(co,{label:"평균 TTFT",value:cs(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)(cg,{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)(cf,{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)(cx,{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 cb({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:t8.map(n=>{let i=`character-roster-${n.seed}`,s=`character-roster-${n.seed}-status`,a=`${n.provider}/${n.model}`,o=!1,l=!1;if(e){for(let t of e)if(t.provider===n.provider&&(o=!0,!0!==t.disabled)){l=!0;break}}let c="web6"!==n.provider&&(t?.get(n.provider)===!1||o&&!l);return(0,r.jsxs)("article",{className:l7("character-roster-item",c&&"is-unavailable"),role:"listitem","aria-labelledby":i,"aria-describedby":c?s:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(nR,{seed:n.seed,size:48,provider:n.provider}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{id:i,children:n.alias}),c?(0,r.jsx)("span",{id:s,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:a,children:a})]}),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 cy({open:e,sessionId:t,activeTab:n,onTabChange:s,usage:o,className:l}){let c=(0,i.useId)(),d=o.state,u=o.loading,[p,h]=(0,i.useState)({status:"idle",data:null,error:null}),[m,g]=(0,i.useState)(null),[f,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),T=(0,i.useRef)(null),I=(0,i.useRef)(new Set),N=(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,d.data]),(0,i.useEffect)(()=>{var r;let i,s,a,o,l,c,d,u,p,h;if(g(null),!e||"usage"!==n||!t)return;let m=(s=(r={onClear(){g(null)},onResult(e){g("fresh"===e.status?e.data:null)}}).intervalMs??2500,a=r.setIntervalImpl??setInterval,o=r.clearIntervalImpl??clearInterval,l=null,c=null,d=0,u=!1,p=()=>{o(i),i=void 0},h=async e=>{c?.abort();let t=c=new AbortController,n=++d,i=await np(e,{signal:t.signal,fetchImpl:r.fetchImpl});u||n!==d||l!==e||t.signal.aborted||r.onResult(i)},{setSessionId(e){u||e===l||(d+=1,c?.abort(),c=null,p(),l=e,r.onClear(e),e&&(h(e),i=a(()=>{l&&h(l)},s)))},stop(){u||(u=!0,d+=1,c?.abort(),c=null,p(),l=null)}});return C.current=m,m.setSessionId(t),()=>{m.stop(),C.current===m&&(C.current=null)}},[n,e,t]);let R=(0,i.useCallback)(async e=>{T.current?.abort();let t=new AbortController;T.current=t,x(!0);let n=await nh({refresh:e,previous:S.current.data,signal:t.signal});T.current!==t||t.signal.aborted||(h(n),x(!1))},[]);(0,i.useEffect)(()=>{e&&"models"===n&&("idle"===S.current.status||"error"===S.current.status)&&R(!1)},[n,e,R]),(0,i.useEffect)(()=>()=>{for(let e of(T.current?.abort(),I.current))e.abort()},[]);let M=(0,i.useCallback)(()=>{"models"===n?R(!0):o.refresh()},[n,R,o]),E=(0,i.useCallback)(()=>o.refresh(),[o]),$=(0,i.useCallback)(async e=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let t=e.credentialId,n=nf(N.current,t);if(!n)return;let r=new AbortController;I.current.add(r),o.setPaused(!0),w(e=>new Map(e).set(t,"toggle")),j(e=>{let n=new Map(e);return n.delete(t),n});try{await nm(t,!0===e.disabled,{signal:r.signal});let n=await E();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 nr&&("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(),o.setPaused(N.current.size>0),w(e=>{let n=new Map(e);return n.delete(t),n})}},[E,o]),L=(0,i.useCallback)(async(e,t)=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let n=e.credentialId,r=nf(N.current,n);if(!r)return;let i=new AbortController;I.current.add(i),o.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 ng(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),s=await E();if(e.ok){let e="fresh"===s.status?s.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 nr&&(e.outcomeUnknown||"timeout"===e.kind)&&!i.signal.aborted&&await E(),i.signal.aborted||j(t=>new Map(t).set(n,function(e){if(e instanceof nr){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(),o.setPaused(N.current.size>0),w(e=>{let t=new Map(e);return t.delete(n),t})}},[E,o]);if(!e)return null;let A="models"===n?p.data?.generatedAt:d.data?.generatedAt,P="models"===n?p.data?.range:void 0,F=P?.from&&P.to?`${ca(P.from)}~${ca(P.to)}`:A?new Date(A).toLocaleTimeString():"",z="models"===n?f:"usage"===n&&u,W=z?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:l7("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",l),"aria-labelledby":c,"aria-busy":z,children:[(0,r.jsx)("h1",{id:c,className:"sr-only",children:"캐릭터"}),(0,r.jsxs)(lN.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>s(e),children:[(0,r.jsxs)(lN.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(lN.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(lN.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(lN.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(lN.J.Indicator,{})]}),(0,r.jsx)(lN.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(cb,{reports:d.data?.reports,providerConnections:v})}),(0,r.jsxs)(lN.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:F}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:M,disabled:z,children:W})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(cm,{state:d,loading:u,accountState:m?.sessionId===t?m:null,pendingActions:y,feedbackByCredential:k,onToggle:e=>{$(e)},onReset:L})]}),(0,r.jsxs)(lN.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:F}),(0,r.jsx)(a.r,{variant:"neutralWeak",size:"xsmall",onClick:M,disabled:z,children:W})]}),(0,r.jsx)(cv,{state:p,loading:f})]})]})]})}let cw="/api/runs";class ck extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let cj=["completed","error","aborted","interrupted","running"],cS=["main","maker","checker","advisor","unattributed"],cC=["primary","rework","review"],cT=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],cI=["all","attributed"];function cN(e){return"object"==typeof e&&null!==e}function cR(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function cM(e){return!!cN(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&&cj.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 cE(e){return!!cN(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&cS.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&cC.includes(e.purpose))&&cR(e.models)&&cR(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 c$(e){return!!cN(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 cL(e){return!!cN(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.errors&&Number.isFinite(e.errors)}function cA(e){return!!cN(e)&&"string"==typeof e.kind&&cS.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)}function cP(e){return!!cN(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(cA)&&"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 cF(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&cT.includes(e))}async function cz(e){try{return await e.json()}catch{throw new ck("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}function cW(e,t){return e instanceof ck||e instanceof Error?e.message:t}let cD={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},cO={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function cB(...e){return e.filter(Boolean).join(" ")}function c_(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 cH(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function cU(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 cq(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 cV(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function cK({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 cJ({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 cG({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",c_(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function cY({outcome:e,t}){return(0,r.jsx)(lR.E,{tone:cD[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function cZ({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(lR.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 cX({run:e,selected:t,onSelect:n,t:i}){let s=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:cB("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:s,children:s}),(0,r.jsx)(cY,{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}",cq(e.wallClockMs))}),(0,r.jsx)(cG,{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"),s=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)(lR.E,{tone:cO[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)(cZ,{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)(cK,{label:t("efficiency.busyTime"),value:cq(e.busyMs)}),(0,r.jsx)(cK,{label:t("efficiency.estimatedCost"),value:c_(e.estimatedCostUsd)}),(0,r.jsx)(cK,{label:t("efficiency.tokens"),value:cU(e.totalTokens)}),(0,r.jsx)(cK,{label:t("efficiency.unpricedRequests"),value:cH(e.unpricedRequests)}),(0,r.jsx)(cK,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?cq(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,r.jsx)(cK,{label:t("efficiency.outputTokens"),value:cU(s)})]}),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}",cH(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)(cK,{label:`${e.purpose} \xb7 ${e.model}`,value:t("efficiency.helperCallsValue",{count:e.requestCount,output:cU(e.outputTokens),tokens:cU(e.totalTokens),cost:c_(e.estimatedCostUsd)})},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.helpersIncludedNote")})]}):null]})}function c0({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:cq(e.ms)})]}),(0,r.jsx)(cJ,{share:e.relative,label:cq(e.ms)})]})}function c1({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:cq(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:cq(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)(cK,{label:t("efficiency.estimatedCost"),value:c_(e.estimatedCostUsd)}),(0,r.jsx)(cK,{label:t("efficiency.tokens"),value:cU(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)(c0,{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}",cq(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)(cK,{label:`${e.toolName} \xb7 ${t("efficiency.toolErrorsValue").replace("{value}",String(e.errors))}`,value:cH(e.calls)},e.toolName))})]}):null]})}function c2(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 c8({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)(cK,{label:t("efficiency.scopeSessions"),value:cH(e.sessionCount)}),(0,r.jsx)(cK,{label:t("efficiency.scopeRuns"),value:cH(e.runCount)}),(0,r.jsx)(cK,{label:t("efficiency.scopeExcludedRuns"),value:cH(e.excludedRunCount)})]})})}function c4({config:e,baselineRuns:t,t:n}){let i=t>0?e.runCount/t:0,s=e.runCount>0?e.reworkRuns/e.runCount:0,a=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:c2(e.roles),children:c2(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:cV(i)})]}),(0,r.jsx)(cJ,{share:i,label:cV(i)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(cK,{label:n("efficiency.medianElapsed"),value:cq(e.medianWallClockMs)}),(0,r.jsx)(cK,{label:n("efficiency.medianBusy"),value:cq(e.medianBusyMs)}),(0,r.jsx)(cK,{label:n("efficiency.medianTokens"),value:cU(e.medianTotalTokens)}),(0,r.jsx)(cK,{label:n("efficiency.medianEstimatedCost"),value:c_(e.medianEstimatedCostUsd)}),(0,r.jsx)(cK,{label:n("efficiency.totalEstimatedCost"),value:c_(e.totalEstimatedCostUsd)}),(0,r.jsx)(cK,{label:n("efficiency.reworkRate"),value:cV(s,1)}),(0,r.jsx)(cK,{label:n("efficiency.errorRate"),value:cV(a,1)}),(0,r.jsx)(cK,{label:n("efficiency.unpricedRuns"),value:cH(e.unpricedRuns)}),(0,r.jsx)(cK,{label:n("efficiency.untimedRuns"),value:cH(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",cH(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function c5({open:e,sessionId:t,activeTab:n,onTabChange:s,client:o,className:c}){let d=(0,i.useId)(),u=(0,i.useId)(),{t:p}=(0,E.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[s]=(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 ck("unreachable","효율 기록에 연결할 수 없습니다.")}let i=await cz(r);if(!r.ok){var s;throw new ck("http",(s=`HTTP ${r.status}`,null!==i&&"object"==typeof i&&"error"in i&&"string"==typeof i.error&&i.error?i.error:s),r.status)}return{response:r,body:i}};return{async listRuns(e,n,r){let{response:i,body:s}=await t(`${cw}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!cN(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(cM)&&cF(e.unmeasured)))throw new ck("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new ck("invalid-response",t,n)}}(s,"실행 목록 응답이 올바르지 않습니다.",i.status)},async getRun(e,n){let{response:r,body:i}=await t(`${cw}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!cM(e)||!(Array.isArray(e.roles)&&e.roles.every(cE)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(c$)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(cL)&&cF(e.unmeasured)))throw new ck("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new ck("invalid-response",t,n)}}(i,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,i){let s=new URLSearchParams;null!==e&&""!==e&&s.set("folder",e),s.set("sessions",String(n)),s.set("scope",r);let{response:a,body:o}=await t(`/api/experiments?${s.toString()}`,{method:"GET",signal:i});return function(e,t,n=null){try{if(!cN(e)||!((null===e.folder||"string"==typeof e.folder)&&cR(e.folders)&&"string"==typeof e.scope&&cI.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(cP)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&cF(e.unmeasured)))throw new ck("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new ck("invalid-response",t,n)}}(o,"구성 비교 응답이 올바르지 않습니다.",a.status)}}}()),[a,o]=(0,i.useState)({status:"idle",runs:[],error:null}),[l,c]=(0,i.useState)({status:"idle",runId:null,detail:null,error:null}),[d,u]=(0,i.useState)({status:"idle",response:null,error:null}),[p,h]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),f=(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),c({status:"idle",runId:null,detail:null,error:null}),o({status:"idle",runs:[],error:null})},[e]);let y=(0,i.useCallback)(()=>{if(!t||"governor"!==n||!e)return;f.current?.abort();let r=new AbortController;f.current=r,o(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),s.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&f.current===r){if(0===e.runs.length)return void o({status:"empty",runs:[],error:null});o({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||f.current!==r||o({status:"error",runs:[],error:cW(e,"실행 목록을 불러오지 못했습니다.")})})},[n,s,e,t]),w=(0,i.useCallback)(e=>{if(!t)return;x.current?.abort();let n=new AbortController;x.current=n,c({status:"loading",runId:e,detail:null,error:null}),s.getRun(e,n.signal).then(t=>{n.signal.aborted||x.current!==n||c({status:"ready",runId:e,detail:t,error:null})}).catch(t=>{n.signal.aborted||x.current!==n||c({status:"error",runId:e,detail:null,error:cW(t,"실행 상세를 불러오지 못했습니다.")})})},[s,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})),s.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:cW(e,"구성 비교를 불러오지 못했습니다.")})})},[n,s,t]);(0,i.useEffect)(()=>{if(t&&"governor"===n)return y(),()=>{f.current?.abort(),f.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)(()=>()=>{f.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,i.useCallback)(e=>{x.current?.abort(),x.current=null,h(e),null===e&&c({status:"idle",runId:null,detail:null,error:null})},[]);return{list:a,detail:l,experiments:d,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,g(e)),k(n,t)},[k]),experimentFolder:m}}({sessionId:t,visible:e,activeTab:n,client:o}),[m,g]=(0,i.useState)(""),f=(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:cB("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",c),"aria-labelledby":d,"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:d,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)(a.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:cB("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:()=>s(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;g(t??""),h.refreshExperiments(t,b)},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.folderAll")}),f.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),v&&!f.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=>g(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)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===b,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all"),children:p("efficiency.scopeAttributed")}),(0,r.jsx)(lR.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)(cX,{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)(c1,{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)(c8,{response:e,t:p}),e.configs.map(e=>(0,r.jsx)(c4,{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)(c8,{response:e,t:p})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")})]})})()})]})}function c6(e){return"message"===e.type&&"message"in e}function c3(e){let t=e,n=t.branchPreview,r=c6(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&c6(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function c7({node:e,activePathIds:t,depth:n,isLast:i,parentLines:s,onSelect:a}){let{node:o,skipped:l,branchPreview:c,labelEntry:d}=c3(e),u=t.has(o.entry.id),p=t.has(e.entry.id)||t.has(o.entry.id),h=c?.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}(d),m=c?c.role??null:c6(d)?d.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>a(o.entry.id),children:[s.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom: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"}),l>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",l]}),(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})]}),o.children.map((e,l)=>(0,r.jsx)(c7,{node:e,activePathIds:t,depth:n+1,isLast:l===o.children.length-1,parentLines:[...s,!i],onSelect:a},e.entry.id))]})}function c9({tree:e,activeLeafId:t,onLeafChange:n,hasSession:s}){let{t:a}=(0,E.s)(),o=(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 s=e(i.children,n);if(s)return s}return null}(e,[])??[]):new Set,[e,t]),l=(0,i.useCallback)(e=>{n(e)},[n]),c=s?!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)?a("i18n.noBranches"):null:a("i18n.noActiveSession"),d=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=c3(e[0]).node;return t.children.length>1?t.children:[]}(e);return!c&&d.length>0?(0,r.jsx)("div",{className:"branch-navigator-tree",children:d.map((e,t)=>(0,r.jsx)(c7,{node:e,activePathIds:o,depth:0,isLast:t===d.length-1,parentLines:[],onSelect:l},e.entry.id))}):(0,r.jsx)("p",{className:"branch-navigator-empty",children:c??a("i18n.noBranches")})}function de(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function dt(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function dn(e){let t=e.currentTime;[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),s=e.createGain();i.connect(s),s.connect(e.destination),i.type="sine",i.frequency.value=n;let a=t+.18*r;s.gain.setValueAtTime(0,a),s.gain.linearRampToValueAtTime(.18,a+.02),s.gain.exponentialRampToValueAtTime(.001,a+.45),i.start(a),i.stop(a+.45)})}async function dr(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function di(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 ds(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null}function da(e){let t=ds(e);return t1(e)||"warning"===e.status||null!==t&&t>=90}let dl="omp-sidebar-usage-collapsed";function dc(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function dd(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function du({usage:e,onOpen:t}){var n;let s,a,o,{t:l}=(0,E.s)(),c=z(),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(!0);(0,i.useEffect)(()=>{try{h("0"!==window.localStorage.getItem(dl))}catch{}},[]);let m=e.bai,g=e.state.data?.reports??[],f=l6(1e4),x=(s=nn(g),a=[],o=[],g.forEach((e,t)=>{if(!0===e.disabled)return;let n=s[t],r="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>f,i=(e.limits??[]).some(e=>e.scope?.shared===!0&&t1(e)),l=(e.limits??[]).some(e=>null!==dc(e)&&"short"!==di(e));for(let t of e.limits??[]){let s=dc(t);if(null===s||l&&"short"===di(t)&&!da(t))continue;let c=r?"blocked":i?"account-spent":t1(t)?"spent":"usable",d={key:`${e.provider}:${e.credentialId??n.seed}:${t.id}`,account:n.alias,seed:n.seed,provider:e.provider,label:t.label||t.id,percent:Math.round(100*s),state:c};("usable"===c?a:o).push(d)}}),[...a,...o]),v=d?x:x.slice(0,2),b=x.length-v.length,y="measured"===m.status?(n=m.tokens)>=1e9?`${(n/1e9).toFixed(1)}B`:n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${Math.round(n/1e3)}K`:String(Math.round(n)):l("empty"===m.status?"usage.baiEmpty":"usage.baiUnmeasured"),w="measured"===m.status&&null!==m.from&&null!==m.to?l("usage.baiRange",{from:dd(m.from),to:dd(m.to)}):null,k=e=>"usable"===e.state?null:l("blocked"===e.state?"usage.accountBlocked":"account-spent"===e.state?"usage.accountSpent":"usage.limitSpent"),j=l("usage.open",{rows:[...v.map(e=>{let t=k(e);return`${e.account} ${e.label} ${e.percent}%${null===t?"":` (${t})`}`}),`${l("usage.bai")} ${y}${null===w?"":` \xb7 ${w}`}`].join(", ")})+(b>0?l("usage.openMore",{count:b}):""),S=0===x.length?{label:l("usage.bai"),value:y,danger:!1}:{label:x[0].label,value:`${x[0].percent}%`,danger:x[0].percent>=90},C=(0,r.jsxs)("div",{role:"button",tabIndex:0,className:"navigator-usage",onClick:t,onKeyDown:e=>{e.target!==e.currentTarget||("Enter"===e.key||" "===e.key)&&(" "===e.key&&e.preventDefault(),t())},"aria-label":j,children:[0===v.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:l("usage.none")}):v.map(e=>(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}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(nR,{seed:e.seed,size:24,provider:e.provider}),e.account,null===k(e)?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:k(e)})]}),(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)),(b>0||d)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":d,onClick:e=>{e.stopPropagation(),u(e=>!e)},children:d?l("usage.showLess"):l("usage.showMore",{count:b})}),(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:l("usage.bai")}),(0,r.jsx)("span",{className:"navigator-usage-value",style:"measured"===m.status?void 0:{color:"var(--text-dim)"},children:y})]}),null===w?null:(0,r.jsx)("span",{className:"navigator-usage-account",children:w})]})]});return c?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!p,"aria-label":p?j:l("usage.showLess"),onClick:()=>{let e=!p;h(e);try{window.localStorage.setItem(dl,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:p?S.label:l("usage.showLess")}),p&&(0,r.jsx)("span",{className:"navigator-usage-value",style:S.danger?{color:"var(--danger)"}:void 0,children:S.value}),(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:p?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),p?null:C]}):C}let dp={snapshot:null,revision:0,streaming:new Map};function dh(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,s]of e)(s.generation<t||r.has(n))&&i.delete(n);return i.size===e.size?e:i}function dm(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:dh(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:dh(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 dg="/api/lounge";function df(e){try{return JSON.parse(e.data)}catch{return null}}async function dx(e){try{let t=await e.json();if("string"==typeof t?.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}var dv=n(96607);let db=["slow","normal","active"],dy=[5,10,20,30,60,120].filter(e=>e>=1&&e<=120);function dw({row:e,lt:t,locale:n,now:i,compact:s}){let a="weekly"!==e.kind?e.label:e.tier?t("lounge.usage.weeklyTier",{tier:e.tier}):t("lounge.usage.weekly"),o="blocked"===e.state?t("lounge.usage.blocked"):"spent"===e.state?t("lounge.usage.spent"):null,l=!s&&null!==e.resetsAt&&e.resetsAt>i?t("lounge.usage.resets",{when:(0,U.fw)(new Date(e.resetsAt),n,new Date(i))}):null,c="usable"!==e.state;return(0,r.jsxs)("span",{className:"lounge-usage","data-compact":s?"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:a}),l?(0,r.jsx)("span",{className:"lounge-usage-reset",children:l}):null,o?(0,r.jsx)("span",{className:"lounge-usage-state",children:o}):null,(0,r.jsxs)("span",{className:"lounge-usage-value",children:[e.percent,"%"]})]}),s?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:c?"var(--danger)":"var(--metric)"}})})]})}function dk({member:e,lounge:t,usage:n,now:s,disabled:a}){let{lt:o,locale:l}=V(),c=K(e.alias,l),d=function(e,t,n){let r=t.account,i=[],s=[];if(r&&(r.selectionRequired||void 0===r.credentialId))return{selectionRequired:!0,primary:i,warnings:s};let a=nn(e);return e.forEach((e,o)=>{if(e.provider!==t.provider||(r?e.credentialId!==r.credentialId:a[o].alias!==t.alias)||!0===e.disabled)return;let l="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,c=(e.limits??[]).flatMap(t=>{let n=ds(t);if(null===n)return[];let r=l?"blocked":t1(t)?"spent":"warning"===t.status||n>=90?"warning":"usable",i=t.window?.resetsAt,s=t.scope?.tier??t.scope?.modelId;return[{row:{key:`${e.provider}:${e.credentialId??o}:${t.id}`,label:t.label||t.id,kind:di(t),tier:"string"==typeof s&&s?s:null,percent:n,resetsAt:"number"==typeof i&&Number.isFinite(i)?i:null,state:r},alert:da(t)}]}),d=c.filter(({row:e})=>"short"!==e.kind);d.length>0?(i.push(...d.map(({row:e})=>e)),s.push(...c.filter(({row:e,alert:t})=>"short"===e.kind&&t).map(({row:e})=>e))):i.push(...c.map(({row:e})=>e))}),{selectionRequired:!1,primary:i,warnings:s}}(n.state.data?.reports??[],e,s),u=e.weeklyUsage?[{key:`${e.id}:weekly`,label:o("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"}]:d.primary,p=null===n.state.data&&n.loading,h=o(`lounge.state.${e.state}`),m=`lounge-member-${e.id}-status`,g=t.snapshot?.room.participants??[],f=e.account,x=f?.credentialId,v=void 0!==x&&!f?.choices.some(e=>e.credentialId===x),b=void 0!==f&&(f.selectionRequired||void 0===x||v),y=void 0!==f&&f.choices.length>1,[w,k]=(0,i.useState)(!1),j=void 0!==f&&(b||y&&w),S=`lounge-member-${e.id}-account`,C=u.filter(e=>null===e.tier),T=[...u.filter(e=>null!==e.tier),...d.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)(nR,{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:c}),(0,r.jsx)("span",{id:m,className:"lounge-member-state",children:h})]}),(0,r.jsxs)(dv.h.Root,{size:"16",tone:"neutral",className:"lounge-switch",checked:e.enabled,disabled:a,onCheckedChange:n=>{let r=n?[...g.filter(t=>t!==e.id),e.id]:g.filter(t=>t!==e.id);t.updateSettings({participants:r})},children:[(0,r.jsx)(dv.h.HiddenInput,{"aria-label":o("lounge.participate",{name:c}),"aria-describedby":m}),(0,r.jsx)(dv.h.Control,{children:(0,r.jsx)(dv.h.Thumb,{})})]})]}),e.reason?(0,r.jsx)("span",{className:"lounge-member-reason",children:e.reason}):null,C.length+T.length>0?(0,r.jsxs)("span",{className:"lounge-member-usage",children:[C.map(e=>(0,r.jsx)(dw,{row:e,lt:o,locale:l,now:s},e.key)),T.map(e=>(0,r.jsx)(dw,{row:e,lt:o,locale:l,now:s,compact:!0},e.key))]}):(0,r.jsx)("span",{className:"lounge-member-usage-empty",children:p?o("lounge.usage.loading"):d.selectionRequired?o("lounge.account.required"):o("lounge.usage.none")}),(0,r.jsxs)("span",{className:"lounge-member-meta",children:[(0,r.jsxs)("span",{className:"lounge-member-model",children:[nt(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:o("lounge.account.change")}):null]}),j&&f?(0,r.jsxs)("span",{className:"lounge-member-account",children:[(0,r.jsx)("label",{className:"sr-only",htmlFor:S,children:o("lounge.account.for",{name:c})}),(0,r.jsxs)("select",{id:S,className:"lounge-select",value:void 0===x?"":String(x),disabled:a||0===f.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:o("lounge.account.choose")}):null,v?(0,r.jsx)("option",{value:String(x),disabled:!0,children:o("lounge.account.missing",{id:x})}):null,f.choices.map(e=>(0,r.jsx)("option",{value:String(e.credentialId),children:e.label},e.credentialId))]})]}):null]})]})}function dj({lounge:e,usage:t,onOpenLounge:n,loungeOpen:i=!1}){var s;let a,{lt:o,locale:l}=V(),c=l6(1e4),d=e.snapshot,u=d?.room??null,p=d?.members??[],h=d?.loadError??null,m=e.pending.has("settings"),g=null===d||null!==h,f=p.filter(e=>e.enabled).length,x=new Intl.DateTimeFormat(l,{hour:"2-digit",minute:"2-digit"}),v=u&&!dy.includes(u.sleepAfterMinutes)?[...dy,u.sleepAfterMinutes].sort((e,t)=>e-t):dy,b=d?.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:o("lounge.title")}),(0,r.jsxs)(dv.h.Root,{size:"24",tone:"neutral",className:"lounge-switch lounge-room-switch",checked:u?.enabled??!1,disabled:g||m,onCheckedChange:t=>{e.updateSettings({enabled:t})},children:[(0,r.jsx)(dv.h.Label,{className:"lounge-room-switch-label",children:u?.enabled?o("lounge.roomOn"):o("lounge.roomOff")}),(0,r.jsx)(dv.h.HiddenInput,{"aria-label":o("lounge.roomSwitch")}),(0,r.jsx)(dv.h.Control,{children:(0,r.jsx)(dv.h.Thumb,{})})]})]}),null===d?(0,r.jsx)("p",{className:"lounge-panel-note",role:e.loadError?"alert":"status",children:e.loadError?o("lounge.loadFailed",{error:e.loadError}):o("lounge.connecting")}):h?(0,r.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:o("lounge.loadFailed",{error:h})}):u&&!u.enabled?(0,r.jsx)("p",{className:"lounge-panel-note",children:o("lounge.roomOffHint")}):u?.asleep?(0,r.jsx)("p",{className:"lounge-panel-note",children:o("lounge.asleep")}):null,"reconnecting"===e.connection&&null!==d?(0,r.jsx)("p",{className:"lounge-panel-note",role:"status",children:o("lounge.reconnecting")}):null,e.actionError?(0,r.jsx)("p",{className:"lounge-panel-note","data-tone":"danger",role:"alert",children:o("lounge.actionFailed",{error:e.actionError})}):null,n?(0,r.jsx)("button",{type:"button",className:"lounge-panel-open","aria-pressed":i,onClick:n,children:o("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:o("lounge.members")}),p.length>0?(0,r.jsx)("span",{className:"lounge-panel-count",children:o("lounge.membersCount",{active:f,total:p.length})}):null]}),(0,r.jsx)("ul",{className:"lounge-member-list","aria-label":o("lounge.members"),children:p.map(n=>(0,r.jsx)(dk,{member:n,lounge:e,usage:t,now:c,disabled:g||m},n.id))}),p.some(e=>e.account)?(0,r.jsx)("p",{id:"lounge-account-hint",className:"lounge-panel-hint",children:o("lounge.account.hint")}):null]}),u?(0,r.jsxs)("div",{className:"lounge-panel-settings",role:"group","aria-label":o("lounge.settings"),children:[(0,r.jsx)("div",{className:"lounge-panel-section-head",children:(0,r.jsx)("span",{children:o("lounge.settings")})}),(0,r.jsxs)("div",{className:"lounge-setting",children:[(0,r.jsx)("span",{className:"lounge-setting-label",id:"lounge-pace-label",children:o("lounge.pace")}),(0,r.jsx)("div",{className:"lounge-segmented",role:"radiogroup","aria-labelledby":"lounge-pace-label",children:db.map(t=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":u.pace===t,disabled:g||m,onClick:()=>{u.pace!==t&&e.updateSettings({pace:t})},children:o(`lounge.pace.${t}`)},t))})]}),(0,r.jsxs)("label",{className:"lounge-setting lounge-setting-inline",children:[(0,r.jsx)("span",{className:"lounge-setting-label",children:o("lounge.sleep")}),(0,r.jsx)("select",{className:"lounge-select",value:u.sleepAfterMinutes,disabled:g||m,onChange:t=>{e.updateSettings({sleepAfterMinutes:Number(t.target.value)})},children:v.map(e=>(0,r.jsx)("option",{value:e,children:o("lounge.sleepMinutes",{minutes:e})},e))})]}),(0,r.jsxs)("div",{className:"lounge-setting",children:[(0,r.jsxs)(dv.h.Root,{size:"16",tone:"neutral",className:"lounge-switch lounge-setting-switch",checked:u.autoTalk,disabled:g||m,onCheckedChange:t=>{e.updateSettings({autoTalk:t})},children:[(0,r.jsx)(dv.h.Label,{className:"lounge-setting-label",children:o("lounge.autoTalk")}),(0,r.jsx)(dv.h.HiddenInput,{"aria-describedby":"lounge-autotalk-hint"}),(0,r.jsx)(dv.h.Control,{children:(0,r.jsx)(dv.h.Thumb,{})})]}),(0,r.jsx)("span",{id:"lounge-autotalk-hint",className:"lounge-setting-hint",children:o("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:o("lounge.calls",{window:(s=b.calls.windowMs,(a=Math.round(s/36e5))>=1?new Intl.NumberFormat(l,{style:"unit",unit:"hour",unitDisplay:"long"}).format(a):o("lounge.sleepMinutes",{minutes:Math.max(1,Math.round(s/6e4))})),used:b.calls.used,limit:b.calls.limit})}):null,b?(0,r.jsx)("span",{children:o("lounge.perTurn",{limit:b.perTurnLimit})}):null,u.enabled&&!u.asleep&&null!==u.sleepAt&&u.sleepAt>c?(0,r.jsx)("span",{children:o("lounge.sleepAt",{time:x.format(new Date(u.sleepAt))})}):null]})]}):null]})}let dS="cuelo-lounge-draft",dC=["\uD83D\uDC4D","❤️","\uD83D\uDE02","\uD83D\uDE2E","\uD83D\uDE4F","\uD83D\uDC40"],dT=Math.floor(1600),dI=[],dN=[];function dR(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 dM({lounge:e,visible:t=!0,onBack:n}){let{lt:s,locale:o}=V(),l=e.snapshot,c=l?.room??null,d=l?.run??null,u=l?.members??dI,p=l?.messages??dN,h=l?.loadError??null,m=(0,i.useMemo)(()=>new Map(u.map(e=>[e.id,e])),[u]),g=(0,i.useMemo)(()=>new Map(p.map(e=>[e.id,e])),[p]),f=(0,i.useCallback)(e=>{if("user"===e)return s("lounge.you");let t=m.get(e);return t?K(t.alias,o):e},[o,s,m]),x=(0,i.useMemo)(()=>u.flatMap(e=>[K(e.alias,"ko"),K(e.alias,"en")]),[u]),v=(0,i.useMemo)(()=>new Intl.DateTimeFormat(o,{hour:"2-digit",minute:"2-digit"}),[o]),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,T]=(0,i.useState)(null),I=(0,i.useRef)(null),N=(0,i.useRef)(null),R=(0,i.useRef)(!0),M=(0,i.useId)();(0,i.useEffect)(()=>{y(function(){try{return window.sessionStorage.getItem(dS)??""}catch{return""}}())},[]);let E=(0,i.useCallback)(e=>{y(e);try{e?window.sessionStorage.setItem(dS,e):window.sessionStorage.removeItem(dS)}catch{}},[]),$=e.streaming.map(e=>`${e.messageId}:${e.text.length}`).join("|");(0,i.useLayoutEffect)(()=>{let e=N.current;e&&t&&R.current&&(e.scrollTop=e.scrollHeight)},[p.length,$,t]),(0,i.useEffect)(()=>{let e=N.current;if(!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>{R.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||K(t.alias,"ko").toLowerCase().startsWith(e)||K(t.alias,"en").toLowerCase().startsWith(e)||t.id.startsWith(e))},[u,j]),A=c?.enabled===!0&&null===h&&null!==l,P=e.pending.has("send"),F=b.trim(),z=w?g.get(w)??null:null,W=e=>{if(!j)return;let t=K(e.alias,o),n=I.current,r=n?.selectionStart??b.length;E(`${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)})},D=async()=>{!A||P||!F||F.length>2e3||await e.send(F,z?.id)&&(E(""),k(null),R.current=!0)},O=d?.active?d.currentMemberId:null,B=e.streaming.some(e=>e.memberId===O),_=d?.active?d.queuedMemberIds.map(f):[],H=(t,n,i,a)=>{let o="user"===n,l=m.get(n),c=a.message,d=c?.replyToId?g.get(c.replyToId)??null:null;return(0,r.jsxs)("div",{id:c?`lounge-message-${c.id}`:void 0,className:"lounge-bubble-row","data-mine":o?"true":void 0,"data-grouped":a.grouped?"true":void 0,"data-streaming":a.streaming?"true":void 0,children:[o?null:(0,r.jsx)("span",{className:"lounge-bubble-face",children:a.grouped||!l?null:(0,r.jsx)(nR,{seed:l.seed,size:32,provider:l.provider})}),(0,r.jsxs)("div",{className:"lounge-bubble-stack",children:[o||a.grouped?null:(0,r.jsx)("span",{className:"lounge-bubble-name",children:f(n)}),(0,r.jsxs)("div",{className:"lounge-bubble-line",children:[(0,r.jsxs)("div",{className:"lounge-bubble",children:[c?.replyToId?(0,r.jsxs)("button",{type:"button",className:"lounge-bubble-quote",onClick:()=>{document.getElementById(`lounge-message-${c.replyToId}`)?.scrollIntoView({block:"center",behavior:"smooth"})},children:[(0,r.jsx)("span",{className:"lounge-bubble-quote-name",children:d?f(d.memberId):s("lounge.missingMessage")}),(0,r.jsx)("span",{className:"lounge-bubble-quote-text",children:d?d.text:""})]}):null,(0,r.jsx)("div",{className:"lounge-bubble-text",children:i})]}),void 0!==a.createdAt?(0,r.jsx)("time",{className:"lounge-bubble-time",dateTime:new Date(a.createdAt).toISOString(),children:v.format(new Date(a.createdAt))}):null]}),c?(0,r.jsxs)("div",{className:"lounge-bubble-foot",children:[c.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":s("lounge.reaction",{emoji:t.emoji,count:t.by.length}),title:t.by.map(f).join(", "),disabled:!A,onClick:()=>{e.react(c.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:!A,onClick:()=>{k(c.id),I.current?.focus()},children:s("lounge.reply")}),(0,r.jsx)("button",{type:"button",className:"lounge-bubble-action","aria-expanded":C===c.id,disabled:!A,onClick:()=>T(e=>e===c.id?null:c.id),children:s("lounge.react")})]}),C===c.id?(0,r.jsx)("span",{className:"lounge-reaction-picker",role:"group","aria-label":s("lounge.react"),children:dC.map(t=>(0,r.jsx)("button",{type:"button",onClick:()=>{T(null),e.react(c.id,t)},children:t},t))}):null]}):null]})]},t)},U=O?s("lounge.speaking",{name:f(O)}):null;return(0,r.jsxs)("section",{className:"lounge-view","aria-label":s("lounge.title"),hidden:!t,children:[(0,r.jsxs)("header",{className:"lounge-view-header",children:[n?(0,r.jsx)(a.r,{variant:"ghost",size:"small",className:"lounge-view-back",onClick:n,children:s("lounge.back")}):null,(0,r.jsxs)("div",{className:"lounge-view-heading",children:[(0,r.jsx)("h2",{className:"lounge-view-title",children:s("lounge.title")}),(0,r.jsx)("span",{className:"lounge-view-room","data-on":c?.enabled?"true":"false",children:c?.enabled?s("lounge.roomOn"):s("lounge.roomOff")})]}),(0,r.jsx)("ul",{className:"lounge-view-faces","aria-label":s("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)(nR,{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:`${f(e.id)} ${s(`lounge.state.${e.state}`)}`})]},e.id))})]}),e.loadError&&!l?(0,r.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:s("lounge.loadFailed",{error:e.loadError})}):null,h?(0,r.jsx)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:s("lounge.loadFailed",{error:h})}):null,"reconnecting"===e.connection&&l?(0,r.jsx)("p",{className:"lounge-banner",role:"status",children:s("lounge.reconnecting")}):null,e.actionError?(0,r.jsxs)("p",{className:"lounge-banner","data-tone":"danger",role:"alert",children:[(0,r.jsx)("span",{children:s("lounge.actionFailed",{error:e.actionError})}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:e.dismissActionError,"aria-label":"✕",children:"✕"})]}):null,!c||c.enabled||h?c?.asleep?(0,r.jsx)("p",{className:"lounge-banner",children:s("lounge.asleep")}):c?.autoTalk&&c.autoTalkPausedReason?(0,r.jsx)("p",{className:"lounge-banner",role:"status",children:c.autoTalkPausedReason}):null:(0,r.jsxs)("p",{className:"lounge-banner",children:[(0,r.jsx)("span",{children:s("lounge.roomOffBanner")}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",disabled:e.pending.has("settings"),onClick:()=>{e.updateSettings({enabled:!0})},children:s("lounge.turnOn")})]}),(0,r.jsxs)("div",{ref:N,className:"lounge-log",role:"log","aria-label":s("lounge.messages"),onScroll:e=>{let t=e.currentTarget;R.current=t.scrollHeight-t.scrollTop-t.clientHeight<80},children:[l&&0===p.length&&0===e.streaming.length?(0,r.jsx)("p",{className:"lounge-empty",children:s("lounge.empty")}):null,l||e.loadError?null:(0,r.jsx)("p",{className:"lounge-empty",children:s("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 H(e.id,e.memberId,dR(e.text,x),{message:e,createdAt:e.createdAt,grouped:r})}),e.streaming.map(e=>H(`stream-${e.messageId}`,e.memberId,(0,r.jsxs)(r.Fragment,{children:[dR(e.text,x),(0,r.jsx)("span",{className:"lounge-caret","aria-hidden":"true"})]}),{grouped:!1,streaming:!0})),O&&!B?H(`typing-${O}`,O,(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,_.length>0?(0,r.jsx)("span",{children:s("lounge.queued",{names:_.join(", ")})}):null]}),z?(0,r.jsxs)("div",{className:"lounge-reply-chip",children:[(0,r.jsxs)("span",{className:"lounge-reply-chip-text",children:[(0,r.jsx)("strong",{children:s("lounge.replyTo",{name:f(z.memberId)})}),(0,r.jsx)("span",{children:z.text})]}),(0,r.jsx)("button",{type:"button",className:"lounge-banner-action",onClick:()=>k(null),children:s("lounge.cancelReply")})]}):null,(0,r.jsxs)("div",{className:"lounge-composer-row",children:[j&&L.length>0?(0,r.jsx)("ul",{id:M,className:"lounge-mention-list",role:"listbox","aria-label":s("lounge.mentionList"),children:L.map((e,t)=>(0,r.jsxs)("li",{id:`${M}-${e.id}`,role:"option","aria-selected":t===j.index,onMouseDown:t=>{t.preventDefault(),W(e)},children:[(0,r.jsx)(nR,{seed:e.seed,size:20,provider:e.provider}),(0,r.jsx)("span",{children:K(e.alias,o)}),(0,r.jsx)("span",{className:"lounge-mention-state",children:s(`lounge.state.${e.state}`)})]},e.id))}):null,(0,r.jsx)("textarea",{ref:I,className:"lounge-composer-input",rows:1,value:b,maxLength:2e3,disabled:!A,placeholder:A?s("lounge.placeholder"):s("lounge.placeholderOff"),"aria-label":s("lounge.composer"),role:"combobox","aria-expanded":null!==j&&L.length>0,"aria-controls":M,"aria-autocomplete":"list","aria-activedescendant":j&&L[j.index]?`${M}-${L[j.index].id}`:void 0,onChange:e=>{var t;let n,r,i=e.target.value;E(i);let s=(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(s?{...s,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(),W(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(),D())}}}),d?.active?(0,r.jsxs)(a.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"})}),s("lounge.stop")]}):null,(0,r.jsx)(a.r,{variant:"neutralSolid",size:"small",className:"lounge-composer-button",disabled:!A||!F||F.length>2e3,loading:P,onClick:()=>{D()},children:s("lounge.send")})]}),b.length>=dT?(0,r.jsx)("span",{className:"lounge-composer-counter",children:s("lounge.textLimit",{count:b.length,max:2e3})}):null]})]})}let dE="git pull && bun install && bun run build && node Tools/CUELO_Setup/files/native-runtime-patch.js --target .";function d$(e){return"unknown"===e?e:`v${e}`}function dL(){let{locale:e,t}=(0,E.s)(),n=z(),[s,a]=(0,i.useState)(null),[o,l]=(0,i.useState)("idle"),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),g=(0,i.useRef)(null),f=(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=f.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=st(e.top,e.bottom,t,sn(t,.72,620),{margin:12,minHeight:0}),i=Math.min(430,window.innerWidth-24),s=Math.max(12,window.innerWidth-i-12);y({left:Math.min(e.right+8,s),width:i,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,i.useEffect)(()=>c?(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),[c,w]);let k=(0,i.useCallback)(async e=>{l("loading");try{let t=await fetch("/api/updates",{cache:"no-store",signal:e});if(!t.ok)return;let n=await t.json();a(n),l("ready")}catch{e?.aborted||l("ready")}},[]);if((0,i.useEffect)(()=>{let e=new AbortController;return k(e.signal),()=>e.abort()},[k]),(0,i.useEffect)(()=>()=>{clearTimeout(g.current??void 0),g.current=null},[]),(0,i.useEffect)(()=>{if(!c)return;let e=e=>{f.current?.contains(e.target)||x.current?.contains(e.target)||d(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),d(!1),v.current?.focus({preventScroll:!0}))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[c]),"ready"!==o||!s?.updateAvailable||!s.latestRelease)return null;let j=s.latestRelease,S=j.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(j.publishedAt)):null,C=j.body.trim()||j.name,T=async e=>{try{await tz(e),clearTimeout(g.current??void 0),m(e),g.current=setTimeout(()=>m(null),1600)}catch{p(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:f,"data-dismissible-layer":c?"":void 0,style:{position:"relative",width:"100%"},children:[(0,r.jsxs)("button",{ref:v,type:"button","aria-expanded":c,"aria-haspopup":"dialog",onClick:()=>{d(e=>!e),p(null)},title:t("updates.availableTitle",{version:d$(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:d$(j.version)})]}),c&&b&&(0,W.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:d$(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:d$(s.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)(tB,{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:dE}),(0,r.jsx)("button",{type:"button",onClick:()=>void T(dE),title:h===dE?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":h===dE?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===dE?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:h===dE?(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 dA="pi-web:last-open-by-workspace";function dP(){try{return window.localStorage}catch{return null}}function dF(e){let t=e.getItem(dA);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function dz(e,t=dP()){if(t)try{let n=dF(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(dA):t.setItem(dA,JSON.stringify(n))}catch{}}let dW="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",dD="omp-web:wide-chat";function dO(){try{return lG(window.localStorage)}catch{return lG(null)}}function dB({auxiliaryDeck:e,resourcePanel:t}={}){var n,p,m,g;let k,j,S,C,T,I,N,R,M,$,L,A,z,W,D,O,B,_,H=(0,s.useRouter)(),U=(0,s.useSearchParams)(),[q]=(0,i.useState)(()=>{let e;return{requestedCwd:e=U.get("cwd")?.trim()||null,sessionId:e?null:U.get("session")}}),{preference:V,toggleTheme:K}=tF(),{locale:J,setLocale:G,t:Y,supportedLocales:Z}=(0,E.s)(),X=function(){let[e,t]=(0,i.useState)(null),[n,r]=(0,i.useState)(!1),s=(0,i.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,i.useEffect)(()=>{try{r("1"===window.localStorage.getItem(lC))}catch{}return s(),window.addEventListener("focus",s),()=>window.removeEventListener("focus",s)},[s]),{permission:e,dismissed:n,request:(0,i.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,s)},[s]),dismiss:(0,i.useCallback)(()=>{r(!0);try{window.localStorage.setItem(lC,"1")}catch{}},[])}}(),Q=(0,i.useSyncExternalStore)(P.subscribe,P.getSnapshot,F);(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,s=.01>Math.abs(e.scale-1);i&&s&&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:ee,onSoundToggle:et,playCueSound:en,preloadCueSound:er,unlockAudio:es,soundEnabledRef:ea}=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),s=(0,i.useRef)(null),a=(0,i.useRef)(0),o=(0,i.useRef)(new Map),l=(0,i.useRef)(new Map),c=(0,i.useRef)(new Map),d=(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=dr(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),g=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),f=(0,i.useCallback)(()=>(d.current??=r7(),d.current),[]);(0,i.useEffect)(()=>{f()},[f]);let x=(0,i.useCallback)(async e=>{if(!e)return;let t=await f();for(let r of r1){let i=r3(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(()=>{})}}},[f,m]),v=(0,i.useCallback)(()=>{a.current+=1;let e=s.current;if(s.current=null,e)try{e.stop()}catch{}},[]),b=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=g();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[g]);(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=g();if(!t)return;v();let r=a.current,i=()=>{if(r===a.current&&n.current&&(!e||e()))try{dn(t)}catch{}};"suspended"===t.state?t.resume().then(i).catch(()=>{}):i()},[g,v]);return{soundEnabled:e,onSoundToggle:y,playCueSound:(0,i.useCallback)(async(e,t="done",r)=>{let i=await f(),d=null===t?null:r3(i,e,t),p=`${e??""}\u0000${t??""}`,h=d?r9(d.stickers,l.current.get(p)??null):null;null!==h&&l.current.set(p,h);let x=d?r9(d.voices,o.current.get(p)??null):null,b=x?d?.lines.get(x)??null:null;!x&&d&&null!==(b=r9(d.captions,c.current.get(p)??null))&&c.current.set(p,b);let y={sticker:h,text:b};if(!n.current||r&&!r())return y;let k=g();if(!k)return y;if(!x)return null!==t&&r8[t]||w(r),y;v();let j=a.current,S=()=>j!==a.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=()=>{s.current===n&&(s.current=null)},s.current=n,n.start(),o.current.set(p,x)}catch{if(S()||null!==t&&r8[t])return;try{dn(k)}catch{}}})(),y},[g,w,v,f,m]),preloadCueSound:x,unlockAudio:b,soundEnabledRef:n}}(),eo=function(){let[e,t]=(0,i.useState)({status:"idle",data:null,error:null}),[n,r]=(0,i.useState)(!0),[s,a]=(0,i.useState)(null),o=(0,i.useRef)(null),l=(0,i.useRef)(null),c=(0,i.useCallback)(()=>{l.current?.abort();let e=new AbortController;l.current=e,nh({signal:e.signal}).then(t=>{e.signal.aborted||a(t)})},[]);(0,i.useEffect)(()=>{var e;let n,i,s,a,d,u,p,h,m,g,f=(i=(e={onResult(e){t(e),r(!1)}}).intervalMs??6e4,s=e.setIntervalImpl??setInterval,a=e.clearIntervalImpl??clearInterval,d=e.initialData??null,u=null,p=0,h=!1,m=!1,g=async t=>{u?.abort(),u=new AbortController;let n=++p,r=await nu({refresh:t,previous:d,signal:u.signal,fetchImpl:e.fetchImpl});return h&&n===p&&(r.data&&(d=r.data),e.onResult(r)),r},{start(){h||(h=!0,g(!1),n=s(()=>{m||g(!1)},i))},refresh:()=>h?g(!0):Promise.resolve(na(d,new nr("사용량 폴링이 중지되었습니다.","aborted"))),setPaused(e){m=e},stop(){h=!1,p+=1,u?.abort(),u=null,a(n),n=void 0}});return o.current=f,f.start(),c(),()=>{f.stop(),l.current?.abort(),o.current===f&&(o.current=null)}},[c]);let d=(0,i.useCallback)(async()=>{let e=o.current;if(!e)return{status:"error",data:null,error:new nr("사용량 폴링이 시작되지 않았습니다.","aborted")};r(!0),c();let t=await e.refresh();return r(!1),t},[c]);return{state:e,loading:n,refresh:d,setPaused:(0,i.useCallback)(e=>{o.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}})(s),[s])}}();n=eo.state.data?.reports,(0,i.useEffect)(()=>{!function(e){let t=e??nv,n=t.map(e=>[e.provider,e.credentialId??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===ny)return;ny=n;let r=nn(t),i=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!nC(n))return;let s=nT(e.provider,n);i.has(s)||i.set(s,{seed:r[t].seed,alias:r[t].alias})}),nS({faces:i,pins:nb.pins})}(n)},[n]);let[el,ec]=(0,i.useState)(!1),[ed,eu]=(0,i.useState)(!1),ep=function(e=!0){let[t,n]=(0,i.useReducer)(dm,dp),[r,s]=(0,i.useState)("connecting"),[a,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,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,a=new AbortController;fetch(dg,{cache:"no-store",signal:a.signal}).then(async e=>{if(!e.ok)throw Error(await dx(e));let t=await e.json();r||(n({type:"snapshot",source:"get",data:t}),o(null))}).catch(e=>{r||a.signal.aborted||p.current||o(e instanceof Error?e.message:String(e))});let l=()=>{if(r)return;let e=new EventSource("/api/lounge/events");i=e,e.onopen=()=>{r||s("live")},e.onerror=()=>{r||(s("reconnecting"),e.readyState===EventSource.CLOSED&&(e.close(),t=window.setTimeout(l,3e3)))},e.addEventListener("snapshot",e=>{let t=df(e);t&&!r&&(n({type:"snapshot",source:"sse",data:t}),o(null),s("live"))}),e.addEventListener("state",e=>{let t=df(e);t&&!r&&n({type:"state",data:t})}),e.addEventListener("message",e=>{let t=df(e);t&&!r&&n({type:"message",data:t})}),e.addEventListener("delta",e=>{let t=df(e);t&&!r&&n({type:"delta",data:t})})};return l(),()=>{r=!0,a.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(dg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)return c(await dx(e)),!1;let r=await e.json();return r?.snapshot&&n({type:"snapshot",source:"post",data:r.snapshot}),c(null),!0}catch(e){return c(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]),g=(0,i.useCallback)((e,t)=>h(t?{action:"send",text:e,replyToId:t}:{action:"send",text:e}),[h]),f=(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)(()=>c(null),[]),b=(0,i.useMemo)(()=>[...t.streaming.values()],[t.streaming]);return{snapshot:t.snapshot,streaming:b,connection:r,loadError:a,actionError:l,pending:d,updateSettings:m,send:g,stop:f,react:x,dismissActionError:v}}(ed),eh=(0,i.useRef)(new Set),em=(0,i.useCallback)(()=>{ea.current&&en(null,"done")},[en,ea]),[eg,ef]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(null),[eb,ey]=(0,i.useState)(null),ew=(0,i.useRef)(0),ek=(0,i.useRef)(null),[ej,eS]=(0,i.useState)(null),eC=(0,i.useRef)(0),eT=(0,i.useCallback)(e=>{eS(t=>t?.id===e?null:t)},[]),[eI,eN]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{eN("1"===window.localStorage.getItem(dD))}catch{}},[]);let eR=(0,i.useCallback)(()=>{eN(e=>{let t=!e;try{window.localStorage.setItem(dD,t?"1":"0")}catch{}return t})},[]),[eM,eE]=(0,i.useState)(null),[e$,eL]=(0,i.useState)(()=>q.requestedCwd?"validating":"idle"),[eA,eP]=(0,i.useState)(null),[eF,ez]=(0,i.useState)(0),[eW,eD]=(0,i.useState)(0),[eO,eB]=(0,i.useState)(0),[e_,eH]=(0,i.useState)(0),[eU,eq]=(0,i.useState)(!1),[eV,eK]=(0,i.useState)(null),[eJ,eG]=(0,i.useState)(0),eY=(0,i.useRef)(null),eZ=(0,i.useRef)(null),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(!1),[e2,e8]=(0,i.useState)(null),[e4,e5]=(0,i.useReducer)(f,h),[e6,e3]=(0,i.useState)("characters"),[e9,te]=(0,i.useState)("governor"),[tt,tn]=(0,i.useState)(()=>x(0)),[tr]=(0,i.useState)(dO),[ti]=(0,i.useState)(lY),[ts,ta]=(0,i.useState)([]),[to,tl]=(0,i.useState)({sessions:[],complete:!1}),[tc,td]=(0,i.useState)(!1),[tu,tp]=(0,i.useState)(!1),[th,tm]=(0,i.useState)(0),tg=(0,i.useRef)(null),tf=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useCallback)(()=>{tm(e=>e+1)},[]),tb=(0,i.useCallback)(e=>{e&&eu(!0),ec(e),e||tv()},[tv]),ty=(0,i.useCallback)(e=>{tf.current=e},[]),tw=(0,i.useRef)(!1),[tk,tj]=(0,i.useState)(!1),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(!1),tT=(0,i.useRef)(0),[tI,tN]=(0,i.useState)(!1),[tR,tM]=(0,i.useState)(!1),tE=(0,i.useRef)(null),[t$,tL]=(0,i.useState)(null),[tA,tP]=(0,i.useState)(null),tW=(0,i.useRef)(null),tD=(0,i.useRef)(!1);tW.current=t$,(0,i.useEffect)(()=>{tL(sG())},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||tw.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=iX();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:sJ(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(sH,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:eg?.id??null,resumeUrl:r});if(i.entered){tw.current=!0;return}t=i.error},r=async()=>{if(!e&&!tw.current)try{let i=tD.current?null:tW.current,s=await sZ({sessionId:eg?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:i?{requestId:i.requestId,stageHash:i.stageHash}:null});tT.current=0;let a=!!(s.serverBootId&&tE.current&&s.serverBootId!==tE.current);if(tS.current||a){var r=eg?.id??null;iX();try{sessionStorage.setItem(sq,JSON.stringify({schemaVersion:1,sessionId:r,at:Date.now()}))}catch{}window.location.reload();return}s.serverBootId&&(tE.current=s.serverBootId),tC.current=!0,!e&&s.update&&(tP(s.update),s.update.cleanup&&"running"!==s.update.cleanup.status&&(tD.current=!0)),n(s)}catch{tT.current+=1,!e&&tC.current&&tT.current>=2&&(tS.current=!0,tj(!0))}},i=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",i),r();let s=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(s),window.removeEventListener("ompweb:update-maintenance",i)}},[eg?.id]),(0,i.useEffect)(()=>{if(!tk)return;let e=window.setTimeout(()=>tN(!0),12e4);return()=>window.clearTimeout(e)},[tk]),(0,i.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(sq);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(sq),!1):n.sessionId===e&&(sessionStorage.removeItem(sq),!0)})(eg?.id??null)&&tM(!0)},[eg?.id]),(0,i.useEffect)(()=>{if(!tR)return;let e=window.setTimeout(()=>tM(!1),8e3);return()=>window.clearTimeout(e)},[tR]);let tO=t$?.requestId??null,tB=t$?.dismissed??!0,t_=tA?.requestId??null,tH=tA?.deploymentCompleted??!1,tU=tA?.cleanup?.status??null;(0,i.useEffect)(()=>{if(!tO||tB||t_!==tO||!tH)return;let e=sK(tU);if(null===e)return;let t=window.setTimeout(()=>{tL(sY(tO))},e);return()=>window.clearTimeout(t)},[tO,tB,t_,tH,tU]),(0,i.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(sH);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&&eg?.id!==e.sessionId)return;let t=!1;return sX(e).then(()=>{t||(tD.current=!1,tL(sG()),ez(e=>e+1),eB(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[eg?.id]);let tq=(0,i.useCallback)(e=>{if("Tab"!==e.key)return;let t=tx.current;if(!t)return;let n=Array.from(t.querySelectorAll(dW));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())},[]),[tV,tK]=(0,i.useState)(!0),[tJ,tG]=(0,i.useState)(!1),[tY,tZ]=(0,i.useState)(!1),tX=(0,i.useRef)(tV),tQ=(0,i.useRef)(!1),t0=(0,i.useRef)(!0),t1=(0,i.useRef)(null);tX.current=tV;let t2=(k=(p={clientPainted:tJ,compactWorkspace:Q,requestedOpen:tV}).requestedOpen&&p.clientPainted,{laidOut:p.requestedOpen&&(!p.compactWorkspace||p.clientPainted),presented:k,drawer:k&&p.compactWorkspace}),t8=(0,i.useCallback)(e=>{tQ.current=e,tK(e),e5(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),t4=(0,i.useRef)(null),t5=(0,i.useRef)(!1),t6=(0,i.useRef)(260),t3=(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}),[]),t7=function(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:s,getMaxWidth:a,growthDirection:o,maxWidth:l,minWidth:c,storageKey:d,widthRef:u}=e,p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(!1),[g,f]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),b=(0,i.useCallback)(()=>Math.min(l,Math.max(c,a())),[a,l,c]),y=(0,i.useCallback)(e=>{var t;let n,r;return t=b(),n=Number.isFinite(e)?e:c,r=Math.max(c,t),Math.round(Math.max(c,Math.min(r,n)))},[b,c]),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),s=i!==u.current;return w(i),f(i),r&&(s||n)&&dt(d,i),i},[w,y,d,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]),T=(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"===o?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,o]),I=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),N=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),R=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,i.useCallback)(()=>{k(s?.()??r,{forcePersist:!0})},[k,r,s]),E=(0,i.useCallback)(()=>{k(u.current)},[k,u]),$=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===o?"ArrowRight":"ArrowLeft",r="right"===o?"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(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),k(b(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),M())},[k,b,o,c,M,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}}(d),t=k(e??s?.()??r,{persist:!1});null!==e&&e!==t&&dt(d,t)},[k,r,s,d]),(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:E,resetWidth:M,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":b(),"aria-valuemin":c,"aria-valuenow":g,"aria-valuetext":`${g} px`,onDoubleClick:M,onKeyDown:$,onLostPointerCapture:R,onPointerCancel:N,onPointerDown:C,onPointerMove:T,onPointerUp:I,role:"separator",tabIndex:0},width:g}}({ariaLabel:Y("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:t3,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:t6}),t9=t7.reclampWidth;(0,i.useEffect)(()=>{let e=t1.current;if(e===Q)return;tZ(!0),null!==e&&(e?tQ.current=tX.current:t0.current=tX.current),t1.current=Q;let t=Q?tQ.current:t0.current;Q?t8(t):tK(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>tZ(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[Q,t8]),(0,i.useEffect)(()=>{tG(!0)},[]),(0,i.useEffect)(()=>{let e=t5.current;if(t5.current=t2.drawer,t2.drawer){let e=t7.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(dW)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||t4.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[t2.drawer,t7.panelRef]),(0,i.useEffect)(()=>{t9()},[t9,e4.activeView]),(0,i.useEffect)(()=>{let e=tg.current;if(!e)return;let t=e=>{tn(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(!th)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>tf.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[th]),(0,i.useEffect)(()=>{if("command-palette"!==e4.transientLayer)return;let e=tx.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(dW)?.focus()});return()=>cancelAnimationFrame(t)},[e4.transientLayer]),(0,i.useEffect)(()=>{Q||"navigator-drawer"!==e4.transientLayer||e5({type:"close-layer"})},[Q,e4.transientLayer]),(0,i.useEffect)(()=>{let e=new AbortController;return tl(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");ta(t.sessions),tl({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()},[eF,eg?.id]);let ne=(0,i.useRef)(null),nt=(0,i.useRef)(null),[ni,ns]=(0,i.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),no=(0,i.useRef)(null),nl=(0,i.useCallback)((e,t,n)=>{no.current=n,ns(n=>{let r=n$.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),nc=(0,i.useCallback)(e=>{ns(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),no.current?.(e)},[]),[nd,np]=(0,i.useState)(null),nm=(0,i.useCallback)(e=>{np(e)},[]),[ng,nf]=(0,i.useState)(null),[nx,nw]=(0,i.useState)([]),[nk,nj]=(0,i.useState)(null),[nI,nN]=(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,s="number"==typeof i?i:"string"==typeof i?Number.parseInt(i,10):NaN;!e.signal.aborted&&Number.isFinite(s)&&s>0&&nj(s)}).catch(()=>{}),()=>e.abort()},[]);let[nR,nM]=(0,i.useState)({kind:"idle"}),nE=(0,i.useRef)(null),n$=(0,i.useRef)(eg?.id??null);n$.current=eg?.id??null;let nL=(0,i.useCallback)(e=>{nf(e)},[]),[nA,nP]=(0,i.useState)(null),nF=(0,i.useRef)(null),nz=(0,i.useCallback)((e,t)=>{tz(t).then(()=>{nF.current&&clearTimeout(nF.current),nP(e),nF.current=setTimeout(()=>nP(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nF.current&&clearTimeout(nF.current),nE.current&&clearTimeout(nE.current)},[]),(0,i.useEffect)(()=>()=>ek.current?.abort(),[]);let[nW,nD]=(0,i.useState)(null),nO=(0,i.useCallback)(e=>{nD(e)},[]),[nB,n_]=(0,i.useState)(null),[nH,nU]=(0,i.useState)(null),[nq,nV]=(0,i.useState)(null),[nK,nJ]=(0,i.useState)(!1),[nG,nY]=(0,i.useState)("subagents"),nZ=(0,i.useCallback)((e,t=!1)=>{e5({type:"select-view",view:e}),nU(null),Q&&t8(!1),(t||"chat"===e)&&tv()},[Q,tv,t8]),nX=(0,i.useCallback)(e=>{let t=e4.transientLayer===e;nU(null),Q&&"navigator-drawer"===e4.transientLayer&&t8(!1),e5({type:"toggle-layer",layer:e}),t&&tv()},[Q,tv,t8,e4.transientLayer]),nQ=(0,i.useCallback)(()=>{if("chat"!==e4.activeView){nY(e4.activeView),nZ("chat",!0);return}nZ(nG,!0)},[nG,nZ,e4.activeView]),n0=(0,i.useCallback)(()=>eX?(e0||(eQ(!1),tv()),!0):eU?(eq(!1),tv(),!0):nK?(nJ(!1),tv(),!0):nH?(nU(null),tv(),!0):e4.transientLayer?("navigator-drawer"===e4.transientLayer&&t8(!1),e5({type:"close-layer"}),tv(),!0):"chat"!==e4.activeView&&(e5({type:"select-view",view:"chat"}),tv(),!0),[nK,nH,e0,eX,tv,t8,eU,e4.activeView,e4.transientLayer]),n1=(0,i.useCallback)(e=>{e5({type:"close-layer"}),Q&&t8(!1),nU(t=>t===e?null:e)},[Q,t8]),n2=(0,i.useCallback)(()=>{e5({type:"close-layer"}),Q&&t8(!1),nU("session")},[Q,t8]),n8=(0,i.useCallback)(()=>{if(nU(null),Q){let e="navigator-drawer"!==e4.transientLayer;t8(e),e||tv();return}e5({type:"close-layer"}),tK(e=>{let t=!e;return t0.current=t,t})},[Q,tv,t8,e4.transientLayer]);(0,i.useEffect)(()=>{if(!nH||!nt.current)return;let e=()=>{let e=nt.current.getBoundingClientRect();nV({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(nt.current),()=>t.disconnect()},[nH]);let[n4,n5]=(0,i.useState)([]),[n6,n3]=(0,i.useState)(null),n7=(0,i.useCallback)(()=>{"view-stack"===tt.deck&&e5({type:"select-view",view:"chat"}),Q&&t8(!1),tv()},[Q,tt.deck,tv,t8]),n9=(0,i.useCallback)((e,t)=>{let n;ne.current?.insertText((n=t?`${e}/`:e).includes(" ")?`@"${n}" `:`@${n} `),n7()},[n7]),re=(0,i.useCallback)((e,t,n)=>{let r,i,s,a;ne.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),s=e.includes(" ")?`@"${e}"`:`@${e}`,a=r===i?`:${r}`:`:${r}-${i}`,`${s}${a} `)),n7()},[n7]),rt=q.sessionId,[rn,rr]=(0,i.useState)(null);tF({cwd:eg?.cwd??eM??rn,syncWithOmp:!0});let ri=(0,i.useRef)(null),[rs,ra]=(0,i.useState)(()=>!rt),ro=(0,i.useRef)(!1),rl=(0,i.useRef)(0),rc=(0,i.useCallback)(()=>{rl.current+=1},[]);(0,i.useEffect)(()=>{eg&&function(e,t,n=dP()){if(n)try{let r=dF(n);r[e]=t,n.setItem(dA,JSON.stringify(r))}catch{}}(eg.projectRoot??ri.current??eg.cwd,eg.id)},[eg]),(0,i.useEffect)(()=>{let e=q.requestedCwd;if(!e)return;let t=new AbortController;return eL("validating"),eP(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}`);ro.current=!0,eE(t.cwd),eL("ready")}).catch(e=>{t.signal.aborted||(eP(e instanceof Error?e.message:String(e)),eL("error"))}),()=>t.abort()},[q]);let rd=(0,i.useCallback)(e=>{let t=++rl.current,n=function(e,t=dP()){if(!t)return null;try{let n=dF(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!==rl.current)return;let i=r?.sessions.find(e=>e.id===n);if(!i){r&&dz(e);return}(i.projectRoot??i.cwd)!==e?dz(e):(ef(i),eD(e=>e+1),new URLSearchParams(window.location.search).get("session")!==i.id&&H.replace(`?session=${encodeURIComponent(i.id)}`,{scroll:!1}))}).catch(()=>{})},[H]),ru=(0,i.useCallback)((e,t)=>{if(rc(),rr(e),!e)return;let n=t??e,r=ri.current??(eg?eg.projectRoot??eg.cwd:null);if(ri.current=n,ro.current){ro.current=!1;return}r!==n&&(ew.current+=1,ek.current?.abort(),ek.current=null,ev(null),ey(null),ef(null),eE(t=>t&&t!==e?null:t),eD(e=>e+1),ns({sessionId:null,tree:[],leafId:null,navigation:0}),np(null),nU(null),n5([]),n3(null),e5({type:"select-view",view:"chat"}),rd(n),H.replace("/",{scroll:!1}))},[H,eg,rc,rd]),rp=(0,i.useCallback)((e,t,n)=>{eE(null),ey(n),ef(e),ns({sessionId:e.id,tree:[],leafId:null,navigation:0}),eD(e=>e+1),np(null),ra(!0),Q&&!t&&(t8(!1),e5({type:"select-view",view:"chat"})),t&&(ro.current=!0),t||H.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[Q,H,t8]),rh=(0,i.useCallback)((e,t=!1)=>{if(ri.current=e.projectRoot??e.cwd,rc(),!t&&eg){let t=(eg.projectRoot??eg.cwd)===(e.projectRoot??e.cwd);if(eg.id===e.id&&t){ew.current+=1,ek.current?.abort(),ek.current=null,ev(null),Q&&t8(!1);return}}if(!t&&ex?.id===e.id)return;ew.current+=1;let n=ew.current;if(ek.current?.abort(),t||!eg){ek.current=null,ev(null),rp(e,t,null);return}let r=new AbortController;ek.current=r,ev(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");ew.current===n&&rp(e,!1,r)}).catch(t=>{r.signal.aborted||ew.current!==n||(console.error("Failed to preload session before switching:",t),rp(e,!1,null))}).finally(()=>{ew.current===n&&(ek.current=null,ev(null))})},[rp,rc,Q,ex?.id,eg,t8]),rm=(0,i.useCallback)((e,t)=>{ew.current+=1,ek.current?.abort(),ek.current=null,ev(null),ey(null),rc(),ef(null),eE(t),eD(e=>e+1),ns({sessionId:null,tree:[],leafId:null,navigation:0}),np(null),nU(null),e5({type:"select-view",view:"chat"}),Q&&t8(!1),H.replace("/",{scroll:!1})},[rc,Q,H,t8]),rg=(0,i.useCallback)(e=>{let t=eg?.projectRoot??ri.current??eg?.cwd??rn;if(!t||!eg)return;let n=ts.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===eg.id);if(r<0)return;let i=n[r+e];i&&(nU(null),e5({type:"close-layer"}),rh(i),tv())},[rn,ts,rh,tv,eg]);m={onNewSession:e=>rm(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>nX("command-palette"),onToggleNavigator:n8,onToggleResources:()=>nZ("resource"===e4.activeView?"chat":"resource",!0),onSelectView:e=>nZ(e,!0),onCycleView:(0,i.useCallback)(e=>{let t=(d.indexOf(e4.activeView)+e+d.length)%d.length;nZ(d[t],!0)},[nZ,e4.activeView]),onNavigateSession:rg,onEscape:n0,enabled:!eU&&!eX,activeCwd:rn},(j=(0,i.useRef)(m)).current=m,(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,s=!!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()):!(s||i?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(i?.closest("[data-capture-keys]")||!1===t.enabled)return;let a=e.key.toLowerCase(),o=(e.ctrlKey||e.metaKey)&&!e.altKey;if(o&&!e.shiftKey&&"k"===a)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(o&&!e.shiftKey&&"b"===a)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(o&&!e.shiftKey&&"u"===a)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(o&&!e.shiftKey&&/^[1-7]$/.test(a)){if(!t.onSelectView)return;let n=d[Number(a)-1];return n&&(e.preventDefault(),t.onSelectView(n))}o&&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"===a&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,j.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 rf=(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&&ef(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),rx=(0,i.useCallback)(e=>{rc(),eE(null),ef(e),ez(e=>e+1),rf(e.id),H.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[rc,H,rf]),rv=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&sD({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&rh(e)}})},[rh]),rb=(0,i.useCallback)(e=>{ez(e=>e+1),eY.current?.pending&&eG(e=>e+1),eB(e=>e+1),eg&&rf(eg.id),"completed"===e.outcome&&sz()&&rv({targetSession:eg,title:eg?.name??Y("i18n.sessionComplete"),body:Y("i18n.taskFinished")})},[rv,rf,eg,Y]),ry=(0,i.useCallback)(e=>{var t;sz()&&(t=eh.current,!(!sW(e)||t.has(e.id))&&(t.add(e.id),1)&&rv({targetSession:eg,title:Y("i18n.attentionNeeded"),body:"custom"===e.method?Y("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rv,eg,Y]),rw=(0,i.useCallback)(async()=>{let e=eg?.id;if(e&&"naming"!==nR.kind){nE.current&&clearTimeout(nE.current),nU(null),nM({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(ez(e=>e+1),n$.current!==e)return;ef(t=>t?.id===e?{...t,name:r}:t),nf(t=>t?.sessionId===e?{...t,sessionName:r}:t),nM({kind:"success"}),nE.current=setTimeout(()=>nM({kind:"idle"}),1800)}catch(t){if(n$.current!==e)return;nM({kind:"error",message:t instanceof Error?t.message:String(t)}),nE.current=setTimeout(()=>nM({kind:"idle"}),5e3)}}},[nR.kind,eg?.id]);(0,i.useEffect)(()=>{nE.current&&clearTimeout(nE.current),nM({kind:"idle"})},[eg?.id]);let rk=(0,i.useCallback)(e=>{rc(),ez(e=>e+1),eD(e=>e+1),eE(null),ef(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),rf(e),H.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[rc,H,rf]),rj=(0,i.useCallback)(()=>{ra(!0)},[]),rS=(0,i.useCallback)(e=>{if(rc(),ez(e=>e+1),eg?.id===e){let e=eg.cwd;ef(null),eE(e??null),eD(e=>e+1),ns({sessionId:null,tree:[],leafId:null,navigation:0}),np(null),nU(null),e5({type:"select-view",view:"chat"}),tv(),H.replace("/",{scroll:!1})}},[rc,tv,eg,H]),rC=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=`file:${e}`;n5(n=>{let a=n.find(e=>e.id===s);if(!a)return[...n,{id:s,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:i}];let o=!r||a.sourceSessionId===r,l=!i||a.initialDisplayMode===i;return o&&l?n:n.map(e=>{if(e.id!==s)return e;let t={...e};return r&&(t.sourceSessionId=r),i&&(t.initialDisplayMode=i),t})}),n3(s),e5({type:"select-view",view:"files"}),nU(null),Q&&t8(!1)},[Q,t8]),rT=(0,i.useCallback)(e=>{rC(e,e7(e),{sourceSessionId:eg?.id??null})},[rC,eg?.id]),rI=(0,i.useCallback)(e=>{let t=n4.filter(t=>t.id!==e);n5(t),n3(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===e4.activeView&&nZ("chat",!0)},[n4,nZ,e4.activeView]),rN=(0,i.useCallback)(()=>{eg&&window.open(`/api/sessions/${encodeURIComponent(eg.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[eg]),rR=eM??(null===eg&&rn?rn:null),rM=null!==eg||null!==rR,rE="chat"!==e4.activeView,r$=eg?.cwd??rR,rL=rs&&!rM,rA=(0,i.useCallback)((e,t)=>{eY.current=e,eK(e),e8(e.error?Y("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&eQ(!1),eH(e=>e+1),eD(e=>e+1))},[Y]);(0,i.useEffect)(()=>{let e=eZ.current!==r$;if(eZ.current=r$,e&&(eY.current=null,eK(null),eQ(!1),e8(null)),!r$)return;let t=eY.current,n=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(r$)}`,{signal:n.signal}).then(async e=>{let n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);rA(n,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>n.abort()},[rA,r$,eJ]);let rP=(0,i.useCallback)(async e=>{if(r$&&!e0){e1(!0),e8(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r$,action:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let r=eY.current;rA(n,r),(n.trusted||"cancel"===e)&&(eQ(!1),tv())}catch(e){e8(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[rA,e0,r$,tv]),rF=n4.find(e=>e.id===n6)??null,rz=rn?e7(rn)||rn:null,rW=(eg?.name?.trim()||eg?.firstMessage?.trim()||(rR?Y("i18n.newSession"):rz)||"CUELO").replace(/\s+/g," ").trim(),rD=rW.length>96?`${rW.slice(0,93)}…`:rW,rO=rz?`${rD} — ${rz} — CUELO`:`${rD} — CUELO`,rB=rz?`${rW} — ${rz}`:rW,r_=eg?.transient?`${rB} \xb7 ${Y("session.inMemory")}`:rB,rH=nx.filter(e=>"pending"===e.status||"running"===e.status).length,rU=nI?Y("workspace.mainAttention"):tu?Y("workspace.mainWaiting"):tc?Y("workspace.mainWorking"):Y("workspace.mainIdle"),rq=`${nI?"⚠":tu?"○":tc?"●":"○"} Main ${rU} \xb7 Sub ${rH}${nk?`/${nk}`:""}`;(0,i.useEffect)(()=>{let e=()=>{document.title!==rO&&(document.title=rO)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rO]);let rV="ko"===J?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat"},rK="chat"!==e4.activeView,rJ=rK?rV[e4.activeView]:rV[nG],rG=(S=nW&&Number.isFinite(nW.contextWindow)&&nW.contextWindow>0?nW.contextWindow:null,C=nW&&"number"==typeof nW.tokens&&Number.isFinite(nW.tokens)?Math.max(0,nW.tokens):null,I=null===(T=nW&&"number"==typeof nW.percent&&Number.isFinite(nW.percent)?nW.percent:null!==C&&null!==S?C/S*100:null)?"normal":T>90?"critical":T>70?"warning":"normal",N=null===C?"?":de(C),R=null===S?"?":de(S),M=null===T?"?":`${T.toFixed(0)}%`,{level:I,percent:T,fillPercent:null===T?0:Math.min(100,Math.max(0,T)),readout:null===S?null:`${M} \xb7 ${N}/${R}`,usedLabel:N,limitLabel:R,percentLabel:M}),rY=rG.readout,rZ=rY?Y("chat.contextUsageTitle",{used:rG.usedLabel,limit:rG.limitLabel,percent:rG.percentLabel}):null,rX="critical"===rG.level?Y("chat.contextUsageCritical"):"warning"===rG.level?Y("chat.contextUsageWarning"):null,rQ=(g=ng?.userMessages,!eg||eg.transient?"unsaved":("number"==typeof g?g:0)>0||eg.messageCount>0?null:"no-messages"),r0="unsaved"===rQ?Y("title.unsaved"):"no-messages"===rQ?Y("title.noMessages"):null,r2=r0??("error"===nR.kind?nR.message:null),r4="naming"===nR.kind?Y("title.generating"):"success"===nR.kind?Y("title.updated"):"error"===nR.kind?Y("title.failed"):Y("title.generate"),r5=(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)(aq,{tabs:n4,activeTabId:n6??"",onSelectTab:n3,onCloseTab:rI})}),(0,r.jsx)("div",{className:"workspace-file-content",children:rF?.filePath?(0,r.jsx)(aH,{filePath:rF.filePath,cwd:rn??void 0,sourceSessionId:rF.sourceSessionId,gitRefreshKey:eO,initialDisplayMode:rF.initialDisplayMode,onMentionLines:re,onAtMention:n9,onOpenFile:e=>rC(e,e7(e),{sourceSessionId:rF.sourceSessionId})}):(0,r.jsx)("div",{className:"workspace-file-empty",children:Y("files.noneOpen")})})]}),r6=(0,r.jsx)(cy,{open:"resource"===e4.activeView,sessionId:eg?.id??null,activeTab:e6,onTabChange:e3,usage:eo}),ie=(0,r.jsx)(c5,{open:"efficiency"===e4.activeView,sessionId:eg?.id??null,activeTab:e9,onTabChange:te}),it=(0,r.jsx)(lB,{title:rV.process,data:nB,onOpenFile:rT}),ir=eg?eg.path?eg.path:ng?.sessionId===eg.id&&ng.sessionFile?ng.sessionFile:null:null,ii=(0,r.jsx)(l5,{title:rV.sidechat,sessionId:eg?.id??null,sessionPath:ir,sessionName:eg?.name,historyStore:tr,flights:ti,sessionCensus:to,visible:"sidechat"===e4.activeView}),is=rE?(0,r.jsx)(lO,{activeView:e4.activeView,onViewChange:e=>nZ(e),viewLabels:rV,sessionId:eg?.id??null,sessionPath:ir,sessionName:eg?.name,sessionCwd:eg?.cwd??rR??void 0,liveSubagents:nx,processSlot:it,fileSlot:r5,sideChatSlot:ii,resourceSlot:t??r6,efficiencySlot:ie,visible:!0,onClose:()=>e5({type:"select-view",view:"chat"}),onReturnFocus:tv}):null,ia=e??is,io=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ei,{selectedSessionId:ex?.id??eg?.id??null,optimisticSession:ex??eg,onSelectSession:rh,onNewSession:rm,initialSessionId:rt,skipInitialProjectSelection:null!==q.requestedCwd,onInitialRestoreDone:rj,refreshKey:eF,onSessionDeleted:rS,selectedCwd:eg?.cwd??eM??null,onCwdChange:ru,onBackgroundTaskDone:em,loungePanel:(0,r.jsx)(dj,{lounge:ep,usage:eo,loungeOpen:el,onOpenLounge:Q?()=>t8(!1):void 0}),loungeActive:el,onLoungeActiveChange:tb}),(0,r.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[el?null:(0,r.jsx)(du,{usage:eo,onOpen:()=>{e3("usage"),nZ("resource",!1)}}),(0,r.jsx)(dL,{}),(0,r.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{nU(null),e5({type:"close-layer"}),Q&&t8(!1),eq(!0)},title:Y("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"})]}),Y("common.settings")]})]})]}),il=t$&&tA&&tA.requestId===t$.requestId&&tA.deploymentCompleted?tA:null,ic=il?.cleanup??null,id=il&&!t$?.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:sK(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:sK(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sK(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:sK(e.status)}}(ic):null;return(0,r.jsxs)(r.Fragment,{children:[tk?(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:Y("restart.title")}),(0,r.jsx)("span",{children:Y(tI?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:tg,className:"workspace-shell","data-active-view":e4.activeView,"data-deck-mode":tt.deck,"data-deck-visible":rE,"data-chat-wide":eI?"true":void 0,children:[(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${t2.drawer?" is-open":""}${tJ?"":" sidebar-mobile-pending"}${tY?" sidebar-mode-shift":""}`,onClick:()=>{t8(!1),tv()}}),(0,r.jsx)("div",{ref:t7.panelRef,id:"session-sidebar",className:`sidebar-container${t2.laidOut?" sidebar-open":" sidebar-closed"}${tJ?"":" sidebar-mobile-pending"}${tY?" sidebar-mode-shift":""}${t7.isResizing?" sidebar-resizing":""}`,"aria-hidden":Q&&!t2.presented,inert:Q&&!t2.presented,style:{"--sidebar-width":`${t7.width}px`},children:io}),t2.laidOut&&(0,r.jsx)("div",{...t7.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${t7.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${Y("layout.resizeSidebar")}: ${Y("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":e4.activeView,"aria-hidden":t2.drawer,inert:t2.drawer,children:[(0,r.jsxs)("div",{ref:nt,className:"workspace-header-stack",children:[id&&t$&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":id.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:id.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:id.detail}),id.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tL(sY(t$.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tR&&!(id&&t$)&&(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:Y("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:Y("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tM(!1),"aria-label":Y("restart.returnedDismiss"),children:Y("i18n.close")})]}),(0,r.jsx)(lT,{variant:"banner",locale:J,...X}),(0,r.jsxs)("header",{className:"workspace-header-seam",children:[(0,r.jsx)(a.r,{ref:t4,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:n8,"aria-controls":"session-sidebar","aria-expanded":t2.presented,title:t2.presented?Y("sidebar.hide"):Y("sidebar.show"),"aria-label":t2.presented?Y("sidebar.hide"):Y("sidebar.show"),children:t2.presented?(0,r.jsx)(o.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)(o.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:r_,children:[(0,r.jsx)("strong",{children:rD}),(0,r.jsx)("span",{"aria-live":"polite",children:rq})]}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===nR.kind?nR.message:""}),rM&&eV?.requiresTrust&&!eV.trusted&&(0,r.jsxs)(a.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{e8(eV.error?Y("trust.applyFailed",{error:eV.error}):null),nU(null),e5({type:"close-layer"}),eQ(!0),eV.pending&&eG(e=>e+1)},title:Y("grant"===eV.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":Y("grant"===eV.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"})]}),!Q&&(0,r.jsx)("span",{children:Y("trust.resourcesNotLoaded")})]}),rM&&rY&&(0,r.jsxs)(a.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:n2,"aria-expanded":"session"===nH,title:rZ??Y("session.title"),"aria-label":rX?`${rZ}. ${rX}`:rZ??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":rG.level,style:{inlineSize:`${rG.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":rG.level,children:rY})]}),rM&&(0,r.jsx)(l.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:rK,onPressedChange:nQ,"aria-controls":"workspace-auxiliary-panel",title:"ko"===J?"보조 패널":"Auxiliary panel",children:rJ}),(0,r.jsxs)(c.k.Root,{open:nK,onOpenChange:e=>nJ(e),placement:"bottom-end",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(a.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===J?"더 보기":"More","aria-label":"ko"===J?"더 보기":"More",children:(0,r.jsx)(o.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)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":"ko"===J?"세션 및 환경 메뉴":"Session and environment menu",children:(0,r.jsxs)(c.k.ScrollArea,{children:[(0,r.jsxs)(c.k.Group,{children:[(0,r.jsx)(c.k.GroupLabel,{children:"ko"===J?"세션":"Session"}),(0,r.jsx)(c.k.Item,{onClick:n2,children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:Y("session.title")})})}),(0,r.jsx)(c.k.Item,{onClick:rN,disabled:!eg,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:Y("history.label")}),!eg&&(0,r.jsx)(c.k.ItemDescription,{children:Y("history.unsaved")})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>void rw(),disabled:null!==r0||"naming"===nR.kind,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:r4}),r2&&(0,r.jsx)(c.k.ItemDescription,{children:r2})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>n1("branches"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:Y("i18n.branches")})})}),(0,r.jsx)(c.k.Item,{onClick:()=>n1("system"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:Y("system.label")})})})]}),(0,r.jsxs)(c.k.Group,{children:[(0,r.jsx)(c.k.GroupLabel,{children:"ko"===J?"환경":"Environment"}),(0,r.jsx)(lT,{variant:"menu",locale:J,...X}),(0,r.jsx)(c.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();K({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:Y("light"===V?"theme.light":"dark"===V?"theme.dark":"theme.auto")})})}),Z.map(e=>(0,r.jsx)(c.k.Item,{role:"menuitemradio","aria-checked":J===e.id,onClick:()=>G(e.id),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id)),(0,r.jsx)(c.k.Item,{onClick:()=>{nU(null),e5({type:"close-layer"}),Q&&t8(!1),eq(!0)},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:Y("common.settings")})})})]})]})})})]})]}),nH&&nq&&(0,r.jsxs)("div",{style:{position:"fixed",top:nq.top,left:nq.left,width:nq.width,maxHeight:`calc(100dvh - ${nq.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===nH&&(0,r.jsx)("div",{className:"workspace-top-panel","aria-label":Y("i18n.branches"),children:(0,r.jsx)(c9,{tree:ni.sessionId===(eg?.id??null)?ni.tree:[],activeLeafId:ni.sessionId===(eg?.id??null)?ni.leafId:null,onLeafChange:nc,hasSession:!!eg})}),"system"===nH&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:nd?(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:nd}):""===nd?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Y("system.empty")}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Y("system.load")})}),"session"===nH&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:ng?($=ng.totalActiveMs??0,L=[...ng.sessionName?[{label:Y("session.name"),value:ng.sessionName,copyField:null}]:[],{label:Y("session.file"),value:ng.sessionFile??Y("session.inMemory"),copyField:"file"},{label:Y("session.id"),value:ng.sessionId,copyField:"id"},...$>0?[{label:Y("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`})($),copyField:null}]:[]],A=[[Y("session.user"),ng.userMessages.toLocaleString(J)],[Y("session.assistant"),ng.assistantMessages.toLocaleString(J)],[Y("session.toolCalls"),ng.toolCalls.toLocaleString(J)],[Y("session.toolResults"),ng.toolResults.toLocaleString(J)],[Y("session.total"),ng.totalMessages.toLocaleString(J)]],z=[[Y("session.input"),ng.tokens.input.toLocaleString(J)],[Y("session.output"),ng.tokens.output.toLocaleString(J)],...ng.tokens.cacheRead>0?[[Y("session.cacheRead"),ng.tokens.cacheRead.toLocaleString(J)]]:[],...ng.tokens.cacheWrite>0?[[Y("session.cacheWrite"),ng.tokens.cacheWrite.toLocaleString(J)]]:[],[Y("session.total"),ng.tokens.total.toLocaleString(J)]],W=nW??ng.contextUsage,D=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),O=[...ng.cost>0?[[Y("session.cost"),`$${ng.cost.toFixed(4)}`]]:[],...W?.contextWindow?[[Y("session.context"),`${null!==W.tokens?D(W.tokens):"?"} / ${D(W.contextWindow)}${null!==W.percent?` \xb7 ${W.percent.toFixed(1)}%`:""}`]]:[],...ng.tokens.cacheRead+ng.tokens.cacheWrite>0&&ng.tokens.cacheRead+ng.tokens.cacheWrite+ng.tokens.input>0?[[Y("session.cacheHitRate"),`${(ng.tokens.cacheRead/(ng.tokens.cacheRead+ng.tokens.cacheWrite+ng.tokens.input)*100).toFixed(1)}%`]]:[]],B=(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,s])=>(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:s})]},`${e}:${t}`))})]}),_=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:Y("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:L.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=nA===t,(0,r.jsx)("button",{type:"button",title:i?Y("session.copied"):Y("file"===t?"session.copyFile":"session.copyId"),onClick:()=>nz(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:Q?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:Q?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[_,B(Y("session.messages"),A),B(Y("session.tokens"),[...z,...O],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:Y("session.load")})})]})]}),(0,r.jsxs)("div",{className:"chat-content-layout",children:[(0,r.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-lounge-open":el?"true":void 0,children:[rM?(0,r.jsx)(ag,{session:eg,newSessionCwd:rR,initialSessionData:eb,transitioning:null!==ex,onAgentEnd:rb,onAttentionNeeded:ry,onSessionCreated:rx,onSessionForked:rk,modelsRefreshKey:e_,chatInputRef:ne,onBranchDataChange:nl,onSystemPromptChange:nm,onSessionStatsChange:nL,onSessionStatsPanelOpen:n2,onContextUsageChange:nO,onSubagentsChange:nw,onProcessLogChange:n_,onOpenFile:rT,transcriptReplacement:"view-stack"===tt.deck&&rE?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:ia}):null,onComposerFocusChange:ty,onSessionBusyChange:td,onWaitingChange:tp,onAttentionChange:nN,soundEnabled:ee,onSoundToggle:et,playCueSound:en,preloadCueSound:er,unlockAudio:es,jumpRequest:ej,onJumpHandled:eT},eW):rE&&"view-stack"===tt.deck?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:ia}):"validating"===e$?(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:Y("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:q.requestedCwd})]}):"error"===e$?(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:Y("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:q.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eA})]}):rL?rn?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:Y("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:Y("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."}),Y("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),Y("workspace.addModels")]})]})]}):null,ed?(0,r.jsx)(dM,{lounge:ep,visible:el,onBack:()=>tb(!1)}):null]}),"pinned"===tt.deck&&rE&&(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:ia})]})]}),"command-palette"===e4.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(e5({type:"close-layer"}),tv())},children:(0,r.jsxs)("div",{ref:tx,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:tq,"aria-label":"ko"===J?"명령 팔레트":"Command palette",children:[(0,r.jsxs)("header",{children:[(0,r.jsx)("strong",{children:"ko"===J?"명령 팔레트":"Command palette"}),(0,r.jsx)("kbd",{children:"Ctrl K"})]}),(0,r.jsx)(ak,{t:Y,onPick:(e,t)=>{e5({type:"close-layer"}),nZ("chat",!1),eC.current+=1,eS({id:eC.current,sessionId:e.id,entryId:t.entryId}),rh(e)}}),(0,r.jsxs)("div",{className:"workspace-command-list",children:[d.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>nZ(e,!0),children:[(0,r.jsx)("span",{children:rV[e]}),(0,r.jsx)("small",{children:e4.activeView===e?"ko"===J?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{e3(e),nZ("resource",!1)},children:[(0,r.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,r.jsx)("small",{children:rV.resource})]},e)),(0,r.jsxs)("button",{type:"button",onClick:n8,children:[(0,r.jsx)("span",{children:t2.presented?Y("sidebar.hide"):Y("sidebar.show")}),(0,r.jsx)("small",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:eR,children:(0,r.jsx)("span",{children:Y(eI?"palette.wideChatOff":"palette.wideChatOn")})}),(0,r.jsx)("button",{type:"button",onClick:()=>{e5({type:"close-layer"}),eq(!0)},children:(0,r.jsx)("span",{children:Y("common.settings")})})]})]})})]}),eU&&(0,r.jsx)(lj,{cwd:r$,sessionId:eg?.id??null,onClose:()=>{eq(!1),eG(e=>e+1),tv()},onModelsChanged:()=>eH(e=>e+1),onReloaded:()=>eD(e=>e+1)}),eX&&r$&&(0,r.jsx)(lI,{cwd:r$,busy:e0,scheduled:eV?.pending==="grant",error:e2,onCancel:()=>{e0||(eQ(!1),tv())},onConfirm:()=>void rP("grant"),onCancelSchedule:()=>void rP("cancel")})]})}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>s,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],s=["read","bash","edit","write","grep","glob"],a=Object.fromEntries(s.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===a[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...s].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...s]:[...i]}},69575:(e,t,n)=>{Promise.resolve().then(n.bind(n,13481)),Promise.resolve().then(n.bind(n,92176))},92176:(e,t,n)=>{"use strict";n.d(t,{I18nProvider:()=>h,s:()=>m});var r=n(95155),i=n(12115);let s=JSON.parse('{"common.ok":"확인","common.language":"언어","common.models":"모델","common.skills":"스킬","common.plugins":"플러그인","common.settings":"설정","updates.available":"CUELO 업데이트 있음","updates.availableTitle":"CUELO {version} 릴리스가 나왔습니다","updates.dialogEyebrow":"CUELO 릴리스","updates.dialogTitle":"새 CUELO 버전","updates.current":"현재 CUELO {version}","updates.changelog":"변경 사항","updates.viewRelease":"릴리스 보기","updates.manual":"소스에서 실행 중이면 아래 명령으로 갱신한 뒤 다시 시작하세요.","updates.copyCommand":"명령어 복사","updates.commandCopied":"명령어 복사됨","updates.copyFailed":"명령어를 복사할 수 없습니다","sidebar.hide":"사이드바 숨기기","sidebar.show":"사이드바 표시","theme.light":"라이트 모드 (클릭하면 다크)","theme.dark":"다크 모드 (클릭하면 시스템)","theme.auto":"시스템 테마 (클릭하면 라이트)","history.full":"전체 기록","history.unsaved":"전체 기록은 세션 저장 후 사용할 수 있습니다","history.label":"전체 기록","title.generating":"생성 중...","title.updated":"제목 업데이트됨","title.failed":"생성 실패","title.generate":"제목 생성","title.unsaved":"제목 생성은 세션 저장 후 사용할 수 있습니다","title.noMessages":"세션 이름을 지정하기 전에 메시지를 보내세요","title.generateSession":"세션 제목 생성","system.prompt":"시스템 프롬프트","system.empty":"시스템 프롬프트가 비어 있습니다 (도구 비활성화됨)","system.load":"시스템 프롬프트를 불러오려면 메시지를 보내세요","system.label":"시스템","session.info":"세션 정보","session.name":"이름","session.file":"파일","session.inMemory":"메모리 내","session.id":"ID","session.user":"사용자","session.assistant":"어시스턴트","session.toolCalls":"도구 호출","session.toolResults":"도구 결과","session.total":"합계","session.input":"입력","session.output":"출력","session.cacheRead":"캐시 읽기","session.cacheWrite":"캐시 쓰기","session.cost":"비용","session.context":"컨텍스트","session.copy":"{value} 복사","session.copied":"복사됨","session.title":"세션 정보","session.load":"세션 정보를 불러오려면 메시지를 보내거나 /session을 실행하세요","session.infoSection":"세션 정보","session.messages":"메시지","session.tokens":"Token","session.copyFile":"파일 경로 복사","session.copyId":"세션 ID 복사","session.cacheHitRate":"평균 캐시 적중률","session.totalActive":"활동 시간","workspace.opening":"워크스페이스를 여는 중...","workspace.unable":"워크스페이스를 열 수 없습니다","workspace.selectSession":"사이드바에서 세션을 선택하세요","workspace.getStarted":"시작하기","workspace.selectProject":"사이드바에서 프로젝트 디렉터리를 선택하세요","workspace.addModels":"하단의 모델 버튼으로 모델을 추가하세요","workspace.stepProject":"사이드바에서 프로젝트 디렉터리를 선택하세요","workspace.stepModels":"하단의 모델 버튼으로 모델을 추가하세요","workspace.mainWorking":"작업중","workspace.mainWaiting":"대기중","workspace.mainIdle":"대기","workspace.mainAttention":"입력필요","files.hidePanel":"파일 패널 숨기기","files.showPanel":"파일 패널 표시","files.noneOpen":"열린 파일 없음","layout.resizeSidebar":"사이드바 크기 조절","layout.resizeFilePanel":"파일 패널 크기 조절","layout.resizeHint":"드래그하여 크기를 조절합니다. 더블 클릭 또는 Enter 키로 초기화합니다.","sidebar.new":"새로 만들기","sidebar.newSessionTitle":"{path}에서 새 세션","sidebar.refresh":"새로고침","sidebar.projects":"프로젝트","subagents.title":"서브 Agent","subagents.running":"실행 중","subagents.finished":"완료됨","subagents.history":"기록","subagents.runningCount":"{count}개 실행 중","subagents.finishedCount":"{count}개 완료됨","subagents.failed":"실패","subagents.aborted":"중단됨","subagents.back":"서브 Agent 목록으로 돌아가기","subagents.retrying":"재시도 중 {attempt}/{max}","subagents.usingTool":"{tool} 사용 중","subagents.details":"서브 Agent 실행 상세","subagents.closeDetails":"서브 Agent 상세 닫기","subagents.noTask":"작업 설명 없음","subagents.tools":"도구 {count}개","subagents.tokens":"{count} Token","subagents.loadingTranscript":"실시간 기록을 불러오는 중…","subagents.noTranscript":"서브 Agent가 아직 기록 메시지를 작성하지 않았습니다.","subagents.transcriptUnavailable":"실시간 기록을 아직 사용할 수 없습니다. 서브 Agent가 실행되는 동안 재시도합니다.","sidebar.searchProjectsAndSessions":"프로젝트 및 세션 제목 검색…","sidebar.addProject":"사용자 지정 프로젝트 경로 추가","sidebar.projectActions":"프로젝트 작업","sidebar.projectAlias":"별칭","sidebar.projectAliasEdit":"별칭 편집","sidebar.projectHide":"숨기기","sidebar.projectUnhide":"숨김 해제","sidebar.projectShowHidden":"숨긴 프로젝트 표시","sidebar.temporaryProjects":"임시\xb7시스템 경로","sidebar.projectMoveUp":"위로 이동","sidebar.projectMoveDown":"아래로 이동","sidebar.projectMoveDisabledWhileFiltering":"프로젝트 순서를 변경하려면 검색 필터를 지우세요","sidebar.projectUpdateFailed":"프로젝트 변경 사항을 저장할 수 없습니다. 다시 시도하세요.","sidebar.expandProject":"프로젝트 펼치기","sidebar.collapseProject":"프로젝트 접기","sidebar.showMore":"더 보기","sidebar.showLess":"간략히 보기","sidebar.selectProject":"프로젝트 선택…","sidebar.filterProjects":"프로젝트 필터…","sidebar.noMatchingProjects":"일치하는 프로젝트 없음","sidebar.useDefaultDirectory":"기본 디렉터리 사용","sidebar.customPath":"사용자 지정 경로…","directoryPicker.selectDirectory":"디렉터리 선택","directoryPicker.goToParent":"상위 디렉터리로 이동","directoryPicker.directoryPath":"디렉터리 경로","directoryPicker.goToDirectory":"디렉터리로 이동","directoryPicker.go":"이동","directoryPicker.loadingDirectories":"디렉터리를 불러오는 중…","directoryPicker.noSubdirectories":"하위 디렉터리 없음","directoryPicker.openBeforeSelecting":"선택하기 전에 이 경로를 엽니다","directoryPicker.selectCurrentDirectory":"현재 디렉터리 선택","directoryPicker.selectThisFolder":"이 폴더 선택","directoryPicker.noDrives":"드라이브를 찾을 수 없음","sidebar.checking":"확인 중…","sidebar.open":"열기","sidebar.cancel":"취소","sidebar.openRepoRoot":"저장소 루트 열기","sidebar.openRepoRootTitle":"worktree를 관리하려면 저장소 루트를 여세요.","sidebar.gitRepoRootOnly":"Git 저장소 루트 전용","sidebar.gitRepoRootOnlyTitle":"worktree는 Git 저장소 루트에서만 사용할 수 있습니다.","sidebar.worktrees":"Worktree...","sidebar.checkingWorktrees":"이 디렉터리의 worktree를 확인합니다.","sidebar.filterWorktrees":"worktree 필터…","sidebar.noMatchingWorktrees":"일치하는 worktree 없음","sidebar.switchWorktree":"worktree 전환","sidebar.switchWorktreeTitle":"worktree 전환: {path}","sidebar.main":"main","sidebar.forceRemoveCheckout":"커밋되지 않은 변경 사항이 있습니다. 체크아웃을 강제로 제거할까요?","sidebar.force":"강제","sidebar.createWorktreeTitle":"Branch에 대한 worktree 체크아웃을 생성합니다","sidebar.newWorktree":"새 worktree…","sidebar.branchName":"Branch 이름","sidebar.creating":"생성 중…","sidebar.create":"생성","sidebar.loading":"불러오는 중...","sidebar.noSessions":"세션 없음","sidebar.agentRunning":"Agent 실행 중…","sidebar.newActivity":"새 활동","sidebar.newSessionActivity":"새 세션 활동","sidebar.deleteSession":"{title}을(를) 삭제할까요?","sidebar.rename":"이름 변경","sidebar.pin":"맨 위에 고정","sidebar.unpin":"고정 해제","sidebar.pinned":"고정됨","sidebar.delete":"삭제","sidebar.deleteWithShiftClick":"삭제 (Shift+클릭으로 확인 없이 삭제)","sidebar.clearProjectSessions":"세션 비우기","sidebar.clearPriorityList":"목록 비우기","sidebar.newScratchSession":"새 세션","sidebar.newScratchSessionTitle":"프로젝트 없이 세션 시작 (홈 폴더의 날짜별 임시 폴더)","sidebar.newScratchSessionFailed":"임시 폴더를 만들지 못했습니다: {error}","sidebar.clearSessionsTitle":"세션 삭제 확인","sidebar.clearSessionsProjectBody":"{project} 프로젝트의 세션 {count}개를 영구 삭제합니다. 되돌릴 수 없습니다.","sidebar.clearSessionsPriorityBody":"우선순위 목록의 세션 {count}개를 영구 삭제합니다. 되돌릴 수 없습니다.","sidebar.clearSessionsRunningExcluded":"실행 중인 세션 {count}개는 삭제하지 않습니다.","sidebar.clearSessionsNone":"지금 삭제할 수 있는 세션이 없습니다.","sidebar.clearSessionsConfirm":"삭제","sidebar.clearSessionsCancel":"취소","sidebar.clearSessionsBusy":"삭제 중…","sidebar.clearSessionsFailed":"{count}개 세션을 삭제하지 못했습니다: {names}","sidebar.archive":"보관 (목록에서 숨김, 복원 가능)","sidebar.archived":"보관됨","sidebar.restore":"복원","sidebar.noArchivedSessions":"보관된 세션 없음","sidebar.expandForks":"Fork 펼치기","sidebar.collapseForks":"Fork 접기","sidebar.messagesCount":"메시지 {count}개","sidebar.worktreePath":"Worktree: {path}","sidebar.removeWorktreeTitle":"worktree 체크아웃 {path}을(를) 제거합니다. Branch는 유지됩니다","files.deleted":"삭제됨","files.insertPath":"채팅에 경로 삽입","files.mention":"멘션","chat.loadingSession":"세션 불러오는 중...","chat.runningTool":"도구 실행 중...","chat.runningNamedTool":"{name} 실행 중...","chat.runningTools":"{names} 실행 중...","chat.runningToolsMore":"{names} (+{count}) 실행 중...","chat.waitingModel":"모델 응답 대기 중...","todo.progress":"{percent}% \xb7 {total}개 중 {completed}개 완료 \xb7 {remaining}개 남음","todo.progressDone":"{percent}% \xb7 {total}개 중 {completed}개 완료","todo.allDone":"{count}개 모두 완료","todo.showCompleted":"완료 {count}개 보기","todo.hideCompleted":"완료 {count}개 접기","chat.runningCommand":"명령 실행 중...","chat.thinking":"생각 중...","chat.contextUsageTitle":"컨텍스트 윈도우: {limit} Token 중 {used} 사용 ({percent})","chat.contextUsageWarning":"컨텍스트 윈도우가 거의 차고 있습니다","chat.contextUsageCritical":"컨텍스트 윈도우가 거의 가득 찼습니다","chat.processDetails":"프로세스 상세","chat.message":"메시지","chat.messages":"메시지","chat.toolCall":"도구 호출","chat.toolCalls":"도구 호출","chat.collapseProcess":"프로세스 상세 접기","chat.expandProcess":"프로세스 상세 펼치기","process.empty":"이 세션에는 아직 작업 과정 기록이 없습니다","process.turn":"턴","process.turns":"턴","chat.loadEarlier":"위로 스크롤하면 이전 메시지를 불러옵니다 ({count}개 숨김)","chat.extensionRequest":"확장 요청","chat.responseSending":"응답을 보내는 중...","chat.responseFailed":"응답이 Agent에 전달되지 않았습니다. 아직 기다리는 중이니 다시 시도하세요.","chat.cancel":"취소","chat.confirm":"확인","chat.submit":"제출","chat.agentQuestion":"Agent가 입력을 기다립니다","chat.agentQuestionHint":"옵션을 선택하거나 직접 응답을 입력하세요.","chat.askAutoSelectHint":"{seconds}초 동안 응답이 없으면 추천안으로 자동 선택합니다. 선택하거나 입력하면 대기 시간이 다시 시작됩니다.","chat.recommended":"추천","chat.customAnswer":"기타 응답 (선택)","chat.chatAboutThis":"이것에 대해 대화","chat.submitAnswer":"답변 제출","chat.planApproval":"계획 승인","chat.planFeedback":"추가 계획 수립을 위한 피드백 (선택)","chat.refinePlan":"계획 계속하기","chat.approvePlan":"승인 후 구현","chat.extensionInput":"확장 터미널 입력","chat.extensionPanel":"확장 패널","chat.close":"닫기","chat.queued":"대기 중 \xb7 {count}","chat.recall":"입력창으로 되돌리기","chat.recallTitle":"대기 중인 메시지를 모두 제거하고 편집할 수 있도록 입력창에 다시 넣습니다","chat.queueRemove":"이 대기 메시지만 취소","chat.retrying":"재시도 중 ({attempt}/{max})…","chat.loadingCommands":"명령 불러오는 중...","chat.slashCommands":"슬래시 명령 \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"명령이 없습니다","chat.match":"일치 1개","chat.matches":"일치 {count}개","chat.command":"명령 1개","chat.commands":"명령 {count}개","chat.loadingFiles":"파일 불러오는 중...","chat.files":"파일 \xb7 {label}{hint}","chat.searching":"검색 중…","chat.noMatchingFiles":"일치하는 파일 없음","chat.searchingAll":" \xb7 전체 파일 검색 중…","chat.indexTruncated":" \xb7 인덱스 일부 생략됨","chat.steerPlaceholder":"지금 지시하거나 후속 메시지를 대기열에 추가하세요...","chat.agentPlaceholder":"Agent 실행 중…","chat.messagePlaceholder":"메시지 입력… 명령어는 /, 파일은 @ 입력","chat.steer":"지시","chat.followUp":"후속 메시지","chat.send":"보내기","chat.attachImageLimit":"메시지 하나에 이미지를 최대 {count}개까지 첨부할 수 있습니다.","chat.attachImageTooLarge":"{name} 파일이 이미지당 {limit} 제한을 초과합니다.","chat.attachFile":"파일 첨부","chat.attachments":"첨부 파일","chat.removeImage":"이미지 {index} 제거","chat.removeAttachment":"{name} 제거","chat.attachExtracting":"텍스트 추출 중","chat.attachExtractingWait":"첨부 파일 처리가 끝날 때까지 기다려 주세요","chat.attachLimit":"메시지 하나에 이미지를 제외한 첨부 파일을 최대 {count}개까지 넣을 수 있습니다.","chat.attachTooLarge":"{name} 파일이 문서당 {limit} 제한을 초과합니다.","chat.attachTotalTooLarge":"첨부 문서의 합계가 {limit} 제한을 초과합니다.","chat.attachTextTooLarge":"{name}에서 추출한 텍스트가 {limit}자 제한을 초과합니다.","chat.attachTooManyPages":"{name} 파일이 PDF {limit}페이지 제한을 초과합니다.","chat.attachNoPdfText":"{name}에서 추출할 수 있는 텍스트가 없습니다. 스캔 또는 이미지 전용 PDF에 필요한 OCR은 지원하지 않습니다.","chat.attachPasswordProtected":"{name}은(는) 암호로 보호되어 텍스트를 추출할 수 없습니다.","chat.attachExtractFailed":"{name}에서 텍스트를 추출하지 못했습니다.","chat.attachKindAudio":"음성","chat.attachKindFile":"파일","chat.attachUploading":"저장 중","chat.attachTranscribing":"받아쓰기 중","chat.attachTranscribeFailed":"받아쓰기 실패","chat.attachTranscribeFailedNotice":"{name} 받아쓰기에 실패해 저장된 파일 경로만 첨부했습니다: {error}","chat.attachStoredTooLarge":"{name} 파일이 파일당 {limit} 제한을 초과합니다.","chat.attachUploadFailed":"{name} 파일을 저장하지 못했습니다: {error}","chat.steerTitle":"현재 실행을 중단하고 이 메시지를 바로 전달합니다","chat.followUpTitle":"Agent가 끝난 후 이 메시지를 전달하도록 대기열에 추가합니다","chat.filterModels":"모델 필터…","chat.noMatchingModels":"일치하는 모델 없음","chat.modelRoles":"역할","chat.allModels":"전체 모델","chat.mainPreset":"Main 프리셋","roles.title":"모델 역할","roles.description":"omp는 하나의 현재 모델이 아니라 역할별로 작업을 라우팅합니다. 각 역할에 모델을 지정하면 CUELO과 omp CLI 모두에서 사용됩니다.","roles.scope":"저장 위치","roles.scopeGlobal":"전역","roles.scopeProject":"이 프로젝트","roles.unset":"— 미설정 —","roles.needsProject":"모델 역할을 편집하려면 프로젝트를 여세요.","roles.source.global":"전역 설정에서","roles.source.project":"프로젝트 설정에서","roles.source.default":"omp 기본값","roles.thinking":"Thinking","roles.thinkingInherit":"설정된 기본 thinking 수준 사용","chat.moreControls":"실행 옵션","chat.collapseControls":"실행 옵션 닫기","chat.shell":"Shell","chat.outputLocal":"출력은 로컬에만 유지","chat.outputModel":"출력을 모델로 전송","chat.noTools":"도구 없음, 읽기 전용","chat.builtInTools":"코어: {tools} \xb7 그 외 등록된 도구는 계속 활성화됨","chat.allBuiltInTools":"코어: {tools} \xb7 그 외 등록된 도구는 계속 활성화됨","chat.changeReasoning":"추론 수준 변경: {level}","chat.changeReasoningLabel":"추론 수준 변경","chat.changeToolPreset":"도구 프리셋 변경","chat.stopCompaction":"압축 중지","chat.compactContext":"컨텍스트 압축","chat.compacting":"압축 중…","chat.compact":"Compact","chat.stopAgent":"Agent 중지","chat.stop":"중지","chat.liveVoice":"라이브 음성","chat.liveStart":"라이브 음성 시작","chat.liveStop":"라이브 음성 종료","chat.liveConnecting":"연결 중","chat.liveOn":"통화 중","chat.liveWorking":"작업 수행 중","chat.liveUnsupported":"이 브라우저에서는 라이브 통화를 할 수 없습니다","chat.liveMicDenied":"마이크 권한이 거부됐습니다","chat.liveMicUnavailable":"사용할 수 있는 마이크가 없습니다","chat.liveAuthRequired":"라이브 음성을 쓰려면 Codex 로그인이 필요합니다","chat.liveUpstreamFailed":"Codex가 라이브 통화를 거부했습니다","chat.liveFailed":"라이브 통화를 시작하지 못했습니다","chat.liveNeedsSession":"먼저 폴더를 선택하세요 — 라이브 통화는 이 대화의 에이전트로 말합니다","chat.disableSound":"완료 알림음 끄기","chat.enableSound":"완료 알림음 켜기","chat.thinkingAuto":"추론 강도 자동 선택","chat.thinkingAutoCapped":"자동 선택, 최대 {level}","chat.thinkingOff":"추론 끔","chat.thinkingMinimal":"최소 추론","chat.thinkingLow":"낮은 추론","chat.thinkingMedium":"중간 추론","chat.thinkingHigh":"높은 추론","chat.thinkingXhigh":"매우 높은 추론","chat.thinkingMax":"최대 추론","chat.builtIn":"기본 제공","chat.extensions":"확장","chat.customCommands":"사용자 지정 명령어","chat.mcpPrompts":"MCP 프롬프트","chat.prompts":"프롬프트","chat.fileCommands":"명령어 파일","chat.skills":"Skill","chat.dormant":"휴면","chat.commandCompact":"컨텍스트를 압축합니다. 선택적으로 지침을 지정할 수 있습니다","chat.commandReload":"확장, Skill, 프롬프트, 도구를 다시 불러옵니다","chat.commandName":"세션 표시 이름을 설정합니다","chat.commandSession":"세션의 메시지, Token, 비용 통계를 표시합니다","chat.commandCopy":"마지막 어시스턴트 메시지를 복사합니다","chat.goalLabel":"목표","chat.goalPaused":"일시정지됨","chat.goalBudgetLeft":"{left} 남음","chat.goalTokensUsed":"{used} 사용","chat.jumpToBottom":"맨 아래로 이동","chat.loadLater":"아래로 스크롤하면 이후 메시지를 불러옵니다 ({count}개 남음)","chat.jumpMissing":"이 메시지는 지금 대화 화면에 없습니다(다른 분기이거나 압축된 기록).","chat.questionRail":"내 질문","chat.searchPlaceholder":"대화에서 찾기","chat.searchNoResults":"결과 없음","chat.searchCount":"{index}/{total}","chat.searchPrevious":"이전 결과","chat.searchNext":"다음 결과","chat.searchClose":"찾기 닫기","chat.stallLabel":"조용함","chat.stallMessage":"3분 넘게 새 이벤트가 없어요. 작업이 오래 걸리거나 연결이 멈췄을 수 있어요. 실행은 그대로 둡니다.","chat.compactionLabel":"압축","chat.compactionProgress":"컨텍스트 압축 중 \xb7 {seconds}초","chat.compactionReason.manual":"수동","chat.compactionReason.threshold":"임계치","chat.compactionReason.overflow":"초과","chat.compactionReason.idle":"유휴","chat.compactionReason.incomplete":"미완료","chat.compactedFrom":"{tokens} 토큰에서 압축됨","chat.interruptedTitle":"지난 실행이 중단됐어요","chat.interruptedDetail":"서버나 PC가 꺼지는 등으로 실행 도중 멈췄습니다. 아무것도 다시 보내지 않았어요.","chat.interruptedDismiss":"닫기","chat.frequentModels":"자주 쓰는 모델","chat.modelPickCount":"{count}회","palette.searchPlaceholder":"대화 내용 검색","palette.searchResults":"대화 검색 결과","palette.searching":"검색 중…","palette.searchFailed":"검색하지 못했습니다","palette.searchEmpty":"일치하는 메시지가 없습니다","palette.searchHits":"메시지 {count}개","palette.searchTruncated.time":"시간 한도로 세션 {total}개 중 {scanned}개까지만 검색","palette.searchTruncated.bytes":"크기 한도로 세션 {total}개 중 {scanned}개까지만 검색","palette.searchTruncated.results":"앞쪽 결과만 표시 중 \xb7 검색어를 좁혀 보세요","palette.searchCompacted":"압축된 기록의 {count}개는 제외","palette.searchRoleUser":"내 질문","palette.searchRoleAssistant":"답변","palette.wideChatOn":"넓은 대화 폭 사용","palette.wideChatOff":"기본 대화 폭 사용","chat.compacted":"압축됨","chat.tokensSaved":"{saved} 절약","chat.filesWritten":"변경된 파일","chat.openWrittenFile":"{name} 열기","chat.lessonsSaved":"[교훈 저장] 이번 턴에 에이전트가 직접 저장했습니다.","chat.savedLesson":"교훈: {memory}","chat.savedSkill":"스킬 {action}: {name}","i18n.close":"닫기","i18n.copy":"복사","i18n.copied":"복사됨","i18n.cancel":"취소","i18n.save":"저장","i18n.saving":"저장 중…","i18n.saved":"저장됨","i18n.remove":"제거","i18n.removing":"제거 중…","i18n.delete":"삭제","i18n.loading":"불러오는 중...","i18n.search":"검색","i18n.refresh":"새로고침","i18n.update":"업데이트","i18n.updating":"업데이트 중...","restart.title":"CUELO 재시작 중","restart.body":"서버가 돌아오면 이 페이지가 자동으로 새로고침됩니다.","restart.slow":"재시작이 2분 넘게 끝나지 않았습니다. 서버 PC의 %USERPROFILE%\\\\.omp\\\\restart-ompweb.log에서 READY/FAILED를 확인하세요. 서버가 돌아오면 이 페이지는 그대로 새로고침됩니다.","restart.returnedTitle":"CUELO 재시작 완료","restart.returnedBody":"서버가 돌아와 이 탭을 같은 대화로 다시 연결했습니다.","restart.returnedDismiss":"재시작 알림 닫기","i18n.check":"확인","i18n.checking":"확인 중...","i18n.install":"설치","i18n.installing":"설치 중...","i18n.noResults":"결과 없음","i18n.searchProviders":"Provider 검색…","i18n.noProviders":"일치하는 Provider 없음","i18n.newModel":"새 모델","i18n.addProvider":"Provider 추가","i18n.selectProviderModel":"Provider 또는 모델을 선택하세요","i18n.visibleInPrompt":"모델 프롬프트에 표시됨 — 클릭하여 비활성화","i18n.hiddenFromPrompt":"모델 프롬프트에서 숨겨짐 — 클릭하여 활성화","i18n.dormant":"휴면","i18n.hiddenButInvocable":"모델에서 숨겨졌지만 수동 호출은 가능합니다","i18n.skillSearchPlaceholder":"예: react, testing, deploy","i18n.searching":"검색 중…","i18n.noSkills":"Skill을 찾을 수 없음","i18n.checkUpdates":"업데이트 확인","i18n.updates":"업데이트","i18n.noResolvedResources":"확인된 리소스 없음","i18n.enablePackage":"패키지 활성화","i18n.disablePackage":"패키지 비활성화","i18n.filtered":"필터링됨","i18n.openSessionToReload":"다시 불러오려면 세션을 여세요","i18n.notFound":"찾을 수 없음","i18n.noPlugins":"구성된 Plugin 없음","trust.resourcesNotLoaded":"제한 모드","trust.trustProject":"프로젝트 신뢰","trust.trusting":"신뢰 처리 중...","trust.cancel":"취소","trust.dialogTitle":"이 프로젝트를 신뢰하시겠습니까?","trust.dialogBody":"프로젝트 리소스는 로컬 코드를 실행할 수 있습니다. 내용을 알고 있는 프로젝트만 신뢰하세요.","trust.skillsNotLoaded":"이 프로젝트가 신뢰되지 않아 프로젝트 Skill이 로드되지 않았습니다.","trust.pluginsNotLoaded":"이 프로젝트가 신뢰되지 않아 프로젝트 Plugin이 로드되지 않았습니다.","trust.projectScopeUnavailable":"프로젝트 리소스가 로드되지 않은 동안에는 프로젝트 설치를 사용할 수 없습니다.","trust.pendingBadge":"제한 모드 \xb7 신뢰 예약됨","trust.scheduledTitle":"신뢰가 예약됐습니다","trust.scheduledBody":"이 프로젝트는 아직 제한 모드입니다. 이 프로젝트의 모든 세션이 지금 하는 작업을 마치면 신뢰가 적용되며, 실행 중인 작업은 중단되지 않습니다.","trust.cancelSchedule":"예약 취소","trust.close":"닫기","trust.applyFailed":"예약한 신뢰를 적용하지 못해 프로젝트는 계속 제한 모드입니다: {error}. 다시 시도하려면 다시 신뢰하세요.","trust.settingsNav":"프로젝트 신뢰","trust.settingsDescription":"자체 확장\xb7hook\xb7도구\xb7MCP 서버가 있는 프로젝트는 신뢰한 뒤에만 그 코드를 불러옵니다. 세션이 작업 중일 때 바꾼 설정은 그 프로젝트의 모든 세션이 idle이 되면 적용되며, 실행 중인 작업은 중단되지 않습니다.","trust.settingsEmpty":"아직 신뢰 결정이 필요한 프로젝트가 없습니다.","trust.loadFailed":"프로젝트 신뢰 상태를 불러오지 못했습니다: {error}","trust.stateTrusted":"신뢰됨","trust.stateRestricted":"제한 모드","trust.stateNotRequired":"신뢰가 필요한 프로젝트 코드 없음","trust.pendingGrant":"신뢰를 승인했지만 아직 적용 전입니다. 세션들이 작업을 마칠 때까지 제한 모드가 유지됩니다.","trust.pendingRevoke":"신뢰 해제는 이미 저장됐습니다. 실행 중인 세션 {count}개가 아직 프로젝트 코드를 쓰고 있으며, 지금 작업이 끝나면 제한 모드로 다시 시작합니다.","trust.runtime":"실행 세션 {sessions} \xb7 작업 중 {running} \xb7 프로젝트 코드 로드 {loaded}","trust.revoke":"신뢰 해제","trust.trustAgain":"다시 신뢰","trust.confirm":"확인","trust.working":"저장 중…","trust.confirmGrant":"이 프로젝트를 신뢰할까요? 프로젝트의 확장\xb7hook\xb7도구\xb7MCP 서버가 이 컴퓨터에서 실행될 수 있습니다.","trust.confirmTrustAgain":"해제를 되돌리는 것은 새 신뢰 승인입니다. 프로젝트의 확장\xb7hook\xb7도구\xb7MCP 서버가 이 컴퓨터에서 실행될 수 있습니다.","trust.confirmRevoke":"신뢰를 해제할까요? 새 세션은 바로 제한 모드로 시작하고, 실행 중인 세션은 지금 작업을 마친 뒤 적용됩니다.","trust.doneApplied":"적용했습니다. 이 프로젝트의 세션은 이제 이 설정으로 시작합니다.","trust.doneCancelled":"예약을 취소했습니다. 프로젝트는 계속 제한 모드입니다.","trust.refresh":"새로고침","i18n.creatingSession":"새 세션 생성 중…","i18n.creating":"생성 중…","i18n.subscription":"구독","i18n.subscriptions":"구독 목록","i18n.customEndpoint":"사용자 지정 엔드포인트 형식","i18n.noChanges":"변경 사항 없음","i18n.branches":"Branch 목록","i18n.noActiveSession":"활성 세션 없음","i18n.noBranches":"이 세션에는 Branch가 없습니다","i18n.source":"소스","i18n.preview":"미리보기","i18n.diff":"Diff","i18n.downloadFile":"파일 다운로드","i18n.liveSync":"실시간 동기화 활성","i18n.notWatching":"감시 안 함","i18n.fileViewMode":"파일 보기 모드","i18n.compareHead":"작업 트리를 HEAD와 비교","i18n.mentionSelectedLines":"선택한 줄 멘션","i18n.disableWrap":"자동 줄바꿈 끄기","i18n.enableWrap":"자동 줄바꿈 켜기","i18n.htmlPreview":"HTML 미리보기","i18n.previewFile":"{file} 미리보기","i18n.invalidMermaid":"잘못된 Mermaid 다이어그램","i18n.renderingMermaid":"Mermaid 다이어그램 렌더링 중","i18n.previewAfterStreaming":"스트리밍 완료 후 미리보기 가능","i18n.showMermaidSource":"Mermaid 소스 보기","i18n.previewMermaid":"Mermaid 다이어그램 미리보기","i18n.openMermaidViewer":"다이어그램 뷰어 열기","i18n.mermaidViewer":"Mermaid 다이어그램 뷰어","i18n.mermaidDiagram":"Mermaid 다이어그램","i18n.zoomOut":"축소","i18n.zoomIn":"확대","i18n.fitToWidth":"너비에 맞춤","models.discoveryFetching":"모델 가져오는 중…","models.discoveryFetch":"모델 가져오기…","models.discoveryFilterPlaceholder":"{count}개 모델 필터…","models.discoveryFilter":"업스트림 모델 필터","models.discoverySelectShown":"표시된 항목 선택","models.discoveryNoMatches":"일치하는 모델이 없습니다.","models.discoveryAdded":"추가됨","models.discoveryShowing":"전체 {total}개 중 처음 {shown}개 표시","models.discoveryFetched":"{count}개 모델을 가져왔습니다","models.discoveryAddSelected":"선택 항목 추가","models.discoveryAddSelectedCount":"선택 항목 추가 ({count})","models.catalogSource":"출처: models.dev ↗","models.catalogFilling":"세부 정보 채우는 중…","models.catalogFill":"모델 세부 정보 채우기","models.catalogFilled":"{count}개 필드가 채워졌습니다","models.catalogNoEmptyFields":"채울 빈 필드가 없습니다","models.catalogNoExactMatch":"models.dev에서 정확히 일치하는 항목 없음","models.catalogPriceProvider":"Provider {provider}와 가격 일치","models.catalogPriceBaseUrl":"Base URL이 {provider}와 가격 일치","models.catalogPriceConsensus":"{total}개 중 {support}개 레코드에서 가격 일치","models.catalogPriceUnreliable":"신뢰할 수 있는 가격을 찾지 못했습니다","models.catalogUndo":"실행 취소","i18n.testingModel":"모델 연결 테스트 중...","i18n.connected":"연결됨","i18n.failed":"실패","i18n.test":"테스트","i18n.testConnection":"모델 연결 테스트","i18n.provider":"제공자","i18n.model":"모델","i18n.providerName":"Provider 이름","i18n.rename":"이름 변경","i18n.default":"기본값","i18n.disabled":"비활성화됨","i18n.noResources":"리소스 없음","i18n.unknown":"알 수 없음","i18n.installedVersion":"설치됨 {version}","i18n.configuredVersion":"설정됨 {version}","i18n.extensions":"확장","i18n.prompts":"프롬프트","i18n.themes":"테마","i18n.resourceCount":"{count} {label}","i18n.extensionShort":"확장","i18n.skillShort":"Skill","i18n.promptShort":"프롬프트","i18n.themeShort":"테마","i18n.custom":"사용자 지정","i18n.clearAll":"모두 지우기","i18n.connectedSuccessfully":"연결에 성공했습니다.","i18n.notConnected":"연결 안 됨","i18n.configured":"설정됨","i18n.notConfigured":"설정 안 됨","i18n.openingBrowser":"브라우저를 여는 중…","i18n.submit":"제출","i18n.login":"로그인","i18n.relogin":"다시 로그인","i18n.disconnect":"연결 해제","i18n.networkError":"네트워크 오류","i18n.continuing":"계속 진행 중…","i18n.skills":"Skill","i18n.plugins":"Plugin","i18n.addSkill":"Skill 추가","i18n.addPlugin":"Plugin 추가","i18n.selectSkill":"Skill 선택","i18n.selectPackage":"패키지 선택","i18n.updateAvailable":"업데이트 있음","i18n.upToDate":"최신 상태","i18n.automaticChecksUnavailable":"자동 확인 불가","i18n.checkFailed":"확인 실패","i18n.installed":"설치됨","i18n.status":"상태","i18n.version":"버전","i18n.package":"패키지","i18n.resources":"리소스","i18n.installedPath":"설치 경로","i18n.cwd":"CWD","i18n.resolvedResources":"확인된 리소스","i18n.reloadSession":"세션 다시 불러오기","i18n.reloading":"다시 불러오는 중...","i18n.packageRemoved":"패키지가 제거되었습니다.","i18n.packageInstalled":"패키지가 설치되었습니다.","i18n.packageUpdated":"패키지가 업데이트되었습니다.","i18n.packageDisabled":"패키지가 비활성화되었습니다.","i18n.packageEnabled":"패키지가 활성화되었습니다.","i18n.sessionReloaded":"세션을 다시 불러왔습니다.","i18n.thinking":"사고 과정","i18n.loadingThinking":"사고 과정 불러오는 중...","i18n.copyMessage":"메시지 복사","i18n.editFromHere":"여기서부터 편집","i18n.editFromHereTitle":"여기서부터 편집 — 이 세션 내에서 분기합니다","i18n.newSession":"새 세션","i18n.newSessionTitle":"새 세션 — 여기서부터 독립된 복사본을 만듭니다","i18n.estimatedTokens":"스트리밍 중 예상 Token 수","i18n.messageUsage":"사용량","i18n.messageUsageTitle":"이 메시지의 Token\xb7비용 보기","i18n.noOutput":"(출력 없음)","i18n.noSummary":"(요약 없음)","i18n.conversationCompacted":"대화가 압축됨","i18n.compactionDescription":"이 지점 이전의 대화 기록이 다음 요약으로 압축되었습니다:","i18n.fileContext":"파일 컨텍스트: {details}","i18n.readFiles":"읽은 파일","i18n.modifiedFiles":"수정된 파일","i18n.hiddenExtensionMessage":"숨겨진 확장 메시지","i18n.noMessage":"(메시지 없음)","i18n.showExtensionMessage":"확장 메시지 표시","i18n.collapse":"접기","i18n.expand":"펼치기","i18n.hideDetails":"세부 정보 숨기기","i18n.showDetails":"세부 정보 표시","i18n.thinkingUnavailable":"사고 내용을 사용할 수 없음","i18n.before":"이전","i18n.after":"이후","i18n.largeMessageReveal":"메시지 내용이 매우 큽니다 ({size}). 클릭하면 일반 텍스트로 표시합니다 — 페이지 반응성을 유지하기 위해 마크다운 렌더링은 비활성화됩니다.","i18n.sessionComplete":"세션 완료","i18n.taskFinished":"작업이 완료되었습니다.","i18n.attentionNeeded":"확인이 필요합니다","i18n.extensionInputNeeded":"확장이 입력을 기다립니다.","navigator.toolbar":"탐색 보기","navigator.priority":"우선순위","navigator.view":"{label} 보기","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"이 세션은 6 Pro 연결번호 {handle}에 묶여 있습니다.","usage.none":"사용량 —","usage.open":"사용량 자세히 보기: {rows}","usage.openMore":", 그 외 {count}개","usage.showMore":"나머지 {count}개 보기","usage.showLess":"접기","usage.accountBlocked":"자동 차단","usage.accountSpent":"계정 한도 소진","usage.limitSpent":"한도 소진","usage.bai":"B.AI 누적토큰","usage.baiEmpty":"기록 없음","usage.baiRange":"집계 {from}~{to}","usage.baiUnmeasured":"미측정","efficiency.title":"효율","efficiency.governor":"실행 통제","efficiency.lab":"구성 비교","efficiency.refresh":"새로고침","efficiency.refreshing":"불러오는 중…","efficiency.noSession":"세션을 선택하면 실행 기록을 볼 수 있습니다.","efficiency.loadingRuns":"실행 목록을 불러오는 중…","efficiency.runsEmpty":"이 세션에 기록된 실행이 없습니다.","efficiency.runsError":"실행 목록을 불러오지 못했습니다.","efficiency.selectRun":"실행을 고르면 역할\xb7병목\xb7미측정 공백을 볼 수 있습니다.","efficiency.loadingDetail":"실행 상세를 불러오는 중…","efficiency.detailError":"실행 상세를 불러오지 못했습니다.","efficiency.noTitle":"제목 없는 요청","efficiency.elapsed":"경과","efficiency.busyTotal":"생성시간 합","efficiency.noSumNote":"경과와 생성시간 합은 나란히만 두고 더하지 않습니다.","efficiency.summarySection":"요약","efficiency.rolesSection":"역할","efficiency.rolesEmpty":"이 실행에서 요청을 처리한 역할이 없습니다.","efficiency.bottlenecksSection":"병목","efficiency.bottlenecksEmpty":"측정된 병목이 없습니다.","efficiency.toolsSection":"도구 호출","efficiency.unmeasuredGap":"원인 미측정 공백","efficiency.elapsedValue":"경과 {value}","efficiency.estimatedCostValue":"추정 {value}","efficiency.estimatedCost":"추정 비용","efficiency.untimedLowerBound":"소요시간이 기록되지 않은 요청 {value}건 — 생성시간은 하한입니다.","efficiency.bottleneckOrderNote":"관측된 크기가 큰 순서입니다. 막대는 1위 대비 길이이며 경과시간 대비가 아닙니다.","efficiency.untimedRuns":"소요시간 미기록 run","efficiency.untimedMedianLowerBound":"소요시간이 기록되지 않은 요청이 있는 run {value}건 — 생성시간 중앙값은 하한입니다.","efficiency.unpricedLowerBound":"가격 미기록 포함 — 하한","efficiency.unmeasuredShort":"미측정","efficiency.effortLabel":"effort {value}","efficiency.requestsValue":"요청 {value}회","efficiency.toolCallsValue":"도구 호출 {value}회","efficiency.busyTime":"생성시간","efficiency.tokens":"토큰","efficiency.unpricedRequests":"가격 미기록 요청","efficiency.firstTokenAvg":"첫 응답 대기(평균)","efficiency.firstTokenPartial":"첫 응답 대기는 기록된 요청 {recorded}/{total}건의 평균입니다.","efficiency.outputTokens":"대화 출력 토큰","efficiency.helpersTitle":"보조 모델 호출","efficiency.helperCallsValue":"{count}회 \xb7 출력 {output} \xb7 합계 {tokens} \xb7 {cost}","efficiency.helpersIncludedNote":"보조 호출의 토큰\xb7비용은 위 토큰\xb7추정 비용 합계에 들어 있고, 요청 수\xb7첫 응답 대기\xb7대화 출력 토큰에서는 빠집니다.","efficiency.toolErrorsValue":"오류 {value}회","efficiency.unmeasuredGapValue":"원인 미측정 공백 {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"미배정","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"완료","efficiency.outcomeError":"오류","efficiency.outcomeAborted":"중단됨","efficiency.outcomeInterrupted":"요청으로 끊김","efficiency.outcomeRunning":"실행 중","efficiency.folder":"폴더","efficiency.folderAll":"전체 폴더","efficiency.folderPlaceholder":"폴더로 걸러보기, Enter로 적용","efficiency.loadingExperiments":"구성 비교를 불러오는 중…","efficiency.experimentsEmpty":"비교할 구성이 기록되지 않았습니다.","efficiency.experimentsError":"구성 비교를 불러오지 못했습니다.","efficiency.difficultyNote":"작업 난이도는 보정되지 않음","efficiency.runsValue":"실행 {value}회","efficiency.medianElapsed":"경과 중앙값","efficiency.medianBusy":"생성시간 중앙값","efficiency.medianTokens":"토큰 중앙값","efficiency.medianEstimatedCost":"추정 비용 중앙값","efficiency.totalEstimatedCost":"추정 비용 합","efficiency.reworkRate":"재작업률","efficiency.errorRate":"오류율","efficiency.unpricedRuns":"가격 미기록 run","efficiency.scopeAttributed":"현재 역할 체계만","efficiency.scopeAll":"전체 기록","efficiency.scopeSessions":"집계 세션","efficiency.scopeRuns":"집계 run","efficiency.scopeExcludedRuns":"제외된 run"}'),a=["en","zh-CN","ko"],o=new Map;function l(e){if(!e.id.trim())throw Error("Locale id must not be empty");if(o.has(e.id))throw Error(`Locale already registered: ${e.id}`);o.set(e.id,e)}function c(){return[...o.keys()]}l({id:"en",label:"English",messages:{"common.ok":"OK","common.language":"Language","common.models":"Models","common.skills":"Skills","common.plugins":"Plugins","common.settings":"Settings","updates.available":"CUELO update available","updates.availableTitle":"CUELO {version} is available","updates.dialogEyebrow":"CUELO release","updates.dialogTitle":"New CUELO version","updates.current":"Running CUELO {version}","updates.changelog":"Changelog","updates.viewRelease":"View release","updates.manual":"Running from source? Update with this command, then restart.","updates.copyCommand":"Copy command","updates.commandCopied":"Command copied","updates.copyFailed":"Unable to copy the command","sidebar.hide":"Hide sidebar","sidebar.show":"Show sidebar","theme.light":"Light mode (click for dark)","theme.dark":"Dark mode (click for system)","theme.auto":"System theme (click for light)","history.full":"Full history","history.unsaved":"Full history is available after the session is saved","history.label":"Full history","title.generating":"Generating...","title.updated":"Title updated","title.failed":"Generation failed","title.generate":"Generate title","title.unsaved":"Title generation is available after the session is saved","title.noMessages":"Send a message before naming this session","title.generateSession":"Generate a session title","system.prompt":"System prompt","system.empty":"System prompt is empty (tools are disabled)","system.load":"Send a message to load the system prompt","system.label":"System","session.info":"Session info","session.name":"Name","session.file":"File","session.inMemory":"In-memory","session.id":"ID","session.user":"User","session.assistant":"Assistant","session.toolCalls":"Tool Calls","session.toolResults":"Tool Results","session.total":"Total","session.input":"Input","session.output":"Output","session.cacheRead":"Cache Read","session.cacheWrite":"Cache Write","session.cost":"Cost","session.context":"Context","session.cacheHitRate":"Avg cache hit rate","session.copy":"Copy {value}","session.copied":"Copied","session.title":"Session info","session.load":"Send a message or run /session to load session info","session.infoSection":"Session Info","session.messages":"Messages","session.tokens":"Tokens","session.totalActive":"Active Time","session.copyFile":"Copy file path","session.copyId":"Copy session ID","workspace.opening":"Opening workspace...","workspace.unable":"Unable to open workspace","workspace.selectSession":"Select a session from the sidebar","workspace.getStarted":"Get Started","workspace.selectProject":"Select a project directory from the sidebar","workspace.addModels":"Add models via the Models button at the bottom","workspace.stepProject":"Select a project directory from the sidebar","workspace.stepModels":"Add models via the Models button at the bottom","workspace.mainWorking":"Working","workspace.mainWaiting":"Waiting","workspace.mainIdle":"Idle","workspace.mainAttention":"Input needed","files.hidePanel":"Hide file panel","files.showPanel":"Show file panel","files.noneOpen":"No file open","layout.resizeSidebar":"Resize sidebar","layout.resizeFilePanel":"Resize file panel","layout.resizeHint":"Drag to resize. Double-click or press Enter to reset.","sidebar.new":"New","sidebar.newSessionTitle":"New session in {path}","sidebar.refresh":"Refresh","sidebar.projects":"Projects","subagents.title":"Subagents","subagents.running":"Running","subagents.finished":"Finished","subagents.history":"History","subagents.runningCount":"{count} running","subagents.finishedCount":"{count} finished","subagents.failed":"Failed","subagents.aborted":"Aborted","subagents.back":"Back to subagents","subagents.retrying":"Retrying {attempt}/{max}","subagents.usingTool":"Using {tool}","subagents.details":"Subagent execution details","subagents.closeDetails":"Close subagent details","subagents.noTask":"No task description","subagents.tools":"{count} tools","subagents.tokens":"{count} tokens","subagents.loadingTranscript":"Loading live transcript…","subagents.noTranscript":"The subagent has not written any transcript messages yet.","subagents.transcriptUnavailable":"Live transcript is not available yet. Retrying while the subagent runs.","sidebar.searchProjectsAndSessions":"Search projects and session titles…","sidebar.addProject":"Add custom project path","sidebar.projectActions":"Project actions","sidebar.projectAlias":"Alias","sidebar.projectAliasEdit":"Edit alias","sidebar.projectHide":"Hide","sidebar.projectUnhide":"Unhide","sidebar.projectShowHidden":"Show hidden projects","sidebar.temporaryProjects":"Temporary / system paths","sidebar.projectMoveUp":"Move up","sidebar.projectMoveDown":"Move down","sidebar.projectMoveDisabledWhileFiltering":"Clear the search filter to reorder projects","sidebar.projectUpdateFailed":"Unable to save project changes. Try again.","sidebar.expandProject":"Expand project","sidebar.collapseProject":"Collapse project","sidebar.showMore":"Show more","sidebar.showLess":"Show less","sidebar.selectProject":"Select project…","sidebar.filterProjects":"Filter projects…","sidebar.noMatchingProjects":"No matching projects","sidebar.useDefaultDirectory":"Use default directory","sidebar.customPath":"Custom path…","directoryPicker.selectDirectory":"Select directory","directoryPicker.goToParent":"Go to parent directory","directoryPicker.directoryPath":"Directory path","directoryPicker.goToDirectory":"Go to directory","directoryPicker.go":"Go","directoryPicker.loadingDirectories":"Loading directories…","directoryPicker.noSubdirectories":"No subdirectories","directoryPicker.openBeforeSelecting":"Open this path before selecting it","directoryPicker.selectCurrentDirectory":"Select current directory","directoryPicker.selectThisFolder":"Select this folder","directoryPicker.noDrives":"No drives found","sidebar.checking":"Checking…","sidebar.open":"Open","sidebar.cancel":"Cancel","sidebar.openRepoRoot":"Open repo root","sidebar.openRepoRootTitle":"Open the repository root to manage worktrees.","sidebar.gitRepoRootOnly":"Git repo root only","sidebar.gitRepoRootOnlyTitle":"Worktrees are available in Git repository roots.","sidebar.worktrees":"Worktrees...","sidebar.checkingWorktrees":"Checking worktrees for this directory.","sidebar.filterWorktrees":"Filter worktrees…","sidebar.noMatchingWorktrees":"No matching worktrees","sidebar.switchWorktree":"Switch worktree","sidebar.switchWorktreeTitle":"Switch worktree: {path}","sidebar.main":"main","sidebar.forceRemoveCheckout":"Uncommitted changes. Force remove checkout?","sidebar.force":"Force","sidebar.createWorktreeTitle":"Create a worktree checkout for a branch","sidebar.newWorktree":"New worktree…","sidebar.branchName":"branch name","sidebar.creating":"Creating…","sidebar.create":"Create","sidebar.loading":"Loading...","sidebar.noSessions":"No sessions found","sidebar.agentRunning":"Agent running…","sidebar.newActivity":"New activity","sidebar.newSessionActivity":"New session activity","sidebar.deleteSession":"Delete {title}?","sidebar.rename":"Rename","sidebar.pin":"Pin to top","sidebar.unpin":"Unpin","sidebar.pinned":"Pinned","sidebar.delete":"Delete","sidebar.deleteWithShiftClick":"Delete (Shift+click to delete without confirmation)","sidebar.clearProjectSessions":"Clear sessions","sidebar.clearPriorityList":"Clear list","sidebar.newScratchSession":"New session","sidebar.newScratchSessionTitle":"Start a session without a project (in a dated scratch folder under your home)","sidebar.newScratchSessionFailed":"Could not create the scratch folder: {error}","sidebar.clearSessionsTitle":"Confirm session deletion","sidebar.clearSessionsProjectBody":"Permanently delete {count} session(s) in {project}. This cannot be undone.","sidebar.clearSessionsPriorityBody":"Permanently delete {count} session(s) in the priority list. This cannot be undone.","sidebar.clearSessionsRunningExcluded":"{count} running session(s) will be kept.","sidebar.clearSessionsNone":"No session can be deleted right now.","sidebar.clearSessionsConfirm":"Delete","sidebar.clearSessionsCancel":"Cancel","sidebar.clearSessionsBusy":"Deleting…","sidebar.clearSessionsFailed":"Could not delete {count} session(s): {names}","sidebar.archive":"Archive (hide from list, restorable)","sidebar.archived":"Archived","sidebar.restore":"Restore","sidebar.noArchivedSessions":"No archived sessions","sidebar.expandForks":"Expand forks","sidebar.collapseForks":"Collapse forks","sidebar.messagesCount":"{count} msgs","sidebar.worktreePath":"Worktree: {path}","sidebar.removeWorktreeTitle":"Remove worktree checkout {path}; the branch is kept","files.deleted":"Deleted","files.insertPath":"Insert path into chat","files.mention":"mention","chat.loadingSession":"Loading session...","chat.runningTool":"Running tool...","chat.runningNamedTool":"Running {name}...","chat.runningTools":"Running {names}...","chat.runningToolsMore":"Running {names} (+{count})...","chat.waitingModel":"Waiting for model...","todo.progress":"{percent}% \xb7 {completed} of {total} done \xb7 {remaining} remaining","todo.progressDone":"{percent}% \xb7 {completed} of {total} done","todo.allDone":"All {count} done","todo.showCompleted":"Show {count} completed","todo.hideCompleted":"Hide {count} completed","chat.runningCommand":"Running command...","chat.thinking":"Thinking...","chat.contextUsageTitle":"Context window: {used} of {limit} tokens ({percent})","chat.contextUsageWarning":"Context window is getting full","chat.contextUsageCritical":"Context window is nearly full","chat.processDetails":"Process details","chat.message":"message","chat.messages":"messages","chat.toolCall":"tool call","chat.toolCalls":"tool calls","chat.collapseProcess":"Collapse process details","chat.expandProcess":"Expand process details","process.empty":"No process activity in this session yet","process.turn":"turn","process.turns":"turns","chat.filesWritten":"Files changed","chat.openWrittenFile":"Open {name}","chat.lessonsSaved":"[Lessons saved] The agent stored these itself during this turn.","chat.savedLesson":"Lesson: {memory}","chat.savedSkill":"Skill {action}: {name}","chat.loadEarlier":"Scroll up to load earlier messages ({count} hidden)","chat.extensionRequest":"extension request","chat.responseSending":"Sending your answer...","chat.responseFailed":"Your answer did not reach the agent. It is still waiting - try again.","chat.cancel":"Cancel","chat.confirm":"Confirm","chat.submit":"Submit","chat.agentQuestion":"Agent needs your input","chat.agentQuestionHint":"Choose an option or provide a custom response.","chat.askAutoSelectHint":"If there is no response for {seconds}s, the recommended option is selected automatically. Choosing or typing restarts the wait.","chat.recommended":"Recommended","chat.customAnswer":"Other response (optional)","chat.chatAboutThis":"Chat about this","chat.submitAnswer":"Submit answer","chat.planApproval":"Plan approval","chat.planFeedback":"Feedback for another planning pass (optional)","chat.refinePlan":"Continue planning","chat.approvePlan":"Approve and implement","chat.extensionInput":"Extension terminal input","chat.extensionPanel":"Extension panel","chat.close":"Close","chat.queued":"Queued \xb7 {count}","chat.recall":"Recall to input","chat.recallTitle":"Remove all queued messages and put them back into the input box for editing","chat.queueRemove":"Cancel this queued message only","chat.retrying":"Retrying ({attempt}/{max})…","chat.loadingCommands":"Loading commands...","chat.slashCommands":"Slash commands \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"No commands found","chat.match":"1 match","chat.matches":"{count} matches","chat.command":"1 command","chat.commands":"{count} commands","chat.loadingFiles":"Loading files...","chat.files":"Files \xb7 {label}{hint}","chat.searching":"Searching…","chat.noMatchingFiles":"No matching files","chat.searchingAll":" \xb7 searching all files…","chat.indexTruncated":" \xb7 index truncated","chat.steerPlaceholder":"Steer now / queue follow-up...","chat.agentPlaceholder":"Agent is running…","chat.messagePlaceholder":"Message… Type / for commands, @ for files","chat.steer":"Steer","chat.followUp":"Follow-up","chat.send":"Send","chat.attachImageLimit":"A message can include at most {count} images.","chat.attachImageTooLarge":"{name} exceeds the {limit} per-image limit.","chat.attachFile":"Attach files","chat.attachments":"Attachments","chat.removeImage":"Remove image {index}","chat.removeAttachment":"Remove {name}","chat.attachExtracting":"Extracting text","chat.attachExtractingWait":"Wait for the attachments to finish processing","chat.attachLimit":"A message can include at most {count} non-image attachments.","chat.attachTooLarge":"{name} exceeds the {limit} per-document limit.","chat.attachTotalTooLarge":"Attached documents exceed the {limit} combined size limit.","chat.attachTextTooLarge":"{name} exceeds the {limit}-character extracted text limit.","chat.attachTooManyPages":"{name} exceeds the {limit}-page PDF limit.","chat.attachNoPdfText":"{name} has no extractable text. Scanned or image-only PDFs require OCR, which is not supported.","chat.attachPasswordProtected":"{name} is password-protected and cannot be extracted.","chat.attachExtractFailed":"Could not extract text from {name}.","chat.attachKindAudio":"Audio","chat.attachKindFile":"File","chat.attachUploading":"Saving","chat.attachTranscribing":"Transcribing","chat.attachTranscribeFailed":"Transcription failed","chat.attachTranscribeFailedNotice":"Could not transcribe {name}; only the saved file path is attached: {error}","chat.attachStoredTooLarge":"{name} exceeds the {limit} per-file limit.","chat.attachUploadFailed":"Could not save {name}: {error}","chat.steerTitle":"Interrupt the current run and inject this message now","chat.followUpTitle":"Queue this message after the agent finishes","chat.filterModels":"Filter models…","chat.noMatchingModels":"No matching models","chat.modelRoles":"Roles","chat.allModels":"All models","chat.mainPreset":"Main preset","roles.title":"Model roles","roles.description":"omp routes work by role, not by one current model. Assign a model to each role and both CUELO and the omp CLI use it.","roles.scope":"Save to","roles.scopeGlobal":"Global","roles.scopeProject":"This project","roles.unset":"— not set —","roles.needsProject":"Open a project to edit its model roles.","roles.source.global":"from global config","roles.source.project":"from project config","roles.source.default":"omp default","roles.thinking":"Thinking","roles.thinkingInherit":"Use the configured default thinking level","chat.moreControls":"Run options","chat.collapseControls":"Close run options","chat.shell":"Shell","chat.outputLocal":"output stays local","chat.outputModel":"output sent to model","chat.noTools":"No tools, read-only","chat.builtInTools":"Core: {tools} \xb7 other registered tools stay enabled","chat.allBuiltInTools":"Core: {tools} \xb7 other registered tools stay enabled","chat.changeReasoning":"Change reasoning level: {level}","chat.changeReasoningLabel":"Change reasoning level","chat.changeToolPreset":"Change tool preset","chat.stopCompaction":"Stop compaction","chat.compactContext":"Compact context","chat.compacting":"Compacting…","chat.compact":"Compact","chat.stopAgent":"Stop agent","chat.stop":"Stop","chat.liveVoice":"Live voice","chat.liveStart":"Start live voice","chat.liveStop":"End live voice","chat.liveConnecting":"Connecting","chat.liveOn":"Live","chat.liveWorking":"Working","chat.liveUnsupported":"This browser cannot make live calls","chat.liveMicDenied":"Microphone access was denied","chat.liveMicUnavailable":"No microphone is available","chat.liveAuthRequired":"Sign in to Codex to use live voice","chat.liveUpstreamFailed":"Codex refused the live call","chat.liveFailed":"The live call could not start","chat.liveNeedsSession":"Choose a folder first — a live call speaks as this conversation's agent","chat.disableSound":"Disable completion sound","chat.enableSound":"Enable completion sound","chat.thinkingAuto":"Automatically select reasoning effort","chat.thinkingAutoCapped":"Automatic, at most {level}","chat.thinkingOff":"Reasoning off","chat.thinkingMinimal":"Minimal reasoning","chat.thinkingLow":"Low reasoning","chat.thinkingMedium":"Medium reasoning","chat.thinkingHigh":"High reasoning","chat.thinkingXhigh":"Extra-high reasoning","chat.thinkingMax":"Max reasoning","chat.builtIn":"Built-in","chat.extensions":"Extensions","chat.customCommands":"Custom commands","chat.mcpPrompts":"MCP prompts","chat.prompts":"Prompts","chat.fileCommands":"Command files","chat.skills":"Skills","chat.dormant":"dormant","chat.commandCompact":"Compress context, optionally with instructions","chat.commandReload":"Reload extensions, skills, prompts, and tools","chat.commandName":"Set the session display name","chat.commandSession":"Show session message, token, and cost stats","chat.commandCopy":"Copy the last assistant message","chat.goalLabel":"Goal","chat.goalPaused":"paused","chat.goalBudgetLeft":"{left} left","chat.goalTokensUsed":"{used} used","chat.jumpToBottom":"Jump to bottom","chat.loadLater":"Scroll down to load later messages ({count} below)","chat.jumpMissing":"That message is not in this conversation view (another branch or compacted history).","chat.questionRail":"Your questions","chat.searchPlaceholder":"Find in conversation","chat.searchNoResults":"No results","chat.searchCount":"{index}/{total}","chat.searchPrevious":"Previous match","chat.searchNext":"Next match","chat.searchClose":"Close find","chat.stallLabel":"Quiet","chat.stallMessage":"No new events for over 3 minutes. The work may be slow or the connection stuck; the run keeps going.","chat.compactionLabel":"Compacting","chat.compactionProgress":"Compacting context \xb7 {seconds}s","chat.compactionReason.manual":"manual","chat.compactionReason.threshold":"threshold","chat.compactionReason.overflow":"overflow","chat.compactionReason.idle":"idle","chat.compactionReason.incomplete":"incomplete","chat.compactedFrom":"Compacted from {tokens} tokens","chat.interruptedTitle":"The last run was interrupted","chat.interruptedDetail":"It stopped mid-run, for example when the server or PC went down. Nothing was re-sent.","chat.interruptedDismiss":"Dismiss","chat.frequentModels":"Frequently used","chat.modelPickCount":"{count}\xd7","palette.searchPlaceholder":"Search conversations","palette.searchResults":"Conversation search results","palette.searching":"Searching…","palette.searchFailed":"Search failed","palette.searchEmpty":"No matching messages","palette.searchHits":"{count} messages","palette.searchTruncated.time":"stopped at the time limit after {scanned} of {total} sessions","palette.searchTruncated.bytes":"stopped at the size limit after {scanned} of {total} sessions","palette.searchTruncated.results":"showing the first results; refine the query for more","palette.searchCompacted":"{count} in compacted history not shown","palette.searchRoleUser":"You","palette.searchRoleAssistant":"Answer","palette.wideChatOn":"Use wide chat","palette.wideChatOff":"Use standard chat width","chat.compacted":"Compacted","chat.tokensSaved":"{saved} saved","i18n.close":"Close","i18n.copy":"Copy","i18n.copied":"Copied","i18n.cancel":"Cancel","i18n.save":"Save","i18n.saving":"Saving…","i18n.saved":"Saved","i18n.remove":"Remove","i18n.removing":"Removing…","i18n.delete":"Delete","i18n.loading":"Loading...","i18n.search":"Search","i18n.refresh":"Refresh","i18n.update":"Update","i18n.updating":"Updating...","restart.title":"CUELO is restarting","restart.body":"This page reloads automatically when the server is back.","restart.slow":"The restart is taking longer than two minutes. Check READY or FAILED in %USERPROFILE%\\.omp\\restart-ompweb.log on the server PC. This page still reloads when the server is back.","restart.returnedTitle":"CUELO restarted","restart.returnedBody":"The server is back and this tab reconnected to the same conversation.","restart.returnedDismiss":"Dismiss restart notice","i18n.check":"Check","i18n.checking":"Checking...","i18n.install":"Install","i18n.installing":"Installing...","i18n.noResults":"No results","i18n.searchProviders":"Search providers…","i18n.noProviders":"No providers match","i18n.newModel":"new model","i18n.addProvider":"Add provider","i18n.selectProviderModel":"Select a provider or model","i18n.visibleInPrompt":"Visible in model prompt — click to disable","i18n.hiddenFromPrompt":"Hidden from model prompt — click to enable","i18n.dormant":"Dormant","i18n.hiddenButInvocable":"Hidden from model, still manually invocable","i18n.skillSearchPlaceholder":"e.g. react, testing, deploy","i18n.searching":"Searching…","i18n.noSkills":"No skills found","i18n.checkUpdates":"Check updates","i18n.updates":"updates","i18n.noResolvedResources":"No resolved resources","i18n.enablePackage":"Enable package","i18n.disablePackage":"Disable package","i18n.filtered":"filtered","i18n.openSessionToReload":"Open a session to reload","i18n.notFound":"Not found","i18n.noPlugins":"No plugins configured","trust.resourcesNotLoaded":"Restricted mode","trust.trustProject":"Trust project","trust.trusting":"Trusting...","trust.cancel":"Cancel","trust.dialogTitle":"Trust this project?","trust.dialogBody":"Project resources can run local code. Trust only projects whose contents you know.","trust.skillsNotLoaded":"Project skills are not loaded because this project is not trusted.","trust.pluginsNotLoaded":"Project plugins are not loaded because this project is not trusted.","trust.projectScopeUnavailable":"Project installs are unavailable while project resources are not loaded.","trust.pendingBadge":"Restricted mode \xb7 trust scheduled","trust.scheduledTitle":"Trust scheduled","trust.scheduledBody":"This project is still in restricted mode. Trust applies once every session in this project has finished its current work; nothing that is running gets interrupted.","trust.cancelSchedule":"Cancel scheduled trust","trust.close":"Close","trust.applyFailed":"The scheduled trust was not applied, so the project is still restricted: {error}. Trust it again to retry.","trust.settingsNav":"Project trust","trust.settingsDescription":"A project that ships its own extensions, hooks, tools, or MCP servers loads that code only after you trust it. A change made while a session is working applies when every session in that project is idle — running work is never interrupted.","trust.settingsEmpty":"No project needs a trust decision yet.","trust.loadFailed":"Could not load project trust: {error}","trust.stateTrusted":"Trusted","trust.stateRestricted":"Restricted","trust.stateNotRequired":"No project code needs trust","trust.pendingGrant":"Trust approved but not applied yet. The project stays restricted until its sessions finish their work.","trust.pendingRevoke":"Trust is already revoked. {count} running session(s) still use the project code and restart restricted when their current work ends.","trust.runtime":"Live sessions {sessions} \xb7 running {running} \xb7 project code loaded {loaded}","trust.revoke":"Revoke trust","trust.trustAgain":"Trust again","trust.confirm":"Confirm","trust.working":"Saving…","trust.confirmGrant":"Trust this project? Its extensions, hooks, tools, and MCP servers can run on this machine.","trust.confirmTrustAgain":"Undoing a revoke is a new trust approval. Its extensions, hooks, tools, and MCP servers can run on this machine.","trust.confirmRevoke":"Revoke trust? New sessions start restricted right away; running sessions finish their current work first.","trust.doneApplied":"Applied. Sessions in this project now start with this setting.","trust.doneCancelled":"Scheduled trust cancelled. The project stays restricted.","trust.refresh":"Refresh","i18n.creatingSession":"Creating new session…","i18n.creating":"Creating…","i18n.subscription":"Subscription","i18n.subscriptions":"Subscriptions","i18n.customEndpoint":"Custom endpoint format","i18n.noChanges":"No changes","i18n.branches":"Branches","i18n.noActiveSession":"No active session","i18n.noBranches":"This session has no branches","i18n.source":"Source","i18n.preview":"Preview","i18n.diff":"Diff","i18n.downloadFile":"Download file","i18n.liveSync":"Live sync active","i18n.notWatching":"Not watching","i18n.fileViewMode":"File view mode","i18n.compareHead":"Compare working tree with HEAD","i18n.mentionSelectedLines":"Mention selected lines","i18n.disableWrap":"Disable word wrap","i18n.enableWrap":"Enable word wrap","i18n.htmlPreview":"HTML preview","i18n.previewFile":"Preview {file}","i18n.invalidMermaid":"Invalid Mermaid diagram","i18n.renderingMermaid":"Rendering Mermaid diagram","i18n.previewAfterStreaming":"Preview available after streaming","i18n.showMermaidSource":"Show Mermaid source","i18n.previewMermaid":"Preview Mermaid diagram","i18n.openMermaidViewer":"Open diagram viewer","i18n.mermaidViewer":"Mermaid diagram viewer","i18n.mermaidDiagram":"Mermaid diagram","i18n.zoomOut":"Zoom out","i18n.zoomIn":"Zoom in","i18n.fitToWidth":"Fit to width","models.discoveryFetching":"Importing models…","models.discoveryFetch":"Import models…","models.discoveryFilterPlaceholder":"Filter {count} models…","models.discoveryFilter":"Filter upstream models","models.discoverySelectShown":"Select shown","models.discoveryNoMatches":"No matching models.","models.discoveryAdded":"added","models.discoveryShowing":"Showing first {shown} of {total}","models.discoveryFetched":"{count} models fetched","models.discoveryAddSelected":"Add selected","models.discoveryAddSelectedCount":"Add selected ({count})","models.catalogSource":"source: models.dev ↗","models.catalogFilling":"Filling details…","models.catalogFill":"Fill model details","models.catalogFilled":"{count} fields filled","models.catalogNoEmptyFields":"No empty fields to fill","models.catalogNoExactMatch":"No exact models.dev match","models.catalogPriceProvider":"Price matched Provider {provider}","models.catalogPriceBaseUrl":"Price matched Base URL to {provider}","models.catalogPriceConsensus":"Price agreed by {support}/{total} records","models.catalogPriceUnreliable":"No reliable price found","models.catalogUndo":"Undo","i18n.testingModel":"Testing model connection...","i18n.connected":"Connected","i18n.failed":"Failed","i18n.test":"Test","i18n.testConnection":"Test model connection","i18n.provider":"Provider","i18n.model":"Model","i18n.providerName":"Provider name","i18n.rename":"Rename","i18n.default":"Default","i18n.disabled":"Disabled","i18n.noResources":"No resources","i18n.unknown":"Unknown","i18n.installedVersion":"installed {version}","i18n.configuredVersion":"configured {version}","i18n.extensions":"Extensions","i18n.prompts":"Prompts","i18n.themes":"Themes","i18n.resourceCount":"{count} {label}","i18n.extensionShort":"ext","i18n.skillShort":"skills","i18n.promptShort":"prompts","i18n.themeShort":"themes","i18n.custom":"Custom","i18n.clearAll":"clear all","i18n.connectedSuccessfully":"Connected successfully.","i18n.notConnected":"not connected","i18n.configured":"configured","i18n.notConfigured":"not configured","i18n.openingBrowser":"Opening browser…","i18n.submit":"Submit","i18n.login":"Login","i18n.relogin":"Re-login","i18n.disconnect":"Disconnect","i18n.networkError":"Network error","i18n.continuing":"Continuing…","i18n.skills":"Skills","i18n.plugins":"Plugins","i18n.addSkill":"Add skill","i18n.addPlugin":"Add plugin","i18n.selectSkill":"Select a skill","i18n.selectPackage":"Select a package","i18n.updateAvailable":"Update available","i18n.upToDate":"Up to date","i18n.automaticChecksUnavailable":"Automatic checks unavailable","i18n.checkFailed":"Check failed","i18n.installed":"Installed","i18n.status":"Status","i18n.version":"Version","i18n.package":"Package","i18n.resources":"Resources","i18n.installedPath":"Installed path","i18n.cwd":"CWD","i18n.resolvedResources":"Resolved Resources","i18n.reloadSession":"Reload session","i18n.reloading":"Reloading...","i18n.packageRemoved":"Package removed.","i18n.packageInstalled":"Package installed.","i18n.packageUpdated":"Package updated.","i18n.packageDisabled":"Package disabled.","i18n.packageEnabled":"Package enabled.","i18n.sessionReloaded":"Session reloaded.","i18n.thinking":"Thinking","i18n.largeMessageReveal":"Message content is very large ({size}). Click to view as plain text — markdown rendering is disabled to keep the page responsive.","i18n.loadingThinking":"Loading thinking...","i18n.copyMessage":"Copy message","i18n.editFromHere":"Edit from here","i18n.editFromHereTitle":"Edit from here — branches within this session","i18n.newSession":"New session","i18n.newSessionTitle":"New session — creates an independent copy from here","i18n.estimatedTokens":"Estimated token count while streaming","i18n.messageUsage":"Usage","i18n.messageUsageTitle":"Show this message's tokens and cost","i18n.noOutput":"(no output)","i18n.noSummary":"(no summary)","i18n.conversationCompacted":"Conversation compacted","i18n.compactionDescription":"The conversation history before this point was compacted into the following summary:","i18n.fileContext":"File context: {details}","i18n.readFiles":"Read files","i18n.modifiedFiles":"Modified files","i18n.hiddenExtensionMessage":"hidden extension message","i18n.noMessage":"(no message)","i18n.showExtensionMessage":"Show extension message","i18n.collapse":"Collapse","i18n.expand":"Expand","i18n.hideDetails":"Hide details","i18n.showDetails":"Show details","i18n.thinkingUnavailable":"Thinking content unavailable","i18n.before":"Before","i18n.after":"After","i18n.sessionComplete":"Session complete","i18n.taskFinished":"Task finished.","i18n.attentionNeeded":"Pi needs your attention","i18n.extensionInputNeeded":"An extension is waiting for your input.","navigator.toolbar":"Navigator views","navigator.priority":"Priority","navigator.view":"{label} navigator","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"This session is bound to 6 Pro connection number {handle}.","usage.none":"Usage —","usage.open":"Open usage details: {rows}","usage.openMore":", and {count} more","usage.showMore":"Show {count} more","usage.showLess":"Show less","usage.accountBlocked":"auto-blocked","usage.accountSpent":"account limit used up","usage.limitSpent":"limit used up","usage.bai":"B.AI tokens","usage.baiEmpty":"none recorded","usage.baiRange":"aggregated {from}–{to}","usage.baiUnmeasured":"not measured","efficiency.title":"Efficiency","efficiency.governor":"Run control","efficiency.lab":"Experiment Lab","efficiency.refresh":"Refresh","efficiency.refreshing":"Loading…","efficiency.noSession":"Select a session to see its runs.","efficiency.loadingRuns":"Loading runs…","efficiency.runsEmpty":"No runs recorded in this session.","efficiency.runsError":"Could not load runs.","efficiency.selectRun":"Select a run to see roles, bottlenecks, and unmeasured gaps.","efficiency.loadingDetail":"Loading run detail…","efficiency.detailError":"Could not load the run detail.","efficiency.noTitle":"Untitled request","efficiency.elapsed":"Elapsed","efficiency.busyTotal":"Generation time total","efficiency.noSumNote":"Elapsed and generation total are shown side by side, never added.","efficiency.summarySection":"Summary","efficiency.rolesSection":"Roles","efficiency.rolesEmpty":"No role recorded a request in this run.","efficiency.bottlenecksSection":"Bottlenecks","efficiency.bottlenecksEmpty":"No bottleneck measured.","efficiency.toolsSection":"Tool calls","efficiency.unmeasuredGap":"Unmeasured gap","efficiency.elapsedValue":"Elapsed {value}","efficiency.estimatedCostValue":"Est. {value}","efficiency.estimatedCost":"Est. cost","efficiency.untimedLowerBound":"{value} request(s) have no recorded duration — generation time is a lower bound.","efficiency.bottleneckOrderNote":"Largest observed items, longest first. Bar length is relative to the top item, not to elapsed time.","efficiency.untimedRuns":"Runs missing duration","efficiency.untimedMedianLowerBound":"{value} run(s) contain requests with no recorded duration — the median generation time is a lower bound.","efficiency.unpricedLowerBound":"Includes unpriced records — lower bound","efficiency.unmeasuredShort":"Unmeasured","efficiency.effortLabel":"Effort {value}","efficiency.requestsValue":"{value} requests","efficiency.toolCallsValue":"{value} tool calls","efficiency.busyTime":"Generation time","efficiency.tokens":"Tokens","efficiency.unpricedRequests":"Unpriced requests","efficiency.firstTokenAvg":"Wait for first token (avg)","efficiency.firstTokenPartial":"First-token wait is averaged over {recorded}/{total} requests that recorded it.","efficiency.outputTokens":"Conversation output tokens","efficiency.helpersTitle":"Auxiliary model calls","efficiency.helperCallsValue":"{count} calls \xb7 output {output} \xb7 total {tokens} \xb7 {cost}","efficiency.helpersIncludedNote":"Auxiliary call tokens and cost are included in the token and estimated cost totals above, and excluded from request count, first-token wait, and conversation output tokens.","efficiency.toolErrorsValue":"{value} errors","efficiency.unmeasuredGapValue":"Unmeasured gap {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"Unattributed","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"Completed","efficiency.outcomeError":"Error","efficiency.outcomeAborted":"Aborted","efficiency.outcomeInterrupted":"Interrupted","efficiency.outcomeRunning":"Running","efficiency.folder":"Folder","efficiency.folderAll":"All folders","efficiency.folderPlaceholder":"Filter by folder, Enter to apply","efficiency.loadingExperiments":"Loading config comparison…","efficiency.experimentsEmpty":"No config recorded for comparison.","efficiency.experimentsError":"Could not load the config comparison.","efficiency.difficultyNote":"Task difficulty is not normalized.","efficiency.runsValue":"{value} runs","efficiency.medianElapsed":"Median elapsed","efficiency.medianBusy":"Median generation","efficiency.medianTokens":"Median tokens","efficiency.medianEstimatedCost":"Median est. cost","efficiency.totalEstimatedCost":"Total est. cost","efficiency.reworkRate":"Rework rate","efficiency.errorRate":"Error rate","efficiency.unpricedRuns":"Unpriced runs","efficiency.scopeAttributed":"Current roles only","efficiency.scopeAll":"All runs","efficiency.scopeSessions":"Sessions counted","efficiency.scopeRuns":"Runs counted","efficiency.scopeExcludedRuns":"Runs excluded"}}),l({id:"zh-CN",label:"简体中文",messages:{"common.ok":"确定","common.language":"语言","common.models":"模型","common.skills":"技能","common.plugins":"插件","common.settings":"设置","updates.available":"有可用的 CUELO 更新","updates.availableTitle":"CUELO {version} 可用","updates.dialogEyebrow":"CUELO 发布","updates.dialogTitle":"新的 CUELO 版本","updates.current":"当前 CUELO {version}","updates.changelog":"更新日志","updates.viewRelease":"查看发布","updates.manual":"从源码运行时,用以下命令更新后重启。","updates.copyCommand":"复制命令","updates.commandCopied":"命令已复制","updates.copyFailed":"无法复制命令","sidebar.hide":"隐藏侧边栏","sidebar.show":"显示侧边栏","theme.light":"浅色模式(点击切换到深色)","theme.dark":"深色模式(点击切换到跟随系统)","theme.auto":"跟随系统(点击切换到浅色)","history.full":"完整历史","history.unsaved":"会话保存后才能查看完整历史","history.label":"完整历史","title.generating":"正在生成...","title.updated":"标题已更新","title.failed":"生成失败","title.generate":"生成标题","title.unsaved":"会话保存后才能生成标题","title.noMessages":"请先发送消息,再为会话命名","title.generateSession":"生成会话标题","system.prompt":"系统提示词","system.empty":"系统提示词为空(工具已禁用)","system.load":"发送消息以加载系统提示词","system.label":"系统","session.info":"会话信息","session.name":"名称","session.file":"文件","session.inMemory":"内存中","session.id":"ID","session.user":"用户","session.assistant":"助手","session.toolCalls":"工具调用","session.toolResults":"工具结果","session.total":"总计","session.input":"输入","session.output":"输出","session.cacheRead":"缓存读取","session.cacheWrite":"缓存写入","session.cost":"费用","session.context":"上下文","session.cacheHitRate":"平均缓存命中率","session.copy":"复制{value}","session.copied":"已复制","session.title":"会话信息","session.load":"发送消息或运行 /session 以加载会话信息","session.infoSection":"会话信息","session.messages":"消息","session.tokens":"Token","session.totalActive":"活跃时长","session.copyFile":"复制文件路径","session.copyId":"复制会话 ID","workspace.opening":"正在打开工作区...","workspace.unable":"无法打开工作区","workspace.selectSession":"从侧边栏选择一个会话","workspace.getStarted":"开始使用","workspace.selectProject":"从侧边栏选择项目目录","workspace.addModels":"点击底部的“模型”按钮添加模型","workspace.stepProject":"从侧边栏选择项目目录","workspace.stepModels":"点击底部的“模型”按钮添加模型","workspace.mainWorking":"工作中","workspace.mainWaiting":"等待中","workspace.mainIdle":"空闲","workspace.mainAttention":"需要输入","files.hidePanel":"隐藏文件面板","files.showPanel":"显示文件面板","files.noneOpen":"没有打开的文件","layout.resizeSidebar":"调整侧边栏宽度","layout.resizeFilePanel":"调整文件面板宽度","layout.resizeHint":"拖动调整宽度。双击或按 Enter 恢复默认值。","sidebar.new":"新建","sidebar.newSessionTitle":"在 {path} 中新建会话","sidebar.refresh":"刷新","sidebar.projects":"项目","subagents.title":"子代理","subagents.running":"运行中","subagents.finished":"已完成","subagents.history":"历史","subagents.runningCount":"运行中 {count}","subagents.finishedCount":"已完成 {count}","subagents.failed":"失败","subagents.aborted":"已中止","subagents.back":"返回子代理列表","subagents.retrying":"正在重试 {attempt}/{max}","subagents.usingTool":"正在使用 {tool}","subagents.details":"子代理执行详情","subagents.closeDetails":"关闭子代理详情","subagents.noTask":"无任务描述","subagents.tools":"{count} 个工具","subagents.tokens":"{count} 个 Token","subagents.loadingTranscript":"正在加载实时记录…","subagents.noTranscript":"子代理尚未写入任何会话记录。","subagents.transcriptUnavailable":"实时记录暂不可用。子代理运行期间将继续重试。","sidebar.searchProjectsAndSessions":"搜索项目和会话标题…","sidebar.addProject":"添加自定义项目路径","sidebar.projectActions":"项目操作","sidebar.projectAlias":"别名","sidebar.projectAliasEdit":"编辑别名","sidebar.projectHide":"隐藏","sidebar.projectUnhide":"取消隐藏","sidebar.projectShowHidden":"显示隐藏的项目","sidebar.temporaryProjects":"临时/系统路径","sidebar.projectMoveUp":"上移","sidebar.projectMoveDown":"下移","sidebar.projectMoveDisabledWhileFiltering":"清除搜索筛选后才能重新排序项目","sidebar.projectUpdateFailed":"无法保存项目更改,请重试。","sidebar.expandProject":"展开项目","sidebar.collapseProject":"收起项目","sidebar.showMore":"显示更多","sidebar.showLess":"收起","sidebar.selectProject":"选择项目…","sidebar.filterProjects":"筛选项目…","sidebar.noMatchingProjects":"没有匹配的项目","sidebar.useDefaultDirectory":"使用默认目录","sidebar.customPath":"自定义路径…","directoryPicker.selectDirectory":"选择目录","directoryPicker.goToParent":"转到上级目录","directoryPicker.directoryPath":"目录路径","directoryPicker.goToDirectory":"转到目录","directoryPicker.go":"转到","directoryPicker.loadingDirectories":"正在加载目录…","directoryPicker.noSubdirectories":"没有子目录","directoryPicker.openBeforeSelecting":"选择前请先打开此路径","directoryPicker.selectCurrentDirectory":"选择当前目录","directoryPicker.selectThisFolder":"选择此文件夹","directoryPicker.noDrives":"未找到盘符","sidebar.checking":"检查中…","sidebar.open":"打开","sidebar.cancel":"取消","sidebar.openRepoRoot":"打开仓库根目录","sidebar.openRepoRootTitle":"打开仓库根目录以管理 worktree。","sidebar.gitRepoRootOnly":"仅 Git 仓库根目录","sidebar.gitRepoRootOnlyTitle":"只能在 Git 仓库根目录使用 worktree。","sidebar.worktrees":"Worktrees...","sidebar.checkingWorktrees":"正在检查此目录的 worktree。","sidebar.filterWorktrees":"筛选 worktree…","sidebar.noMatchingWorktrees":"没有匹配的 worktree","sidebar.switchWorktree":"切换 worktree","sidebar.switchWorktreeTitle":"切换 worktree:{path}","sidebar.main":"主分支","sidebar.forceRemoveCheckout":"存在未提交的更改。强制移除 checkout?","sidebar.force":"强制移除","sidebar.createWorktreeTitle":"为分支创建 worktree checkout","sidebar.newWorktree":"新建 worktree…","sidebar.branchName":"分支名称","sidebar.creating":"创建中…","sidebar.create":"创建","sidebar.loading":"加载中...","sidebar.noSessions":"未找到会话","sidebar.agentRunning":"Agent 运行中…","sidebar.newActivity":"有新活动","sidebar.newSessionActivity":"会话有新活动","sidebar.deleteSession":"删除 {title}?","sidebar.rename":"重命名","sidebar.pin":"固定到顶部","sidebar.unpin":"取消固定","sidebar.pinned":"已固定","sidebar.delete":"删除","sidebar.deleteWithShiftClick":"删除(按住 Shift 点击可跳过确认)","sidebar.clearProjectSessions":"清空会话","sidebar.clearPriorityList":"清空列表","sidebar.newScratchSession":"新建会话","sidebar.newScratchSessionTitle":"不选择项目直接开始会话(使用主目录下按日期命名的临时文件夹)","sidebar.newScratchSessionFailed":"无法创建临时文件夹:{error}","sidebar.clearSessionsTitle":"确认删除会话","sidebar.clearSessionsProjectBody":"将永久删除 {project} 中的 {count} 个会话,且无法恢复。","sidebar.clearSessionsPriorityBody":"将永久删除优先级列表中的 {count} 个会话,且无法恢复。","sidebar.clearSessionsRunningExcluded":"保留 {count} 个正在运行的会话。","sidebar.clearSessionsNone":"当前没有可删除的会话。","sidebar.clearSessionsConfirm":"删除","sidebar.clearSessionsCancel":"取消","sidebar.clearSessionsBusy":"删除中…","sidebar.clearSessionsFailed":"有 {count} 个会话删除失败:{names}","sidebar.archive":"归档(从列表隐藏,可恢复)","sidebar.archived":"已归档","sidebar.restore":"恢复","sidebar.noArchivedSessions":"没有已归档的会话","sidebar.expandForks":"展开分叉","sidebar.collapseForks":"折叠分叉","sidebar.messagesCount":"{count} 条消息","sidebar.worktreePath":"Worktree:{path}","sidebar.removeWorktreeTitle":"移除 worktree checkout {path};保留分支","files.deleted":"已删除","files.insertPath":"将路径插入聊天","files.mention":"提及","chat.loadingSession":"正在加载会话...","chat.runningTool":"正在运行工具...","chat.runningNamedTool":"正在运行 {name}...","chat.runningTools":"正在运行 {names}...","chat.runningToolsMore":"正在运行 {names}(另有 {count} 个)...","chat.waitingModel":"正在等待模型...","todo.progress":"{percent}% \xb7 {total} 项中完成 {completed} 项 \xb7 剩余 {remaining} 项","todo.progressDone":"{percent}% \xb7 {total} 项中完成 {completed} 项","todo.allDone":"{count} 项全部完成","todo.showCompleted":"查看已完成 {count} 项","todo.hideCompleted":"收起已完成 {count} 项","chat.runningCommand":"正在运行命令...","chat.thinking":"正在思考...","chat.contextUsageTitle":"上下文窗口:已用 {used} / {limit} Token({percent})","chat.contextUsageWarning":"上下文窗口正在接近上限","chat.contextUsageCritical":"上下文窗口几乎已满","chat.processDetails":"处理详情","chat.message":"条消息","chat.messages":"条消息","chat.toolCall":"次工具调用","chat.toolCalls":"次工具调用","chat.collapseProcess":"收起处理详情","chat.expandProcess":"展开处理详情","process.empty":"此会话还没有处理记录","process.turn":"轮","process.turns":"轮","chat.filesWritten":"改动的文件","chat.openWrittenFile":"打开 {name}","chat.lessonsSaved":"[已保存经验] 代理在本轮中自行保存了以下内容。","chat.savedLesson":"经验:{memory}","chat.savedSkill":"技能 {action}:{name}","chat.loadEarlier":"向上滚动以加载更早的消息(隐藏 {count} 条)","chat.extensionRequest":"扩展请求","chat.responseSending":"正在发送你的回复...","chat.responseFailed":"回复未送达代理。它仍在等待 - 请重试。","chat.cancel":"取消","chat.confirm":"确认","chat.submit":"提交","chat.agentQuestion":"代理需要你的输入","chat.agentQuestionHint":"选择一个选项,或提供自定义回复。","chat.askAutoSelectHint":"{seconds} 秒内无响应将自动选择推荐选项。选择或输入会重新开始计时。","chat.recommended":"推荐","chat.customAnswer":"其他回复(可选)","chat.chatAboutThis":"对此进行讨论","chat.submitAnswer":"提交回答","chat.planApproval":"计划审批","chat.planFeedback":"下一轮计划的反馈(可选)","chat.refinePlan":"继续规划","chat.approvePlan":"批准并实施","chat.extensionInput":"扩展终端输入","chat.extensionPanel":"扩展面板","chat.close":"关闭","chat.queued":"已排队 \xb7 {count}","chat.recall":"移回输入框","chat.recallTitle":"移除所有排队消息并将其放回输入框编辑","chat.queueRemove":"仅取消这条排队消息","chat.retrying":"正在重试({attempt}/{max})…","chat.loadingCommands":"正在加载命令...","chat.slashCommands":"斜杠命令 \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"未找到命令","chat.match":"1 个匹配项","chat.matches":"{count} 个匹配项","chat.command":"1 个命令","chat.commands":"{count} 个命令","chat.loadingFiles":"正在加载文件...","chat.files":"文件 \xb7 {label}{hint}","chat.searching":"搜索中…","chat.noMatchingFiles":"未找到匹配的文件","chat.searchingAll":" \xb7 正在搜索所有文件…","chat.indexTruncated":" \xb7 索引不完整","chat.steerPlaceholder":"立即引导 / 排队后续消息...","chat.agentPlaceholder":"Agent 运行中…","chat.messagePlaceholder":"消息…输入 / 使用命令,输入 @ 查找文件","chat.steer":"引导","chat.followUp":"后续消息","chat.send":"发送","chat.attachImageLimit":"每条消息最多可附加 {count} 张图片。","chat.attachImageTooLarge":"{name} 超出每张图片 {limit} 的限制。","chat.attachFile":"附加文件","chat.attachments":"附件","chat.removeImage":"移除图片 {index}","chat.removeAttachment":"移除 {name}","chat.attachExtracting":"正在提取文本","chat.attachExtractingWait":"请等待附件处理完成","chat.attachLimit":"每条消息最多可附加 {count} 个非图片附件。","chat.attachTooLarge":"{name} 超出每个文档 {limit} 的限制。","chat.attachTotalTooLarge":"附加文档总大小超出 {limit} 的限制。","chat.attachTextTooLarge":"从 {name} 提取的文本超出 {limit} 个字符的限制。","chat.attachTooManyPages":"{name} 超出 PDF {limit} 页的限制。","chat.attachNoPdfText":"无法从 {name} 提取文本。扫描版或纯图片 PDF 需要 OCR,目前不支持。","chat.attachPasswordProtected":"{name} 受密码保护,无法提取文本。","chat.attachExtractFailed":"无法从 {name} 提取文本。","chat.attachKindAudio":"音频","chat.attachKindFile":"文件","chat.attachUploading":"正在保存","chat.attachTranscribing":"正在转写","chat.attachTranscribeFailed":"转写失败","chat.attachTranscribeFailedNotice":"无法转写 {name},仅附加了已保存的文件路径:{error}","chat.attachStoredTooLarge":"{name} 超出每个文件 {limit} 的限制。","chat.attachUploadFailed":"无法保存 {name}:{error}","chat.steerTitle":"中断当前运行并立即注入此消息","chat.followUpTitle":"在 Agent 完成后将此消息加入队列","chat.filterModels":"筛选模型…","chat.noMatchingModels":"没有匹配的模型","chat.modelRoles":"角色","chat.allModels":"全部模型","chat.mainPreset":"Main 预设","roles.title":"模型角色","roles.description":"omp 按角色分派任务,而非只用一个当前模型。为每个角色分配模型后,CUELO 与 omp 命令行都会使用该配置。","roles.scope":"保存到","roles.scopeGlobal":"全局","roles.scopeProject":"当前项目","roles.unset":"— 未设置 —","roles.needsProject":"打开一个项目后即可编辑其模型角色。","roles.source.global":"来自全局配置","roles.source.project":"来自项目配置","roles.source.default":"omp 默认值","roles.thinking":"推理","roles.thinkingInherit":"使用配置的默认推理级别","chat.moreControls":"运行选项","chat.collapseControls":"关闭运行选项","chat.shell":"Shell","chat.outputLocal":"输出保留在本地","chat.outputModel":"输出发送给模型","chat.noTools":"不使用工具,仅只读","chat.builtInTools":"核心:{tools} \xb7 其他已注册工具仍保持启用","chat.allBuiltInTools":"核心:{tools} \xb7 其他已注册工具仍保持启用","chat.changeReasoning":"更改推理级别:{level}","chat.changeReasoningLabel":"更改推理级别","chat.changeToolPreset":"更改工具预设","chat.stopCompaction":"停止压缩","chat.compactContext":"压缩上下文","chat.compacting":"正在压缩…","chat.compact":"压缩","chat.stopAgent":"停止 Agent","chat.stop":"停止","chat.liveVoice":"实时语音","chat.liveStart":"开始实时语音","chat.liveStop":"结束实时语音","chat.liveConnecting":"正在连接","chat.liveOn":"通话中","chat.liveWorking":"正在执行","chat.liveUnsupported":"当前浏览器无法进行实时通话","chat.liveMicDenied":"麦克风权限被拒绝","chat.liveMicUnavailable":"没有可用的麦克风","chat.liveAuthRequired":"使用实时语音需要登录 Codex","chat.liveUpstreamFailed":"Codex 拒绝了本次实时通话","chat.liveFailed":"无法启动实时通话","chat.liveNeedsSession":"请先选择文件夹 — 实时通话以本对话的智能体身份说话","chat.disableSound":"关闭完成提示音","chat.enableSound":"开启完成提示音","chat.thinkingAuto":"自动选择推理强度","chat.thinkingAutoCapped":"自动选择,最高 {level}","chat.thinkingOff":"关闭推理","chat.thinkingMinimal":"最低限度推理","chat.thinkingLow":"低强度推理","chat.thinkingMedium":"中等强度推理","chat.thinkingHigh":"高强度推理","chat.thinkingXhigh":"超高强度推理","chat.thinkingMax":"最高强度推理","chat.builtIn":"内置","chat.extensions":"扩展","chat.customCommands":"自定义命令","chat.mcpPrompts":"MCP 提示词","chat.prompts":"提示词","chat.fileCommands":"命令文件","chat.skills":"技能","chat.dormant":"休眠","chat.commandCompact":"压缩上下文,可选附加说明","chat.commandReload":"重新加载扩展、技能、提示词和工具","chat.commandName":"设置会话显示名称","chat.commandSession":"显示会话消息、Token 和费用统计","chat.commandCopy":"复制最后一条助手消息","chat.goalLabel":"目标","chat.goalPaused":"已暂停","chat.goalBudgetLeft":"剩余 {left}","chat.goalTokensUsed":"已用 {used}","chat.jumpToBottom":"回到底部","chat.loadLater":"向下滚动以加载之后的消息(下方 {count} 条)","chat.jumpMissing":"该消息不在当前会话视图中(其他分支或已压缩的记录)。","chat.questionRail":"我的提问","chat.searchPlaceholder":"在会话中查找","chat.searchNoResults":"无结果","chat.searchCount":"{index}/{total}","chat.searchPrevious":"上一个结果","chat.searchNext":"下一个结果","chat.searchClose":"关闭查找","chat.stallLabel":"静默","chat.stallMessage":"超过 3 分钟没有新事件。任务可能较慢或连接卡住;运行不会被中止。","chat.compactionLabel":"压缩","chat.compactionProgress":"正在压缩上下文 \xb7 {seconds} 秒","chat.compactionReason.manual":"手动","chat.compactionReason.threshold":"阈值","chat.compactionReason.overflow":"溢出","chat.compactionReason.idle":"空闲","chat.compactionReason.incomplete":"未完成","chat.compactedFrom":"从 {tokens} 个 token 压缩","chat.interruptedTitle":"上次运行已中断","chat.interruptedDetail":"运行在中途停止,例如服务器或电脑关机。没有重新发送任何内容。","chat.interruptedDismiss":"关闭","chat.frequentModels":"常用模型","chat.modelPickCount":"{count} 次","palette.searchPlaceholder":"搜索会话内容","palette.searchResults":"会话搜索结果","palette.searching":"搜索中…","palette.searchFailed":"搜索失败","palette.searchEmpty":"没有匹配的消息","palette.searchHits":"{count} 条消息","palette.searchTruncated.time":"因时间限制,仅搜索了 {total} 个会话中的 {scanned} 个","palette.searchTruncated.bytes":"因大小限制,仅搜索了 {total} 个会话中的 {scanned} 个","palette.searchTruncated.results":"仅显示前面的结果,请缩小搜索词","palette.searchCompacted":"已压缩记录中的 {count} 条未显示","palette.searchRoleUser":"我的提问","palette.searchRoleAssistant":"回答","palette.wideChatOn":"使用宽会话","palette.wideChatOff":"使用标准会话宽度","chat.compacted":"已压缩","chat.tokensSaved":"节省 {saved}","i18n.close":"关闭","i18n.copy":"复制","i18n.copied":"已复制","i18n.cancel":"取消","i18n.save":"保存","i18n.saving":"保存中…","i18n.saved":"已保存","i18n.remove":"移除","i18n.removing":"移除中…","i18n.delete":"删除","i18n.loading":"加载中...","i18n.search":"搜索","i18n.refresh":"刷新","i18n.update":"更新","i18n.updating":"更新中...","restart.title":"CUELO 正在重启","restart.body":"服务器恢复后页面会自动刷新。","restart.slow":"重启已超过两分钟。请在服务器电脑的 %USERPROFILE%\\.omp\\restart-ompweb.log 中查看 READY 或 FAILED。服务器恢复后本页仍会自动刷新。","restart.returnedTitle":"CUELO 已重启","restart.returnedBody":"服务器已恢复,此标签页已重新连接到同一对话。","restart.returnedDismiss":"关闭重启通知","i18n.check":"检查","i18n.checking":"检查中...","i18n.install":"安装","i18n.installing":"安装中...","i18n.noResults":"没有结果","i18n.searchProviders":"搜索 Provider…","i18n.noProviders":"没有匹配的 Provider","i18n.newModel":"新模型","i18n.addProvider":"添加 Provider","i18n.selectProviderModel":"选择 Provider 或模型","i18n.visibleInPrompt":"在模型提示词中可见,点击以禁用","i18n.hiddenFromPrompt":"在模型提示词中隐藏,点击以启用","i18n.dormant":"休眠","i18n.hiddenButInvocable":"对模型隐藏,仍可手动调用","i18n.skillSearchPlaceholder":"例如 react、testing、deploy","i18n.searching":"搜索中…","i18n.noSkills":"未找到技能","i18n.checkUpdates":"检查更新","i18n.updates":"项更新","i18n.noResolvedResources":"没有已解析资源","i18n.enablePackage":"启用包","i18n.disablePackage":"禁用包","i18n.filtered":"已筛选","i18n.openSessionToReload":"打开会话后才能重新加载","i18n.notFound":"未找到","i18n.noPlugins":"未配置插件","trust.resourcesNotLoaded":"受限模式","trust.trustProject":"信任项目","trust.trusting":"正在信任...","trust.cancel":"取消","trust.dialogTitle":"信任此项目?","trust.dialogBody":"项目资源可以运行本地代码。请仅信任你了解其内容的项目。","trust.skillsNotLoaded":"此项目尚未受信任,项目技能未加载。","trust.pluginsNotLoaded":"此项目尚未受信任,项目插件未加载。","trust.projectScopeUnavailable":"项目资源未加载时,无法安装到项目范围。","trust.pendingBadge":"受限模式 \xb7 已计划信任","trust.scheduledTitle":"已计划信任","trust.scheduledBody":"此项目仍处于受限模式。项目中的所有会话完成当前工作后才会应用信任,正在运行的工作不会被中断。","trust.cancelSchedule":"取消计划的信任","trust.close":"关闭","trust.applyFailed":"计划的信任未能应用,项目仍处于受限模式:{error}。请重新信任以重试。","trust.settingsNav":"项目信任","trust.settingsDescription":"自带扩展、钩子、工具或 MCP 服务器的项目,只有在你信任后才会加载这些代码。会话工作期间所做的更改会在该项目的所有会话空闲时应用,正在运行的工作不会被中断。","trust.settingsEmpty":"目前没有需要做出信任决定的项目。","trust.loadFailed":"无法加载项目信任状态:{error}","trust.stateTrusted":"已信任","trust.stateRestricted":"受限","trust.stateNotRequired":"没有需要信任的项目代码","trust.pendingGrant":"已批准信任但尚未应用。在会话完成工作之前,项目保持受限。","trust.pendingRevoke":"信任已撤销。仍有 {count} 个运行中的会话在使用项目代码,当前工作结束后将以受限模式重新启动。","trust.runtime":"活动会话 {sessions} \xb7 运行中 {running} \xb7 已加载项目代码 {loaded}","trust.revoke":"撤销信任","trust.trustAgain":"重新信任","trust.confirm":"确认","trust.working":"正在保存…","trust.confirmGrant":"信任此项目?其扩展、钩子、工具和 MCP 服务器可以在本机运行。","trust.confirmTrustAgain":"取消撤销就是一次新的信任批准。其扩展、钩子、工具和 MCP 服务器可以在本机运行。","trust.confirmRevoke":"撤销信任?新会话会立即以受限模式启动;运行中的会话会先完成当前工作。","trust.doneApplied":"已应用。此项目的会话现在将以此设置启动。","trust.doneCancelled":"已取消计划的信任。项目仍处于受限模式。","trust.refresh":"刷新","i18n.creatingSession":"正在创建新会话…","i18n.creating":"创建中…","i18n.subscription":"订阅","i18n.subscriptions":"订阅服务","i18n.customEndpoint":"自定义端点格式","i18n.noChanges":"没有更改","i18n.branches":"分支","i18n.noActiveSession":"没有活动会话","i18n.noBranches":"此会话没有分支","i18n.source":"源代码","i18n.preview":"预览","i18n.diff":"Diff","i18n.downloadFile":"下载文件","i18n.liveSync":"实时同步已启用","i18n.notWatching":"未监视","i18n.fileViewMode":"文件视图模式","i18n.compareHead":"比较工作区与 HEAD","i18n.mentionSelectedLines":"提及所选行","i18n.disableWrap":"禁用自动换行","i18n.enableWrap":"启用自动换行","i18n.htmlPreview":"HTML 预览","i18n.previewFile":"预览 {file}","i18n.invalidMermaid":"Mermaid 图表无效","i18n.renderingMermaid":"正在渲染 Mermaid 图表","i18n.previewAfterStreaming":"流式输出完成后可预览","i18n.showMermaidSource":"显示 Mermaid 源码","i18n.previewMermaid":"预览 Mermaid 图表","i18n.openMermaidViewer":"打开图表查看器","i18n.mermaidViewer":"Mermaid 图表查看器","i18n.mermaidDiagram":"Mermaid 图表","i18n.zoomOut":"缩小","i18n.zoomIn":"放大","i18n.fitToWidth":"适应宽度","models.discoveryFetching":"正在导入模型…","models.discoveryFetch":"导入模型…","models.discoveryFilterPlaceholder":"筛选 {count} 个模型…","models.discoveryFilter":"筛选上游模型","models.discoverySelectShown":"选择当前结果","models.discoveryNoMatches":"没有匹配的模型。","models.discoveryAdded":"已添加","models.discoveryShowing":"显示前 {shown} 个,共 {total} 个","models.discoveryFetched":"已获取 {count} 个模型","models.discoveryAddSelected":"添加所选模型","models.discoveryAddSelectedCount":"添加所选模型({count})","models.catalogSource":"来源:models.dev ↗","models.catalogFilling":"正在填入模型信息…","models.catalogFill":"填入模型信息","models.catalogFilled":"已填入 {count} 个字段","models.catalogNoEmptyFields":"没有需要填入的空字段","models.catalogNoExactMatch":"models.dev 中没有精确匹配","models.catalogPriceProvider":"价格已匹配 Provider {provider}","models.catalogPriceBaseUrl":"价格已按 Base URL 匹配 {provider}","models.catalogPriceConsensus":"价格得到 {support}/{total} 条记录支持","models.catalogPriceUnreliable":"未找到可靠价格","models.catalogUndo":"撤销","i18n.testingModel":"正在测试模型连接...","i18n.connected":"已连接","i18n.failed":"失败","i18n.test":"测试","i18n.testConnection":"测试模型连接","i18n.provider":"Provider","i18n.model":"模型","i18n.providerName":"Provider 名称","i18n.rename":"重命名","i18n.default":"默认","i18n.disabled":"已禁用","i18n.noResources":"没有资源","i18n.unknown":"未知","i18n.installedVersion":"已安装 {version}","i18n.configuredVersion":"已配置 {version}","i18n.extensions":"扩展","i18n.prompts":"提示词","i18n.themes":"主题","i18n.resourceCount":"{count}{label}","i18n.extensionShort":"扩展","i18n.skillShort":"技能","i18n.promptShort":"提示词","i18n.themeShort":"主题","i18n.custom":"自定义","i18n.clearAll":"清除全部","i18n.connectedSuccessfully":"连接成功。","i18n.notConnected":"未连接","i18n.configured":"已配置","i18n.notConfigured":"未配置","i18n.openingBrowser":"正在打开浏览器…","i18n.submit":"提交","i18n.login":"登录","i18n.relogin":"重新登录","i18n.disconnect":"断开连接","i18n.networkError":"网络错误","i18n.continuing":"继续中…","i18n.skills":"技能","i18n.plugins":"插件","i18n.addSkill":"添加技能","i18n.addPlugin":"添加插件","i18n.selectSkill":"选择技能","i18n.selectPackage":"选择包","i18n.updateAvailable":"有可用更新","i18n.upToDate":"已是最新","i18n.automaticChecksUnavailable":"自动检查不可用","i18n.checkFailed":"检查失败","i18n.installed":"已安装","i18n.status":"状态","i18n.version":"版本","i18n.package":"包","i18n.resources":"资源","i18n.installedPath":"安装路径","i18n.cwd":"CWD","i18n.resolvedResources":"已解析资源","i18n.reloadSession":"重新加载会话","i18n.reloading":"重新加载中...","i18n.packageRemoved":"包已移除。","i18n.packageInstalled":"包已安装。","i18n.packageUpdated":"包已更新。","i18n.packageDisabled":"包已禁用。","i18n.packageEnabled":"包已启用。","i18n.sessionReloaded":"会话已重新加载。","i18n.thinking":"思考","i18n.largeMessageReveal":"消息内容过大({size})。点击以纯文本查看 — 已禁用 markdown 渲染以避免页面卡顿。","i18n.loadingThinking":"正在加载思考内容...","i18n.copyMessage":"复制消息","i18n.editFromHere":"从此处编辑","i18n.editFromHereTitle":"从此处编辑,此会话内创建分支","i18n.newSession":"新会话","i18n.newSessionTitle":"新会话,从此处创建独立副本","i18n.estimatedTokens":"流式输出期间的估算 Token 数","i18n.messageUsage":"用量","i18n.messageUsageTitle":"查看该消息的 Token 与费用","i18n.noOutput":"(无输出)","i18n.noSummary":"(无摘要)","i18n.conversationCompacted":"会话已压缩","i18n.compactionDescription":"此处之前的会话历史已压缩为以下摘要:","i18n.fileContext":"文件上下文:{details}","i18n.readFiles":"读取的文件","i18n.modifiedFiles":"修改的文件","i18n.hiddenExtensionMessage":"隐藏的扩展消息","i18n.noMessage":"(无消息)","i18n.showExtensionMessage":"显示扩展消息","i18n.collapse":"收起","i18n.expand":"展开","i18n.hideDetails":"隐藏详情","i18n.showDetails":"显示详情","i18n.thinkingUnavailable":"思考内容不可用","i18n.before":"之前","i18n.after":"之后","i18n.sessionComplete":"任务完成","i18n.taskFinished":"任务已完成。","i18n.attentionNeeded":"Pi 需要你的操作","i18n.extensionInputNeeded":"扩展正在等待你的输入。","navigator.toolbar":"导航视图","navigator.priority":"优先级","navigator.view":"{label}导航","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"该会话已绑定到 6 Pro 连接编号 {handle}。","usage.none":"用量 —","usage.open":"查看用量详情:{rows}","usage.openMore":",另有 {count} 项","usage.showMore":"查看其余 {count} 项","usage.showLess":"收起","usage.accountBlocked":"自动拦截","usage.accountSpent":"账户额度用尽","usage.limitSpent":"额度用尽","usage.bai":"B.AI 累计 Token","usage.baiEmpty":"无记录","usage.baiRange":"统计 {from}~{to}","usage.baiUnmeasured":"未测量","efficiency.title":"效率","efficiency.governor":"运行管控","efficiency.lab":"配置比较","efficiency.refresh":"刷新","efficiency.refreshing":"正在加载…","efficiency.noSession":"选择会话后查看其运行记录。","efficiency.loadingRuns":"正在加载运行记录…","efficiency.runsEmpty":"该会话暂无运行记录。","efficiency.runsError":"无法加载运行记录。","efficiency.selectRun":"选择一条运行,查看角色、瓶颈与未测量空白。","efficiency.loadingDetail":"正在加载运行详情…","efficiency.detailError":"无法加载运行详情。","efficiency.noTitle":"无标题请求","efficiency.elapsed":"耗时","efficiency.busyTotal":"生成时间合计","efficiency.noSumNote":"耗时与生成时间合计并列显示,绝不相加。","efficiency.summarySection":"摘要","efficiency.rolesSection":"角色","efficiency.rolesEmpty":"本次运行中没有角色处理请求。","efficiency.bottlenecksSection":"瓶颈","efficiency.bottlenecksEmpty":"没有测量到瓶颈。","efficiency.toolsSection":"工具调用","efficiency.unmeasuredGap":"原因未测量空白","efficiency.elapsedValue":"耗时 {value}","efficiency.estimatedCostValue":"预估 {value}","efficiency.estimatedCost":"预估费用","efficiency.untimedLowerBound":"有 {value} 个请求没有记录耗时 — 生成时间为下限。","efficiency.bottleneckOrderNote":"按观测到的时长从大到小排列。条形长度相对于第一项,而非经过时间。","efficiency.untimedRuns":"缺少耗时的 run","efficiency.untimedMedianLowerBound":"有 {value} 个 run 含未记录耗时的请求 — 生成时间中位数为下限。","efficiency.unpricedLowerBound":"包含未计价记录 — 下限","efficiency.unmeasuredShort":"未测量","efficiency.effortLabel":"effort {value}","efficiency.requestsValue":"{value} 次请求","efficiency.toolCallsValue":"{value} 次工具调用","efficiency.busyTime":"生成时间","efficiency.tokens":"Token","efficiency.unpricedRequests":"未计价请求","efficiency.firstTokenAvg":"首个 Token 等待(平均)","efficiency.firstTokenPartial":"首个 Token 等待为已记录的 {recorded}/{total} 个请求的平均值。","efficiency.outputTokens":"对话输出 Token","efficiency.helpersTitle":"辅助模型调用","efficiency.helperCallsValue":"{count} 次 \xb7 输出 {output} \xb7 合计 {tokens} \xb7 {cost}","efficiency.helpersIncludedNote":"辅助调用的 Token 与费用已计入上方 Token 与预估费用合计,但不计入请求数、首个 Token 等待和对话输出 Token。","efficiency.toolErrorsValue":"{value} 次错误","efficiency.unmeasuredGapValue":"原因未测量空白 {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"未归属","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"已完成","efficiency.outcomeError":"错误","efficiency.outcomeAborted":"已中止","efficiency.outcomeInterrupted":"被下一请求打断","efficiency.outcomeRunning":"运行中","efficiency.folder":"文件夹","efficiency.folderAll":"全部文件夹","efficiency.folderPlaceholder":"按文件夹过滤,回车应用","efficiency.loadingExperiments":"正在加载配置比较…","efficiency.experimentsEmpty":"没有可比较的配置记录。","efficiency.experimentsError":"无法加载配置比较。","efficiency.difficultyNote":"任务难度未归一化。","efficiency.runsValue":"{value} 次运行","efficiency.medianElapsed":"耗时中位数","efficiency.medianBusy":"生成时间中位数","efficiency.medianTokens":"Token 中位数","efficiency.medianEstimatedCost":"预估费用中位数","efficiency.totalEstimatedCost":"预估费用合计","efficiency.reworkRate":"返工率","efficiency.errorRate":"错误率","efficiency.unpricedRuns":"未计价运行","efficiency.scopeAttributed":"仅当前角色体系","efficiency.scopeAll":"全部记录","efficiency.scopeSessions":"纳入会话","efficiency.scopeRuns":"纳入 run","efficiency.scopeExcludedRuns":"已排除 run"}}),l({id:"ko",label:"한국어",messages:s});var d=n(2730);let u="pi-locale",p=(0,i.createContext)(null);function h({children:e}){let[t,n]=(0,i.useState)("en"),[s,l]=(0,i.useState)(!1),m=(0,i.useMemo)(()=>c().map(e=>o.get(e)).filter(e=>!!e),[]),g=(0,i.useMemo)(()=>Object.fromEntries(c().flatMap(e=>{let t=o.get(e);return t?[[e,t.messages]]:[]})),[]);(0,i.useEffect)(()=>{let e=function(){var e;let t=null;try{t=window.localStorage.getItem(u)}catch{}let n=window.navigator.languages.length?window.navigator.languages:[window.navigator.language];return"string"==typeof(e=t)&&a.includes(e)?e:function(e){for(let t of e){let e=t.toLowerCase();if("en"===e||e.startsWith("en-"))return"en";if("ko"===e||e.startsWith("ko-"))break;if("zh"===e||e.startsWith("zh-"))return"zh-CN"}return"ko"}(n)}();n(e),document.documentElement.lang=e,l(!0)},[]);let f=(0,i.useCallback)(e=>{if(o.get(e)){n(e),document.documentElement.lang=e;try{window.localStorage.setItem(u,e)}catch{}}},[]),x=(0,i.useCallback)((e,n)=>(0,d.u0)(t,e,g,n),[t,g]),v=(0,i.useMemo)(()=>({locale:s?t:"en",setLocale:f,t:x,supportedLocales:m}),[s,t,f,x,m]);return(0,r.jsx)(p.Provider,{value:v,children:e})}function m(){let e=(0,i.useContext)(p);if(!e)throw Error("useI18n must be used inside I18nProvider");return e}},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"}}},e=>{e.O(0,[863,2100,7330,2545,8579,8441,3794,7358],()=>e(e.s=69575)),_N_E=e.O()}]);