cuelo 0.10.63 → 0.10.64

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 (61) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +24 -24
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/_not-found.html +1 -1
  18. package/.next/server/app/_not-found.rsc +3 -3
  19. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  20. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  21. package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  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 +2 -2
  25. package/.next/server/app/api/sessions/search/route.js +1 -1
  26. package/.next/server/app/api/skills/search/route.js +1 -1
  27. package/.next/server/app/api/updates/route.js +1 -1
  28. package/.next/server/app/index.html +1 -1
  29. package/.next/server/app/index.rsc +5 -5
  30. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  31. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  32. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  33. package/.next/server/app/index.segments/_index.segment.rsc +3 -3
  34. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  35. package/.next/server/app/page.js +2 -2
  36. package/.next/server/app/page_client-reference-manifest.js +1 -1
  37. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  38. package/.next/server/app/recover.html +1 -1
  39. package/.next/server/app/recover.rsc +3 -3
  40. package/.next/server/app/recover.segments/_full.segment.rsc +3 -3
  41. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  42. package/.next/server/app/recover.segments/_index.segment.rsc +3 -3
  43. package/.next/server/app/recover.segments/_tree.segment.rsc +2 -2
  44. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  45. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  46. package/.next/server/app-paths-manifest.json +24 -24
  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-c5595de9530a89ce.js → layout-8098cf3ae16b7456.js} +1 -1
  52. package/.next/static/chunks/app/{page-e8392556c750db83.js → page-76c2b89618aa9bf9.js} +3 -3
  53. package/.next/static/css/{c3eda266127d528b.css → 9d938d4b37937dcb.css} +1 -1
  54. package/.next/trace +108 -108
  55. package/.next/trace-build +1 -1
  56. package/README.md +3 -1
  57. package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
  58. package/Tools/OMP_Global_Config/agent/extensions/lib/cross-review.ts +5 -3
  59. package/package.json +1 -1
  60. /package/.next/static/{kdP9_fbz33acOidpEPBo6 → _jvVAFFZ2I5elmu3hRLde}/_buildManifest.js +0 -0
  61. /package/.next/static/{kdP9_fbz33acOidpEPBo6 → _jvVAFFZ2I5elmu3hRLde}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2730:(e,t,n)=>{"use strict";function r(e,t,n,i={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,i)}n.d(t,{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"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.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===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},42661:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>gH});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),o=n(81886),l=n(68890),c=n(6057);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,deckExpanded:!1}),f=Object.fromEntries(d.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===f[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let n,r=m(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=m(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}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,y=!1,b=-1/0;function w(e,t=Date.now()){y=e,e||(b=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function I(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function T(e,t){let n=null;for(let[r,i]of Object.entries(t.opened))(e.opened[r]??-1/0)>=i||((n??={...e.opened})[r]=i);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function R(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function E(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 $(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=E(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 L(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(E(e.key),e.order);let r=[...e],i=new Set(e.map(E));for(let e of t){let t=E(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(E(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 P=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function A(e){let t=e.match(P);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(92176);let z=`(max-width: ${p.navigator-1}px)`;function W(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 D=W("(max-width: 640px)"),O=W(z);function H(){return!1}function U(){return(0,i.useSyncExternalStore)(D.subscribe,D.getSnapshot,H)}var _=n(47650);async function B(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 q(){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 V(){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 K({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await B(e),n=t.path??e??"/";d(n),p(t.parentPath??null),f(!0===t.upToDrives),g(n),v(t.directories??[]),b(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),C()},[C]);let N=m.trim()!==c,I=!!c&&!N&&!n,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,_.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==y?(0,r.jsx)(r.Fragment,{children:y.length>0?y.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(V,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(q,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!I,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:I?1:.6,cursor:I?"pointer":"default"},children:s(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var G=n(21443),J=n.n(G);async function Z(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function Y({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),o=(0,i.useRef)(null),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,y]=(0,i.useState)(""),[b,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[R,E]=(0,i.useState)(50),$=p?.device?.state==="pending",L=n||S,P=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await Z("/api/github/projects");h(e),e.connected&&m((await Z("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function A(){j(!0),I(null);try{let{device:e}=await Z("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function z(e){if(e.preventDefault(),v.trim()&&!L){C(!0),I(null);try{let{cwd:e}=await Z("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{c(!0),P()},[P]),(0,i.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,i.useEffect)(()=>{let e;if(!$||d)return;let t=!1,n=async()=>{try{let e=await Z("/api/github/projects");if(t)return;if(h(e),e.connected)return void await P();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[$,d,P]),!l)return null;if(d)return(0,r.jsx)(K,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let W=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,_.createPortal)((0,r.jsx)("dialog",{ref:o,className:J().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),L||e()},children:(0,r.jsxs)("form",{onSubmit:z,className:J().form,children:[(0,r.jsxs)("header",{className:J().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:J().sources,children:[(0,r.jsx)("span",{className:J().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:L,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:J().body,children:[(0,r.jsxs)("section",{className:J().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:b||L,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void A(),disabled:b||k||$||L,children:k||$?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),$&&(0,r.jsxs)("div",{className:J().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:J().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:J().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:J().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:L}),b?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:J().list,children:W.slice(0,R).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:J().repo,"aria-pressed":v===e.fullName,disabled:L,onClick:()=>y(e.fullName),children:[(0,r.jsxs)("span",{className:J().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:J().repoDescription,children:e.description})]})},e.fullName))}),!W.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),W.length>R&&(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:J().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>y(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:L,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:J().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:L,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:J().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:J().footer,children:[(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:e,disabled:L,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:J().primary,disabled:L||!v.trim(),children:L?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function X({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var Q=n(2730);let ee={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브 통화로 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and a Codex live call on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,通过 ChatGPT 账号的 Codex 实时通话,把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","translator.open":"打开口译","translator.me":"我","translator.them":"对方","translator.myLanguage":"我的语言","translator.theirLanguage":"对方语言","translator.swap":"交换语言","translator.clear":"清除","translator.start":"开始口译","translator.stop":"结束口译","translator.empty":"按开始口译,把手机放在两人之间。无论谁说话,都会立即译成对方的语言说出来。","translator.connecting":"连接中…","translator.live":"正在听 \xb7 直接说话","translator.unsupported":"此浏览器不支持实时通话(WebRTC 和麦克风)。手机请用 Chrome 或 Safari 打开。","translator.insecure":"麦克风只能在 HTTPS 地址上使用。","translator.micDenied":"麦克风权限被阻止。请在浏览器设置中允许此地址使用麦克风。","translator.micUnavailable":"无法打开麦克风。请确认没有其他应用正在使用。","translator.auth":"Codex 登录不存在或已过期。请在模型设置中用 ChatGPT 账号重新登录。","translator.upstream":"Codex 实时连接已断开:{error}","translator.failed":"无法开始口译:{error}","translator.original":"原文","translator.translationPending":"口译中…","translator.conversation":"口译记录"}};function et(){let{locale:e}=(0,F.s)();return{tt:(0,i.useCallback)((t,n)=>(0,Q.u0)(e,t,ee,n),[e]),locale:e}}let en="omp-web:unread-session-ids",er="omp-web:pinned-session-ids",ei="omp-web:removed-projects";function ea(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 es(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eo({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 el({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(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 ec="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ed(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ec[Math.floor(Math.random()*ec.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.63/18.12.6":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.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)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(X,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eu(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 ep({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:f,translatorActive:m=!1,onTranslatorActiveChange:g}){let x,{tt:v}=et(),{t:y,locale:b}=(0,F.s)(),w=U(),[P,A]=(0,i.useState)([]),z=(0,i.useMemo)(()=>t&&!P.some(e=>e.id===t.id)?[t,...P]:P,[P,t]),[W,D]=(0,i.useState)(!0),[O,H]=(0,i.useState)(null),[_,B]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[G,J]=(0,i.useState)(!1),[Z,X]=(0,i.useState)(""),[Q,ee]=(0,i.useState)("projects"),[ec,ef]=(0,i.useState)(()=>new Set),[ev,ey]=(0,i.useState)(()=>new Set),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)({version:1,projects:[]}),[eI,eT]=(0,i.useState)(!1),[eM,eR]=(0,i.useState)(!1),[eE,e$]=(0,i.useState)(!1),[eL,eP]=(0,i.useState)(null),[eA,eF]=(0,i.useState)(""),[ez,eW]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(""),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)(!1),[eJ,eZ]=(0,i.useState)(null),[eY,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(""),[e8,e4]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(!1),[ti,ta]=(0,i.useState)(!1),[ts,to]=(0,i.useState)(()=>new Set),[tl,tc]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(en);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}})()),[td,tu]=(0,i.useState)(()=>new Set),[tp,th]=(0,i.useState)(null),[tf,tm]=(0,i.useState)(!1),tg=(0,i.useRef)(new Set),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(null);(0,i.useEffect)(()=>{tu(function(){try{let e=window.localStorage.getItem(er);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}}())},[]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}th(I(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=I(e.newValue,Date.now());th(e=>e?T(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let ty=(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}`);eN(await e.json())}catch{eN({version:1,projects:[]})}finally{eT(!0)}},[]);(0,i.useEffect)(()=>{ty()},[ty,c]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ei)}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 eu(n.map(e=>({key:E(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ei)}catch{}await ty()})()},[ty]);let tb=(0,i.useCallback)(async e=>{if(tr.current)throw Error("Project update in progress");tr.current=!0,eW(!0);try{await eu(e),await ty()}finally{tr.current=!1,eW(!1)}},[ty]);(0,i.useEffect)(()=>{eL&&tt.current?.select()},[eL]);let tw=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!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();A(r.sessions),tx.current||to(new Set(r.runningSessionIds??[])),H(null),e||(ta(!0),tv.current&&clearTimeout(tv.current),tv.current=setTimeout(()=>ta(!1),2e3))}catch(e){H(String(e))}finally{e&&D(!1)}},[]),tk=(0,i.useCallback)(e=>{tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tu(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),th(t=>t&&R(t,[e])),d?.(e),tw()},[tw,d]),[tj,tS]=(0,i.useState)(null),[tC,tN]=(0,i.useState)(!1),[tI,tT]=(0,i.useState)(null),tM=(0,i.useCallback)(()=>{tC||(tS(null),tT(null))},[tC]),tR=(0,i.useCallback)(async e=>{tN(!0),tT(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&&(tx.current=!0,to(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(tc(n),tu(n),th(e=>e&&R(e,t)),t))d?.(e)}(await tw(),tN(!1),r.length>0)?tT(y("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tS(null)},[tw,d,y]),[tE,t$]=(0,i.useState)(0),tL=(0,i.useCallback)(()=>{t$(e=>e+1),tw()},[tw]),tP=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tP.current;tP.current=!0,tw(e,!e)},[tw,c]),(0,i.useEffect)(()=>{try{ee(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 tA=(0,i.useCallback)(e=>{ee(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&&tw(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tw,Q]),(0,i.useEffect)(()=>{try{0===tl.size?window.localStorage.removeItem(en):window.localStorage.setItem(en,JSON.stringify([...tl]))}catch{}},[tl]),(0,i.useEffect)(()=>{try{0===td.size?window.localStorage.removeItem(er):window.localStorage.setItem(er,JSON.stringify([...td]))}catch{}},[td]),(0,i.useEffect)(()=>{if(tp)try{var e,t,n;let r,i,a=window.localStorage;a.setItem(N,(e=a.getItem(N),t=Date.now(),i=(r=Object.entries((n=T(tp,I(e,t))).opened)).length>500?r.sort((e,t)=>t[1]-e[1]).slice(0,500):r,JSON.stringify({since:n.since,opened:Object.fromEntries(i)})))}catch{}},[tp]);let tF=(0,i.useCallback)(e=>{tu(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;tx.current=!0,to(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tg.current,n=[...t].filter(t=>!ts.has(t)&&t!==e),r=[...ts].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tc(e=>{let t=new Set(e);return ts.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!P.some(t=>t.id===e));(n.length>0||i)&&tw(!1,!0),n.length>0&&h?.(),tg.current=ts},[ts,e,P,tw,h]),(0,i.useEffect)(()=>{e&&tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let tz=e?z.find(t=>t.id===e)?.modified:void 0,tW=null!==tp;(0,i.useEffect)(()=>{e&&void 0!==tz&&tW&&th(t=>{var n;let r;return t&&(n={id:e,modified:tz},r=Math.max(Date.now(),M(n)??0),(t.opened[n.id]??-1/0)>=r?t:{since:t.since,opened:{...t.opened,[n.id]:r}})})},[e,tz,tW]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tD=(0,i.useRef)(!1),tO=(0,i.useCallback)(e=>{if(!e)return null;if(eJ&&eJ.forCwd===e||eJ?.worktrees.some(t=>t.path===e))return eJ.projectRoot;let t=z.find(t=>t.cwd===e);return t?.projectRoot??e},[eJ,z]),tH=(0,i.useRef)(null);(0,i.useEffect)(()=>{tH.current!==_&&(tH.current=_,p?.(_,tO(_)))},[_,p,tO]);let tU=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tU.current&&(tU.current=u,B(u))},[u]);let[t_,tB]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!_)return void eZ(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(_)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eZ(null);eZ({forCwd:_,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eZ(null)}),()=>{e=!0}},[_,t_,c]),(0,i.useEffect)(()=>{if(0!==P.length&&!o&&null===_){if(s&&!tD.current){tD.current=!0;let e=P.find(e=>e.id===s);if(e){B(e.cwd),n(e,!0);return}l?.()}if(!eI)return;let e=new Map(eC.projects.map(e=>[e.key,e])),t=L(P.length>0?$(P):[],eC.projects).filter(t=>!e.get(E(t))?.hidden);t.length>0&&B(t[0])}},[P,_,s,o,n,l,eC,eI]);let tq=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eK){eG(!0),eV(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 eV(n.error??y("workspace.unable"));let r=n.cwd??t,i=E(r),a=eC.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tb([{key:i,path:r,hidden:!1}])}catch{}B(r),eB(!1)}catch{eV(y("workspace.unable"))}finally{eG(!1)}}},[tb,eK,eC.projects,y]),tV=(0,i.useCallback)(()=>{eB(!0),eV(null)},[]),tK=(0,i.useCallback)(async()=>{let e=e1.trim();if(e&&!e5&&eJ){e6(!0),e4(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e4(n.error??`HTTP ${t.status}`);e0(!1),e2(""),eX(!1),eZ(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[e1,e5,eJ]),tG=(0,i.useCallback)(async(e,t)=>{if(eJ&&!e5){e6(!0),e4(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e7(e);e4(r.error??`HTTP ${n.status}`);return}e7(null),_===e&&B(eJ.projectRoot),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[eJ,e5,_]);(0,i.useEffect)(()=>{let e=e=>{e9.current&&!e9.current.contains(e.target)&&(eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU(""),ek(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tJ=(0,i.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),tZ=(0,i.useCallback)((e=_)=>{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)}`;B(e),a?.(t,e)},[_,a]),[tY,tX]=(0,i.useState)(!1),[tQ,t0]=(0,i.useState)(null),t1=(0,i.useCallback)(async()=>{tX(!0),t0(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}`);tZ(t.cwd)}catch(e){t0(y("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tX(!1)}},[tZ,y]),t2=(0,i.useCallback)(e=>{ey(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),t8=tO(_),t4=null===t8?null:E(t8),t5=(0,i.useMemo)(()=>new Map(eC.projects.map(e=>[e.key,e])),[eC.projects]),t6=$(z);if(null!==t8){let e=E(t8);t6.some(t=>E(t)===e)||t6.unshift(t8)}let t3=L(t6,eC.projects),t7=t3.filter(e=>eM||!t5.get(E(e))?.hidden),t9=t3.some(e=>t5.get(E(e))?.hidden),ne=()=>{eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU("")},nt=async(e,t)=>{ne();try{await tb([{key:E(e),path:e,hidden:t}]),t&&t4&&t4===E(e)&&B(null),t||t3.some(t=>E(t)!==E(e)&&t5.get(E(t))?.hidden)||eR(!1)}catch{}},nn=async e=>{if(tn.current){tn.current=!1,eP(null);return}let t=eA.trim();if(t===(t5.get(E(e))?.alias??""))return void eP(null);eO(null);try{await tb([{key:E(e),path:e,alias:t||null}]),eP(null)}catch{eO(y("sidebar.projectUpdateFailed"))}},nr=async(e,t)=>{if(Z)return;let n=t7.indexOf(e),r=n+t;if(n<0||r<0||r>=t7.length)return;let i=new Set(t7),a=t3.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...t3],o=a[n],l=a[r];[s[o],s[l]]=[s[l],s[o]],ne();try{await tb(s.map((e,t)=>({key:E(e),path:e,order:t})))}catch{}},ni=new Map;for(let e of z){let t=e.projectRoot??e.cwd;if(!t)continue;let n=E(t),r=ni.get(n);r?r.push(e):ni.set(n,[e])}let na=(0,i.useMemo)(()=>{let e=new Map;for(let t of z){let n=t.projectRoot??t.cwd;if(!n)continue;let r=E(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),ts.has(t.id)&&i.running++,tl.has(t.id)&&i.unread++}return e},[z,ts,tl]),ns=Z.trim().toLowerCase(),no=Z.length>0,nl=t7.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=E(e),r=t5.get(n),i=r?.alias??t,a=(ni.get(n)??[]).slice().sort((e,t)=>{let n=Number(td.has(t.id))-Number(td.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!ns)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(ns)||t.toLowerCase().includes(ns),o=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(ns));return s||0!==o.length?[{project:e,key:n,name:i,sessions:s?a:o,hidden:r?.hidden===!0}]:[]}),nc=[],nd=[];for(let e of nl){let t=e.key===t4||(na.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?nd.push(e):nc.push(e)}let nu={running:0,unread:0};for(let e of nd){let t=na.get(e.key);t&&(nu.running+=t.running,nu.unread+=t.unread)}let np=no||eE,nh=[...nc.map(e=>({kind:"project",group:e})),...nd.length>0?[{kind:"temporary"}]:[],...np?nd.map(e=>({kind:"project",group:e})):[]],nf=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))}(nh.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nm=(0,i.useMemo)(()=>tp?z.filter(e=>(function(e,t,n){if(e.transient||t.has(e.id))return!1;let r=M(e);return null!==r&&r>(n.opened[e.id]??n.since)})(e,ts,tp)):[],[tp,ts,z]),ng=tf&&null!==tp,[nx,nv]=(0,i.useState)(null),ny=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),c=l.filter(e=>a.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(p>=o)continue;p+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=u.get(r);i?i.push(e):u.set(r,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:i,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.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(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:u.get(e)??[]});return h})(ng?z.filter(e=>e.id===nx&&!ts.has(e.id)||nm.includes(e)):z,ts,new Date,b,y("navigator.priority"),td,y("sidebar.pinned"),ng?1/0:void 0),[nx,b,td,nm,ng,ts,z,y]),nb=(0,i.useCallback)(e=>{nv(e.id),tJ(e)},[tJ]),nw=!!(eJ?.isGit&&eJ.isTopLevel&&_&&t8===eJ.projectRoot),nk=eJ?.worktrees.find(e=>e.path===_)??eJ?.worktrees.find(e=>e.isMain),nj=(eJ?.worktrees.length??0)>=8,nS=nj&&eH.trim()?(eJ?.worktrees??[]).filter(e=>(e.branch??es(e.path,q)).toLowerCase().includes(eH.trim().toLowerCase())):eJ?.worktrees??[],nC=(()=>{if(!tj)return[];let e="project"===tj.kind?ni.get(E(tj.project))??[]:ny.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nN=nC.filter(e=>!ts.has(e.id)),nI=e=>{let t=new Set;for(let n of e)n.transient||ts.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nT=void 0!==f&&m;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[e_&&(0,r.jsx)(G?Y:K,{busy:eK,error:eq,onCancel:()=>{eB(!1),eV(null)},onSelect:e=>void tq(e)}),tj&&(0,r.jsx)(eh,{scope:tj,eligible:nN.length,runningExcluded:nC.length-nN.length,busy:tC,error:tI,onCancel:tM,onConfirm:()=>void tR(nN)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ed,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>tZ(),disabled:!_,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:_?"var(--text-muted)":"var(--text-dim)",cursor:_?"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:_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),"aria-label":_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),onMouseEnter:e=>{_&&(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=_?"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${ti?" is-success":""}`,onClick:()=>tw(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ti?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ti?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ti?"#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=>{ti||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{ti||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:y("sidebar.refresh"),children:ti?(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"})]})})]})]})}),G&&!nT&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tV,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:y("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":y("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?y("sidebar.projects"):y("navigator.priority"),n=!nT&&Q===e;return(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tA(e),nT&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==f&&(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:v("translator.tab")}),"aria-pressed":nT,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!nT),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:nT?"var(--bg-selected)":"transparent",color:nT?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nT?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!nT&&"projects"===Q&&(0,r.jsx)("button",{type:"button",onClick:()=>eR(e=>!e),disabled:!t9,title:y("sidebar.projectShowHidden"),"aria-label":y("sidebar.projectShowHidden"),"aria-pressed":eM,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eM?"var(--bg-selected)":"transparent",color:eM?"var(--accent)":"var(--text-dim)",cursor:t9?"pointer":"default",opacity:t9?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"}),!eM&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nT&&"projects"===Q&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tV,title:y("sidebar.addProject"),"aria-label":y("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"})]})})]}),nT&&f,!nT&&"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:Z,onChange:e=>X(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),X(""),e.currentTarget.blur())},placeholder:y("sidebar.searchProjectsAndSessions"),"aria-label":y("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}})]}),!nT&&"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:[(W||!eI)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),eD&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!W&&eI&&!O&&0===nl.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ns?y("sidebar.noMatchingProjects"):y("sidebar.noSessions")}),!W&&eI&&!O&&nh.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":np,title:y("sidebar.temporaryProjects"),onClick:()=>e$(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:np?"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:y("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nd.length}),eb(nu,y)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t4,p=nf.has(l.toLowerCase())&&es((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),q)||null,h=!ev.has(s)&&!ns,f=ec.has(s),m=eL===s,g=t7.indexOf(s),x=ez||no||g<=0,v=ez||no||g>=t7.length-1,b=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}(f?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:ej===s?e9:void 0,onMouseEnter:()=>ek(s),onMouseLeave:()=>ek(e=>e===s&&ej!==s?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:()=>t2(s),title:h?y("sidebar.expandProject"):y("sidebar.collapseProject"),"aria-label":h?y("sidebar.expandProject"):y("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"})})}),m?(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:tt,value:eA,onChange:e=>eF(e.target.value),onBlur:()=>void nn(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tn.current=!0,eP(null))},"aria-label":y("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:()=>B(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children: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}),eb(na.get(o),y)]}),(0,r.jsx)("button",{type:"button",onClick:()=>tZ(s),title:y("sidebar.newSessionTitle",{path:s}),"aria-label":y("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||ew===s?1:0,pointerEvents:w||ew===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ek(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eS(ej===s?null:s),eX(!1),e0(!1),e4(null),u||B(s)},title:y("sidebar.projectActions"),"aria-label":y("sidebar.projectActions"),"aria-expanded":ej===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ej===s?"var(--bg-selected)":"transparent",color:u&&nk&&!nk.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ew===s||ej===s?1:0,pointerEvents:w||ew===s||ej===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ek(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(el,{open:ej===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[nw&&eJ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eX(e=>!e),title:nk?y("sidebar.switchWorktreeTitle",{path:nk.path}):y("sidebar.switchWorktree"),"aria-label":y("sidebar.worktrees"),"aria-expanded":eY,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eY?"1px solid var(--border)":"none",background:eY?"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:y("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)(el,{open:eY,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:[nj&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eH,onChange:e=>eU(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eU(""),eX(!1))},placeholder:y("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===_||e.isMain&&!eJ.worktrees.some(e=>e.path===_);return e3===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:y("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tG(e.path,!0),disabled:e5,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:y("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>e7(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:y("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:()=>{B(e.path),eX(!1),e4(null),eU("")},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)(eo,{text:e.branch??es(e.path,q),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:y("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tG(e.path,!1),disabled:e5,title:y("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)}),nj&&0===nS.length&&eH.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:y("sidebar.noMatchingWorktrees")})]}),eQ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:te,value:e1,onChange:e=>{e2(e.target.value),e4(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tK()),"Escape"===e.key&&(e0(!1),e2(""),e4(null))},placeholder:y("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 tK(),disabled:e5||!e1.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e5||!e1.trim()?"not-allowed":"pointer",opacity:e5||!e1.trim()?.65:1},children:e5?y("sidebar.creating"):y("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e0(!1),e2(""),e4(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:y("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e0(!0),e4(null),setTimeout(()=>te.current?.focus(),0)},title:y("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:y("sidebar.newWorktree")})]}),e8&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e8})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=t5.get(E(s))?.alias??"",void(tn.current=!1,eO(null),eF(e),eP(s),ne())},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:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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"})]}),y(t5.get(E(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),y("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),y("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>void nt(s,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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"})]}),y(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nI(ni.get(o)??[])||tC,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{ne(),tT(null),tS({kind:"project",project:s,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:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),y("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:y("sidebar.noSessions")}),!h&&b.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:b.map(t=>(0,r.jsx)(ex,{node:t,selectedSessionId:e,runningSessionIds:ts,unreadSessionIds:tl,pinnedSessionIds:td,onSelectSession:tJ,onTogglePinnedSession:tF,onRenamed:tw,onSessionDeleted:tk,onSessionArchived:tL,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ef(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?y("sidebar.showLess"):y("sidebar.showMore")})]},s)})]}),!nT&&(0,r.jsx)(eg,{refreshKey:tE,selectedSessionId:e,onSelectSession:tJ,onRestored:tL}),!nT&&"priority"===Q&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[W&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),!W&&!O&&(x=nI(ny.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:tY,onClick:()=>void t1(),title:y("sidebar.newScratchSessionTitle"),style:ea(tY,w),children:y("sidebar.newScratchSession")}),ny.length>0&&!ng&&(0,r.jsx)("button",{type:"button",disabled:0===x||tC,onClick:()=>{tT(null),tS({kind:"priority"})},style:ea(0===x||tC,w),children:y("sidebar.clearPriorityList")})]})),!W&&!O&&tp&&(0,r.jsx)("div",{style:{display:"flex",padding:"6px 2px 4px"},children:(0,r.jsxs)("button",{type:"button","aria-pressed":ng,"aria-label":y("navigator.resultsToCheckCount",{count:nm.length}),title:y("navigator.resultsToCheckHint"),onClick:()=>{nv(null),tm(e=>!e)},style:{...ea(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ng?"var(--border-strong)":"var(--border)",background:ng?"var(--bg-selected)":"transparent",color:ng||nm.length>0?"var(--text)":"var(--text-muted)",fontWeight:ng?600:500,whiteSpace:"nowrap"},children:[y("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:9,background:nm.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nm.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nm.length})]})}),tQ&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tQ}),!W&&!O&&0===ny.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ng?y("navigator.resultsToCheckEmpty"):y("sidebar.noSessions")}),!W&&!O&&ny.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)(em,{session:t,selected:t.id===e,running:ts.has(t.id),unread:tl.has(t.id),pinned:td.has(t.id),onSelect:ng?nb:tJ,onTogglePin:tF},t.id))]},t.key))]})]})}function eh({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,F.s)(),d=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let f=(0,i.useRef)(o);return f.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(),f.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||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")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":a,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(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ef({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 em({session:e,selected:t,running:n,unread:i,pinned:a,onSelect:s,onTogglePin:o}){let{t:l}=(0,F.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:()=>s(e),title:`${c}
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2730:(e,t,n)=>{"use strict";function r(e,t,n,i={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,i)}n.d(t,{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"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.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===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},42661:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>gH});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),o=n(81886),l=n(68890),c=n(6057);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,deckExpanded:!1}),f=Object.fromEntries(d.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===f[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let n,r=m(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=m(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}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,y=!1,b=-1/0;function w(e,t=Date.now()){y=e,e||(b=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function I(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function T(e,t){let n=null;for(let[r,i]of Object.entries(t.opened))(e.opened[r]??-1/0)>=i||((n??={...e.opened})[r]=i);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function R(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function E(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 $(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=E(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 L(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(E(e.key),e.order);let r=[...e],i=new Set(e.map(E));for(let e of t){let t=E(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(E(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 P=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function A(e){let t=e.match(P);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(92176);let z=`(max-width: ${p.navigator-1}px)`;function W(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 D=W("(max-width: 640px)"),O=W(z);function H(){return!1}function U(){return(0,i.useSyncExternalStore)(D.subscribe,D.getSnapshot,H)}var _=n(47650);async function B(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 q(){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 V(){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 K({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await B(e),n=t.path??e??"/";d(n),p(t.parentPath??null),f(!0===t.upToDrives),g(n),v(t.directories??[]),b(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),C()},[C]);let N=m.trim()!==c,I=!!c&&!N&&!n,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,_.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==y?(0,r.jsx)(r.Fragment,{children:y.length>0?y.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(V,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(q,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!I,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:I?1:.6,cursor:I?"pointer":"default"},children:s(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var G=n(21443),J=n.n(G);async function Z(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function Y({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),o=(0,i.useRef)(null),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,y]=(0,i.useState)(""),[b,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[R,E]=(0,i.useState)(50),$=p?.device?.state==="pending",L=n||S,P=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await Z("/api/github/projects");h(e),e.connected&&m((await Z("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function A(){j(!0),I(null);try{let{device:e}=await Z("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function z(e){if(e.preventDefault(),v.trim()&&!L){C(!0),I(null);try{let{cwd:e}=await Z("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{c(!0),P()},[P]),(0,i.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,i.useEffect)(()=>{let e;if(!$||d)return;let t=!1,n=async()=>{try{let e=await Z("/api/github/projects");if(t)return;if(h(e),e.connected)return void await P();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[$,d,P]),!l)return null;if(d)return(0,r.jsx)(K,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let W=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,_.createPortal)((0,r.jsx)("dialog",{ref:o,className:J().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),L||e()},children:(0,r.jsxs)("form",{onSubmit:z,className:J().form,children:[(0,r.jsxs)("header",{className:J().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:J().sources,children:[(0,r.jsx)("span",{className:J().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:L,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:J().body,children:[(0,r.jsxs)("section",{className:J().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:b||L,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void A(),disabled:b||k||$||L,children:k||$?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),$&&(0,r.jsxs)("div",{className:J().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:J().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:J().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:J().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:L}),b?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:J().list,children:W.slice(0,R).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:J().repo,"aria-pressed":v===e.fullName,disabled:L,onClick:()=>y(e.fullName),children:[(0,r.jsxs)("span",{className:J().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:J().repoDescription,children:e.description})]})},e.fullName))}),!W.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),W.length>R&&(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:J().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>y(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:L,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:J().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:L,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:J().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:J().footer,children:[(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:e,disabled:L,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:J().primary,disabled:L||!v.trim(),children:L?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function X({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var Q=n(2730);let ee={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브 통화로 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and a Codex live call on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,通过 ChatGPT 账号的 Codex 实时通话,把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","translator.open":"打开口译","translator.me":"我","translator.them":"对方","translator.myLanguage":"我的语言","translator.theirLanguage":"对方语言","translator.swap":"交换语言","translator.clear":"清除","translator.start":"开始口译","translator.stop":"结束口译","translator.empty":"按开始口译,把手机放在两人之间。无论谁说话,都会立即译成对方的语言说出来。","translator.connecting":"连接中…","translator.live":"正在听 \xb7 直接说话","translator.unsupported":"此浏览器不支持实时通话(WebRTC 和麦克风)。手机请用 Chrome 或 Safari 打开。","translator.insecure":"麦克风只能在 HTTPS 地址上使用。","translator.micDenied":"麦克风权限被阻止。请在浏览器设置中允许此地址使用麦克风。","translator.micUnavailable":"无法打开麦克风。请确认没有其他应用正在使用。","translator.auth":"Codex 登录不存在或已过期。请在模型设置中用 ChatGPT 账号重新登录。","translator.upstream":"Codex 实时连接已断开:{error}","translator.failed":"无法开始口译:{error}","translator.original":"原文","translator.translationPending":"口译中…","translator.conversation":"口译记录"}};function et(){let{locale:e}=(0,F.s)();return{tt:(0,i.useCallback)((t,n)=>(0,Q.u0)(e,t,ee,n),[e]),locale:e}}let en="omp-web:unread-session-ids",er="omp-web:pinned-session-ids",ei="omp-web:removed-projects";function ea(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 es(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eo({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 el({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(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 ec="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ed(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ec[Math.floor(Math.random()*ec.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.64/18.12.6":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.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)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(X,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eu(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 ep({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:f,translatorActive:m=!1,onTranslatorActiveChange:g}){let x,{tt:v}=et(),{t:y,locale:b}=(0,F.s)(),w=U(),[P,A]=(0,i.useState)([]),z=(0,i.useMemo)(()=>t&&!P.some(e=>e.id===t.id)?[t,...P]:P,[P,t]),[W,D]=(0,i.useState)(!0),[O,H]=(0,i.useState)(null),[_,B]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[G,J]=(0,i.useState)(!1),[Z,X]=(0,i.useState)(""),[Q,ee]=(0,i.useState)("projects"),[ec,ef]=(0,i.useState)(()=>new Set),[ev,ey]=(0,i.useState)(()=>new Set),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)({version:1,projects:[]}),[eI,eT]=(0,i.useState)(!1),[eM,eR]=(0,i.useState)(!1),[eE,e$]=(0,i.useState)(!1),[eL,eP]=(0,i.useState)(null),[eA,eF]=(0,i.useState)(""),[ez,eW]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(""),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)(!1),[eJ,eZ]=(0,i.useState)(null),[eY,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(""),[e8,e4]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(!1),[ti,ta]=(0,i.useState)(!1),[ts,to]=(0,i.useState)(()=>new Set),[tl,tc]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(en);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}})()),[td,tu]=(0,i.useState)(()=>new Set),[tp,th]=(0,i.useState)(null),[tf,tm]=(0,i.useState)(!1),tg=(0,i.useRef)(new Set),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(null);(0,i.useEffect)(()=>{tu(function(){try{let e=window.localStorage.getItem(er);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}}())},[]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}th(I(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=I(e.newValue,Date.now());th(e=>e?T(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let ty=(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}`);eN(await e.json())}catch{eN({version:1,projects:[]})}finally{eT(!0)}},[]);(0,i.useEffect)(()=>{ty()},[ty,c]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ei)}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 eu(n.map(e=>({key:E(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ei)}catch{}await ty()})()},[ty]);let tb=(0,i.useCallback)(async e=>{if(tr.current)throw Error("Project update in progress");tr.current=!0,eW(!0);try{await eu(e),await ty()}finally{tr.current=!1,eW(!1)}},[ty]);(0,i.useEffect)(()=>{eL&&tt.current?.select()},[eL]);let tw=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!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();A(r.sessions),tx.current||to(new Set(r.runningSessionIds??[])),H(null),e||(ta(!0),tv.current&&clearTimeout(tv.current),tv.current=setTimeout(()=>ta(!1),2e3))}catch(e){H(String(e))}finally{e&&D(!1)}},[]),tk=(0,i.useCallback)(e=>{tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tu(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),th(t=>t&&R(t,[e])),d?.(e),tw()},[tw,d]),[tj,tS]=(0,i.useState)(null),[tC,tN]=(0,i.useState)(!1),[tI,tT]=(0,i.useState)(null),tM=(0,i.useCallback)(()=>{tC||(tS(null),tT(null))},[tC]),tR=(0,i.useCallback)(async e=>{tN(!0),tT(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&&(tx.current=!0,to(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(tc(n),tu(n),th(e=>e&&R(e,t)),t))d?.(e)}(await tw(),tN(!1),r.length>0)?tT(y("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tS(null)},[tw,d,y]),[tE,t$]=(0,i.useState)(0),tL=(0,i.useCallback)(()=>{t$(e=>e+1),tw()},[tw]),tP=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tP.current;tP.current=!0,tw(e,!e)},[tw,c]),(0,i.useEffect)(()=>{try{ee(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 tA=(0,i.useCallback)(e=>{ee(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&&tw(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tw,Q]),(0,i.useEffect)(()=>{try{0===tl.size?window.localStorage.removeItem(en):window.localStorage.setItem(en,JSON.stringify([...tl]))}catch{}},[tl]),(0,i.useEffect)(()=>{try{0===td.size?window.localStorage.removeItem(er):window.localStorage.setItem(er,JSON.stringify([...td]))}catch{}},[td]),(0,i.useEffect)(()=>{if(tp)try{var e,t,n;let r,i,a=window.localStorage;a.setItem(N,(e=a.getItem(N),t=Date.now(),i=(r=Object.entries((n=T(tp,I(e,t))).opened)).length>500?r.sort((e,t)=>t[1]-e[1]).slice(0,500):r,JSON.stringify({since:n.since,opened:Object.fromEntries(i)})))}catch{}},[tp]);let tF=(0,i.useCallback)(e=>{tu(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;tx.current=!0,to(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tg.current,n=[...t].filter(t=>!ts.has(t)&&t!==e),r=[...ts].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tc(e=>{let t=new Set(e);return ts.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!P.some(t=>t.id===e));(n.length>0||i)&&tw(!1,!0),n.length>0&&h?.(),tg.current=ts},[ts,e,P,tw,h]),(0,i.useEffect)(()=>{e&&tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let tz=e?z.find(t=>t.id===e)?.modified:void 0,tW=null!==tp;(0,i.useEffect)(()=>{e&&void 0!==tz&&tW&&th(t=>{var n;let r;return t&&(n={id:e,modified:tz},r=Math.max(Date.now(),M(n)??0),(t.opened[n.id]??-1/0)>=r?t:{since:t.since,opened:{...t.opened,[n.id]:r}})})},[e,tz,tW]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tD=(0,i.useRef)(!1),tO=(0,i.useCallback)(e=>{if(!e)return null;if(eJ&&eJ.forCwd===e||eJ?.worktrees.some(t=>t.path===e))return eJ.projectRoot;let t=z.find(t=>t.cwd===e);return t?.projectRoot??e},[eJ,z]),tH=(0,i.useRef)(null);(0,i.useEffect)(()=>{tH.current!==_&&(tH.current=_,p?.(_,tO(_)))},[_,p,tO]);let tU=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tU.current&&(tU.current=u,B(u))},[u]);let[t_,tB]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!_)return void eZ(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(_)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eZ(null);eZ({forCwd:_,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eZ(null)}),()=>{e=!0}},[_,t_,c]),(0,i.useEffect)(()=>{if(0!==P.length&&!o&&null===_){if(s&&!tD.current){tD.current=!0;let e=P.find(e=>e.id===s);if(e){B(e.cwd),n(e,!0);return}l?.()}if(!eI)return;let e=new Map(eC.projects.map(e=>[e.key,e])),t=L(P.length>0?$(P):[],eC.projects).filter(t=>!e.get(E(t))?.hidden);t.length>0&&B(t[0])}},[P,_,s,o,n,l,eC,eI]);let tq=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eK){eG(!0),eV(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 eV(n.error??y("workspace.unable"));let r=n.cwd??t,i=E(r),a=eC.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tb([{key:i,path:r,hidden:!1}])}catch{}B(r),eB(!1)}catch{eV(y("workspace.unable"))}finally{eG(!1)}}},[tb,eK,eC.projects,y]),tV=(0,i.useCallback)(()=>{eB(!0),eV(null)},[]),tK=(0,i.useCallback)(async()=>{let e=e1.trim();if(e&&!e5&&eJ){e6(!0),e4(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e4(n.error??`HTTP ${t.status}`);e0(!1),e2(""),eX(!1),eZ(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[e1,e5,eJ]),tG=(0,i.useCallback)(async(e,t)=>{if(eJ&&!e5){e6(!0),e4(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e7(e);e4(r.error??`HTTP ${n.status}`);return}e7(null),_===e&&B(eJ.projectRoot),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[eJ,e5,_]);(0,i.useEffect)(()=>{let e=e=>{e9.current&&!e9.current.contains(e.target)&&(eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU(""),ek(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tJ=(0,i.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),tZ=(0,i.useCallback)((e=_)=>{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)}`;B(e),a?.(t,e)},[_,a]),[tY,tX]=(0,i.useState)(!1),[tQ,t0]=(0,i.useState)(null),t1=(0,i.useCallback)(async()=>{tX(!0),t0(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}`);tZ(t.cwd)}catch(e){t0(y("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tX(!1)}},[tZ,y]),t2=(0,i.useCallback)(e=>{ey(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),t8=tO(_),t4=null===t8?null:E(t8),t5=(0,i.useMemo)(()=>new Map(eC.projects.map(e=>[e.key,e])),[eC.projects]),t6=$(z);if(null!==t8){let e=E(t8);t6.some(t=>E(t)===e)||t6.unshift(t8)}let t3=L(t6,eC.projects),t7=t3.filter(e=>eM||!t5.get(E(e))?.hidden),t9=t3.some(e=>t5.get(E(e))?.hidden),ne=()=>{eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU("")},nt=async(e,t)=>{ne();try{await tb([{key:E(e),path:e,hidden:t}]),t&&t4&&t4===E(e)&&B(null),t||t3.some(t=>E(t)!==E(e)&&t5.get(E(t))?.hidden)||eR(!1)}catch{}},nn=async e=>{if(tn.current){tn.current=!1,eP(null);return}let t=eA.trim();if(t===(t5.get(E(e))?.alias??""))return void eP(null);eO(null);try{await tb([{key:E(e),path:e,alias:t||null}]),eP(null)}catch{eO(y("sidebar.projectUpdateFailed"))}},nr=async(e,t)=>{if(Z)return;let n=t7.indexOf(e),r=n+t;if(n<0||r<0||r>=t7.length)return;let i=new Set(t7),a=t3.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...t3],o=a[n],l=a[r];[s[o],s[l]]=[s[l],s[o]],ne();try{await tb(s.map((e,t)=>({key:E(e),path:e,order:t})))}catch{}},ni=new Map;for(let e of z){let t=e.projectRoot??e.cwd;if(!t)continue;let n=E(t),r=ni.get(n);r?r.push(e):ni.set(n,[e])}let na=(0,i.useMemo)(()=>{let e=new Map;for(let t of z){let n=t.projectRoot??t.cwd;if(!n)continue;let r=E(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),ts.has(t.id)&&i.running++,tl.has(t.id)&&i.unread++}return e},[z,ts,tl]),ns=Z.trim().toLowerCase(),no=Z.length>0,nl=t7.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=E(e),r=t5.get(n),i=r?.alias??t,a=(ni.get(n)??[]).slice().sort((e,t)=>{let n=Number(td.has(t.id))-Number(td.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!ns)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(ns)||t.toLowerCase().includes(ns),o=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(ns));return s||0!==o.length?[{project:e,key:n,name:i,sessions:s?a:o,hidden:r?.hidden===!0}]:[]}),nc=[],nd=[];for(let e of nl){let t=e.key===t4||(na.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?nd.push(e):nc.push(e)}let nu={running:0,unread:0};for(let e of nd){let t=na.get(e.key);t&&(nu.running+=t.running,nu.unread+=t.unread)}let np=no||eE,nh=[...nc.map(e=>({kind:"project",group:e})),...nd.length>0?[{kind:"temporary"}]:[],...np?nd.map(e=>({kind:"project",group:e})):[]],nf=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))}(nh.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nm=(0,i.useMemo)(()=>tp?z.filter(e=>(function(e,t,n){if(e.transient||t.has(e.id))return!1;let r=M(e);return null!==r&&r>(n.opened[e.id]??n.since)})(e,ts,tp)):[],[tp,ts,z]),ng=tf&&null!==tp,[nx,nv]=(0,i.useState)(null),ny=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),c=l.filter(e=>a.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(p>=o)continue;p+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=u.get(r);i?i.push(e):u.set(r,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:i,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.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(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:u.get(e)??[]});return h})(ng?z.filter(e=>e.id===nx&&!ts.has(e.id)||nm.includes(e)):z,ts,new Date,b,y("navigator.priority"),td,y("sidebar.pinned"),ng?1/0:void 0),[nx,b,td,nm,ng,ts,z,y]),nb=(0,i.useCallback)(e=>{nv(e.id),tJ(e)},[tJ]),nw=!!(eJ?.isGit&&eJ.isTopLevel&&_&&t8===eJ.projectRoot),nk=eJ?.worktrees.find(e=>e.path===_)??eJ?.worktrees.find(e=>e.isMain),nj=(eJ?.worktrees.length??0)>=8,nS=nj&&eH.trim()?(eJ?.worktrees??[]).filter(e=>(e.branch??es(e.path,q)).toLowerCase().includes(eH.trim().toLowerCase())):eJ?.worktrees??[],nC=(()=>{if(!tj)return[];let e="project"===tj.kind?ni.get(E(tj.project))??[]:ny.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nN=nC.filter(e=>!ts.has(e.id)),nI=e=>{let t=new Set;for(let n of e)n.transient||ts.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nT=void 0!==f&&m;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[e_&&(0,r.jsx)(G?Y:K,{busy:eK,error:eq,onCancel:()=>{eB(!1),eV(null)},onSelect:e=>void tq(e)}),tj&&(0,r.jsx)(eh,{scope:tj,eligible:nN.length,runningExcluded:nC.length-nN.length,busy:tC,error:tI,onCancel:tM,onConfirm:()=>void tR(nN)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ed,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>tZ(),disabled:!_,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:_?"var(--text-muted)":"var(--text-dim)",cursor:_?"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:_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),"aria-label":_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),onMouseEnter:e=>{_&&(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=_?"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${ti?" is-success":""}`,onClick:()=>tw(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ti?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ti?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ti?"#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=>{ti||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{ti||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:y("sidebar.refresh"),children:ti?(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"})]})})]})]})}),G&&!nT&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tV,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:y("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":y("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?y("sidebar.projects"):y("navigator.priority"),n=!nT&&Q===e;return(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tA(e),nT&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==f&&(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:v("translator.tab")}),"aria-pressed":nT,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!nT),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:nT?"var(--bg-selected)":"transparent",color:nT?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nT?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!nT&&"projects"===Q&&(0,r.jsx)("button",{type:"button",onClick:()=>eR(e=>!e),disabled:!t9,title:y("sidebar.projectShowHidden"),"aria-label":y("sidebar.projectShowHidden"),"aria-pressed":eM,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eM?"var(--bg-selected)":"transparent",color:eM?"var(--accent)":"var(--text-dim)",cursor:t9?"pointer":"default",opacity:t9?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"}),!eM&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nT&&"projects"===Q&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tV,title:y("sidebar.addProject"),"aria-label":y("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"})]})})]}),nT&&f,!nT&&"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:Z,onChange:e=>X(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),X(""),e.currentTarget.blur())},placeholder:y("sidebar.searchProjectsAndSessions"),"aria-label":y("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}})]}),!nT&&"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:[(W||!eI)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),eD&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!W&&eI&&!O&&0===nl.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ns?y("sidebar.noMatchingProjects"):y("sidebar.noSessions")}),!W&&eI&&!O&&nh.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":np,title:y("sidebar.temporaryProjects"),onClick:()=>e$(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:np?"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:y("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nd.length}),eb(nu,y)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t4,p=nf.has(l.toLowerCase())&&es((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),q)||null,h=!ev.has(s)&&!ns,f=ec.has(s),m=eL===s,g=t7.indexOf(s),x=ez||no||g<=0,v=ez||no||g>=t7.length-1,b=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}(f?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:ej===s?e9:void 0,onMouseEnter:()=>ek(s),onMouseLeave:()=>ek(e=>e===s&&ej!==s?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:()=>t2(s),title:h?y("sidebar.expandProject"):y("sidebar.collapseProject"),"aria-label":h?y("sidebar.expandProject"):y("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"})})}),m?(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:tt,value:eA,onChange:e=>eF(e.target.value),onBlur:()=>void nn(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tn.current=!0,eP(null))},"aria-label":y("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:()=>B(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children: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}),eb(na.get(o),y)]}),(0,r.jsx)("button",{type:"button",onClick:()=>tZ(s),title:y("sidebar.newSessionTitle",{path:s}),"aria-label":y("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||ew===s?1:0,pointerEvents:w||ew===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ek(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eS(ej===s?null:s),eX(!1),e0(!1),e4(null),u||B(s)},title:y("sidebar.projectActions"),"aria-label":y("sidebar.projectActions"),"aria-expanded":ej===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ej===s?"var(--bg-selected)":"transparent",color:u&&nk&&!nk.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ew===s||ej===s?1:0,pointerEvents:w||ew===s||ej===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ek(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(el,{open:ej===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[nw&&eJ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eX(e=>!e),title:nk?y("sidebar.switchWorktreeTitle",{path:nk.path}):y("sidebar.switchWorktree"),"aria-label":y("sidebar.worktrees"),"aria-expanded":eY,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eY?"1px solid var(--border)":"none",background:eY?"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:y("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)(el,{open:eY,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:[nj&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eH,onChange:e=>eU(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eU(""),eX(!1))},placeholder:y("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===_||e.isMain&&!eJ.worktrees.some(e=>e.path===_);return e3===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:y("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tG(e.path,!0),disabled:e5,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:y("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>e7(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:y("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:()=>{B(e.path),eX(!1),e4(null),eU("")},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)(eo,{text:e.branch??es(e.path,q),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:y("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tG(e.path,!1),disabled:e5,title:y("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)}),nj&&0===nS.length&&eH.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:y("sidebar.noMatchingWorktrees")})]}),eQ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:te,value:e1,onChange:e=>{e2(e.target.value),e4(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tK()),"Escape"===e.key&&(e0(!1),e2(""),e4(null))},placeholder:y("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 tK(),disabled:e5||!e1.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e5||!e1.trim()?"not-allowed":"pointer",opacity:e5||!e1.trim()?.65:1},children:e5?y("sidebar.creating"):y("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e0(!1),e2(""),e4(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:y("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e0(!0),e4(null),setTimeout(()=>te.current?.focus(),0)},title:y("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:y("sidebar.newWorktree")})]}),e8&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e8})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=t5.get(E(s))?.alias??"",void(tn.current=!1,eO(null),eF(e),eP(s),ne())},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:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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"})]}),y(t5.get(E(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),y("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),y("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>void nt(s,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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"})]}),y(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nI(ni.get(o)??[])||tC,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{ne(),tT(null),tS({kind:"project",project:s,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:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),y("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:y("sidebar.noSessions")}),!h&&b.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:b.map(t=>(0,r.jsx)(ex,{node:t,selectedSessionId:e,runningSessionIds:ts,unreadSessionIds:tl,pinnedSessionIds:td,onSelectSession:tJ,onTogglePinnedSession:tF,onRenamed:tw,onSessionDeleted:tk,onSessionArchived:tL,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ef(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?y("sidebar.showLess"):y("sidebar.showMore")})]},s)})]}),!nT&&(0,r.jsx)(eg,{refreshKey:tE,selectedSessionId:e,onSelectSession:tJ,onRestored:tL}),!nT&&"priority"===Q&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[W&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),!W&&!O&&(x=nI(ny.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:tY,onClick:()=>void t1(),title:y("sidebar.newScratchSessionTitle"),style:ea(tY,w),children:y("sidebar.newScratchSession")}),ny.length>0&&!ng&&(0,r.jsx)("button",{type:"button",disabled:0===x||tC,onClick:()=>{tT(null),tS({kind:"priority"})},style:ea(0===x||tC,w),children:y("sidebar.clearPriorityList")})]})),!W&&!O&&tp&&(0,r.jsx)("div",{style:{display:"flex",padding:"6px 2px 4px"},children:(0,r.jsxs)("button",{type:"button","aria-pressed":ng,"aria-label":y("navigator.resultsToCheckCount",{count:nm.length}),title:y("navigator.resultsToCheckHint"),onClick:()=>{nv(null),tm(e=>!e)},style:{...ea(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ng?"var(--border-strong)":"var(--border)",background:ng?"var(--bg-selected)":"transparent",color:ng||nm.length>0?"var(--text)":"var(--text-muted)",fontWeight:ng?600:500,whiteSpace:"nowrap"},children:[y("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:9,background:nm.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nm.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nm.length})]})}),tQ&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tQ}),!W&&!O&&0===ny.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ng?y("navigator.resultsToCheckEmpty"):y("sidebar.noSessions")}),!W&&!O&&ny.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)(em,{session:t,selected:t.id===e,running:ts.has(t.id),unread:tl.has(t.id),pinned:td.has(t.id),onSelect:ng?nb:tJ,onTogglePin:tF},t.id))]},t.key))]})]})}function eh({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,F.s)(),d=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let f=(0,i.useRef)(o);return f.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(),f.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||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")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":a,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(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ef({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 em({session:e,selected:t,running:n,unread:i,pinned:a,onSelect:s,onTogglePin:o}){let{t:l}=(0,F.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:()=>s(e),title:`${c}
2
2
  ${e.cwd}
3
3
  ${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:c}),n&&(0,r.jsx)(ev,{}),!n&&i&&(0,r.jsx)(ey,{})]}),(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":a,"aria-label":l(a?"sidebar.unpin":"sidebar.pin"),title:l(a?"sidebar.unpin":"sidebar.pin"),onClick:()=>o(e.id),style:{width:30,border:"none",background:"transparent",color:a?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(ef,{filled:a})})]})}function eg({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:a}){let{t:s}=(0,F.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})}),a(t)}catch{}},[a]);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"})}),s("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:s("sidebar.noArchivedSessions")}),c.map(e=>{let i=A(e.firstMessage)??e.firstMessage,a=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function ex({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:o,onRenamed:l,onSessionDeleted:c,onTogglePinnedSession:d,onSessionArchived:u,depth:p}){let[h,f]=(0,i.useState)(!1),m=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)(ew,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:a.has(e.session.id),isPinned:s.has(e.session.id),onClick:()=>o(e.session),onTogglePin:()=>d(e.session.id),onRenamed:l,onDeleted:e=>c?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:m,collapsed:h,onToggleCollapse:()=>f(e=>!e)})]}),m&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ex,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:o,onTogglePinnedSession:d,onRenamed:l,onSessionDeleted:c,onSessionArchived:u,depth:p+1},e.session.id))})]})}function ev(){let{t:e}=(0,F.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 ey(){let{t:e}=(0,F.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 eb(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 ew({session:e,isSelected:t,isRunning:n,isUnread:a,isPinned:s,onClick:o,onTogglePin:l,onRenamed:c,onDeleted:d,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:f=!1,onToggleCollapse:m}){let{t:g}=(0,F.s)(),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),I=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y){let e=requestAnimationFrame(()=>I.current?.select());return()=>cancelAnimationFrame(e)}},[y]);let T=A(e.firstMessage)??e.firstMessage,M=e.name||T.slice(0,50)||e.id.slice(0,12),R=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||T.slice(0,50)||e.id.slice(0,12)),b(!0))},[e.name,e.transient,T,e.id]),E=(0,i.useCallback)(async()=>{let t=w.trim();if(b(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[w,e.id,e.name,c,M]),$=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),d?.(e.id)}catch{N(!1)}}},[e.id,e.transient,d]),L=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),P=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?$():S(!0)},[$]),z=(0,i.useCallback)(e=>{e.stopPropagation(),$()},[$]),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":""}${a?" is-unread":""}${j?" is-confirming":""}`,onClick:j||y?void 0:o,onContextMenu:j||y?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||y?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick: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"})]}),g("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:g("sidebar.cancel")})]})]}):y?(0,r.jsx)("input",{ref:I,value:w,onChange:e=>k(e.target.value),onBlur:E,onKeyDown:e=>{"Enter"===e.key&&E(),"Escape"===e.key&&b(!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:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(ev,{}),!n&&a&&(0,r.jsx)(ey,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),m?.()},title:g(f?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:f?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,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:g(s?"sidebar.unpin":"sidebar.pin"),"aria-label":g(s?"sidebar.unpin":"sidebar.pin"),"aria-pressed":s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:s?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(ef,{filled:s})}),(0,r.jsx)("button",{onClick:R,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:L,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{onClick:P,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,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 ek=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,ej=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eS=/\x1B\[([0-9;]*)m/g,eC=/\x1B_pi:c\x07/g,eN=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eI=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function eT(e){return e.replace(eC,"").replace(ek,"")}function eM(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(ej);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 eR(e,t){let n=eM(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eE(e){return eM(e)[0]?.char}function e$(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(eC,""),i=eT(e).trimEnd();if(t.test(i))continue;let a=e,s=eE(a);("│"===s||"┃"===s)&&" "===eE(a=eR(a,0))&&(a=eR(a,0));let o=function(e){let t=eM(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),l=o>=0?eM(a)[o]?.char:void 0;("│"===l||"┃"===l)&&(a=eR(a,o)),n.push(function(e){let t=e;for(;;){let e=eM(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(a))}for(;n.length>0&&""===eT(n[0]).trim();)n.shift();for(;n.length>0&&""===eT(n[n.length-1]).trim();)n.pop();return n.length?n:e}function eL(e){let t,n=[],r={},i=0;for(eS.lastIndex=0;null!==(t=eS.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=eN[r-30];else if(r>=90&&r<=97)n.color=eI[r-90];else if(r>=40&&r<=47)n.backgroundColor=eN[r-40];else if(r>=100&&r<=107)n.backgroundColor=eI[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,a,s]=[t[e+2],t[e+3],t[e+4]];[i,a,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${a}, ${s})`:n.backgroundColor=`rgb(${i}, ${a}, ${s})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return eN[e];if(e>=8&&e<16)return eI[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 eP={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:""},eA={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eF={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"},ez={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 eW(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eD(e){return null!==(eF[eW(e)]??null)}function eO(e){let t;return null!==("pdf"===(t=eW(e))||"docx"===t?t:null)}function eH(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eU(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 e_(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eB(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eU(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 eq(e){return e.filter(e=>"toolCall"===e.type).length}function eV(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}let eK=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function eG(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let a of i)"toolCall"===a.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===n.path;if("eval"===e.toolName){let e;return e=t.content?.at(-1),e?.type==="text"&&eK.test(e.text)}return"read"===e.toolName&&"string"==typeof n.path&&eD(n.path)}(a,t.get(a.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:a.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let eJ=new Map,eZ=new Map,eY="[한국어 번역]\n";function eX(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function eQ(e){if("custom"!==e.role||"korean-reply-translation"!==e.customType)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let n="sourceTimestamp"in t&&"number"==typeof t.sourceTimestamp?t.sourceTimestamp:void 0,r="sourceHash"in t&&"string"==typeof t.sourceHash?t.sourceHash:void 0;return void 0===n&&void 0===r?null:{sourceTimestamp:n,sourceHash:r}}let e0="command",e1="autolearn-saved";function e2(e){return"custom"===e.role&&(e.customType===e0||e.customType===e1&&!1!==e.display)}let e8="local-command:";function e4(e){return e?.startsWith(e8)===!0}function e5(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],a=[];for(let n=0;n<e.length;n++){let s=n<t.length;!(r.has(e[n])||s&&e4(t[n]))&&(i.push(e[n]),s&&a.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=a.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=a.length&&a.splice(t,0,e.entryId)}return{messages:i,entryIds:a}}function e6(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let e3={create:!0,update:!0};function e7(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function e9(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 te(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 tt(e){try{return decodeURIComponent(e)}catch{return e}}function tn(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tr(e){let t=tn(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,a=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){a.length>0&&".."!==a[a.length-1]?a.pop():i||n||r||a.push(e);continue}a.push(e)}let s=a.join("/");return n?s:r?`//${s}`:i?`/${s}`:s}function ti(e,t,n=t){let r,i,a,s,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=tt(l),p=u.startsWith("\\\\"),h=tn(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=tt(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=`${tn(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let m=tr(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&n&&(r=tr(m).replace(/\/+$/,""),i=tr(n).replace(/\/+$/,""),s=(a=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(s===(o=a?i.toLowerCase():i)||s.startsWith(`${o}/`)))?null:m}function ta(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,a=i(e),s=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(a),l=a.startsWith("//");if(o||l)n=a;else if(a.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${a}`:a}else{if(!s)return null;n=`${s}/${a}`}return tr(n)}function ts(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function to(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function tl(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tc(e,t){if(!e||"object"!=typeof e||"delete"===e.op&&!t)return null;let n=e.path??e.resolvedPath;return"string"==typeof n&&n.length>0?n:null}function td(e,t,n=!1){let r=t.details,i=tl(e);if(i)return!n&&r&&"object"==typeof r&&"delete"===r.op?[]:[i];if(!r||"object"!=typeof r)return[];if(Array.isArray(r.perFileResults))return r.perFileResults.map(e=>tc(e,n)).filter(e=>null!==e);let a=tc(r,n);return a?[a]:[]}function tu(e,t){let n=tl(e);return(t?td(e,t,!0):n?[n]:[]).filter(tg)}function tp(e,t,n){let r=tu(e,t);return r.length>0&&r.every(e=>tm(e,n))}let th=new Map(["skills","commands","rules","prompts","extensions","instructions","hooks","tools","agents","plugins","mcp.json",".mcp.json","SYSTEM.md","SYSTEM_TEMPLATE.md","APPEND_SYSTEM.md","AGENTS.md","settings.json","config.yml","secrets.yml"].map(e=>[e.toLowerCase(),e])),tf=[/^\/(?:private\/)?(?:var\/)?tmp(?:\/|$)/,/^\/(?:private\/)?var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/,/^(?:[a-z]:|\/mnt\/[a-z])\/(?:windows\/)?temp(?:\/|$)/i,/^(?:[a-z]:|\/mnt\/[a-z])\/users\/[^/]+\/appdata\/local\/temp(?:\/|$)/i];function tm(e,t){let n=ta(e,t),r=t?ta(t)?.replace(/\/+$/,""):void 0,i=n??e.replace(/\\/g,"/"),a=/^(?:[a-zA-Z]:\/|\/\/|\/mnt\/[a-zA-Z](?:\/|$))/.test(i)||void 0!==r&&/^(?:[a-zA-Z]:\/|\/\/)/.test(r),s=e=>a?e.toLowerCase():e,o=null===n||void 0!==r&&(s(n)===s(r)||s(n).startsWith(`${s(r)}/`));return!!function(e,t){let n=(e,n)=>void 0!==e&&(t?e.toLowerCase()===n:e===n),r=e.findIndex(e=>n(e,".omp"));if(r<0||r===e.length-1)return!1;let i=e[r+1];if(n(i,"agent")||n(i,"wt")||n(i,"profiles")&&n(e[r+3],"agent"))return!1;let a=th.get(i.toLowerCase());return!(void 0!==a&&(t||a===i))}((null!==n&&o&&void 0!==r?n.slice(r.length):i).split("/").filter(e=>""!==e&&"."!==e),a)||!o&&tf.some(e=>e.test(i))}function tg(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tx(e,t,n){let r=new Set,i=[];for(let s of e){var a;if("toolCall"!==s.type||!(ts(a=s.toolName)||to(a)))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of td(s.input,e)){if(!tg(t))continue;let e=ta(t,n);!(!e||tm(t,n))&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}function tv(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}}function ty(e){if(!Array.isArray(e))return null;let{phases:t,malformed:n}=tv(e);return n?null:t}function tb(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}=tv(n);return i?{kind:"unknown"}:{kind:"authoritative",phases:r}}let i=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}function tw(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}function tk(e,t,n=null,r=null){return n||(function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n],i=r.trackerTodos??[];for(let e=i.length-1;e>=0;e-=1){let t=ty(i[e]);if(t)return t}if("assistant"!==r.role)continue;let a=r.content;if(Array.isArray(a))for(let e=a.length-1;e>=0;e-=1){let n=a[e];if("toolCall"!==n.type||!tw(n.toolName))continue;let r=tb(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function tj(e){let t=0,n=0,r=null,i=null,a=null;for(let s of e)for(let e of s.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:s,task:e}):"blocked"===e.status?a||(a={phase:s,task:e}):i||(i={phase:s,task:e}))}let s=r??i??a,o=t+n;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:n,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}function tS(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tC(e){return tS(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tN(e){let t=tS(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tI(e,t){if(!t)return e;let n=tS(e),r=tS(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var tT=n(65063),tM=n(7644),tR=n(32316),tE=n(88374),t$=n(63280),tL=n(94764),tP=n(63835),tA=n(54152),tF=n(84678),tz=n(98164);let tW={...tL.j,attributes:{...tL.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...tL.j.strip||[],"iframe","object","style","form"]};function tD(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,a=0,s=null,o=new Map;for(let e=0;e<n.length;e++){var l;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=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},a=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)||(s=e),a=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){a=0,r.push(t);continue}if(a||t.includes("`")){a=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,a),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>tH(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 f=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(f){let t=f[1],i=f[2].trimEnd();if(i&&!i.includes("$$")){let a=tO(n,e+1,t,o);if(a){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<a.index;i++)r.push(tH(n[i],t));a.content&&r.push(`${t}${a.content}`),r.push(`${t}$$`),e=a.index;continue}}}let m=t.match(/^([ \t]{0,3})\$\$\s*$/);if(m){let t=m[1],i=tO(n,e+1,t,o);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let a=e+1;a<i.index;a++)r.push(tH(n[a],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 tO(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var a,s,o,l;let t=e[i];if(a=t,""===(s=n)?/^ {0,3}\$\$\s*$/.test(a):a.startsWith(s)&&/^\$\$\s*$/.test(a.slice(s.length)))return{index:i,content:"",glued:!1};if(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 tH(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},t_=[[tA.A,["yaml"]],[tF.A,tU],tz.A],tB=[[tA.A,["yaml"]],[tF.A,tU],tz.A],tq=[t$.A,[tP.A,tW],[tE.A,{throwOnError:!1,strict:!1}]],tV=[t$.A,[tP.A,tW],[tE.A,{throwOnError:!1,strict:!1}]],tK="pi-theme",tG=["light","dark","auto"],tJ={preference:"auto",theme:"light"},tZ="omp-theme",tY=null,tX=0,tQ=new Set,t0=null,t1=!1;function t2(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function t8(e){return"auto"===e?t2():e}let t4="--omp-md-";function t5(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(t4)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(t4)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tZ,e)}catch{}}function t6(){if(t0)return t0;let e=function(){try{let e=localStorage.getItem(tK);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tZ);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=t8(e);return t5(t),t0={preference:e,theme:t}}function t3(e,t,n){if(t5(t),n)try{localStorage.setItem(tK,e)}catch{}t0={preference:e,theme:t},tQ.forEach(e=>e())}function t7(){let e=t6();if("auto"!==e.preference)return;let t=t2();t!==e.theme&&t3("auto",t,!1)}function t9(e){return tQ.add(e),t6(),t1||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",t7),window.addEventListener("focus",t7),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&t7()}),t1=!0),t7(),()=>{tQ.delete(e)}}function ne(){return t6()}function nt(){return tJ}async function nn(e){let t=++tX,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===tX){tY=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(tY))}catch{}t5(t6().theme)}}function nr(e){let t=(0,i.useSyncExternalStore)(t9,ne,nt);(0,i.useEffect)(()=>{e?.syncWithOmp&&nn(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=t8(e),r=()=>{t3(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let a=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(a,window.innerWidth-a),Math.max(s,window.innerHeight-s));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${a}px ${s}px)`,`circle(${o}px at ${a}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=t6().preference,r=tG.indexOf(t),tG[(r+1)%tG.length]),e)},[n]),a=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:a,isDark:"dark"===t.theme}}function ni(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}let na={...tM.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tM.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function ns({code:e,isStreaming:t}){let{isDark:a}=nr(),{t:s}=(0,F.s)(),[o,l]=(0,i.useState)(!0),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=`${a?"dark":"light"}
4
4
  ${e}`,f=o&&!t;(0,i.useEffect)(()=>{if(!f)return;let t=!1;return d({key:h,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328)),i=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${i}`,e),await document.fonts.ready,t)return;if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:a?"dark":"default",fontFamily:i}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let s="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await r.render(s,e);t||d({key:h,status:"ready",svg:o.svg})})().catch(()=>{t||d({key:h,status:"error"})}),()=>{t=!0}},[e,h,a,f]);let m=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),disabled:t,title:t?s("i18n.previewAfterStreaming"):f?s("i18n.showMermaidSource"):s("i18n.previewMermaid"),className:["markdown-code-action",f?"is-active":""].filter(Boolean).join(" "),children:f?s("i18n.source"):s("i18n.preview")}),[t,f,s]);if(!f)return(0,r.jsx)(nl,{code:e,lang:"mermaid",headerAction:m,isStreaming:t});let g=c?.key===h&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==h||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!u&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openMermaidViewer"),"aria-label":s("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),u&&(0,r.jsx)(no,{svg:c.svg,onClose:()=>p(!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"}),m]}),g]})}function no({svg:e,onClose:t}){let{t:n}=(0,F.s)(),a=(0,i.useRef)(null),[s,o]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:s>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>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*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let nl=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:a}){let{isDark:s}=nr(),{t:o}=(0,F.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:()=>{ni(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),a?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(tT.A,{language:t||"text",style:s?tM.xJ:na,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-muted)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function nc({children:e,className:t,isStreaming:n,cwd:a,onOpenFile:s}){let o=(0,i.useMemo)(()=>tD(e),[e]),l=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let a=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===a?(0,r.jsx)(ns,{code:s.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(nl,{code:s.replace(/\n$/,""),lang:a,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=s?ti(e,a):null;return i&&s?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?ti(e,a):null,s=i?`/api/files/${tC(i)}?type=read`:e;return(0,r.jsx)("img",{src:s,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[a,n,s]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(tR.oz,{remarkPlugins:t_,rehypePlugins:tq,components:l,children:o})})}function nd(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}var nu=n(54265);let np=(0,i.createContext)(null);function nh(e,t,n){return Math.min(n,Math.max(t,e))}function nf(e,t,n){let r=t.width>0?n.width/t.width:0,i=t.height>0?n.height/t.height:0;return{x:nh((e.x-t.left)*r,0,n.width),y:nh((e.y-t.top)*i,0,n.height)}}function nm(e){let t=nh(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let ng="#e5191f",nx="#ffffff";function nv(e){let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.toBlob(e=>e?n(e):r(Error("canvas encode failed")),"image/png"),t}function ny(e,t){let n=document.createElement("canvas");n.width=e,n.height=t;let r=n.getContext("2d");if(!r)throw Error("canvas 2d unavailable");return[n,r]}async function nb(e,t){let n=await createImageBitmap(e);try{let e={width:n.width,height:n.height},{inner:r,outer:i}=nm(e),a=Math.max(14,7*nm(e).inner),[s,o]=ny(e.width,e.height);o.drawImage(n,0,0),t.forEach((t,n)=>{let s=function(e,t){let{inner:n,outer:r}=nm(t),i=(n,r)=>{let i=nh(e.x-n,r,t.width-r),a=nh(e.y-n,r,t.height-r),s=nh(e.x+e.w+n,r,t.width-r);return{x:i,y:a,w:Math.max(0,s-i),h:Math.max(0,nh(e.y+e.h+n,r,t.height-r)-a)}};return{inner:i(n/2,n/2),outer:i(n+r/2,r/2)}}(t,e);o.lineJoin="miter",o.strokeStyle=nx,o.lineWidth=i,o.strokeRect(s.outer.x,s.outer.y,s.outer.w,s.outer.h),o.strokeStyle=ng,o.lineWidth=r,o.strokeRect(s.inner.x,s.inner.y,s.inner.w,s.inner.h);let l=String(n+1);o.font=`700 ${a}px sans-serif`;let c=Math.round(.35*a),d=Math.ceil(o.measureText(l).width)+2*c,u=Math.round(1.3*a),p=Math.min(Math.max(0,t.x-r),e.width-d),h=t.y-r-u,f=h>=0?h:Math.min(t.y,e.height-u);o.fillStyle=nx,o.fillRect(p-1,f-1,d+2,u+2),o.fillStyle=ng,o.fillRect(p,f,d,u),o.fillStyle=nx,o.textBaseline="middle",o.textAlign="center",o.fillText(l,p+d/2,f+u/2)});let l=await Promise.all(t.map(t=>{let r=function(e,t,n=.12){let r=Math.round(e.w*n),i=Math.round(e.h*n),a=nh(e.x-r,0,t.width),s=nh(e.y-i,0,t.height),o=nh(e.x+e.w+r,0,t.width);return{x:a,y:s,w:o-a,h:nh(e.y+e.h+i,0,t.height)-s}}(t,e),[i,a]=ny(r.w,r.h);return a.drawImage(n,r.x,r.y,r.w,r.h,0,0,r.w,r.h),nv(i)}));return{marked:await nv(s),crops:l}}finally{n.close()}}function nw({src:e,regions:t,max:n,onAdd:a,onNaturalSize:s,regionLabel:o}){let l=(0,i.useRef)(null),[c,d]=(0,i.useState)(null),u=(0,i.useRef)(null),[p,h]=(0,i.useState)(null),f=e=>{let t=l.current,n=u.current;return t&&n&&c?function(e,t,n,r){let i=nh(Math.min(e.x,t.x),n.left,n.left+n.width),a=nh(Math.max(e.x,t.x),n.left,n.left+n.width),s=nh(Math.min(e.y,t.y),n.top,n.top+n.height),o=nh(Math.max(e.y,t.y),n.top,n.top+n.height);if(a-i<6||o-s<6)return null;let l=nf({x:i,y:s},n,r),c=nf({x:a,y:o},n,r),d=Math.floor(l.x),u=Math.floor(l.y),p=Math.min(r.width,Math.ceil(c.x))-d,h=Math.min(r.height,Math.ceil(c.y))-u;return p>0&&h>0?{x:d,y:u,w:p,h}:null}(n.start,e,t.getBoundingClientRect(),c):null},m=(e,t)=>{if(u.current?.pointerId!==e.pointerId)return;let n=t?f({x:e.clientX,y:e.clientY}):null;u.current=null,h(null),n&&a(n)};return(0,r.jsxs)("div",{className:"tool-image-marker","data-drawing":c&&t.length<n?"true":void 0,onPointerDown:e=>{c&&!(t.length>=n)&&("mouse"!==e.pointerType||0===e.button)&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),u.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY}})},onPointerMove:e=>{u.current?.pointerId===e.pointerId&&h(f({x:e.clientX,y:e.clientY}))},onPointerUp:e=>m(e,!0),onPointerCancel:e=>m(e,!1),children:[(0,r.jsx)("img",{ref:l,className:"tool-image-full",src:e,alt:"",draggable:!1,onLoad:e=>{let t={width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight};d(t),s(t)}}),c&&t.map((e,t)=>(0,r.jsx)(nk,{region:e,natural:c,label:String(t+1),title:o(t+1)},`${t}-${e.x}-${e.y}`)),c&&p&&(0,r.jsx)(nk,{region:p,natural:c})]})}function nk({region:e,natural:t,label:n,title:i}){let a={left:e.x/t.width*100,top:e.y/t.height*100,width:e.w/t.width*100,height:e.h/t.height*100};return(0,r.jsx)("span",{className:"tool-image-region","data-draft":n?void 0:"true",role:n?"img":void 0,"aria-label":i,style:{left:`${a.left}%`,top:`${a.top}%`,width:`${a.width}%`,height:`${a.height}%`},children:n&&(0,r.jsx)("span",{className:"tool-image-region-number","aria-hidden":"true",children:n})})}function nj(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}function nS(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}let nC=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,nN=/(?:\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 nI(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let nT={hideThinkingBlock:!1},nM=new Set,nR=nT,nE=0;function n$(e){return nM.add(e),()=>{nM.delete(e)}}function nL(){return nR}function nP(){return nT}async function nA(e){let t=++nE,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!==nE||i.hideThinkingBlock!==nR.hideThinkingBlock&&(nR={hideThinkingBlock:!0===i.hideThinkingBlock},nM.forEach(e=>e()))}function nF(){return(0,i.useSyncExternalStore)(n$,nL,nP)}let nz=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],nW={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},nD=["approval","choice","done","failed","blocked","working"],nO={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},nH={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0},nU="/api/office-characters/",n_={voice:"/audio/completion/",sticker:"/stickers/"};function nB(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function nq(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(nO,e)?e:null}function nV(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:a,ko:s}=i;if("string"!=typeof e||""===e)continue;let o=nq(a);if(null===o)continue;let l=t+e.replace(/^\/+/,""),c=n.get(o);c?c.push(l):n.set(o,[l]),"string"==typeof s&&""!==s.trim()&&r.set(l,s.trim())}return{files:n,lines:r}}function nK(e,t=n_){let n=new Map;if("object"!=typeof e||null===e)return n;let{characters:r}=e;if(!Array.isArray(r))return n;for(let e of r){if("object"!=typeof e||null===e)continue;let{id:r,clips:i,stickers:a,captions:s}=e;if("string"!=typeof r||""===r)continue;let o=nV(i,t.voice),l=nV(a,t.sticker),c=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=nq(e);if(null===i)continue;let a=t.get(i);a?a.push(r.trim()):t.set(i,[r.trim()])}return t}(s),d=new Map;for(let e of nD){let t=o.files.get(e)??[],n=new Map;for(let e of t){let t=o.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:n,captions:c.get(e)??[]})}n.set(r,d)}return n}function nG(e,t,n){let r=t&&Object.hasOwn(nW,t)?nW[t]:null;return r?e.get(r)?.get(n)??null:null}function nJ(e,t,n){return e.get(t)?.get(n)??null}async function nZ(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return nK(await t.json())}catch{return new Map}}function nY(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,a=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&a>=r?a+1:a]}function nX(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)])}function nQ(e,t,n){if(t&&("web6"!==t.provider||t.model!==n0))return{provider:t.provider,credentialId:t.credentialId};for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role)break;if("assistant"===n.role&&("web6"!==n.provider||n.model!==n0))return{provider:n.provider,credentialId:n.credentialId}}return{provider:n,credentialId:void 0}}let n0="ChatGPT 6PRO",n1="/api/sidecars/resource";function n2(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 a=n("used"),s=n("limit");if(null!==a&&null!==s&&a>=s)return!0;let o=n("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==a&&a>=100}let n8=[{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:"hive"},{alias:"SHION(시온)",file:"shion.webp",provider:"web6"},{alias:"HIKARI(히카리)",file:"hikari.webp",provider:"google-antigravity"}],n4=[{seed:3,alias:n8[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:n8[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:n8[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:n8[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:n8[2].alias,provider:"opencode-go",model:"muse-spark-1.3-contributor",voice:"번뜩이는 발상\xb7즉흥적 시제품\xb7낙천적 재도전",summonExample:"노바 불러와",switchExample:"노바로 교체해"},{seed:6,alias:n8[6].alias,provider:"google-antigravity",model:"gemini-3.8-flash",voice:"빠른 관찰\xb7톡 쏘는 한마디\xb7장난스러운 여유",summonExample:"히카리 불러와",switchExample:"히카리로 교체해"},{seed:5,alias:n8[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],n5=n4.filter(e=>null!==e.switchExample),n6={mode:"default",rosterAvailable:!1,seats:[]},n3=n6,n7=new Map,n9=new Map,re=n4,rt=new Set,rn=null,rr=null,ri=!1;function ra(e){let t="office"===e.mode?e.seats.filter(e=>!n8.some(t=>t.alias===e.alias)):[],n=JSON.stringify([e.mode,e.rosterAvailable,t]);if(n!==rr)for(let r of(rr=n,n3={...e,seats:t},n9=new Map([...n7=new Map(t.flatMap(e=>{let t=n8.findIndex(t=>t.alias===e.seat);return t>=0?[[t,e]]:[]}))].flatMap(([e,t])=>{let n=n8[e];return"provider"in n?[[n.provider,{seed:e,alias:t.alias}]]:[]})),re=0===n7.size?n4:n4.map(e=>{let t,n,r,i=n7.get(n8.findIndex(t=>t.alias===e.alias));return i?(t=i.names.findLast(e=>/[가-힣]/.test(e))??i.names[0]??i.alias.split("(",1)[0],{...e,alias:i.alias,voice:i.voice.temperament.split(/(?<=[.。])\s/,1)[0].replace(/[.。]$/,""),summonExample:`${t} 불러와`,switchExample:`${r=(n=t.charCodeAt(t.length-1)-44032)>=0&&n<=11171?n%28:0,`${t}${0===r||8===r?"로":"으로"}`} 교체해`}):e}),rt))r()}function rs(){return n3}function ro(e){return rt.add(e),()=>{rt.delete(e)}}async function rl(e=fetch){try{let t=await e("/api/character-mode",{cache:"no-store"});if(!t.ok)return!1;let n=await t.json();if("object"!=typeof n||null===n)return!1;let{mode:r,rosterAvailable:i,seats:a}=n;return ra({mode:"office"===r?"office":"default",rosterAvailable:!0===i,seats:Array.isArray(a)?a:[]}),!0}catch{return!1}}let rc=new WeakMap;function rd(e){let t=rc.get(e);return t||(t=nK(e.manifest,{voice:nU,sticker:nU}),rc.set(e,t)),t}function ru(e){return e?n3.seats.find(t=>t.seat===e||t.alias===e)??null:null}function rp(e){return n3.seats.find(t=>t.seat===e)?.alias??e}let rh=n8.filter(e=>!("provider"in e)).length,rf=new Map(n8.flatMap((e,t)=>"provider"in e?[[e.provider,t]]:[])),rm=new Map([...rf].map(([e,t])=>[e,{seed:t,alias:n8[t].alias}]));function rg(e){return n9.get(e)??rm.get(e)??null}function rx(e){let t=e%n8.length;return n7.get(t)?.alias??n8[t].alias}function rv(e){let t=e%n8.length;return n7.get(t)?.faceUrl??`/avatars/${n8[t].file}`}function ry(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function rb(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 rw(e){let t=new Map;for(let n of e){if(!Number.isSafeInteger(n.oauthPosition)||n.oauthPosition<0)continue;let e=t.get(n.provider)??new Set;e.add(n.oauthPosition),t.set(n.provider,e)}return e.map(e=>{var n;let r=e.metadata?.email,i=e.metadata?.accountId,a="string"==typeof r&&r.length>0?r:"string"==typeof i?i:"",s=a.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return ry(e);let n=e.slice(t+1),r=n.lastIndexOf("."),i=r<0?n:n.slice(0,r),a=r<0?"":n.slice(r);return`${ry(e.slice(0,t))}@${0===i.length?"":`${i[0]}•••`}${a}`}(a):"",o=(n=e.provider,rf.get(n)??-1);if(o>=0)return{seed:o,alias:rx(o),masked:s,raw:a};let l=e.oauthPosition;if(!Number.isSafeInteger(l)||l<0){let n=t.get(e.provider)??new Set;for(l=0;n.has(l);)l++;n.add(l),t.set(e.provider,n)}let c=l%rh,d=l<rh?rx(c):`${rx(c)}${l+1}`;return{seed:c,alias:d,masked:s,raw:a}})}class rk 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 rj(e,t){return`${n1}${e}${t?"?refresh=1":""}`}function rS(e,t,n=!1){return e instanceof rk?e:t?new rk("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new rk("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new rk(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function rC(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function rN(e,t){let n,r=t.fetchImpl??fetch,i=new AbortController,a=!1,s=()=>i.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0}),null!=t.timeoutMs&&(n=setTimeout(()=>{a=!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 rk("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",n.status,{cause:e})}let a=t&&"object"==typeof t?t:null,s="string"==typeof a?.error?a.error:null;if(!n.ok||s)throw new rk(s??`HTTP ${n.status}`,"http",n.status,{code:"string"==typeof a?.code?a.code:void 0,outcomeUnknown:a?.outcomeUnknown===!0});return t}catch(e){throw rS(e,a,i.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",s)}}let rI="google-antigravity",rT=`${rI}:google:`;function rM(e){if(e.provider!==rI||!Array.isArray(e.limits))return e;let t=e.limits.filter(e=>"string"==typeof e.id&&e.id.startsWith(rT));return t.length===e.limits.length?e:{...e,limits:t}}async function rR(e={}){try{let t=await rN(rj("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new rk("사용량 응답 형식이 올바르지 않습니다.","invalid-response");let n=t.reports.map(rM);return{status:"fresh",data:n.every((e,n)=>e===t.reports[n])?t:{...t,reports:n},error:null}}catch(t){return rC(e.previous,rS(t,!1))}}async function rE(e,t={}){if(!e)return rC(void 0,new rk("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await rN(`/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 rk("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return rC(void 0,rS(e,!1))}}async function r$(e={}){try{let t=await rN(rj("/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 rk("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rC(e.previous,rS(t,!1))}}async function rL(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rk("credential id가 올바르지 않습니다.","invalid-response");let r=await rN(`${n1}/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 rk("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function rP(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rk("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new rk("credit id가 올바르지 않습니다.","invalid-response");let r=await rN(`${n1}/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 rk("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function rA(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let rF={faces:new Map,pins:new Map},rz=[],rW=rF,rD=null,rO=rz,rH=new Map,rU=new Set;function r_(e){let t=(rU.add(e),()=>{rU.delete(e)}),n=ro(e);return()=>{t(),n()}}function rB(e){rW=e,rU.forEach(e=>e())}function rq(e){return Number.isSafeInteger(e)&&e>0}function rV(e,t){return`${e}:${t}`}function rK(e){let t=e??rz;rO=t;let n=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===rD)return;rD=n;let r=rw(t),i=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!rq(n))return;let a=rV(e.provider,n);i.has(a)||i.set(a,{seed:r[t].seed,alias:r[t].alias})}),rB({faces:i,pins:rW.pins})}function rG(e,t,n){if(!t)return null;if(rq(n)){let e=rW.faces.get(rV(t,n));if(e)return e}let r=e?rW.pins.get(e):void 0;if(r&&r.provider===t){let e=rW.faces.get(rV(t,r.credentialId));if(e)return e}return rg(t)}async function rJ(e,t,n){if(!t||rq(n)||rg(t))return rG(e,t,n);try{let{data:n}=await rE(e);if(n?.state==="resolved"&&n.provider===t&&rq(n.credentialId)){let r=new Map(rW.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),rB({faces:rW.faces,pins:r})}}catch{}return rG(e,t,void 0)}function rZ(e,t,n){let r=!!t&&!rq(n)&&!!e;return(0,i.useEffect)(()=>{r&&e&&t&&function(e,t){let n=Date.now(),r=rW.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,a=rH.get(i);void 0!==a&&n-a<3e4||(rH.set(i,n),rE(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!rq(i))return;let a=new Map(rW.pins);a.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),rB({faces:rW.faces,pins:a})}).catch(()=>{}))}(e,t)},[r,e,t]),(0,i.useSyncExternalStore)(r_,()=>rG(e,t,n),()=>null)}function rY(){return(0,i.useEffect)(()=>{if(!ri){ri=!0;let e=()=>{"visible"===document.visibilityState&&rl()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e)}null===rn&&(rn=rl().then(e=>{e||(rn=null)}))},[]),(0,i.useSyncExternalStore)(ro,rs,()=>n6)}ro(()=>{rD=null,rK(rO)});let rX={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","run.dispatching":"발주 중","run.pending":"대기","run.running":"실행 중","run.completed":"실행 완료","run.failed":"실행 실패","run.aborted":"중단됨","run.unobserved":"실행 상태 미관측","verdict.accepted":"Main 수용","verdict.rework":"Main 재작업 요청","verdict.held":"Main 보류","verdict.none":"검수 미기록","verdict.attempt":"{attempt}차","detail.stage":"현재 단계","detail.stageNone":"기록 없음","detail.model":"모델","detail.modelNone":"미관측","detail.fallback":"대체 모델","detail.agentId":"담당 ID","detail.reason":"판정 사유","detail.source.live":"실시간 관측","detail.source.record":"세션 기록","detail.openSubagents":"서브에이전트 상세 열기","detail.openProcess":"작업 기록 열기","summary.live":"진행 중","summary.files":"변경 파일 {count}","summary.files.one":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checks.one":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.verdictUnverified":"판정 미확인 {count}","summary.verdictUnverified.one":"판정 미확인 {count}","summary.expand":"턴 요약 펼치기","summary.collapse":"턴 요약 접기","result.label":"이번 결과","result.open":"결과 보기","result.openNamed":"{name} 결과 보기","result.previewTitle":"{name} 미리보기","result.previewFailed":"미리보기를 불러오지 못했습니다. 결과 보기를 누르세요.","result.more":"다른 결과 {count}","result.previewLoading":"미리보기를 불러오는 중","result.kind.html":"화면","result.kind.pdf":"PDF","result.kind.document":"문서","result.kind.image":"이미지","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.check.exit":"exit {code}","summary.makers":"Maker {count}","summary.makers.one":"Maker {count}","summary.remaining":"남은 일 {count}","summary.heading.remaining":"남은 일","summary.time.unobserved":"시간 기록 없음","summary.time.running":"아직 실행 중","summary.todo.pending":"대기","summary.todo.in_progress":"진행 중","summary.todo.blocked":"막힘","summary.todo.blocker":"막힌 이유: {blocker}","summary.todo.none":"남은 일 없음","flow.heading":"작업 흐름","flow.aria":"이번 턴의 작업 단계","flow.toggle":"작업 흐름","flow.stage.investigate":"조사","flow.stage.edit":"수정","flow.stage.check":"검사","flow.stage.review":"교차리뷰","flow.stage.commit":"커밋\xb7푸시","flow.stage.ci":"CI","flow.stage.deploy":"배포","flow.state.waiting":"대기","flow.state.running":"진행 중","flow.state.done":"완료","flow.state.redone":"다시 고침","flow.state.passed":"통과","flow.state.unverified":"판정 미확인","flow.state.failed":"실패","flow.state.unobserved":"결과 미관측","flow.state.findings":"지적 {count}건","flow.state.findings.one":"지적 {count}건","flow.state.noFindings":"지적 없음","flow.state.open":"미해결 {count}건","flow.state.reviewUnusable":"리뷰 불가","flow.state.skipped":"건너뜀","flow.state.notNeeded":"필요 없음","flow.count.passed":"통과 {count}","flow.count.unverified":"판정 미확인 {count}","flow.count.failed":"실패 {count}","flow.count.unobserved":"결과 미관측 {count}","flow.count.running":"진행 중 {count}","flow.earlier":"이전 회차 {count}건","flow.attempt":"{attempt}회차","flow.label.typecheck":"타입 검사","flow.label.lint":"린트","flow.label.test":"테스트","flow.label.build":"빌드","flow.label.verify":"검증","flow.label.smoke":"스모크 확인","flow.label.check":"검사","flow.label.ci":"CI 확인","flow.label.deploy":"배포 실행","flow.label.review":"리뷰","flow.label.resolve":"지적 처리","flow.label.commit":"커밋\xb7푸시","flow.details":"자세히","flow.commandOmitted":"명령 본문은 압축된 요청의 요약에서 생략했어요.","flow.exit":"셸 종료 코드 {code}","flow.exit.none":"종료 코드 기록 없음","flow.exit.error":"오류로 끝남","flow.evidence":"판정에 쓴 기록","flow.why.confirmed":"확인된 것","flow.why.missing":"없는 것","flow.why.exitZero":"셸 종료 코드 0","flow.why.check":"{label} 명령의 종료 코드. 뒤에 이어 붙인 명령(파이프, ;, || 등)이 결과를 가릴 수 있어서 통과로 세지 않았어요.","flow.why.ci":"CI 결과를 종료 코드로 돌려준 기록. gh run watch --exit-status처럼 결과를 돌려주는 명령이 아니라서 통과로 세지 않았어요.","flow.why.ciOtherRun":"이 커밋의 CI 실행이라는 기록. 기다린 실행은 기록상 다른 커밋 {sha}의 실행이에요.","flow.why.ciPublishRun":"이 커밋의 CI 실행 결과. 이 명령이 기다린 실행은 게시 실행이라 CI 판정으로 세지 않았어요.","flow.why.watched.passed":"기다린 실행이 통과로 끝남","flow.why.watched.failed":"기다린 실행이 실패로 끝남","flow.why.watched.unjudged":"기다린 실행이 판정 없이 끝남({conclusion})","flow.why.ciUnjudged":"이 커밋의 CI 판정. 기다린 실행이 통과도 실패도 아닌 {conclusion} 상태로 끝나서, 명령의 실패를 CI 실패로 세지 않았어요.","flow.why.deploy":"배포가 끝났다는 기록. 배포를 띄우고 바로 돌아오는 명령이라 셸 종료 코드만으로는 끝났는지 알 수 없어요.","flow.strip.running":"{stage} 진행 중","flow.loop.badge":"↻ {attempt}회차","flow.loop.failed":"{stage} {attempt}회차 실패로 수정에 되돌아옴","flow.loop.findings":"{stage} {attempt}회차 지적으로 수정에 되돌아옴","flow.state.stale":"수정 전 통과","flow.state.staleDone":"수정 전 완료","flow.count.stale":"수정 전 통과 {count}","flow.why.stale":"이 결과 뒤에 파일을 다시 고쳐서, 마지막 수정본은 아직 확인하지 않았어요.","flow.compound.failed":"묶은 명령 실패","flow.why.compoundConfirmed":"{stages}를 한 명령으로 돌렸고, 명령 전체가 실패로 끝남","flow.why.compoundMissing":"어느 단계에서 실패했는지","flow.ci.notNeeded":"비공개 저장소에만 반영됐어요. 게시 실행 {run} 뒤에도 공개 {repo}의 {ref}는 CI를 통과한 {sha} 그대로예요.","flow.ci.nothingToPublish":"커밋 {sha}의 게시 실행 로그에 「Public tree already matches; nothing to publish」가 남았어요. 공개 저장소가 그대로라 새로 돌 CI가 없어요.","summary.stale":"수정 전 통과 {count}","summary.compoundFailed":"묶은 명령 실패 {count}","graph.branch":"수정 중 맡긴 Maker {count}","graph.branch.one":"수정 중 맡긴 Maker {count}","graph.parallel.observed":"동시 실행 관측","graph.join":"Main 판정","graph.parallel.batch":"같은 발주 묶음","graph.concurrency.overlapped":"겹쳐 실행","graph.concurrency.unknown":"겹침 여부 모름","graph.kind.feature":"기능","graph.kind.maintenance":"유지보수","graph.kind.diagnostic":"진단","graph.kind.unknown":"종류 미기록","graph.outputs":"변경 결과","graph.files":"파일 {count}","graph.docs":"문서 {count}","graph.files.one":"파일 {count}","graph.docs.one":"문서 {count}","graph.detail.aria":"선택한 노드 자세히","graph.maker.open":"Maker 기록 열기","graph.maker.unavailable":"실시간 기록이 없어 여기서 열 수 없어요.","graph.motion.pause":"움직임 멈춤","graph.replay":"재생","graph.replay.stop":"재생 멈춤","subflow.aria":"이 서브에이전트 실행의 단계","subflow.calls":"도구 {count}회","subflow.reedits":"다시 수정 {count}회","subflow.checks":"검사 {passed}/{total} 통과","subflow.reported":"보고함","subflow.unobserved":"기록 미관측","subflow.rework":"↻ Main 재작업 요청 {count}회로 구현에 되돌아옴","subflow.prior":"이전 판정","subflow.firstTitle":"첫 발주 제목","subflow.runTitle":"이번 실행 제목","delivery.title":"보낸 입력 {count}","delivery.kind.steer":"지금 지시","delivery.kind.followUp":"완료 후 요청","delivery.stage.sending":"보내는 중","delivery.stage.accepted":"접수됨 \xb7 전달 대기","delivery.stage.delivered":"전달됨 \xb7 대화에 들어감","delivery.stage.failed":"보내지 못함 \xb7 입력창에 되돌림","delivery.stage.unconfirmed":"전달 확인 못 함 \xb7 큐에서 빠짐","delivery.images":"이미지 {count}개","delivery.images.one":"이미지 {count}개","delivery.showOlder":"이전 {count}개 더 보기","delivery.showRecent":"최근 {count}개만 보기","live.nativeVoice":"기본 음성","progress.label":"진행","phase.investigate":"조사","phase.implement":"구현","phase.verify":"검증","phase.report":"보고","phase.current":"지금 단계 {phase}","phase.hint":"도구 호출로 읽은 지금 단계입니다. 고친 뒤 다시 고치면 앞 단계로 돌아갑니다.","progress.todo":"할 일 {completed}/{total} ({percent}%)","eta.label":"예상 시간","eta.elapsed":"경과 {duration}","eta.remaining":"남은 시간 보통 {range} (과거 {samples}건)","eta.percent":"약 {percent}% 추정","eta.overrun":"과거 최장 기록({longest}) 이상 경과","eta.sparseTail":"과거 {samples}건 중 {longerRuns}건만 이보다 오래 걸림","eta.hint":"같은 모델\xb7작업 등급의 과거 첫 시도 가운데 지금 경과보다 오래 걸린 실행들의 남은 시간 분포(가운데 절반)입니다.","eta.byTodo":"할 일 기준 약 {duration} 남음 ({completed}/{total} 단계)","eta.byTodoSoon":"할 일 기준 1분 이내 ({completed}/{total} 단계)","eta.byTodoHint":"todo 완료 비율로만 잰 값입니다. 단계마다 걸리는 시간이 달라 오차가 큽니다.","eta.rework":"재작업 {attempt}차 \xb7 첫 발주부터 {duration}","eta.reworkAttempt":"재작업 {attempt}차","eta.reworkHint":"재작업 시도는 과거 소요 기록이 거의 없어 남은 시간\xb7%를 추정하지 않습니다. 첫 발주부터의 시간에는 시도 사이 Main 검수\xb7대기 시간이 들어 있습니다.","eta.rangeMinutes":"{low}~{high}분","eta.range":"{low}~{high}","duration.seconds":"{seconds}초","duration.minutesSeconds":"{minutes}분 {seconds}초","duration.minutes":"{minutes}분","duration.hours":"{hours}시간","duration.hoursMinutes":"{hours}시간 {minutes}분","duration.underMinute":"1분 미만"},en:{"dispatch.title":"Subagents: {count}","dispatch.tally":"{running} running \xb7 {done} finished \xb7 {accepted} accepted by Main","dispatch.expand":"Show dispatch details","dispatch.collapse":"Hide dispatch details","run.dispatching":"Dispatching","run.pending":"Queued","run.running":"Running","run.completed":"Run finished","run.failed":"Run failed","run.aborted":"Stopped","run.unobserved":"Run state not observed","verdict.accepted":"Accepted by Main","verdict.rework":"Main asked for rework","verdict.held":"Held by Main","verdict.none":"No review recorded","verdict.attempt":"attempt {attempt}","detail.stage":"Current step","detail.stageNone":"Not recorded","detail.model":"Model","detail.modelNone":"Not observed","detail.fallback":"fallback","detail.agentId":"Agent ID","detail.reason":"Review note","detail.source.live":"live","detail.source.record":"session record","detail.openSubagents":"Open subagent details","detail.openProcess":"Open work log","summary.live":"In progress","summary.files":"{count} files changed","summary.files.one":"{count} file changed","summary.checks":"{count} checks","summary.checks.one":"{count} check","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.verdictUnverified":"{count} verdicts not confirmed","summary.verdictUnverified.one":"{count} verdict not confirmed","summary.expand":"Show turn summary","summary.collapse":"Hide turn summary","result.label":"Result","result.open":"View result","result.openNamed":"View result: {name}","result.previewTitle":"Preview of {name}","result.previewFailed":"Couldn't load the preview. Use View result to open it.","result.more":"{count} more","result.previewLoading":"Loading preview","result.kind.html":"Page","result.kind.pdf":"PDF","result.kind.document":"Document","result.kind.image":"Image","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.check.exit":"exit {code}","summary.makers":"{count} Makers","summary.makers.one":"{count} Maker","summary.remaining":"{count} left","summary.heading.remaining":"Still to do","summary.time.unobserved":"time not recorded","summary.time.running":"still running","summary.todo.pending":"pending","summary.todo.in_progress":"in progress","summary.todo.blocked":"blocked","summary.todo.blocker":"blocked by: {blocker}","summary.todo.none":"nothing left","flow.heading":"Work flow","flow.aria":"Work stages of this turn","flow.toggle":"Work flow","flow.stage.investigate":"Investigate","flow.stage.edit":"Edit","flow.stage.check":"Check","flow.stage.review":"Cross review","flow.stage.commit":"Commit & push","flow.stage.ci":"CI","flow.stage.deploy":"Deploy","flow.state.waiting":"waiting","flow.state.running":"in progress","flow.state.done":"done","flow.state.redone":"fixed again","flow.state.passed":"passed","flow.state.unverified":"verdict not confirmed","flow.state.failed":"failed","flow.state.unobserved":"result not observed","flow.state.findings":"{count} findings","flow.state.findings.one":"{count} finding","flow.state.noFindings":"no findings","flow.state.open":"{count} open","flow.state.reviewUnusable":"review unusable","flow.state.skipped":"skipped","flow.state.notNeeded":"not needed","flow.count.passed":"{count} passed","flow.count.unverified":"{count} not confirmed","flow.count.failed":"{count} failed","flow.count.unobserved":"{count} not observed","flow.count.running":"{count} running","flow.earlier":"{count} from earlier attempts","flow.attempt":"Attempt {attempt}","flow.label.typecheck":"Type check","flow.label.lint":"Lint","flow.label.test":"Tests","flow.label.build":"Build","flow.label.verify":"Verification","flow.label.smoke":"Smoke check","flow.label.check":"Check","flow.label.ci":"CI check","flow.label.deploy":"Deploy run","flow.label.review":"Review","flow.label.resolve":"Resolve","flow.label.commit":"Commit & push","flow.details":"Details","flow.commandOmitted":"The command body is omitted from this compacted request summary.","flow.exit":"shell exit code {code}","flow.exit.none":"no exit code recorded","flow.exit.error":"ended with an error","flow.evidence":"Judged from","flow.why.confirmed":"Confirmed","flow.why.missing":"Missing","flow.why.exitZero":"shell exit code 0","flow.why.check":"The exit code of the {label} command itself. Commands chained after it (a pipe, ;, || and so on) can hide its result, so it was not counted as passed.","flow.why.ci":"A CI result returned as an exit code. The command does not return one the way gh run watch --exit-status does, so it was not counted as passed.","flow.why.ciOtherRun":"A record that the run belongs to this commit. The watched run is recorded for another commit, {sha}.","flow.why.ciPublishRun":"The result of this commit's CI run. The run this command waited on is the publish run, so its result was not counted as CI.","flow.why.watched.passed":"The watched run ended as passed","flow.why.watched.failed":"The watched run ended as failed","flow.why.watched.unjudged":"The watched run ended without a verdict ({conclusion})","flow.why.ciUnjudged":"This commit's CI verdict. The watched run ended as {conclusion}, neither passed nor failed, so the command's failure was not counted as a CI failure.","flow.why.deploy":"A record that the deploy finished. The command starts the deploy and returns at once, so its exit code cannot tell whether the deploy finished.","flow.strip.running":"{stage} in progress","flow.loop.badge":"↻ attempt {attempt}","flow.loop.failed":"{stage} failed in attempt {attempt}, so the flow went back to edit","flow.loop.findings":"{stage} raised findings in attempt {attempt}, so the flow went back to edit","flow.state.stale":"Passed before edit","flow.state.staleDone":"Done before edit","flow.count.stale":"{count} passed before edit","flow.why.stale":"Files were edited after this result, so the latest revision has not been checked.","flow.compound.failed":"Combined command failed","flow.why.compoundConfirmed":"{stages} ran as one command, and the whole command failed","flow.why.compoundMissing":"Which stage failed","flow.ci.notNeeded":"Only the private repository changed. After publish run {run}, public {repo} {ref} still points at {sha}, which already passed CI.","flow.ci.nothingToPublish":"The publish run log for commit {sha} says “Public tree already matches; nothing to publish”. The public repository did not change, so there is no new CI run.","summary.stale":"{count} passed before edit","summary.compoundFailed":"{count} combined failed","graph.branch":"{count} Makers dispatched during edit","graph.branch.one":"{count} Maker dispatched during edit","graph.parallel.observed":"Seen running together","graph.join":"Main verdict","graph.parallel.batch":"Same dispatch batch","graph.concurrency.overlapped":"Overlapped","graph.concurrency.unknown":"Overlap unknown","graph.kind.feature":"Feature","graph.kind.maintenance":"Maintenance","graph.kind.diagnostic":"Diagnostic","graph.kind.unknown":"Kind not recorded","graph.outputs":"Changed","graph.files":"{count} files","graph.docs":"{count} docs","graph.files.one":"{count} file","graph.docs.one":"{count} doc","graph.detail.aria":"Selected node details","graph.maker.open":"Open Maker record","graph.maker.unavailable":"No live record, so it can't be opened here.","graph.motion.pause":"Pause motion","graph.replay":"Replay","graph.replay.stop":"Stop replay","subflow.aria":"Stages of this subagent run","subflow.calls":"tool calls: {count}","subflow.reedits":"re-edited {count}\xd7","subflow.checks":"{passed}/{total} checks passed","subflow.reported":"Reported","subflow.unobserved":"Not observed","subflow.rework":"↻ Back to implement \xb7 Main rework requests: {count}","subflow.prior":"Previous verdict","subflow.firstTitle":"First dispatch title","subflow.runTitle":"Current run title","delivery.title":"{count} sent","delivery.kind.steer":"Now","delivery.kind.followUp":"After this run","delivery.stage.sending":"Sending","delivery.stage.accepted":"Received \xb7 waiting to deliver","delivery.stage.delivered":"Delivered \xb7 in the conversation","delivery.stage.failed":"Not sent \xb7 back in the composer","delivery.stage.unconfirmed":"Delivery not confirmed \xb7 left the queue","delivery.images":"{count} images","delivery.images.one":"{count} image","delivery.showOlder":"Show {count} earlier","delivery.showRecent":"Show only the latest {count}","live.nativeVoice":"default voice","progress.label":"Progress","phase.investigate":"Investigate","phase.implement":"Implement","phase.verify":"Verify","phase.report":"Report","phase.current":"current phase {phase}","phase.hint":"Current phase read from tool calls. It goes back when the child edits again after checking.","progress.todo":"todo {completed}/{total} ({percent}%)","eta.label":"Estimate","eta.elapsed":"{duration} elapsed","eta.remaining":"usually {range} left ({samples} past runs)","eta.percent":"about {percent}% (estimate)","eta.overrun":"At or beyond the longest past run ({longest})","eta.sparseTail":"Only {longerRuns} of {samples} past runs took longer","eta.hint":"Middle half of the remaining time among past first attempts of the same model and class that ran longer than this one has so far.","eta.byTodo":"about {duration} left by todo ({completed}/{total} steps)","eta.byTodoSoon":"under a minute left by todo ({completed}/{total} steps)","eta.byTodoHint":"Measured from the todo completion ratio only. Steps take different amounts of time, so this can be far off.","eta.rework":"rework attempt {attempt} \xb7 {duration} since first dispatch","eta.reworkAttempt":"rework attempt {attempt}","eta.reworkHint":"Rework attempts have almost no recorded durations, so no remaining time or % is estimated. Time since the first dispatch includes Main review and waiting between attempts.","eta.rangeMinutes":"{low}–{high} min","eta.range":"{low}–{high}","duration.seconds":"{seconds} s","duration.minutesSeconds":"{minutes} min {seconds} s","duration.minutes":"{minutes} min","duration.hours":"{hours} h","duration.hoursMinutes":"{hours} h {minutes} min","duration.underMinute":"under 1 min"},"zh-CN":{"dispatch.title":"{count} 个子代理","dispatch.tally":"运行中 {running} \xb7 运行完成 {done} \xb7 Main 已接受 {accepted}","dispatch.expand":"展开派发详情","dispatch.collapse":"收起派发详情","run.dispatching":"派发中","run.pending":"等待中","run.running":"运行中","run.completed":"运行完成","run.failed":"运行失败","run.aborted":"已中止","run.unobserved":"未观测到运行状态","verdict.accepted":"Main 已接受","verdict.rework":"Main 要求返工","verdict.held":"Main 暂缓","verdict.none":"未记录审查","verdict.attempt":"第 {attempt} 次","detail.stage":"当前步骤","detail.stageNone":"无记录","detail.model":"模型","detail.modelNone":"未观测","detail.fallback":"备用模型","detail.agentId":"代理 ID","detail.reason":"审查说明","detail.source.live":"实时观测","detail.source.record":"会话记录","detail.openSubagents":"打开子代理详情","detail.openProcess":"打开工作记录","summary.live":"进行中","summary.files":"变更文件 {count}","summary.checks":"检查 {count}","summary.files.one":"变更文件 {count}","summary.checks.one":"检查 {count}","summary.checksFailed":"失败 {count}","summary.unverified":"未确认 {count}","summary.verdictUnverified":"判定未确认 {count}","summary.verdictUnverified.one":"判定未确认 {count}","summary.expand":"展开本轮摘要","summary.collapse":"收起本轮摘要","result.label":"本次结果","result.open":"查看结果","result.openNamed":"查看结果:{name}","result.previewTitle":"{name} 预览","result.previewFailed":"无法加载预览。请点击“查看结果”打开。","result.more":"其他结果 {count}","result.previewLoading":"正在加载预览","result.kind.html":"页面","result.kind.pdf":"PDF","result.kind.document":"文档","result.kind.image":"图片","summary.heading.files":"变更文件","summary.heading.checks":"已运行的检查","summary.check.exit":"exit {code}","summary.makers":"Maker {count}","summary.makers.one":"Maker {count}","summary.remaining":"剩余 {count}","summary.heading.remaining":"剩余事项","summary.time.unobserved":"无时间记录","summary.time.running":"仍在运行","summary.todo.pending":"待办","summary.todo.in_progress":"进行中","summary.todo.blocked":"受阻","summary.todo.blocker":"受阻原因:{blocker}","summary.todo.none":"没有剩余事项","flow.heading":"工作流程","flow.aria":"本轮的工作阶段","flow.toggle":"工作流程","flow.stage.investigate":"调查","flow.stage.edit":"修改","flow.stage.check":"检查","flow.stage.review":"交叉评审","flow.stage.commit":"提交\xb7推送","flow.stage.ci":"CI","flow.stage.deploy":"部署","flow.state.waiting":"等待","flow.state.running":"进行中","flow.state.done":"完成","flow.state.redone":"再次修改","flow.state.passed":"通过","flow.state.unverified":"判定未确认","flow.state.failed":"失败","flow.state.unobserved":"结果未观测","flow.state.findings":"意见 {count} 条","flow.state.findings.one":"意见 {count} 条","flow.state.noFindings":"无意见","flow.state.open":"未解决 {count} 条","flow.state.reviewUnusable":"评审无效","flow.state.skipped":"已跳过","flow.state.notNeeded":"无需","flow.count.passed":"通过 {count}","flow.count.unverified":"判定未确认 {count}","flow.count.failed":"失败 {count}","flow.count.unobserved":"结果未观测 {count}","flow.count.running":"进行中 {count}","flow.earlier":"之前轮次 {count} 条","flow.attempt":"第 {attempt} 轮","flow.label.typecheck":"类型检查","flow.label.lint":"Lint","flow.label.test":"测试","flow.label.build":"构建","flow.label.verify":"验证","flow.label.smoke":"冒烟检查","flow.label.check":"检查","flow.label.ci":"CI 确认","flow.label.deploy":"部署执行","flow.label.review":"评审","flow.label.resolve":"处理意见","flow.label.commit":"提交\xb7推送","flow.details":"详情","flow.commandOmitted":"压缩请求的摘要中省略了命令正文。","flow.exit":"Shell 退出码 {code}","flow.exit.none":"没有退出码记录","flow.exit.error":"以错误结束","flow.evidence":"判定依据","flow.why.confirmed":"已确认","flow.why.missing":"缺少","flow.why.exitZero":"Shell 退出码 0","flow.why.check":"{label} 命令本身的退出码。后面接的命令(管道、;、|| 等)可能掩盖其结果,因此未计为通过。","flow.why.ci":"以退出码返回的 CI 结果。该命令不像 gh run watch --exit-status 那样返回结果,因此未计为通过。","flow.why.ciOtherRun":"这次运行属于此提交的记录。所等待的运行在记录中属于另一个提交 {sha}。","flow.why.ciPublishRun":"此提交 CI 运行的结果。该命令等待的是发布运行,因此未计为 CI 判定。","flow.why.watched.passed":"所等待的运行以通过结束","flow.why.watched.failed":"所等待的运行以失败结束","flow.why.watched.unjudged":"所等待的运行未产生判定即结束({conclusion})","flow.why.ciUnjudged":"此提交的 CI 判定。所等待的运行以 {conclusion} 结束,既非通过也非失败,因此该命令的失败未计为 CI 失败。","flow.why.deploy":"部署已完成的记录。该命令启动部署后立即返回,仅凭 Shell 退出码无法判断部署是否完成。","flow.strip.running":"{stage} 进行中","flow.loop.badge":"↻ 第 {attempt} 轮","flow.loop.failed":"{stage} 第 {attempt} 轮失败,回到修改","flow.loop.findings":"{stage} 第 {attempt} 轮有意见,回到修改","flow.state.stale":"修改前通过","flow.state.staleDone":"修改前完成","flow.count.stale":"修改前通过 {count}","flow.why.stale":"此结果之后又修改了文件,最新版本尚未检查。","flow.compound.failed":"组合命令失败","flow.why.compoundConfirmed":"{stages} 在一条命令中运行,整条命令失败","flow.why.compoundMissing":"具体哪个阶段失败","flow.ci.notNeeded":"仅私有仓库有变更。发布运行 {run} 之后,公开 {repo} 的 {ref} 仍是已通过 CI 的 {sha}。","flow.ci.nothingToPublish":"提交 {sha} 的发布运行日志中记录了“Public tree already matches; nothing to publish”。公开仓库没有变化,因此没有新的 CI 运行。","summary.stale":"修改前通过 {count}","summary.compoundFailed":"组合命令失败 {count}","graph.branch":"修改阶段派发的 Maker {count}","graph.branch.one":"修改阶段派发的 Maker {count}","graph.parallel.observed":"观测到同时运行","graph.join":"Main 判定","graph.parallel.batch":"同一派发批次","graph.concurrency.overlapped":"重叠运行","graph.concurrency.unknown":"是否重叠未知","graph.kind.feature":"功能","graph.kind.maintenance":"维护","graph.kind.diagnostic":"诊断","graph.kind.unknown":"类型未记录","graph.outputs":"变更结果","graph.files":"文件 {count}","graph.docs":"文档 {count}","graph.files.one":"文件 {count}","graph.docs.one":"文档 {count}","graph.detail.aria":"所选节点详情","graph.maker.open":"打开 Maker 记录","graph.maker.unavailable":"没有实时记录,无法在此打开。","graph.motion.pause":"暂停动画","graph.replay":"回放","graph.replay.stop":"停止回放","subflow.aria":"此子代理运行的阶段","subflow.calls":"工具调用 {count} 次","subflow.reedits":"重新修改 {count} 次","subflow.checks":"检查通过 {passed}/{total}","subflow.reported":"已报告","subflow.unobserved":"未观测","subflow.rework":"↻ 因 Main 返工请求 {count} 次回到实现","subflow.prior":"上次判定","subflow.firstTitle":"首次派发标题","subflow.runTitle":"本次运行标题","delivery.title":"已发送 {count}","delivery.kind.steer":"立即指示","delivery.kind.followUp":"完成后请求","delivery.stage.sending":"发送中","delivery.stage.accepted":"已接收 \xb7 等待送达","delivery.stage.delivered":"已送达 \xb7 已进入对话","delivery.stage.failed":"未发送 \xb7 已退回输入框","delivery.stage.unconfirmed":"未能确认送达 \xb7 已离开队列","delivery.images":"图片 {count} 张","delivery.images.one":"图片 {count} 张","delivery.showOlder":"显示更早的 {count} 条","delivery.showRecent":"仅显示最近 {count} 条","live.nativeVoice":"默认语音","progress.label":"进度","phase.investigate":"调查","phase.implement":"实现","phase.verify":"验证","phase.report":"报告","phase.current":"当前阶段 {phase}","phase.hint":"根据工具调用判断的当前阶段。验证后再次修改时会回到前一阶段。","progress.todo":"待办 {completed}/{total}({percent}%)","eta.label":"预计时间","eta.elapsed":"已用 {duration}","eta.remaining":"通常还需 {range}(过去 {samples} 次)","eta.percent":"约 {percent}%(估计)","eta.overrun":"已达到或超过过去最长记录({longest})","eta.sparseTail":"过去 {samples} 次中仅 {longerRuns} 次用时更长","eta.hint":"同模型、同等级的过去首次尝试中,运行时间超过当前已用时间的那些实行的剩余时间分布(中间一半)。","eta.byTodo":"按待办约还需 {duration}({completed}/{total} 步)","eta.byTodoSoon":"按待办 1 分钟内({completed}/{total} 步)","eta.byTodoHint":"仅按 todo 完成比例估算。各步骤耗时不同,误差可能很大。","eta.rework":"返工第 {attempt} 次 \xb7 自首次派发 {duration}","eta.reworkAttempt":"返工第 {attempt} 次","eta.reworkHint":"返工尝试几乎没有耗时记录,因此不估算剩余时间和百分比。自首次派发起的时间包含各次尝试之间 Main 审查和等待的时间。","eta.rangeMinutes":"{low}~{high} 分钟","eta.range":"{low}~{high}","duration.seconds":"{seconds} 秒","duration.minutesSeconds":"{minutes} 分 {seconds} 秒","duration.minutes":"{minutes} 分钟","duration.hours":"{hours} 小时","duration.hoursMinutes":"{hours} 小时 {minutes} 分钟","duration.underMinute":"不到 1 分钟"}};function rQ(){let{locale:e}=(0,F.s)();return{st:(0,i.useCallback)((t,n)=>(0,Q.u0)(e,t,rX,n),[e]),locale:e}}function r0({seed:e,size:t,provider:n}){rY();let a=rv(e),[s,o]=(0,i.useState)(null),l=s===a,[c,d]=(0,i.useState)(!1);return l?(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:rx(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(),d(!0)},"aria-label":rx(e),children:(0,r.jsx)("img",{className:"account-avatar",src:a,width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>o(a)})}),c&&(0,r.jsx)(r1,{seed:e,provider:n,onClose:()=>d(!1)})]})}function r1({seed:e,provider:t,onClose:n}){let{t:a}=(0,F.s)(),s=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let o=rx(e);return(0,_.createPortal)((0,r.jsxs)("dialog",{ref:s,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:rv(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:rb(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:a("i18n.close")})]}),document.body)}function r2(e){let t,n=[],r=null,i=0,a=0,s=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(!(s>0||o>0)){if(d.startsWith("--- ")){u(),t=r8(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:r8(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]),a=Number(e[3]),s=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:a++,text:h,type:"context"}}),s>0&&s--,o>0&&o--):"-"===p?(l.push({lineNo:i++,text:h}),s>0&&s--):"+"===p?(c.push({lineNo:a++,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 r8(e){return e.split(" ")[0].trim()}function r4({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,a="blocked"===e.status;return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":n?"is-abandoned":a?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":a?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,a&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let r5="/icons/catppuccin";function r6({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${r5}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${r5}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function r3({size:e=14,open:t=!1}){return(0,r.jsx)(r6,{name:t?"_folder_open":"_folder",size:e})}function r7({size:e=14}){return(0,r.jsx)(r6,{name:"_file",size:e})}let r9={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 ie(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)(r6,{name:i,size:t});let a=r9[n.split(".").pop()??""];return a?(0,r.jsx)(r6,{name:a,size:t}):(0,r.jsx)(r7,{size:t})}function it({files:e,onOpenFile:t}){let{t:n}=(0,F.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=tN(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[ie(i,12),(0,r.jsx)("span",{children:i})]},e)})})}let ir=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function ii(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,a=n>r&&"\r"===e[n-1]?n-1:n;if(!ir.test(e.slice(r,a)))break;i=a,r=-1===t?e.length:t+1}let a=t[0].length-t[0].trimStart().length;n=`${e.slice(0,t.index+a)}${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}function ia(e){let t=e.live,n=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,r=[t?.assignment,t?.progress?.assignment,t?.task].map(ii).find(e=>null!==e)??(n?.taskTitle?.trim()||null),i=t?.progress?.lastIntent?.trim()||"",a=t?.progress?.currentTool?.trim()||"";return{title:r??"담당 업무 미확인",stage:i&&a?`${i} \xb7 ${a}`:i||(a?`${a} 실행 중`:null),explicitTitle:null!==r}}function is(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 t?.resolvedThinkingLevel?t.resolvedThinkingLevel.trim():"",a="string"==typeof r?.thinkingLevel?r.thinkingLevel.trim():"";if(n){let e=n.split("/").pop()||n;return{model:n,modelShort:i&&e.endsWith(`:${i}`)?e.slice(0,-(i.length+1)):e,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:i||a||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:a||null}}class io extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function il(e){try{return await e.json()}catch{throw new io("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function ic(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 id(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 iu(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 ip(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 ih(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 io(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let a=await il(i);if(!i.ok)throw new io("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}(a,`HTTP ${i.status}`),i.status);return{response:i,body:a}};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 io("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new io("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(iu)))throw new io("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:i??[]}},async getLiveTranscript(e,t,r,i){let{body:a}=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(!a||"object"!=typeof a)throw new io("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof a.error&&a.error)throw new io("http",a.error);if(!0!==a.success||!a.data||"object"!=typeof a.data)throw new io("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let s=a.data;if(!Array.isArray(s.entries)||!s.entries.every(ip)||"number"!=typeof s.fromByte||"number"!=typeof s.nextByte||"boolean"!=typeof s.reset)throw new io("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:s.fromByte,nextByte:s.nextByte,reset:s.reset,entries:s.entries}},async getArchive(e,r){let i=`${t}/archive?session=${encodeURIComponent(e)}`,{body:a}=await n(i,{method:"GET",signal:r},"sidecar-unreachable");if(!a||"object"!=typeof a||"string"!=typeof a.sessionId||"string"!=typeof a.dir||"boolean"!=typeof a.found||!Array.isArray(a.subagents)||!a.subagents.every(ic))throw new io("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:a.sessionId,dir:a.dir,found:a.found,subagents:a.subagents,...!0===a.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,r,i=400,a){let s=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(r)}&limit=${encodeURIComponent(String(i))}`,{body:o}=await n(s,{method:"GET",signal:a},"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(id))throw new io("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}let im=["feature","maintenance","diagnostic"],ig=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function ix(e){if("string"!=typeof e)return null;let t=e.split(/\r?\n/),n=t.findIndex(e=>/^\s*TASK_GUARD\s*:\s*$/.test(e));if(n<0)return null;for(let e=n+1;e<t.length;e+=1){let n=ig.exec(t[e]);if(!n)break;if("WORK_CLASS"!==n[1])continue;let r=n[2].toLowerCase();return im.includes(r)?r:null}return null}let iv={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function iy(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function ib(e){return"string"==typeof e&&e.trim()?e:null}function iw(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function ik(e){switch(e){case"pending":case"queued":return"pending";case"running":return"running";case"completed":case"success":return"completed";case"failed":case"error":return"failed";case"aborted":case"cancelled":case"canceled":return"aborted";default:return null}}function ij(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function iS(e,t){if(t?.isError)return null;let n=iy(e.input.tasks),r=iy(t?.details?.progress),i=Math.max(n.length,r.length),a=[];for(let s=0;s<i;s++){let i=r.find(e=>e.index===s)??r[s],o=n[s],l=ib(i?.id)??ib(o?.name);l&&a.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:l,agent:ib(i?.agent)??ib(o?.agent),task:ib(i?.task)??ib(o?.task)??"",workClass:ix(o?.task)??ix(i?.task),spawned:!!t})}return a}let iC=/<task-result\b([^>]*)>/g,iN=/(\w+)="([^"]*)"/g;function iI(e,t,n){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&n.latestByAgent.get(e.agentId)===e.key)}function iT(e,t,n){var r;let i,a,s,o,l=iI(e,t,n),c=l?{key:e.key,identity:"live",live:l.assignment?l:{...l,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},d=ia(c),u=n.runs.get(e.key),p=null;l&&"unknown"!==l.status?(i=l.status,p="live"):u&&"unknown"!==u.status?(i=u.status,p="record"):i=e.spawned?"unobserved":"dispatching";let h=n.verdicts.get(e.key),f=h&&h.length>0?h[h.length-1]:null,m=f?.at??null,g=null===m?null:(r=e.key,a=n.runStartedAt.get(r)??null,s=l?.progress?.durationMs,o=l&&("pending"===l.status||"running"===l.status)&&"number"==typeof s&&l.lastUpdate>0?l.lastUpdate-s:null,null===a?o:null===o?a:Math.max(a,o)),x=null!==m&&null!==g&&g>m;return{member:e,title:d.title,explicitTitle:d.explicitTitle,stage:l?d.stage:null,model:l?is(c):null,run:i,runSource:p,verdict:x?null:f,priorVerdict:x?f:null,runTitle:x?ii(l?.progress?.task):null,observedParallelWith:n.parallelWith.get(e.key)}}function iM(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function iR(e,t){let n=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),r=new Map,i=[];for(let e of n){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?i.push(t):r.set(e.attempt,t)}return[...i,...[...r.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}function iE(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function i$(e,t,n){let r=-1;n.forEach((e,t)=>{"user"===e.role&&(r=t)});let i=n.slice(0,r+1).flatMap(iE),a=n.slice(r+1).flatMap(iE),s=t.findIndex(e=>"user"===e.role),o=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===o?{continuing:null,atCompaction:[...i,...a]}:{continuing:{position:o,calls:a},atCompaction:i}}let iL={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function iP(e){return e.trim()}function iA(e){return iP(e.text)||(e.images>0?"[Image]":"")}function iF(e){let t=e.filter(e=>!iL[e.stage]);if(t.length<=4)return e;let n=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!n.has(e.id))}function iz(e,t){switch(t.type){case"submit":return iF([...e,{id:t.id,kind:t.kind,text:t.text,images:t.images??0,stage:"sending",inQueue:!1}]);case"ack":return e.map(e=>e.id===t.id&&"sending"===e.stage?{...e,stage:"accepted"}:e);case"fail":return iF(e.map(e=>e.id===t.id&&iL[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,i=(e,t)=>{let n=`${e}\u0000${iP(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)i("steer",e);for(let e of n)i("followUp",e);let a=!1,s=e.map(e=>{if(!iL[e.stage])return e;let t=`${e.kind}\u0000${iA(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-1),e.inQueue&&"accepted"===e.stage)?e:(a=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(a=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return a?s:e}(e,t.steering,t.followUp);case"user-message":{let n=iP(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(iL[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&iP(e.text)===n&&e.images===t.images);if(!r)return e;return iF(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>iL[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=iP(t.text),i=e.find(e=>n(e)&&e.kind===t.kind&&(iP(e.text)===r||iA(e)===r));return i?e.filter(e=>e!==i):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}function iW(e){return"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function iD(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}let iO=["investigate","edit","check","review","commit","ci","deploy"];function iH(e,t){let n="",r=t;for(;r<e.length&&'"'!==e[r];){let t=e[r];if("\\"===t&&r+1<e.length){let i=e[r+1];"\n"!==i&&(n+='$`"\\'.includes(i)?i:t+i),r+=2}else if("$"===t&&"("===e[r+1]){let t=iU(e,r+1);n+=e.slice(r,t),r=t}else if("`"===t){let t=i_(e,r+1);n+=e.slice(r,t),r=t}else n+=t,r+=1}return{text:n,end:Math.min(r+1,e.length)}}function iU(e,t){let n=e[t],r="{"===n?"}":")",i=0,a=t;for(;a<e.length;){let t=e[a];if("\\"===t)a+=2;else if("'"===t){let t=e.indexOf("'",a+1);a=t<0?e.length:t+1}else if('"'===t)a=iH(e,a+1).end;else if("`"===t)a=i_(e,a+1);else{if(t===n)i+=1;else if(t===r&&0==--i)return a+1;a+=1}}return e.length}function i_(e,t){let n=t;for(;n<e.length&&"`"!==e[n];)n+="\\"===e[n]?2:1;return Math.min(n+1,e.length)}function iB(e){let t=[],n=[],r={pipelines:[],operators:[],background:!1},i={commands:[],negated:!1},a=[],s=()=>{let t=a.map(e=>e.value).filter(e=>"{"!==e&&"}"!==e);if(0===i.commands.length&&"!"===t[0]&&(i.negated=!0,t.shift()),t.length>0){let r={words:t,text:e.slice(a[0].start,a[a.length-1].end)};i.commands.push(r),n.push(r)}a=[]},o=()=>{s(),i.commands.length>0&&r.pipelines.push(i),i={commands:[],negated:!1}},l=e=>{o(),r.pipelines.length>0&&t.push({...r,background:e}),r={pipelines:[],operators:[],background:!1}};for(let t of function(e){let t=[],n=[],r="",i=-1,a=e=>{i<0||(t.push({value:r,start:i,end:e}),r="",i=-1)},s=0;for(;s<e.length;){let o=e[s];if("\\"===o)"\n"!==e[s+1]&&(i<0&&(i=s),r+=e[s+1]??""),s+=2;else if("'"===o){i<0&&(i=s);let t=e.indexOf("'",s+1),n=t<0?e.length:t;r+=e.slice(s+1,n),s=n+1}else if('"'===o){i<0&&(i=s);let t=iH(e,s+1);r+=t.text,s=t.end}else if("$"===o&&("("===e[s+1]||"{"===e[s+1])){i<0&&(i=s);let t=iU(e,s+1);r+=e.slice(s,t),s=t}else if("`"===o){i<0&&(i=s);let t=i_(e,s+1);r+=e.slice(s,t),s=t}else if("#"===o&&i<0){let t=e.indexOf("\n",s);s=t<0?e.length:t}else if(" "===o||" "===o||"\r"===o)a(s),s+=1;else if("\n"===o){a(s);let r=t[t.length-1];for(let{delimiter:i,stripTabs:a}of("&&"!==r&&"||"!==r&&"|"!==r&&t.push(";"),s+=1,n.splice(0)))for(;s<e.length;){let t=e.indexOf("\n",s),n=t<0?e.length:t,r=e.slice(s,n);if(s=n+1,(a?r.replace(/^\t+/,""):r)===i)break}}else if("<"===o&&"<"===e[s+1]&&"<"!==e[s+2]){a(s);let t=s+2,r="-"===e[t];for(r&&(t+=1);" "===e[t]||" "===e[t];)t+=1;let i="";for(;t<e.length&&!/[\s;&|<>()]/.test(e[t]);){let n=e[t];if("'"===n||'"'===n){let r=e.indexOf(n,t+1),a=r<0?e.length:r;i+=e.slice(t+1,a),t=a+1}else i+="\\"===n?e[t+1]??"":n,t+="\\"===n?2:1}i&&n.push({delimiter:i,stripTabs:r}),s=t}else";"===o?(a(s),t.push(";"),s+=";"===e[s+1]?2:1):"&"===o?"&"===e[s+1]?(a(s),t.push("&&"),s+=2):(">"===e[s+1]||/[<>]$/.test(r)?(i<0&&(i=s),r+=o):(a(s),t.push("&")),s+=1):"|"===o?"|"===e[s+1]?(a(s),t.push("||"),s+=2):r.endsWith(">")?(r+=o,s+=1):(a(s),t.push("|"),s+="&"===e[s+1]?2:1):("("===o||")"===o?a(s):(i<0&&(i=s),r+=o),s+=1)}return a(e.length),t}(e))"string"!=typeof t?a.push(t):"|"===t?s():"&&"===t||"||"===t?(o(),r.operators.push(t)):l("&"===t);return l(!1),{lists:t,commands:n,uncertain:/[(){}!`]/.test(e)}}function iq(e){return e.slice(e.lastIndexOf("/")+1)}let iV={bash:!0,sh:!0,zsh:!0,dash:!0},iK={sudo:!0,env:!0,command:!0,exec:!0,nice:!0,nohup:!0,time:!0,timeout:!0,setsid:!0,"systemd-run":!0},iG={"-u":!0,"--unit":!0,"-p":!0,"--property":!0,"-E":!0,"--setenv":!0,"--description":!0,"--slice":!0,"-M":!0,"--machine":!0,"-H":!0,"--host":!0,"--uid":!0,"--gid":!0,"--working-directory":!0,"-s":!0,"--signal":!0,"-k":!0,"--kill-after":!0},iJ={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},iZ={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function iY(e){let t=i0(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(iV,iq(e[t]))||iX(e,t))return null;for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*c[a-zA-Z]*$/.test(e[n]))return e[n+1]??null;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return null}function iX(e,t){for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*n[a-zA-Z]*$/.test(e[n])||/^-[a-zA-Z]*o$/.test(e[n])&&"noexec"===e[n+1])return!0;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return!1}let iQ={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function i0(e){let t=!1,n="";for(let r=0;r<e.length;r+=1){let i=e[r];if(!(/^[A-Za-z_]\w*=/.test(i)||!t&&Object.hasOwn(iZ,i))){if(t&&(i.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(i))){if(Object.hasOwn(iQ,n)&&iQ[n].test(i))return -1;"command"!==n&&Object.hasOwn(iG,i)&&(r+=1);continue}if(!Object.hasOwn(iK,iq(i)))return r;t=!0,n=iq(i)}}return -1}let i1=/(?:^|\/)wsl\/update\.sh$/;function i2(e,t=0){let n=iY(e);if(null!==n)return t<3&&iB(n).commands.some(e=>i2(e.words,t+1));let r=i0(e);if(r<0)return!1;if(i1.test(e[r]))return!0;if(!Object.hasOwn(iV,iq(e[r]))||iX(e,r))return!1;let i=e.slice(r+1).find(e=>!e.startsWith("-"));return void 0!==i&&i1.test(i)}function i8(e){let t=i0(e),n=t<0?e:e.slice(0,t),r=n.map(iq);return r.includes("systemd-run")?!n.some(e=>Object.hasOwn(iJ,e)):!!(r.includes("sudo")&&n.some(e=>"--background"===e||/^-[a-zA-Z]*b[a-zA-Z]*$/.test(e)))||r.includes("setsid")&&!n.includes("-w")&&!n.includes("--wait")}function i4(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function i5(e){if(e.every(e=>/^[A-Za-z_]\w*=/.test(e)))return!0;let[t,...n]=e;return"cd"===t?n.length<=1:"export"===t?n.every(e=>/^[A-Za-z_]\w*=/.test(e)):"set"===t&&n.every(e=>/^[-+][a-zA-Z]+$/.test(e)&&!/^-[a-zA-Z]*n/.test(e)||"pipefail"===e)}let i6={tail:!0,head:!0,cat:!0,tee:!0},i3=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,i7={bun:!0,bunx:!0,npm:!0,npx:!0,pnpm:!0,yarn:!0,node:!0,python:!0,python3:!0,deno:!0},i9={"--help":!0,"-h":!0,"--version":!0},ae=Object.fromEntries(["-C","-r","--allow-fs-read","--allow-fs-write","--build-snapshot-config","--conditions","--cpu-prof-dir","--debug-port","--inspect-port","--experimental-config-file","--experimental-default-config-file","--experimental-test-isolation","--test-isolation","--report-dir","--report-directory","--cpu-prof-interval","--cpu-prof-name","--diagnostic-dir","--disable-proto","--disable-warning","--dns-result-order","--env-file","--env-file-if-exists","--experimental-loader","--experimental-package-map","--experimental-sea-config","--experimental-test-tag-filter","--heap-prof-dir","--heap-prof-interval","--heap-prof-name","--heapsnapshot-near-heap-limit","--heapsnapshot-signal","--icu-data-dir","--import","--input-type","--inspect-publish-uid","--loader","--localstorage-file","--max-http-header-size","--max-old-space-size-percentage","--network-family-autoselection-attempt-timeout","--openssl-config","--redirect-warnings","--report-filename","--report-signal","--require","--run","--secure-heap","--secure-heap-min","--snapshot-blob","--test-concurrency","--test-coverage-branches","--test-coverage-exclude","--test-coverage-functions","--test-coverage-include","--test-coverage-lines","--test-global-setup","--test-name-pattern","--test-random-seed","--test-reporter","--test-reporter-destination","--test-rerun-failures","--test-shard","--test-skip-pattern","--test-timeout","--title","--tls-cipher-list","--tls-keylog","--trace-event-categories","--trace-event-file-pattern","--trace-require-module","--unhandled-rejections","--use-largepages","--v8-pool-size","--watch-kill-signal","--watch-path"].map(e=>[e,!0]));function at(e){let t=i0(e);if(t<0)return!1;let n=iq(e[t]);if("test"===n||"["===n||e.slice(t+1).some(e=>Object.hasOwn(i9,e)))return!1;if(i3.test(n))return!0;if(!Object.hasOwn(i7,n))return!1;if("node"===n&&function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("--test"===t)return!0;if("--"===t||!t.startsWith("-"))break;Object.hasOwn(ae,t)&&(n+=1)}return!1}(e,t+1))return!0;let r=function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("-m"===t)return e[n+1];if(/^-[a-zA-Z]*[cep]/.test(t)||/^--(?:eval|print)(?:=|$)/.test(t))break;if(!t.startsWith("-")){if("run"===t||"exec"===t||"x"===t||"dlx"===t)return e.slice(n+1).find(e=>!e.startsWith("-"));return t}}}(e,t+1);return void 0!==r&&i3.test(r)}let an={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},ar={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function ai(e){let t=i0(e);if(t<0||"git"!==iq(e[t]))return null;for(let n=t+1;n<e.length;n+=1)if(Object.hasOwn(an,e[n]))n+=1;else if(!e[n].startsWith("-"))return{name:e[n],at:n};return null}function aa(e,t=0,n){let r=iY(e);if(null!==r)return t<3&&iB(r).commands.some(e=>aa(e.words,t+1,n));let i=ai(e);if(!i||"commit"!==i.name&&"push"!==i.name||void 0!==n&&i.name!==n)return!1;let a=ar[i.name];return!e.slice(i.at+1).some(e=>Object.hasOwn(a,e)||"push"===i.name&&/[nd]/.test(function(e){if(!/^-[a-zA-Z0-9]/.test(e))return"";let t="";for(let n of e.slice(1)){if("o".includes(n)||!/[a-zA-Z0-9]/.test(n))break;t+=n}return t}(e)))}function as(e){return i5(e)||null!==ai(e)}let ao={check:({words:e})=>at(e),commit:({words:e})=>aa(e),ci:({words:e})=>{let t=i0(e);return t>=0&&"gh"===iq(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>i2(e.words)},al={test:"test",tests:"test",vitest:"test",jest:"test",pytest:"test",typecheck:"typecheck",tsc:"typecheck",lint:"lint",eslint:"lint",build:"build",check:"verify",verify:"verify",smoke:"smoke"};function ac(e){return!e||"object"!=typeof e||"bash"!==e.toolName||!e.input||"object"!=typeof e.input||Array.isArray(e.input)?null:("string"==typeof e.input.command?e.input.command.trim():"")||null}let ad={"$?":!1,"${PIPESTATUS[0]}":!0};function au(e,t){let n=ak(t);if("notRun"===n)return[];let r=n?void 0:t,i=iB(e),a=[];if(i.commands.some(({words:e})=>(function e(t,n=0){let r=iY(t);return null!==r?n<3&&iB(r).commands.some(t=>e(t.words,n+1)):at(t)})(e))&&a.push("check"),i.commands.some(({words:e})=>aa(e))&&a.push("commit"),i.commands.some(({words:e})=>(function e(t,n=0){let r=iY(t);if(null!==r)return n<3&&iB(r).commands.some(t=>e(t.words,n+1));let i=i0(t);return i>=0&&"gh"===iq(t[i])&&"run"===t[i+1]&&["watch","view","list"].includes(t[i+2])})(e))&&a.push("ci"),i.commands.some(ao.deploy)&&a.push("deploy"),0===a.length)return[];let s=r?nS(r):null,o=null===s?!!r?.isError:0!==s,l=a.length>1?{stages:a,failed:o}:void 0,c=r?aD(r):"";return a.map(e=>{var t;let n,a,d,u="commit"===e?as:i5,p=function e(t,n,r=i5,i=0){let{lists:a}=t,s=[],o=t.uncertain,l=!1;return a.forEach((t,c)=>{for(let d of(t.pipelines.some(e=>e.commands.some(({words:e})=>e.some(e=>e.includes("pipefail"))))&&(l=!1),t.pipelines)){let u=!1;for(let p of d.commands){let h=i<3?iY(p.words):null,f=null===h?null:e(iB(h),n,r,i+1);if(f&&f.decisive.length>0)s.push(...f.decisive);else if(n(p))s.push(p);else{let e=i0(p.words);u&&l&&e>=0&&Object.hasOwn(i6,iq(p.words[e]))||r(p.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let n=i4(e[t])?.words;return n?.[0]==="exit"&&(1===n.length||2===n.length&&"$?"===n[1])}(a,c)||(o=!0);continue}u=!0,(f?.reach==="masked"||d.negated||d.commands.length>1&&!l||t.operators.includes("||")||t.background||i8(p.words)||!function(e,t){if(t===e.length-1)return!0;let n=e[e.length-1],r=i4(n)?.words;return!!r&&"exit"===r[0]&&!n.background&&t===e.length-2&&(1===r.length||2===r.length&&"$?"===r[1])}(a,c))&&(o=!0)}}let d=i4(t)?.words;!t.background&&d?.[0]==="set"&&3===d.length&&"pipefail"===d[2]&&(/^-[a-zA-Z]*o$/.test(d[1])?l=!0:/^\+[a-zA-Z]*o$/.test(d[1])&&(l=!1))}),{reach:0===s.length?"absent":o?"masked":"carried",decisive:s}}(i,ao[e],u),h="check"===e&&p.decisive.some(({words:e})=>e.includes("--if-present")),f=r?(t=ao[e],n=new Map,a=i.lists.map(e=>(function(e){let t=e&&!e.background?i4(e)?.words:void 0;if(!t||"echo"!==t[0]||t.length<2)return null;let n=t.slice(1);if(n.some(e=>e.startsWith("-")||/^(?:\d*[<>]|&>)/.test(e)))return null;let r=n.join(" ");for(let[e,t]of Object.entries(ad)){let n=r.indexOf(e);if(n<0||r.indexOf(e,n+1)>=0)continue;let i=r.slice(0,n),a=r.slice(n+e.length);if(/[$`\\]/.test(i+a)||!/[^\s\d]/.test(i))break;return{prefix:i,suffix:a,first:t}}return null})(e)),d=c.split("\n").map(e=>e.trimEnd()),i.lists.forEach((e,r)=>{let i=a[r+1];if(!i||e.background||e.operators.includes("||"))return;let s=e.pipelines[e.pipelines.length-1],o=e.pipelines.slice(0,-1);if(s.negated||o.some(e=>e.negated||1!==e.commands.length||!u(e.commands[0].words)))return;let l=i.first||1===s.commands.length?s.commands[0]:void 0;if(!l||!t(l)||i8(l.words)||/[(){}!`]/.test(l.text))return;let c=a.filter(e=>e?.prefix===i.prefix&&e.suffix===i.suffix),p=RegExp(`^${i.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(-?\\d+)${i.suffix.trimEnd().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`),h=d.flatMap(e=>{let t=p.exec(e);return t?[{code:Number(t[1]),line:e}]:[]});if(h.length!==c.length)return;let f=a.slice(0,r+2).filter(e=>c.includes(e)).length-1;n.set(l,h[f])}),n):new Map,m=p.decisive.flatMap(e=>f.get(e)??[]),g=m.length>0&&m.length===p.decisive.length?m.find(({code:e})=>0!==e)??m[0]:null;return{stage:e,state:g?0!==g.code?"failed":h?"unverified":"passed":o?l?"unverified":"failed":null===s?"unobserved":"carried"!==p.reach||h?"unverified":"passed",exitCode:s,labels:"check"===e?function(e){let t=[];for(let{words:n}of e){let e=i0(n);n.forEach((n,r)=>{if(r!==e||"test"!==n)for(let e of n.replace(/^-+/,"").toLowerCase().split(":")){let n=Object.hasOwn(al,e)?al[e]:void 0;n&&!t.includes(n)&&t.push(n)}})}return t}(p.decisive):[],...l?{compound:l}:{},...g?{evidence:g.line}:{}}})}function ap(e,t){let n=ac(e),r=null===n?void 0:au(n,t).find(e=>"check"===e.stage);return null!==n&&r?{toolCallId:e.toolCallId,command:n,state:r.state,exitCode:r.exitCode,labels:r.labels,...r.compound?{compound:r.compound}:{}}:null}let ah=/\.(?:md|mdx|markdown|txt)$/i,af=/^docs?$/i,am={read:!0,grep:!0,glob:!0,find:!0,ls:!0,skim:!0,web_search:!0,fetch:!0,ast_grep:!0,lsp:!0,recall:!0,reflect:!0},ag={multiedit:!0,notebookedit:!0,draft:!0},ax={rename:!0,rename_file:!0},av={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function ay(e){return e.split("\n")[0].trim()||void 0}let ab=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,aw=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function ak(e){let t=e?.details;return t&&"object"==typeof t?"__synthetic"in t&&!0===t.__synthetic&&"executed"in t&&!1===t.executed?"notRun":"__interrupted"in t&&!0===t.__interrupted?"interrupted":null:null}let aj=/\btool\.git_finalize\s*\(/,aS=/\bCommitted and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,aC=/\bgit_finalize failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,aN=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/,aI=/^bg_\d+$/;function aT(e,t){let n=/Command exited with code (-?\d+)\s*$/.exec(t.trimEnd());return{jobId:e,text:t,exitCode:n?Number(n[1]):null}}function aM(e){return"passed"===e||"failed"===e||"done"===e}function aR(e){let t=null;for(let n of e.values())"failed"===n.outcome&&(!t||n.order>t.order)&&(t=n);return t?.stage??null}function aE(e){let t=new Map;for(let n of e){if("check"!==n.stage)continue;let e=n.commandKey??n.command,r=t.get(e);(r?.outcome!=="failed"||aM(n.outcome))&&t.set(e,n)}return[...t.values()]}function a$(e){return"compound"in e&&e.compound?.failed===!0}let aL={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function aP(e){return"stale"!==e&&(aM(e)||"running"===e)}function aA(e){if("ci"!==e.stage)return null;let t=iB(e.command).commands.flatMap(({words:e})=>aH(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?aq(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let aF={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},az={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},aW=/^[0-9a-f]{40}$/i;function aD(e){let t=e.content;return"string"==typeof t?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:"").join("\n"):""}function aO(e){let t=[];for(let n of e.split("\n")){let e,r=n.trim();if(r.startsWith("{")||r.startsWith("[")){try{e=JSON.parse(r)}catch{continue}for(let n of Array.isArray(e)?e:[e])n&&"object"==typeof n&&!Array.isArray(n)&&t.push(n)}}return t}function aH(e,t=0){let n=iY(e);if(null!==n)return t<3?iB(n).commands.flatMap(e=>aH(e.words,t+1)):[];let r=i0(e);return r>=0&&"gh"===iq(e[r])?[e.slice(r+1)]:[]}function aU(e,t){for(let n=0;n<e.length;n+=1)for(let r of t){if(e[n]===r)return e[n+1]??null;if(r.startsWith("--")&&e[n].startsWith(`${r}=`))return e[n].slice(r.length+1)}return null}let a_={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function aB(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(a_,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function aq(e){let t=aB(e);return null!==t&&/^\d+$/.test(t)?t:null}let aV=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function aK(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==nS(t))return[];let n=iB(e).commands.flatMap(({words:e})=>aH(e)).filter(e=>"run"===e[0]&&("list"===e[1]||"view"===e[1]));if(0===n.length)return[];let r=1===n.length?n[0]:null,i=r?.[1]==="list"?aU(r,["-c","--commit"])?.toLowerCase():void 0,a=i&&/^[0-9a-f]{7,40}$/.test(i)?i:null,s=aD(t);return a||s.includes("headSha")?aO(s).flatMap(e=>{let t="string"==typeof e.headSha?e.headSha.toLowerCase():a;if(null===t)return[];let n="string"==typeof e.url?aV.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):r?.[1]==="view"?aq(r):null,repo:(n??(r?aU(r,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:r?aU(r,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:r?aU(r,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let aG=/\b\d{9,12}\b/g,aJ=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function aZ(e,t){if(e?.type!=="toolCall")return[];let n=ac(e);return null===n?[]:aK(n,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(az,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let aY="Public tree already matches; nothing to publish";function aX(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function aQ(e){let t="run"===e[0]&&"list"===e[1]?aU(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(aF,t)}function a0(e,t){let n=new Map,r=[];for(let{words:i}of iB(e).commands){let e=i.map(e=>/^([A-Za-z_]\w*)=([\s\S]*)$/.exec(e));if(i.length>0&&e.every(e=>null!==e)){for(let t of e){if(!t)continue;let e=/^\$\(([\s\S]*)\)$/.exec(t[2])?.[1],r=void 0===e?[]:iB(e).commands.flatMap(e=>aH(e.words));n.set(t[1],1===r.length&&aQ(r[0]))}continue}for(let e of aH(i)){if(aQ(e)){r.push({args:e,publish:!0});continue}let i="run"===e[0]&&("watch"===e[1]||"view"===e[1])?aB(e):null,a=aX(i),s=null!==a?!0===n.get(a):null!==i&&/^\d+$/.test(i)&&t(i);r.push({args:e,publish:s})}}return r}function a1(e,t){let n=a0(e,t);return n.length>0&&n.every(({publish:e})=>e)}function a2(e,t){if(!e||!t)return!1;let[n,r]=e.length<=t.length?[e.toLowerCase(),t.toLowerCase()]:[t.toLowerCase(),e.toLowerCase()];return n.length>=7&&/^[0-9a-f]+$/.test(r)&&r.startsWith(n)}function a8(e,t,n){if(a2(e.sha,t.step.commit))return!0;let{title:r}=t.step;return!!r&&!!e.title&&!!e.repo&&!(e.order<=t.order)&&!!e.workflow&&!!Object.hasOwn(az,e.workflow)&&[...n.publishRuns.values()].some(n=>n.order>t.order&&null!==n.sha&&a2(n.sha,t.step.commit)&&null!==n.repo&&n.repo!==e.repo)&&function(e,t){if(e===t)return!0;let n=e.endsWith("…")?e.slice(0,-1):null;return null!==n&&n.length>=20&&t.startsWith(n)}(e.title,r)}let a4={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},a5=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,a6=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) (ROLLED_BACK|ROLLBACK_FAILED|FAIL)\b/,a3=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) START old=\S* target=([0-9a-f]{7,40})\b/;function a7(e,t,n=!1,r=[],i,a=[]){let s,o,l=[],c=[],d=1,u=new Map,p=-1,h=-1,f=new Map,m={publishRuns:new Map,watched:[],heads:[],ciHeads:[],nothingToPublish:[],runs:[]},g=Array.isArray(e)?e:[],x=t instanceof Map?t:new Map,v=function(e,t,n=[]){let r=new Map,i=new Map,a=new Map;for(let e of n)null!==e.after&&a.set(e.after,[...a.get(e.after)??[],e]);let s=(e,t)=>{for(let n of e){let e=i.get(n.jobId);e&&(i.delete(n.jobId),r.set(e.toolCallId,{...e.result,isError:!1,content:[{type:"text",text:n.text}],details:{...null===n.exitCode?{}:{exitCode:n.exitCode},backgroundJob:{jobId:n.jobId,after:t}}}))}};for(let n of Array.isArray(e)?e:[]){if(!n||"toolCall"!==n.type)continue;let e=t.get(n.toolCallId);if(e){let t="bash"===n.toolName||"eval"===n.toolName?function(e){let t=e.details,n=t&&"object"==typeof t&&"async"in t?t.async:null;if(n&&"object"==typeof n&&"jobId"in n&&"string"==typeof n.jobId&&aI.test(n.jobId))return n.jobId;let r=aD(e).trimStart();return r.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(r)?.[1]??null:null}(e):null;t?i.set(t,{toolCallId:n.toolCallId,result:e}):r.set(n.toolCallId,e),"wait"===n.toolName&&s(function(e){let t=e.details,n=t&&"object"==typeof t&&"jobs"in t?t.jobs:null,r=(Array.isArray(n)?n:[]).flatMap(e=>{if(!e||"object"!=typeof e||!("id"in e)||!("status"in e)||!("resultText"in e)||"string"!=typeof e.id||!aI.test(e.id)||"completed"!==e.status&&"failed"!==e.status||"string"!=typeof e.resultText)return[];let t="exitCode"in e&&"number"==typeof e.exitCode?e.exitCode:null;return[{...aT(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(r.length>0)return r;let i=aD(e),a=[...i.matchAll(/^### (bg_\d+) \[\w+\] — (?:completed|failed)$/gm)];return a.map((e,t)=>{let n=(e.index??0)+e[0].length,r=i.slice(n,t+1<a.length?a[t+1].index:i.length),s=r.indexOf("\n```\n"),o=r.lastIndexOf("\n```");return aT(e[1],s>=0&&o>s?r.slice(s+5,o):"")})}(e),n.toolCallId);let a="read"===n.toolName?function(e,t){let n=e.input.path,r="string"==typeof n?/^proc:\/\/(bg_\d+)$/.exec(n)?.[1]:void 0;if(!r)return null;let[i,...a]=aD(t).split("\n");return RegExp(`^1\\|${r} \\[\\w+\\] — (?:completed|failed)\\b`).test(i)?aT(r,a.map(e=>e.replace(/^\d+\|/,"")).join("\n")):null}(n,e):null;a&&s([a],n.toolCallId)}for(let e of a.get(n.toolCallId)??[])s(function(e){let t=e.replace(/^\s*<system-notice>\s*\n?/,"").replace(/\s*<\/system-notice>\s*$/,""),n=/^Background job (bg_\d+) has (?:completed|failed)\b[^\n]*(?:\n|$)/.exec(t);if(n)return[aT(n[1],t.slice(n[0].length))];let r=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return r.flatMap((e,n)=>{if(!aI.test(e[1]))return[];let i=(e.index??0)+e[0].length;return[aT(e[1],t.slice(i,n+1<r.length?r[n+1].index:t.length).replace(/^\n/,""))]})}(e.text),n.toolCallId)}return r}(g,x,Array.isArray(a)?a:[]),y=[];g.forEach((e,t)=>{let r;if(!e||"toolCall"!==e.type)return;let a=v.get(e.toolCallId);for(let s of(!function(e,t,n,r){let i=ac(t);if(null===i||!i.includes("gh"))return;let a=(t,n)=>{let i=e.publishRuns.get(t);i&&(null===n.sha||null!==i.sha)||e.publishRuns.set(t,{...n,order:i?.order??r})};for(let t of aK(i,n))e.runs.push({...t,order:r}),t.id&&t.sha&&t.workflow&&Object.hasOwn(aF,t.workflow)&&a(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==nS(t))return[];let n=iB(e).commands.flatMap(({words:e})=>aH(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==n.length)return[];let r=aU(n[0],["-w","--workflow"])?.toLowerCase(),i=void 0!==r&&Object.hasOwn(aF,r),a=aU(n[0],["-R","--repo"])?.toLowerCase()??null;return aD(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let n=t.toLowerCase();if(!i&&!Object.keys(aF).some(e=>n.includes(e)))return[];let r=t.match(aG)??[];return 1===r.length?[{id:r[0],sha:aJ.exec(n)?.[0]??null,repo:a}]:[]})}(i,n))a(e.id,e);for(let i of aZ(t,n))e.ciHeads.push({...i,order:r});for(let t of function(e,t){let n=iB(e),r=n.commands.flatMap(({words:e})=>aH(e)).filter(e=>"api"===e[0]),i=!n.uncertain&&1===n.commands.length&&1===r.length,a=t&&!t.isError&&0===nS(t)?aD(t).trim():"",s=[];for(let e of r){let t=e.slice(1).find(e=>/^\/?repos\//.test(e)),n=t?/^\/?repos\/([^/]+\/[^/]+)\/commits\/([^/?\s]+)$/.exec(t):null;if(!n)continue;let r=aU(e,["-q","--jq"]),o=null;if(i&&".sha"===r)o=a.split("\n")[0]?.trim();else if(i&&null===r&&a.startsWith("{"))try{o=JSON.parse(a.slice(0,a.lastIndexOf("}")+1)).sha}catch{}let l="string"==typeof o&&aW.test(o)?o.toLowerCase():null;s.push({repo:n[1].toLowerCase(),ref:n[2],sha:l})}return s}(i,n))e.heads.push({...t,order:r});let s=function(e,t){if(!t||t.isError||0!==nS(t)||2!==e.split(aY).length)return null;let{lists:n}=iB(e),r=0;for(;r<n.length&&["set","cd"].includes(i4(n[r])?.words[0]??"");)r+=1;let i=r<n.length-1?function(e){let t=i4(e)?.words,n=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!n)return null;let r=iB(n[2]),i=1===r.lists.length?i4(r.lists[0]):null,a=i?.words[0]==="gh"?aH(i.words):[];if(1!==a.length||"run"!==a[0][0]||"list"!==a[0][1])return null;let s=aU(a[0],["-c","--commit"]),o=aU(a[0],["-w","--workflow"])?.toLowerCase();return s&&aW.test(s)&&o&&Object.hasOwn(aF,o)?{name:n[1],sha:s.toLowerCase()}:null}(n[r]):null;return i&&function(e,t){if(e.background||1!==e.pipelines.length)return!1;let[n]=e.pipelines,[r,i,...a]=n.commands;if(n.negated||!i||a.length>1||"gh"!==r.words[0])return!1;let s=aH(r.words);if(1!==s.length||"run"!==s[0][0]||"view"!==s[0][1]||!s[0].includes("--log"))return!1;let o=aB(s[0]);if(aX(o)!==t)return!1;for(let e=2;e<s[0].length;e+=1){let t=s[0][e];if("-R"===t||"--repo"===t)e+=1;else if(t!==o&&"--log"!==t&&!t.startsWith("--repo=")&&!/^2>/.test(t))return!1}let[l,...c]=i.words,d=c.filter(e=>e.startsWith("-")),u=c.filter(e=>!e.startsWith("-"));if("grep"!==l||!d.every(e=>/^-[oFas]+$/.test(e))||!d.some(e=>e.includes("o"))||1!==u.length||u[0]!==aY)return!1;let[p]=a;return!p||("head"===p.words[0]||"tail"===p.words[0])&&p.words.slice(1).every(e=>/^(?:-n?\d*|\d+)$/.test(e))}(n[n.length-1],i.name)&&n.slice(r+1,-1).flatMap(e=>e.pipelines.flatMap(({commands:e})=>e)).every(({words:e})=>(function(e,t){let[n,...r]=e;if("["===n||"[["===n||"test"===n||"exit"===n||"true"===n||":"===n||"sleep"===n)return!0;if("echo"===n||"printf"===n)return r.every(e=>!/`|\$\(/.test(e)&&!/public|tree|already|matches|nothing|publish/i.test(e)&&[...e.matchAll(/\$\{?([A-Za-z_]\w*|[?])/g)].every(e=>e[1]===t||"?"===e[1]));if("gh"!==n)return!1;let i=aH(e);return 1===i.length&&"run"===i[0][0]&&"watch"===i[0][1]&&aX(aB(i[0]))===t})(e,i.name))&&aD(t).split("\n").some(e=>e.trim()===aY)?i.sha:null}(i,n);s&&e.nothingToPublish.push({sha:s,order:r})}(m,e,a,t),Array.isArray(r=function(e,t,n,r){if(!e.input||"object"!=typeof e.input||Array.isArray(e.input)||"string"!=typeof e.toolName)return null;let i=ak(t);if("notRun"===i)return null;let a={toolCallId:e.toolCallId,attempt:0},s=n&&!i?"running":"unobserved",o=ac(e);if(null!==o){var l;let e,n,r=(l=t,(n=(e=l?.details)&&"object"==typeof e&&"backgroundJob"in e?e.backgroundJob:null)&&"object"==typeof n&&"jobId"in n&&"after"in n&&"string"==typeof n.jobId&&"string"==typeof n.after?{jobId:n.jobId,after:n.after}:null);return au(o,t).map(e=>{if("commit"===e.stage){var n;let r,i,l=t?"unobserved"===e.state&&function(e,t){if(t.isError)return!1;let{commands:n}=iB(e),r=aD(t),i=e=>n.some(({words:t})=>aa(t,0,e));return(!i("commit")||ab.test(r))&&(!i("push")||aw.test(r))}(o,t)?"done":av[e.state]:s;return{...a,stage:"commit",..."done"===l?(r=(n=t)?aD(n):"",(i=ab.exec(r))?{commit:i[1],title:i[2].trim()}:{commit:aw.exec(r)?.[1]??null}):{commit:null},docsOnly:!1,outcome:l}}let i=e.evidence??(r&&null!==e.exitCode?`Command exited with code ${e.exitCode}`:void 0),l=i&&r?`${r.jobId} \xb7 ${i}`:i,c="ci"===e.stage&&"failed"===e.state&&t?function(e,t){let n=iB(e).commands.flatMap(({words:e})=>aH(e)),r=n.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),i=r?aB(r):null;if(null===i||!n.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&aB(e)===i))return null;let a=aO(aD(t)).filter(e=>"completed"===e.status&&"string"==typeof e.conclusion),s=1===a.length?a[0].conclusion:null;return"string"!=typeof s||""===s||"success"===s||Object.hasOwn(a4,s)?null:s}(o,t):null;return{...a,stage:e.stage,command:o,exitCode:e.exitCode,labels:e.labels,outcome:c?"unverified":t?e.state:s,...e.compound?{compound:e.compound}:{},...l?{evidence:c?`${l} \xb7 ${c}`:l}:{},...c?{otherRun:{kind:"unjudged",conclusion:c}}:{}}})}let c=e.toolName.toLowerCase().split(/[.:/]/).pop()??"",d=i?void 0:t,u=d?.details&&"object"==typeof d.details?d.details:{};if("cross_review"===c){let t="resolve"===e.input.action?"resolve":"review";if(!d||d.isError)return{...a,stage:"review",action:t,findings:null,outcome:d?"failed":s};if("resolve"===t){if(!0===u.pass)return{...a,stage:"review",action:t,findings:0,outcome:"passed"};let e=Array.isArray(u.open)?u.open.length:null;return{...a,stage:"review",action:t,findings:e,outcome:!1===u.pass?"failed":"unobserved"}}let n=Array.isArray(u.findings)?u.findings.length:null;if(null!==n&&n>0)return{...a,stage:"review",action:t,findings:n,outcome:"failed"};let r=Array.isArray(u.reviewers)?u.reviewers:[];return!1===u.passable||r.some(e=>!e||"object"!=typeof e||!("status"in e)||"ok"!==e.status)?{...a,stage:"review",action:t,findings:n,outcome:"unverified",unusable:!0}:{...a,stage:"review",action:t,findings:n,outcome:null===n?"unobserved":"done"}}if("git_finalize"===c){let t="string"==typeof e.input.message?ay(e.input.message):void 0,n=t?{title:t}:{};if(!d)return{...a,stage:"commit",commit:null,docsOnly:!1,...n,outcome:s};let r=aS.exec(aD(d)),i=("string"==typeof u.commitSha&&""!==u.commitSha.trim()?u.commitSha.trim():null)??r?.[1]??r?.[2]??null,o=d.isError||!1===u.ok,l=!o&&(!0===u.ok||null!==i),c=e.input.files,p=l&&Array.isArray(c)&&c.length>0&&c.every(e=>"string"==typeof e&&(ah.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>af.test(e))));return{...a,stage:"commit",commit:l?i:null,docsOnly:p,...n,outcome:l?"done":o?"failed":"unobserved"}}if("eval"===c)return function(e,t,n){let r=function(e){if("string"==typeof e.code)return e.code;let t=e.cells;return Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"").join("\n"):""}(e.input);if(!aj.test(r))return null;let i=aN.exec(r)?.[2],a=void 0===i?void 0:ay(i.replace(/\\n/g,"\n").replace(/\\(["'`\\])/g,"$1")),s={toolCallId:e.toolCallId,attempt:0,stage:"commit",docsOnly:!1,...a?{title:a}:{}};if(!t)return{...s,commit:null,outcome:n};let o=aD(t),l=aS.exec(o),c=l?(l[1]??l[2]).toLowerCase():null,d=aC.test(o);return c&&!d?{...s,commit:c,outcome:"done"}:{...s,commit:null,outcome:!c&&(d||t.isError)?"failed":"unobserved"}}(e,d,s);if(function(e,t){if("task"===t||Object.hasOwn(ag,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(ax,e.input.action);if(!ts(e.toolName)&&!to(e.toolName))return!1;let n=e.input.file_path??e.input.path;return"string"!=typeof n||/^[a-zA-Z]:[\\/]/.test(n)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(n)}(e,c))return!i&&t?.isError?null:(ts(e.toolName)||to(e.toolName))&&tp(e.input,d,r)?{...a,stage:"investigate",outcome:i?"unobserved":t||!n?"done":"running"}:{...a,stage:"edit",outcome:d?"done":s,..."task"===c?{dispatch:!0}:{},...!function(e,t,n){if(!t||!(ts(e.toolName)||to(e.toolName)))return!1;let r=tu(e.input,t);return r.length>0&&r.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let n=t?ta(t)??t:void 0,r=tI(ta(e,t)??e,n);if(/^[\\/]/.test(r)||/^[a-zA-Z]:[\\/]/.test(r))return!1;let i=r.split(/[\\/]/).filter(e=>""!==e&&"."!==e);return"HANDOFF.md"===i.at(-1)||"doc"===i[0]&&"history"===i[1]&&i.length>2})(e,n))}(e,d,r)?{}:{recordOnly:!0}};return Object.hasOwn(am,c)?{...a,stage:"investigate",outcome:i?"unobserved":t||!n?"done":"running"}:null}(e,a,n,i))?r:r?[r]:[]))y.push({step:s,order:t})}),s=null,o=!1,y.forEach((e,t)=>{let{step:n,order:r}=e;if("commit"===n.stage&&"done"===n.outcome&&n.commit&&(s={step:{...n,commit:n.commit},order:r},o=!1),"edit"!==n.stage||"done"!==n.outcome||n.dispatch||n.recordOnly||(o=!0),"ci"!==n.stage||!s)return;let i=s,a=iB(n.command).commands.flatMap(({words:e})=>aH(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(a){let e,s=aq(a),l=e=>(m.publishRuns.get(e)?.order??1/0)<=r;if((e=a0(n.command,l).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){a1(n.command,l)||"passed"!==n.outcome&&"failed"!==n.outcome||(s&&"passed"===n.outcome&&m.watched.push({id:s,order:r}),y[t]={order:r,step:{...n,outcome:"unverified",evidence:void 0,otherRun:{kind:"publish",outcome:n.outcome}}});return}let c=s?m.runs.filter(e=>e.id===s):[],d=c.find(e=>null!==e.sha)?.sha;if(!d||c.some(e=>a8(e,i,m))){d&&o&&"passed"===n.outcome&&(y[t]={order:r,step:{...n,stale:!0}});return}if("passed"===n.outcome||"failed"===n.outcome){let e=d.slice(0,7);y[t]={order:r,step:{...n,outcome:"unverified",evidence:`run ${s} \xb7 ${e}`,otherRun:{kind:"commit",sha:e,outcome:n.outcome}}}}return}if("unverified"!==n.outcome)return;let l=m.runs.find(e=>e.order===r&&null!==e.workflow&&Object.hasOwn(az,e.workflow)&&a8(e,i,m));if(!l||"completed"!==l.status||"string"!=typeof l.conclusion)return;let c="success"===l.conclusion?"passed":Object.hasOwn(a4,l.conclusion)?"failed":null;c&&(y[t]={order:r,step:{...n,outcome:c,evidence:`run ${l.id??"?"} \xb7 ${l.status} ${l.conclusion}`,..."passed"===c&&o?{stale:!0}:{}}})}),y.forEach((e,t)=>{let{step:n,order:r}=e;if("deploy"!==n.stage||"unverified"!==n.outcome&&"unobserved"!==n.outcome)return;let i=function(e){let t=[],n=(e,r)=>{let i=iY(e);if(null!==i){if(r<3)for(let e of iB(i).commands)n(e.words,r+1);return}if(!i2(e))return;let a=i0(e),s=i1.test(e[a])?a:e.findIndex((e,t)=>t>a&&!e.startsWith("-")),o=e[s+1];t.push(void 0!==o&&/^[0-9a-f]{7,40}$/i.test(o)?o.toLowerCase():null)};for(let{words:t}of iB(e).commands)n(t,0);return 1===t.length?t[0]:null}(n.command),a=x.get(n.toolCallId);if("number"!=typeof a?.timestamp)return;let s=a.details,o=s&&"object"==typeof s&&"wallTimeMs"in s&&"number"==typeof s.wallTimeMs?s.wallTimeMs:0,l=1e3*Math.floor((a.timestamp-o)/1e3);for(let e=r;e<g.length;e+=1){let a=g[e],s=a?.type==="toolCall"?v.get(a.toolCallId):void 0;if(s)for(let e of aD(s).split("\n")){let a=e.trim().replace(/^\d+[:-](?=\d{4}-\d\d-\d\dT)/,"");if(null===i){let e=a3.exec(a);e&&Date.parse(e[1])>=l&&(i=e[2]);continue}let s=a5.exec(a);if(s&&Date.parse(s[1])>=l&&a2(s[2],i)){y[t]={order:r,step:{...n,outcome:"passed",evidence:`${s[1]} READY ${s[2].slice(0,12)}`}};return}let o=a6.exec(a);if(o&&Date.parse(o[1])>=l){y[t]={order:r,step:{...n,outcome:"failed",evidence:a.length>120?`${a.slice(0,119)}…`:a}};return}}}});let b=(e,t)=>null!==e&&(m.publishRuns.get(e)?.order??1/0)<=t;for(let{step:e,order:t}of y){let n=e;if("ci"===n.stage){let e=iB(n.command).commands.flatMap(({words:e})=>aH(e)).find(e=>"run"===e[0]&&"watch"===e[1]),r=e?aq(e):null;r&&"passed"===n.outcome&&m.watched.push({id:r,order:t}),!n.compound&&a1(n.command,e=>b(e,t))&&(n={toolCallId:n.toolCallId,attempt:n.attempt,stage:"investigate",outcome:"passed"===n.outcome||"unverified"===n.outcome?"done":n.outcome})}if("edit"!==n.stage||"done"!==n.outcome||n.dispatch){if("check"===n.stage||"review"===n.stage||"ci"===n.stage){let e="check"===n.stage?`check:${n.command}`:n.stage,t=u.get(e);(t?.outcome!=="failed"||aM(n.outcome))&&u.set(e,{stage:n.stage,outcome:n.outcome,order:l.length})}}else{let e=aR(u);e&&(c.push({from:e,attempt:d}),d+=1),u=new Map,p=l.length,n.recordOnly||(h=l.length)}n.attempt=d,f.set(n,t),l.push(n)}let w=!1;l.forEach((e,t)=>{t<("commit"===e.stage||w&&("ci"===e.stage||"deploy"===e.stage)?h:p)&&"investigate"!==e.stage&&"edit"!==e.stage&&("passed"===e.outcome||"done"===e.outcome)&&(e.stale=!0),"commit"===e.stage&&"done"===e.outcome&&(w=!0)});let k=l.filter(e=>"commit"===e.stage&&"done"===e.outcome&&e.attempt===d).at(-1),j=k?f.get(k)??-1:-1,S=k&&!k.stale&&k.commit&&aW.test(k.commit)?{sha:k.commit.toLowerCase(),order:j}:null,C=S?function(e,t,n){let r=e.watched.find(({id:n,order:r})=>{let i=e.publishRuns.get(n);return r>t.order&&i?.sha===t.sha&&i.order>t.order&&i.order<=r});if(!r)return null;let i=new Map;for(let t of e.heads)t.order>r.order&&i.set(`${t.repo}#${t.ref}`,t);let a=[...n,...e.ciHeads.filter(e=>e.order<t.order)];for(let e of i.values())if(null!==e.sha&&e.sha!==t.sha&&a.some(t=>t.repo===e.repo&&t.sha===e.sha&&t.branch===e.ref))return{kind:"publicHeadUnchanged",repo:e.repo,ref:e.ref,sha:e.sha,runId:r.id};return null}(m,S,r)??(m.nothingToPublish.some(({sha:e,order:t})=>e===S.sha&&t>S.order)?{kind:"nothingToPublish",commit:S.sha}:null):null;if(C?.kind==="nothingToPublish"){let e=C.commit;l.forEach((t,n)=>{var r;let i,a=f.get(t)??-1;if("ci"!==t.stage||"unverified"!==t.outcome||a<=j||!m.nothingToPublish.some(t=>t.order===a&&t.sha===e)&&(r=t.command,!((i=iB(r).commands.flatMap(({words:e})=>aH(e))).length>0&&i.every(t=>"run"===t[0]&&"list"===t[1]&&aU(t,["-c","--commit"])?.toLowerCase()===e))))return;let s={toolCallId:t.toolCallId,attempt:t.attempt,stage:"investigate",outcome:"done"};l[n]=s,f.set(s,a)})}let N=iO.map(e=>{let t=l.filter(t=>t.stage===e),n="investigate"===e?t:t.filter(e=>e.attempt===d);return{stage:e,status:function(e,t){if(0===t.length)return"waiting";if("check"!==e){let e=new Set,n=null;for(let r of t){let t=r.stale?"stale":r.outcome;if("failed"!==n||aM(r.outcome)){if(null!==n&&!("ci"!==r.stage||aP(t))&&!iB(r.command).commands.some(({words:e})=>aH(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===n&&(aA(r)?.every(t=>e.has(t))??!1);if(aP(n)||t)continue}if(n=t,"stale"===t||"passed"===r.outcome||"failed"===r.outcome)for(let t of aA(r)??[])e.add(t)}}return n??"waiting"}let n="done";for(let e of aE(t)){let t=e.stale?"stale":e.outcome;aL[t]>aL[n]&&(n=t)}return n}(e,n),steps:n,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),I=N[iO.indexOf("deploy")],T=l.some(e=>"commit"===e.stage&&"done"===e.outcome&&!e.docsOnly);!k?.docsOnly||k.stale||T||"waiting"!==I.status||(I.status="notNeeded");let M=N[iO.indexOf("ci")],R=M.steps.some(e=>(f.get(e)??1/0)>j);C&&("waiting"===M.status||("unverified"===M.status||"stale"===M.status)&&!R)?M.status="notNeeded":C=null;let E=-1;N.forEach((e,t)=>{"waiting"!==e.status&&"failed"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status&&"stale"!==e.status&&e.steps.some(e=>!e.stale&&"failed"!==e.outcome&&!a$(e))&&(E=t)});let $=null;if(n&&l.length>0)if(aR(u))$={stage:"edit",returning:!0};else if(E<0)$={stage:N.find(e=>"waiting"!==e.status)?.stage??iO[0],returning:!1};else{let e=N[E].steps.at(-1);if(e?.stage==="review"&&e.unusable)$={stage:"review",returning:!1};else{let e=N.slice(E+1).find(e=>"skipped"!==e.status&&"notNeeded"!==e.status);$=e?{stage:e.stage,returning:!1}:null}}if(N.forEach((e,t)=>{t<E&&"waiting"===e.status&&(e.status="skipped")}),!n&&l.length>0){let e=!T;for(let t of N)"waiting"===t.status&&(t.status=e&&("ci"===t.stage||"deploy"===t.stage)?"notNeeded":"skipped")}return{steps:l,attempt:d,loops:c,stages:N,current:function(e,t,n){let r=e.at(-1);if(!r)return null;if(!n||n.stale)return r.stage;let i=t.filter(e=>("commit"===e.stage||"ci"===e.stage||"deploy"===e.stage)&&e.steps.length>0&&"notNeeded"!==e.status&&"skipped"!==e.status),a=i.find(e=>"commit"!==e.stage&&Object.hasOwn(a9,e.status));return a?.stage??i.at(-1)?.stage??r.stage}(l,N,k),reached:E<0?null:iO[E],next:$,publication:C}}let a9={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0};function se(e){return e.flatMap(e=>e.tasks.flatMap(t=>"completed"===t.status||"abandoned"===t.status?[]:[{phase:e.name,content:t.content,status:t.status,blocker:t.blocker??null}]))}function st(e,t,n){let r=[],i=[],a=null;for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){i.push(n);continue}if(tw(n.toolName)){let e=tb(n,t.get(n.toolCallId));"authoritative"===e.kind&&(a=e.phases);continue}let e=ap(n,t.get(n.toolCallId));e&&r.push(e)}return{checks:r,dispatchCalls:i,files:tx(e,t,n),remaining:a?se(a):null}}function sn(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}function sr(e,t,n){let r=[],i=null;for(let a=Math.max(0,t);a<Math.min(e.length,n);a++){let t=e[a];if("assistant"===t.role)for(let e of t.content??[])"toolCall"===e.type&&(i=e.toolCallId);else if("custom"===t.role&&"async-result"===t.customType){let e="string"==typeof t.content?t.content:t.content.map(e=>"text"===e.type?e.text:"").join("\n");r.push({text:e,after:i})}}return r}function si(e,t){var n;let r=t;for(;r>=0&&(n=e[r],n?.role==="custom"?"compaction"===n.customType:n?.role==="user"&&("steer"===iD(n)||function(e){if("[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."===e||"[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다."===e)return!0;let[t,n]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==n&&n.startsWith("requestId=")}(iW(n))));){let t=r-1;for(;t>=0&&"user"!==e[t].role;)t-=1;r=t}return r}function sa(e,t,n,r){let i=Math.min(e.length,r),a=new Map;for(let t=Math.max(0,n);t<i;t++){let n=e[t];"toolResult"===n.role&&a.set(n.toolCallId,t)}let s=[];for(let r=Math.max(0,n-1);r<i;r++){let i=e[r];if(r>=n&&"assistant"===i.role)for(let e of i.content??[]){if("toolCall"!==e.type||!tw(e.toolName))continue;let n=tb(e,t.get(e.toolCallId));"authoritative"===n.kind&&s.push({at:a.get(e.toolCallId)??r,phases:n.phases})}for(let e of i.trackerTodos??[]){let t=ty(e);t&&s.push({at:r+.5,phases:t})}}let o=null;for(let e of s)(!o||e.at>=o.at)&&(o=e);return o?o.phases:null}function ss(e,t,n,r=0,i=[]){for(let a=Math.max(0,r);a<Math.min(e.length,n);a++){let n=e[a];if("assistant"===n.role)for(let e of n.content??[])"toolCall"===e.type&&i.push(...aZ(e,t.get(e.toolCallId)))}return i}function so(e,t,n){let r=null,i=null;for(let a=Math.max(0,t-1);a<Math.min(e.length,n);a++){let t=e[a];for(let e of[t.timestamp,"assistant"===t.role?t.completedAt:void 0])"number"==typeof e&&Number.isFinite(e)&&((null===r||e<r)&&(r=e),(null===i||e>i)&&(i=e))}return{startedAt:r,endedAt:i}}function sl(e,t){if(0===e.length)return null;let n=[...e].sort((e,t)=>e-t),r=(n.length-1)*t,i=Math.floor(r),a=Math.ceil(r);return n[i]+(n[a]-n[i])*(r-i)}let sc=["investigate","implement","verify","report"],sd={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},su={bash:!0,eval:!0};function sp(e){let t=[],n=new Map;for(let r of e)if("toolResult"===r.role&&n.set(r.toolCallId,r),"assistant"===r.role&&Array.isArray(r.content))for(let e of r.content)"toolCall"===e.type&&t.push(e);return{blocks:t,results:n}}function sh(e,t,n,r){return!0===sd[t]&&!tp(e.input,n.get(e.toolCallId),r)}function sf(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function sm(e){return"yield"===sf(e)&&!Array.isArray(e.input?.type)}function sg(e,t){if(0===e.length)return null;let{blocks:n,results:r}=sp(e),i=-1;n.forEach((e,t)=>{sm(e)&&(i=t)});let a=i>=0&&i===n.length-1,s=a?n.findLastIndex((e,t)=>t<i&&sm(e))+1:i+1,o={calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:a,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1},l=!1;for(let e of n.slice(s)){let n=sf(e);if(sh(e,n,r,t))"verify"===o.phase&&(o.reedits+=1),l=!0,o.phase="implement",o.verifiedAfterEdit=!1;else if(su[n]){if(o.phase=l?"verify":"investigate",l){o.verifiedAfterEdit=!0;let t=ap(e,r.get(e.toolCallId));t?.state==="passed"?o.checks.passed+=1:t?.state==="failed"?o.checks.failed+=1:t&&(o.checks.unknown+=1)}}else"yield"===n&&(o.phase="report",l=!1);o.calls[o.phase]+=1}return o}function sx(e,t){if(!e)return{run:null,stations:sc.map(e=>({phase:e,state:"unobserved",calls:0}))};let n=t&&e.ended?{calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:!1,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1}:e,r=t?sc.indexOf(n.phase):sc.findLastIndex(e=>n.calls[e]>0),i=sc.map((e,i)=>{let a,s=n.calls[e];return a=t&&e===n.phase?"active":s>0?"verify"!==e||n.verifiedAfterEdit?"done":"stale":i<r?"skipped":t?"waiting":"none",{phase:e,state:a,calls:s}});return{run:n,stations:i}}function sv(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function sy(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 sb(e){return"pending"===e||"running"===e}let sw=new Map;function sk(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function sj(e){return e instanceof io&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function sS(e,{sessionId:t,client:n,enabled:r}){let[a,s]=(0,i.useState)(sw),o=(0,i.useRef)(new Map),l=(0,i.useRef)(e);l.current=e;let c=(0,i.useCallback)(()=>{let e=o.current;s(t=>{let n=!1,r=new Map;for(let[i,a]of e){let e=t.get(i),s=e&&e.entries===a.collected&&e.state===a.state?e:{state:a.state,entries:a.collected};s!==e&&(n=!0),r.set(i,s)}return r.size!==t.size&&(n=!0),n?r:t})},[]),d=e.map(e=>`${e.key}|${sk(e)}`).join("\n");return(0,i.useEffect)(()=>{if(!r)return;let e=!1,i=!1,a=null,s=o.current,d=new Set(l.current.map(e=>e.key));for(let e of[...s.keys()])d.has(e)||s.delete(e);for(let e of l.current){let t=sk(e);s.get(e.key)?.signature!==t&&s.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(r,i,a,s)=>{if(!r.archiveName){i.state={kind:"empty",source:"live",note:s};return}try{let o=await n.getArchiveTranscript(t,r.archiveName,400,a);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:s}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:s}}catch(n){if(e||a.aborted)return;let t=sj(n);i.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(r,i)=>{let a=s.get(r.key);if(a){if(!r.liveId)return void await u(r,a,i);try{var o,l;let s=await n.getLiveTranscript(t,r.liveId,a.nextByte,i);if(e)return;let c=(o=s.entries,l=s.fromByte,o.flatMap((e,t)=>{let n=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:n,message:sy(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[]}));s.reset||0===s.fromByte?a.collected=c:c.length>0&&(a.collected=[...a.collected,...c]),a.nextByte=s.nextByte,a.collected.length>0?("ready-live"!==a.state.kind||a.state.entries!==a.collected)&&(a.state={kind:"ready-live",entries:a.collected}):await u(r,a,i)}catch(t){if(e||i.aborted)return;if(r.archiveName){let e=sj(t);await u(r,a,i,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=sj(t);a.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;a=t;try{for(let e of l.current)await p(e,t.signal)}finally{i=!1}e||c()};h();let f=l.current.some(e=>sb(e.status))?setInterval(()=>void h(),3e3):void 0,m=()=>{"visible"===document.visibilityState&&h()};return document.addEventListener("visibilitychange",m),()=>{e=!0,a?.abort(),clearInterval(f),document.removeEventListener("visibilitychange",m)}},[n,r,c,t,d]),a}let sC=(0,i.createContext)({ledger:iv,subagents:[],toolResults:new Map}),sN="omp-web:flow-motion",sI=new Set,sT=null;function sM(){if(null===sT)try{sT="paused"===window.localStorage.getItem(sN)}catch{sT=!1}return sT}function sR(e){return sI.add(e),()=>{sI.delete(e)}}function sE(){return(0,i.useSyncExternalStore)(sR,sM,()=>!1)}function s$({paused:e}){let{st:t}=rQ();return(0,r.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){sT=e;try{e?window.localStorage.setItem(sN,"paused"):window.localStorage.removeItem(sN)}catch{}for(let e of sI)e()})(!e),children:t("graph.motion.pause")})}function sL(e,t,n){return n&&t.current===e.stage?"active":"waiting"===e.status?"deploy"===e.stage?"approval":"waiting":"skipped"===e.status||"notNeeded"===e.status?"skipped":"stale"===e.status?"stale":"done"===e.status||"passed"===e.status?"done":"failed"===e.status||"running"===e.status?e.status:"unverified"}function sP(e){return e.stale?"stale":e.outcome}let sA=(0,r.jsx)("svg",{className:"flow-chevron",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)("polyline",{points:"6 9 12 15 18 9"})});function sF({look:e}){return(0,r.jsxs)("span",{className:"flow-node","aria-hidden":"true",children:[("done"===e||"stale"===e)&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:"stale"===e?"3 4":void 0,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}),"unverified"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"6",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"18",x2:"12",y2:"18.5"})]}),"failed"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"7",y1:"7",x2:"17",y2:"17"}),(0,r.jsx)("line",{x1:"17",y1:"7",x2:"7",y2:"17"})]}),"skipped"===e&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:(0,r.jsx)("line",{x1:"6",y1:"12",x2:"18",y2:"12"})})]})}function sz({outcome:e}){let t={className:"flow-check-icon",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"stale"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,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.jsx)("path",{d:"M12 7v5l4 2"})]}):"passed"===e||"done"===e?(0,r.jsx)("svg",{...t,strokeWidth:2.5,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}):"failed"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2.5,children:[(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"}),(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"})]}):"running"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0"}),(0,r.jsx)("path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0"}),(0,r.jsx)("path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7"}),(0,r.jsx)("path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8"}),(0,r.jsx)("path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69"}),(0,r.jsx)("path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8"}),(0,r.jsx)("path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69"}),(0,r.jsx)("path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7"})]}):(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,r.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}function sW({step:e,st:t}){let n=t(`flow.state.${e.outcome}`);if(e.stale)n=t("passed"===e.outcome?"flow.state.stale":"flow.state.staleDone");else if("review"===e.stage&&"failed"===e.outcome&&null!==e.findings){let r=1===e.findings?"flow.state.findings.one":"flow.state.findings";n=t("resolve"===e.action?"flow.state.open":r,{count:e.findings})}else"review"===e.stage&&e.unusable?n=t("flow.state.reviewUnusable"):"review"===e.stage&&"done"===e.outcome&&(n=t("flow.state.noFindings"));return(0,r.jsxs)("span",{className:"flow-tone","data-tone":sP(e),children:[n,"commit"===e.stage&&e.commit&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsxs)("span",{className:"flow-sha-tail",children:["\xb7\xa0",(0,r.jsx)("code",{className:"flow-sha",children:e.commit.slice(0,7)})]})]})]})}function sD({step:e,label:t,st:n}){let i=a$(e),a=e.compound?.stages.map(e=>n(`flow.stage.${e}`)).join("\xb7")??"",s=e.otherRun,o=i?n("flow.why.compoundConfirmed",{stages:a}):s?.kind==="unjudged"?n("flow.why.watched.unjudged",{conclusion:s.conclusion}):s?n(`flow.why.watched.${s.outcome}`):n("flow.why.exitZero"),l=i?n("flow.why.compoundMissing"):"check"===e.stage?n("flow.why.check",{label:t}):s?.kind==="commit"?n("flow.why.ciOtherRun",{sha:s.sha}):s?.kind==="publish"?n("flow.why.ciPublishRun"):s?.kind==="unjudged"?n("flow.why.ciUnjudged",{conclusion:s.conclusion}):n(`flow.why.${e.stage}`),c=null!==e.exitCode?n("flow.exit",{code:e.exitCode}):n("failed"===e.outcome?"flow.exit.error":"running"===e.outcome?"flow.state.running":"flow.exit.none");return(0,r.jsxs)("div",{className:"flow-raw",children:["unverified"===e.outcome&&(0,r.jsxs)("p",{className:"flow-why",children:[(0,r.jsx)("b",{children:n("flow.why.confirmed")})," ",o,(0,r.jsx)("br",{}),(0,r.jsx)("b",{children:n("flow.why.missing")})," ",l]}),e.stale&&(0,r.jsx)("p",{className:"flow-why",children:n("flow.why.stale")}),void 0===e.commandKey?(0,r.jsx)("code",{className:"flow-raw-command",children:e.command}):(0,r.jsx)("p",{className:"flow-why",children:n("flow.commandOmitted")}),(0,r.jsx)("div",{className:"flow-exit",children:c}),e.evidence&&(0,r.jsxs)("div",{className:"flow-exit",children:[n("flow.evidence")," ",(0,r.jsx)("code",{className:"flow-evidence",children:e.evidence})]})]})}function sO({steps:e,st:t,attempts:n=!1}){return(0,r.jsx)("ul",{className:"flow-checks",children:e.map(e=>{let i="check"===e.stage?e.labels.map(e=>t(`flow.label.${e}`)).join("\xb7")||t("flow.label.check"):"review"===e.stage?t("resolve"===e.action?"flow.label.resolve":"flow.label.review"):"ci"===e.stage||"deploy"===e.stage||"commit"===e.stage?t(`flow.label.${e.stage}`):t(`flow.stage.${e.stage}`),a=sP(e),s=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sz,{outcome:a}),(0,r.jsx)(sW,{step:e,st:t}),(0,r.jsxs)("span",{className:"flow-check-label",children:[n?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${i}`:i,a$(e)&&(0,r.jsx)("span",{className:"flow-compound",children:t("flow.compound.failed")})]})]});return"check"!==e.stage&&"ci"!==e.stage&&"deploy"!==e.stage?(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsx)("div",{className:"flow-check-head",children:s})},e.toolCallId):(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsxs)("details",{children:[(0,r.jsxs)("summary",{className:"flow-check-head",children:[s,(0,r.jsxs)("span",{className:"flow-disclose",children:[t("flow.details"),sA]})]}),(0,r.jsx)(sD,{step:e,label:i,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function sH({steps:e,st:t}){return 0===e.length?null:(0,r.jsxs)("details",{className:"flow-earlier",children:[(0,r.jsxs)("summary",{className:"flow-earlier-toggle",children:[t("flow.earlier",{count:e.length}),sA]}),(0,r.jsx)(sO,{steps:e,st:t,attempts:!0})]})}let sU=["failed","unverified","unobserved","stale","running","passed"];function s_({view:e,flow:t,live:n,st:i,compact:a=!1}){if(n&&t.current===e.stage)return i("flow.state.running");if("waiting"===e.status)return i("flow.state.waiting");if("skipped"===e.status||"notNeeded"===e.status)return i(`flow.state.${e.status}`);let s=e.steps[e.steps.length-1];if("investigate"===e.stage)return i("running"===e.status?"flow.state.running":"flow.state.done");if("edit"===e.stage&&"done"===e.status)return i(t.attempt>1?"flow.state.redone":"flow.state.done");if("check"===e.stage&&!a){let t=new Map;for(let n of aE(e.steps))t.set(sP(n),(t.get(sP(n))??0)+1);return sU.filter(e=>t.has(e)).map((e,n)=>(0,r.jsxs)("span",{children:[n>0&&" \xb7 ",(0,r.jsx)("span",{className:"flow-tone","data-tone":e,children:i(`flow.count.${e}`,{count:t.get(e)??0})})]},e))}return"check"===e.stage||"edit"===e.stage?(0,r.jsx)("span",{className:"flow-tone","data-tone":e.status,children:i(`flow.state.${e.status}`)}):(0,r.jsx)(sW,{step:s,st:i})}function sB({flow:e,live:t,st:n,id:i}){let a=e.loops[e.loops.length-1],s=a?e.steps.filter(e=>e.stage===a.from):[],o=n("flow.loop.badge",{attempt:e.attempt});return(0,r.jsxs)("div",{className:"flow-chain-panel",id:i,children:[(0,r.jsxs)("div",{className:"flow-chain-wrap","data-loop":a?"":void 0,style:a?{"--loop-from":iO.indexOf(a.from)}:void 0,children:[(0,r.jsx)("ol",{className:"flow-chain","aria-label":n("flow.aria"),children:e.stages.map(i=>{let a=sL(i,e,t);return(0,r.jsxs)("li",{className:"flow-link","data-state":a,"aria-current":"active"===a?"step":void 0,children:[(0,r.jsx)(sF,{look:a}),(0,r.jsx)("span",{className:"flow-link-name",children:n(`flow.stage.${i.stage}`)}),(0,r.jsx)("span",{className:"flow-link-state",children:(0,r.jsx)(s_,{view:i,flow:e,live:t,st:n,compact:!0})})]},i.stage)})}),a&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flow-loop","aria-hidden":"true",children:[(0,r.jsx)("svg",{width:"22",height:"15",viewBox:"0 0 22 15",children:(0,r.jsx)("polyline",{points:"3 12 11 3 19 12",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,r.jsx)("span",{className:"flow-loop-count",children:o})]}),(0,r.jsxs)("p",{className:"flow-loop-caption",children:[(0,r.jsx)("span",{className:"flow-loop-caption-count",children:o}),n("review"===a.from?"flow.loop.findings":"flow.loop.failed",{stage:n(`flow.stage.${a.from}`),attempt:a.attempt})]})]})]}),s.length>0&&(0,r.jsx)("div",{className:"flow-chain-attempts",children:(0,r.jsx)(sO,{steps:s,st:n,attempts:!0})})]})}function sq({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:a=!0,cwd:s}){let o=(0,i.useMemo)(()=>t.filter(e=>sb(e.status)),[t]),l=r&&!!e&&o.length>0,c=sS((0,i.useMemo)(()=>o.map(e=>({key:e.id,liveId:e.id,status:e.status})),[o]),{sessionId:e??"",client:n,enabled:l&&a}),[d,u]=(0,i.useState)(null),p=o.map(e=>e.id).sort().join("\n");return(0,i.useEffect)(()=>{let t;if(!l||!e)return;let n=new AbortController,r=p.split("\n"),i=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,a=!0,s=0;async function o(){try{let t=await fetch(i,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!n.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),a=r.some(e=>!s.histories[e]))}catch{}finally{if(!n.signal.aborted){let e=a&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{n.abort(),window.clearTimeout(t)}},[p,l,e]),(0,i.useMemo)(()=>{let t=new Map;if(!l)return t;let n=d&&d.sessionId===e?d.histories:void 0;for(let e of o){let r=(a?c.get(e.id)?.entries??[]:[]).flatMap(e=>"message"in e?[e.message]:[]);t.set(e.id,{phase:function(e,t){if(0===e.length)return null;let{blocks:n,results:r}=sp(e),i="investigate",a=!1;for(let e of n){let n=sf(e);sh(e,n,r,t)?(a=!0,i="implement"):su[n]?i=a?"verify":"investigate":"yield"===n&&(i="report",a=!1)}return i}(r,s),trace:sg(r,s),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=tk([...e],t);if(!n)return null;let r=tj(n);return 0===r.total||null===r.percent?null:{completed:r.completed,total:r.total,percent:r.percent,activeTask:r.activeTask?.content??null}}(r),history:n?.[e.id]??null})}return t},[o,s,d,l,c,e,a])}function sV(e,t){let n=sv(t);return n?0===n.hours?e("duration.minutes",{minutes:n.minutes}):0===n.minutes?e("duration.hours",{hours:n.hours}):e("duration.hoursMinutes",{hours:n.hours,minutes:n.minutes}):e("duration.underMinute")}function sK(e,t){let n=Math.floor(t/1e3);return n<60?e("duration.seconds",{seconds:n}):n<3600?e("duration.minutesSeconds",{minutes:Math.floor(n/60),seconds:n%60}):sV(e,t)}function sG({phase:e}){let{st:t}=rQ();return(0,r.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,r.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,r.jsx)("span",{"aria-hidden":"true",children:sc.map((n,i)=>(0,r.jsxs)("span",{children:[i>0&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,r.jsx)("span",{"data-current":n===e?"":void 0,style:n===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${n}`)})]},n))})]})}let sJ={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function sZ(e,t){let n=t.passed+t.failed+t.unknown,i=t.failed>0?"failed":t.unknown>0?"unverified":"passed";return(0,r.jsx)("span",{className:"flow-tone","data-tone":i,children:e("subflow.checks",{passed:t.passed,total:n})})}function sY({flow:e,live:t,verdict:n,attempts:i}){let{st:a}=rQ(),s=sE(),o=e.stations.findIndex(e=>"active"===e.state),l=sc.indexOf("implement"),c=i.filter(e=>"rework"===e.verdict).length,d=n?"accepted"===n.verdict?"done":"unverified":"waiting",u=n?`${a(`verdict.${n.verdict}`)}${null!==n.attempt&&n.attempt>1?` \xb7 ${a("verdict.attempt",{attempt:n.attempt})}`:""}`:a(t?"flow.state.waiting":"verdict.none");return(0,r.jsxs)("div",{className:"subagent-flow",children:[t&&o>=0&&(0,r.jsx)(s$,{paused:s}),(0,r.jsxs)("ol",{className:"flow-graph","aria-label":a("subflow.aria"),"data-live":t?"":void 0,"data-motion":s?"paused":void 0,children:[e.stations.map((t,n)=>{let i=sJ[t.state];return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":t.phase,"data-state":i,"data-loop":c>0&&n>=l?"":void 0,"aria-current":"active"===t.state?"step":void 0,style:{"--col":n+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a(`phase.${t.phase}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(sF,{look:i}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:function(e,t,n){let i="verify"===t.phase&&null!==n&&n.checks.passed+n.checks.failed+n.checks.unknown>0;switch(t.state){case"active":return i&&n?(0,r.jsxs)(r.Fragment,{children:[e("flow.state.running")," \xb7 ",sZ(e,n.checks)]}):e("flow.state.running");case"waiting":return e("flow.state.waiting");case"skipped":return e("flow.state.skipped");case"none":return e("detail.stageNone");case"unobserved":return e("subflow.unobserved");case"stale":return e(n&&n.checks.passed>0?"flow.state.stale":"flow.state.staleDone");case"done":if("report"===t.phase)return e("subflow.reported");if(i&&n)return sZ(e,n.checks);if("implement"===t.phase&&n&&n.reedits>0)return`${e("subflow.calls",{count:t.calls})} \xb7 ${e("subflow.reedits",{count:n.reedits})}`;return e("subflow.calls",{count:t.calls})}}(a,t,e.run)})]})]})},t.phase)}),(0,r.jsx)("li",{className:"flow-graph-station","data-stage":"verdict","data-state":d,style:{"--col":sc.length+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a("graph.join")}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(sF,{look:d}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:u})]})]})}),c>0&&(0,r.jsxs)("li",{className:"flow-graph-return",style:{"--from":l+1,"--to":sc.length+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsx)("span",{className:"flow-graph-return-text",children:a("subflow.rework",{count:c})})]})]})]})}function sX(e,t){let n=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${n} \xb7 ${t.activeTask}`:n}function sQ({snapshot:e,view:t,id:n}){var i,a,s;let o,l,c,{st:d}=rQ(),u=nd(5e3),p="number"!=typeof(o=e.progress?.durationMs)?null:o+(("pending"===e.status||"running"===e.status)&&e.lastUpdate>0?Math.max(0,u-e.lastUpdate):0);if(null===p)return null;let h=function(e,t){if(!e||e.rework||null===t||e.durationsSec.length<3)return null;let n=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(n.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:n.length};let r=sl(n,.5)??0;return{kind:"remaining",p25Ms:sl(n,.25)??0,medianMs:r,p75Ms:sl(n,.75)??0,samples:n.length,percent:Math.round(t/(t+r)*100)}}(t.history,p),f=(i=t.todo,!i||null===p||0===i.completed||i.completed>=i.total?null:p*(i.total-i.completed)/i.completed),m={color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},g=t.history,x=g?.rework&&null!==g.firstDispatchedAtMs?u-g.firstDispatchedAtMs:null;return(0,r.jsxs)("span",{id:n,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,r.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:d("eta.elapsed",{duration:sK(d,p)})}),g?.rework&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:m,title:d("eta.reworkHint"),children:null!==x&&x>=0?d("eta.rework",{attempt:g.attempt,duration:sK(d,x)}):d("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{title:d("eta.hint"),children:d("eta.remaining",{range:(a=h.p25Ms,s=h.p75Ms,l=sv(a),c=sv(s),l&&c&&0===l.hours&&0===c.hours?l.minutes===c.minutes?d("duration.minutes",{minutes:l.minutes}):d("eta.rangeMinutes",{low:l.minutes,high:c.minutes}):d("eta.range",{low:sV(d,a),high:sV(d,s)})),samples:h.samples})})," \xb7 ",(0,r.jsx)("span",{style:m,children:d("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:{color:"var(--warning)"},title:d("eta.hint"),children:0===h.longerRuns?d("eta.overrun",{longest:sV(d,h.longestMs)}):d("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==f&&t.todo&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:m,title:d("eta.byTodoHint"),children:f<6e4?d("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):d("eta.byTodo",{duration:sV(d,f),completed:t.todo.completed,total:t.todo.total})})]})]})}let s0={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},s1={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function s2({maker:e,st:t}){let n=e.verdict?.verdict??"none",i=e.verdict?.attempt;return(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(s0[e.run])}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":n,children:[t(s1[n]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function s8(e,t){let n=[],r=new Map;for(let t of e)"message"in t&&("assistant"===t.message.role?n.push(...t.message.content??[]):"toolResult"===t.message.role&&r.set(t.message.toolCallId,t.message));return st(n,r,t)}function s4(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function s5(e,t){let n=e?.state;return n?.kind!=="ready-live"?null:sg(n.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function s6({maker:e,st:t}){let n=e.runTitle??e.title;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:n,children:n}),e.priorVerdict&&!e.runTitle&&(0,r.jsx)("span",{className:"answer-dispatch-title-note",children:t("subflow.firstTitle")})]})}function s3({calls:e}){let{ledger:t,subagents:n,toolResults:a,onOpenPanel:s,sessionId:o,cwd:l,onOpenMaker:c,selectedMaker:d}=(0,i.useContext)(sC),{st:u}=rQ(),{t:p}=(0,F.s)(),[h,f]=(0,i.useState)(!1),m=(0,i.useId)(),g=(0,i.useMemo)(()=>ih(),[]),x=(0,i.useMemo)(()=>e.flatMap(e=>iS(e,a.get(e.toolCallId))??[]).map(e=>iT(e,n,t)),[e,a,n,t]),v=(0,i.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=iI(e.member,n,t);return r?[r]:[]}),[x,n,t]),y=sq({sessionId:o,snapshots:v,client:g,enabled:!0,transcripts:h,cwd:l}),b=(0,i.useMemo)(()=>new Map(x.flatMap(e=>{let t=iM(e.member,n);return t?[[e.member.key,t]]:[]})),[x,n]),w=(0,i.useMemo)(()=>h?[...b].filter(([,e])=>!sb(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:s4(t)})):[],[b,h]),k=sS(w,{sessionId:o??"",client:g,enabled:h&&!!o&&w.length>0}),j=d?.origin?x.find(e=>e.member.key===d.origin):void 0,S=j?.run,C=j?.verdict??null;if((0,i.useEffect)(()=>{if(!d||!c||!S)return;let e=d.status;e&&e.run===S&&e.verdict?.order===C?.order||c({...d,status:{run:S,verdict:C}},!1)},[c,d,S,C]),0===x.length)return null;let N=0,I=0,T=0;for(let e of x)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(N+=1),"completed"===e.run&&(I+=1),e.verdict?.verdict==="accepted"&&(T+=1);return(0,r.jsxs)("section",{className:"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":h,"aria-controls":m,title:u(h?"dispatch.collapse":"dispatch.expand"),onClick:()=>f(e=>!e),children:[(0,r.jsx)("span",{className:"answer-dispatch-heading",children:u("dispatch.title",{count:x.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:u("dispatch.tally",{running:N,done:I,accepted:T})}),(0,r.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,r.jsx)("ul",{className:"answer-dispatch-list",id:m,"aria-label":h?p("dispatchLane.label"):void 0,children:x.map(e=>{var n;let i,a="pending"===e.run||"running"===e.run,s=a?v.find(t=>t.id===e.member.agentId):void 0,o=s?y.get(s.id):void 0,p=b.get(e.member.key),f=e.member.key===d?.origin,m=a&&"live"===e.runSource,g=h?sx(m?o?.trace??null:s5(k.get(e.member.key),l),m):null,x=h?iR(e.member,t):[];return(0,r.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":f?"":void 0,children:[h?(0,r.jsx)(s7,{maker:e,phase:m&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,n){if(!t)return{kind:"unobserved"};if(sb(t.status))return{kind:"running"};let r=e?.state;if(!r||"loading"===r.kind)return{kind:"loading"};if("ready-live"===r.kind){let{checks:e}=s8(r.entries,n);return{kind:"counted",passed:e.filter(e=>"passed"===e.state).length,total:e.length}}return"empty"===r.kind&&"live"===r.source?{kind:"counted",passed:0,total:0}:{kind:"unobserved"}}(k.get(e.member.key),p,l),onOpen:p&&c?()=>c({key:`live:${p.id}`,toolCallId:e.member.toolCallId,origin:e.member.key,status:{run:e.run,verdict:e.verdict}}):null}):(0,r.jsxs)("div",{className:"answer-dispatch-line",children:[(0,r.jsx)(s6,{maker:e,st:u}),(0,r.jsx)(s2,{maker:e,st:u})]}),g&&(0,r.jsx)(sY,{flow:g,live:m,verdict:e.verdict,attempts:x}),h&&(0,r.jsx)(oe,{attempts:x}),s&&o&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[o.todo?`${sX(u,o.todo)} \xb7 `:null,(0,r.jsx)(sQ,{snapshot:s,view:o})]}),h&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[a&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??u("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.model")}),(0,r.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${u("detail.fallback")}`:""}`:u("detail.modelNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${u("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("subflow.prior")}),(0,r.jsx)("dd",{children:(i=null!==(n=e.priorVerdict).attempt&&n.attempt>1?` \xb7 ${u("verdict.attempt",{attempt:n.attempt})}`:"",`${u(s1[n.verdict])}${i}${n.reason?` \xb7 ${n.reason}`:""}`)})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u(e.runTitle?"subflow.firstTitle":"subflow.runTitle")}),(0,r.jsx)("dd",{children:e.runTitle?e.title:u("detail.stageNone")})]}),e.verdict?.reason&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),h&&s&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:u("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:u("detail.openProcess")})]})]})}function s7({maker:e,phase:t,checks:n,onOpen:i}){let{st:a}=rQ(),{t:s}=(0,F.s)(),o=e.verdict?.verdict??"none",l=a(s0[e.run]),c="running"===n.kind?null:"counted"===n.kind?s("dispatchLane.checks",{passed:n.passed,total:n.total}):s("loading"===n.kind?"dispatchLane.checksLoading":"dispatchLane.checksUnobserved");return(0,r.jsxs)("div",{className:"answer-dispatch-line is-lane",children:[(0,r.jsx)(s6,{maker:e,st:a}),(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?s("dispatchLane.runPhase",{run:l,phase:t}):l}),c&&(0,r.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===n.kind&&n.passed<n.total?"failed":n.kind,children:c}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsx)("span",{className:"answer-status-verdict","data-verdict":o,children:a(s1[o])})]}),i?(0,r.jsx)("button",{type:"button",className:"answer-link answer-dispatch-open","aria-label":s("dispatchLane.openLabel",{title:e.title}),onClick:i,children:s("dispatchLane.open")}):(0,r.jsx)("span",{className:"answer-dispatch-unavailable",title:s("makerDetail.unavailable"),children:s("dispatchLane.unavailable")})]})}function s9({maker:e}){let{ledger:t,subagents:n,sessionId:a,cwd:s}=(0,i.useContext)(sC),o=(0,i.useMemo)(()=>ih(),[]),l="pending"===e.run||"running"===e.run,c=l&&"live"===e.runSource,d=l?iI(e.member,n,t):void 0,u=sq({sessionId:a,snapshots:(0,i.useMemo)(()=>d?[d]:[],[d]),client:o,enabled:!0,transcripts:!0,cwd:s}),p=iM(e.member,n),h=(0,i.useMemo)(()=>p&&!sb(p.status)?[{key:e.member.key,liveId:p.id,status:p.status,archiveName:s4(p)}]:[],[p,e.member.key]),f=sS(h,{sessionId:a??"",client:o,enabled:!!a&&h.length>0}),m=d?u.get(d.id):void 0,g=sx(c?m?.trace??null:s5(f.get(e.member.key),s),c),x=iR(e.member,t);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sY,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,r.jsx)(oe,{attempts:x})]})}function oe({attempts:e}){let{t}=(0,F.s)();return e.length<2?null:(0,r.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":t("dispatchLane.label"),children:e.map((e,n)=>(0,r.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[n>0&&(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→ "}),null===e.attempt?t("dispatchLane.attemptUnknown"):t("dispatchLane.attempt",{attempt:e.attempt})," ",t(`dispatchLane.verdict.${e.verdict}`)]},`${e.attempt??"n"}-${n}`))})}let ot={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},on={html:0,document:1,image:2},or=/\.(?:md|mdx|markdown|txt)$/i;function oi(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function oa(e,t,n){return"investigate"!==e.stage&&("edit"===e.stage?n>0||e.earlier.length>0:e.steps.length>0||e.earlier.length>0||"ci"===e.stage&&null!==t.publication)}function os({entry:e,st:t}){let n="running"===e.maker.run||"pending"===e.maker.run||"dispatching"===e.maker.run;return e.bar&&null!==e.durationMs?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"flow-graph-track","aria-hidden":"true",children:(0,r.jsx)("span",{className:"flow-graph-bar",style:{left:oi(e.bar.offset),width:oi(e.bar.width)}})}),(0,r.jsx)("span",{className:"flow-graph-time",children:sK(t,e.durationMs)})]}):(0,r.jsx)("span",{className:"flow-graph-time-missing",children:t(n?"summary.time.running":"summary.time.unobserved")})}function oo({entry:e,together:t,batch:n=!1,st:i}){let a=e.maker.member.workClass;return(0,r.jsxs)("span",{className:"flow-graph-maker-tags",children:[(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":a?void 0:"",children:i(`graph.kind.${a??"unknown"}`)}),n&&e.batchSize>1&&(0,r.jsx)("span",{className:"flow-graph-chip",children:i("graph.parallel.batch")}),t&&(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":"unknown"===e.concurrency?"":void 0,"data-concurrency":e.concurrency,children:i(`graph.concurrency.${e.concurrency}`)})]})}function ol({selectable:e,selected:t,detailId:n,onSelect:i,className:a,children:s,style:o}){return e?(0,r.jsx)("button",{type:"button",className:a,style:o,"aria-pressed":t,"aria-controls":n,onClick:i,children:s}):(0,r.jsx)("div",{className:a,style:o,children:s})}function oc({summary:e,makers:t,timings:n,live:a=!1,onOpenFile:s}){let o,l,c,{subagents:d,onOpenMaker:u}=(0,i.useContext)(sC),{st:p}=rQ(),h=(0,i.useId)(),{flow:f}=e,m=(0,i.useMemo)(()=>(function(e,t,n,r){let i=function(e,t){let n=t.map(e=>null!==e.startedAt&&null!==e.durationMs?{start:e.startedAt,end:e.startedAt+e.durationMs}:null),r=e.startedAt,i=e.endedAt;for(let e of n)e&&((null===r||e.start<r)&&(r=e.start),(null===i||e.end>i)&&(i=e.end));let a=null!==r&&null!==i?i-r:0;return n.map(e=>e?a<=0||null===r?{offset:0,width:1}:{offset:(e.start-r)/a,width:(e.end-e.start)/a}:null)}(n,t),a=e.map(e=>"live"===e.runSource&&"running"===e.run),s=new Map;for(let t of e)s.set(t.member.toolCallId,(s.get(t.member.toolCallId)??0)+1);let o=e.map((n,r)=>{let o="unknown";for(let t=0;t<e.length;t+=1)if(t!==r&&(a[r]&&a[t]||n.observedParallelWith?.has(e[t].member.key))){o="overlapped";break}return{maker:n,bar:i[r],durationMs:t[r]?.durationMs??null,concurrency:o,batchSize:s.get(n.member.toolCallId)??1,liveRunning:a[r]}});return{makers:o,parallel:o.some(e=>"overlapped"===e.concurrency)?"observed":o.some(e=>e.batchSize>1)?"batch":"none",files:r.filter(e=>!or.test(e.filePath)),docs:r.filter(e=>or.test(e.filePath))}})(t,n,e.span,e.files),[t,n,e.span,e.files]),[g,x]=(0,i.useState)(void 0),v=sE(),y=e.files.length,b=a&&f.current?f.stages.find(e=>e.stage===f.current):void 0,w=void 0===g?b&&oa(b,f,y)?`stage:${b.stage}`:(o=f.stages.filter(e=>oa(e,f,y)),l=f.loops[f.loops.length-1],(c=(f.next?.returning&&l?o.find(e=>e.stage===l.from):void 0)??o.find(e=>"failed"===e.status)??o.find(e=>"unverified"===e.status||"stale"===e.status)??o.findLast(e=>"notNeeded"!==e.status&&"skipped"!==e.status)??o[o.length-1])?`stage:${c.stage}`:y>0?"files":null):g,k=f.loops[f.loops.length-1],j=k?iO.indexOf(k.from):-1,S=iO.indexOf("edit"),C=b?iO.indexOf(b.stage):-1,N=m.makers.some(e=>e.liveRunning),I=m.files.length>0||m.docs.length>0,T=(0,i.useMemo)(()=>a?[]:function(e,t,n,r){let i=iO.indexOf("edit"),a=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,s=[],o=n,l=e=>{let t=iO.indexOf(e.stage);o&&t>i&&(s.push("branch"),o=!1),s.push(e.stage),o&&t===i&&(s.push("branch"),o=!1)},c=t[t.length-1];if(c){let t=iO.indexOf(c.from);for(let n of e)iO.indexOf(n.stage)<=t&&(a(n)||n.earlier.length>0||n.stage===c.from)&&l(n);for(let t of(o&&(s.push("branch"),o=!1),s.push("return"),e))iO.indexOf(t.stage)>=i&&a(t)&&l(t)}else for(let t of e)a(t)&&l(t);return o&&s.push("branch"),r&&s.push("outputs"),s}(f.stages,f.loops,m.makers.length>0,I),[a,f.stages,f.loops,m.makers.length,I]),[M,R]=(0,i.useState)(null),E=null!==M&&M<T.length?M:null;(0,i.useEffect)(()=>{if(null===E)return;let e=window.setTimeout(()=>R(E+1<T.length?E+1:null),800);return()=>window.clearTimeout(e)},[E,T.length]);let $=e=>{if(null!==E&&T.includes(e))return T[E]===e?"now":T.slice(0,E).includes(e)?"past":"ahead"},L=new Map;for(let e of m.makers){let t=e.maker.verdict?.verdict??"none";L.set(t,(L.get(t)??0)+1)}let P=1===L.size&&L.has("accepted"),A=f.stages[S+1],F=A?sL(A,f,a):"skipped",z=m.makers.length>0&&(0,r.jsxs)("li",{className:"flow-graph-branch","data-loop":k&&j>S?"":void 0,"data-merge":"skipped"===F||"waiting"===F||"approval"===F?"quiet":void 0,"data-beat":$("branch"),children:[(0,r.jsxs)("p",{className:"flow-graph-branch-head",children:[(0,r.jsx)("span",{children:p(1===m.makers.length?"graph.branch.one":"graph.branch",{count:m.makers.length})}),"none"!==m.parallel&&(0,r.jsx)("span",{className:"flow-graph-chip","data-parallel":m.parallel,children:p(`graph.parallel.${m.parallel}`)})]}),(0,r.jsx)("ul",{className:"flow-graph-lanes",children:m.makers.map(e=>{let t=`maker:${e.maker.member.key}`;return(0,r.jsx)("li",{className:"flow-graph-lane","data-run":e.maker.run,"data-live":e.liveRunning?"":void 0,children:(0,r.jsxs)(ol,{selectable:!0,selected:w===t,detailId:h,onSelect:()=>x(w===t?null:t),className:"flow-graph-maker",children:[(0,r.jsx)("span",{className:"flow-graph-maker-name",title:e.maker.title,children:e.maker.title}),(0,r.jsx)(oo,{entry:e,together:m.makers.length>1,st:p}),(0,r.jsx)("span",{className:"flow-graph-maker-time",children:(0,r.jsx)(os,{entry:e,st:p})}),(0,r.jsx)(s2,{maker:e.maker,st:p})]})},e.maker.member.key)})}),(0,r.jsxs)("p",{className:"flow-graph-join","data-state":P?"done":"unverified",children:[(0,r.jsx)(sF,{look:P?"done":"unverified"}),(0,r.jsx)("span",{className:"flow-graph-join-label",children:p("graph.join")}),(0,r.jsx)("span",{className:"flow-graph-join-counts",children:["accepted","rework","held","none"].filter(e=>L.has(e)).map(e=>(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":e,children:[p(s1[e])," ",L.get(e)]},e))})]})]},"branch"),W=k&&(0,r.jsxs)("li",{className:"flow-graph-return","data-beat":$("return"),style:{"--from":S+1,"--to":j+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsxs)("span",{className:"flow-graph-return-text",children:[(0,r.jsx)("b",{children:p("flow.loop.badge",{attempt:f.attempt})})," ",p("review"===k.from?"flow.loop.findings":"flow.loop.failed",{stage:p(`flow.stage.${k.from}`),attempt:k.attempt})]})]},"return"),D=f.stages.map((e,t)=>{let n=sL(e,f,a),i=`stage:${e.stage}`,s=e.steps.some(a$);return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":e.stage,"data-state":n,"data-again":e.earlier.length>0?"":void 0,"data-loop":k&&t>=S&&t<j?"":void 0,"data-beat":$(e.stage),"aria-current":"active"===n?"step":void 0,style:{"--col":t+1},children:(0,r.jsxs)(ol,{selectable:oa(e,f,y),selected:w===i,detailId:h,onSelect:()=>x(i),className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:p(`flow.stage.${e.stage}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(sF,{look:n}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:(0,r.jsx)(s_,{view:e,flow:f,live:a,st:p})})]}),s&&(0,r.jsx)("span",{className:"flow-compound",children:p("flow.compound.failed")})]})},e.stage)}),O=[];D.forEach((e,t)=>{O.push(e),t===S&&z&&O.push(z),t===j&&W&&O.push(W)});let H=null;if(w?.startsWith("stage:")){let t=f.stages.find(e=>`stage:${e.stage}`===w);if(t){let n="ci"===t.stage&&null!==f.publication&&"notNeeded"===t.status,i="edit"===t.stage||n?[]:t.steps;H=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:p(`flow.stage.${t.stage}`)}),"ci"===t.stage&&f.publication&&(0,r.jsx)("p",{className:"flow-graph-note",children:"nothingToPublish"===f.publication.kind?p("flow.ci.nothingToPublish",{sha:f.publication.commit.slice(0,7)}):p("flow.ci.notNeeded",{run:f.publication.runId,repo:f.publication.repo,ref:f.publication.ref,sha:f.publication.sha.slice(0,7)})}),"edit"===t.stage&&(0,r.jsx)(it,{files:e.files,onOpenFile:s}),i.length>0&&(0,r.jsx)(sO,{steps:i,st:p}),(0,r.jsx)(sH,{steps:t.earlier,st:p})]})}}else if(w?.startsWith("maker:")){let e=m.makers.find(e=>`maker:${e.maker.member.key}`===w);if(e){let t=iM(e.maker.member,d);H=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,r.jsx)(oo,{entry:e,together:m.makers.length>1,batch:!0,st:p}),(0,r.jsx)("p",{className:"flow-graph-detail-line",children:(0,r.jsx)(s2,{maker:e.maker,st:p})}),(0,r.jsx)("div",{className:"flow-graph-maker-time",children:(0,r.jsx)(os,{entry:e,st:p})}),(0,r.jsx)(s9,{maker:e.maker}),t&&u?(0,r.jsx)("button",{type:"button",className:"flow-graph-open",onClick:()=>u({key:`live:${t.id}`,toolCallId:e.maker.member.toolCallId,origin:e.maker.member.key,status:{run:e.maker.run,verdict:e.maker.verdict}}),children:p("graph.maker.open")}):(0,r.jsx)("p",{className:"flow-graph-note",children:p("graph.maker.unavailable")})]})}}else("files"===w||"docs"===w)&&(H=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:"files"===w?p(1===m.files.length?"graph.files.one":"graph.files",{count:m.files.length}):p(1===m.docs.length?"graph.docs.one":"graph.docs",{count:m.docs.length})}),(0,r.jsx)(it,{files:"files"===w?m.files:m.docs,onOpenFile:s})]}));return(0,r.jsxs)("section",{className:"flow-section",children:[(0,r.jsxs)("div",{className:"flow-graph-head",children:[(0,r.jsx)("h4",{className:"flow-heading",children:p("flow.heading")}),(C>=0||N)&&(0,r.jsx)(s$,{paused:v}),T.length>1&&(0,r.jsx)("button",{type:"button",className:"flow-graph-replay",onClick:()=>R(null===E?0:null),children:p(null===E?"graph.replay":"graph.replay.stop")})]}),(0,r.jsx)("div",{className:"flow-graph-frame",children:(0,r.jsxs)("ol",{className:"flow-graph","aria-label":p("flow.aria"),"data-live":a?"":void 0,"data-motion":v?"paused":void 0,"data-replay":null===E?void 0:"",children:[O,I&&(0,r.jsxs)("li",{className:"flow-graph-outputs","data-beat":$("outputs"),children:[(0,r.jsx)("span",{className:"flow-graph-outputs-label",children:p("graph.outputs")}),m.files.length>0&&(0,r.jsx)(ol,{selectable:!0,selected:"files"===w,detailId:h,onSelect:()=>x("files"),className:"flow-graph-output",children:p(1===m.files.length?"graph.files.one":"graph.files",{count:m.files.length})}),m.docs.length>0&&(0,r.jsx)(ol,{selectable:!0,selected:"docs"===w,detailId:h,onSelect:()=>x("docs"),className:"flow-graph-output",children:p(1===m.docs.length?"graph.docs.one":"graph.docs",{count:m.docs.length})})]})]})}),H&&(0,r.jsx)("div",{className:"flow-graph-detail",id:h,role:"region","aria-label":p("graph.detail.aria"),children:H})]})}function od(e,t,n){let r=new URLSearchParams({type:t});return n&&r.set("sessionId",n),`/api/files/${tC(e)}?${r}`}function ou(e,t){let[n,r]=(0,i.useState)({kind:"loading"});return(0,i.useEffect)(()=>{let n=new AbortController;return r({kind:"loading"}),fetch(e,{method:"head"===t?"HEAD":"GET",cache:"no-store",signal:n.signal}).then(async e=>{if(!e.ok)return null;if("head"===t)return"";if("text"===t)return e.text();let n=await e.json();return"string"==typeof n.content?n.content:null}).then(e=>{n.signal.aborted||r(null===e?{kind:"failed"}:{kind:"ready",content:e})}).catch(()=>{n.signal.aborted||r({kind:"failed"})}),()=>n.abort()},[e,t]),n}function op({messageKey:e}){let{st:t}=rQ();return(0,r.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function oh({deliverable:e,sessionId:t,title:n}){let{filePath:i,kind:a}=e;if("image"===a){let e=od(i,"read",t);return(0,r.jsx)(ox,{src:e,title:n},e)}if("html"===a){let e=od(i,"read",t);return(0,r.jsx)(of,{url:e,title:n},e)}if(i.toLowerCase().endsWith(".pdf")){let e=od(i,"read",t);return(0,r.jsx)(om,{url:e,title:n},e)}let s=od(i,"preview",t);return(0,r.jsx)(og,{url:s,title:n},s)}function of({url:e,title:t}){let n=ou(e,"json");return"ready"!==n.kind?(0,r.jsx)(op,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-scripts",title:t,scrolling:"no",inert:!0})}function om({url:e,title:t}){let n=ou(e,"head");return"ready"!==n.kind?(0,r.jsx)(op,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",src:`${e}#toolbar=0&view=FitH`,title:t,inert:!0})}function og({url:e,title:t}){let n=ou(e,"text");return"ready"!==n.kind?(0,r.jsx)(op,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-same-origin",title:t,inert:!0})}function ox({src:e,title:t}){let[n,a]=(0,i.useState)("loading");return"failed"===n?(0,r.jsx)(op,{messageKey:"result.previewFailed"}):(0,r.jsxs)(r.Fragment,{children:["loading"===n?(0,r.jsx)(op,{messageKey:"result.previewLoading"}):null,(0,r.jsx)("img",{className:"answer-result-media","data-fit":"contain",src:e,alt:t,draggable:!1,hidden:"loading"===n,onLoad:()=>a("ready"),onError:()=>a("failed")})]})}function ov({deliverables:e,onOpenFile:t}){let{sessionId:n}=(0,i.useContext)(sC),{st:a}=rQ(),[o,l]=function(){let e=(0,i.useRef)(null),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{let r=e.current;if(!r||t)return;if("u"<typeof IntersectionObserver)return void n(!0);let i=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n(!0)},{rootMargin:"200px 0px"});return i.observe(r),()=>i.disconnect()},[t]),[e,t]}(),[c,...d]=e;if(!c)return null;let u=tN(c.filePath),p=a("result.previewTitle",{name:u}),h=t?()=>t(c.filePath):void 0;return(0,r.jsxs)("section",{className:"answer-result","aria-label":a("result.label"),children:[(0,r.jsxs)("div",{ref:o,className:"answer-result-frame","data-kind":c.kind,children:[l&&(0,r.jsx)(oh,{deliverable:c,sessionId:n,title:p}),h&&(0,r.jsx)("button",{type:"button",className:"answer-result-cover",tabIndex:-1,"aria-hidden":"true",onClick:h})]}),(0,r.jsxs)("div",{className:"answer-result-bar",children:[(0,r.jsxs)("span",{className:"answer-result-title",children:[(0,r.jsx)("span",{className:"answer-result-kind",children:a("html"===c.kind?"result.kind.html":"image"===c.kind?"result.kind.image":c.filePath.toLowerCase().endsWith(".pdf")?"result.kind.pdf":"result.kind.document")}),(0,r.jsx)("span",{className:"answer-result-name",title:c.filePath,children:u})]}),h&&(0,r.jsx)(s.r,{className:"answer-result-open",variant:"neutralSolid",size:"medium",onClick:h,"aria-label":a("result.openNamed",{name:u}),children:a("result.open")})]}),d.length>0&&(0,r.jsxs)("div",{className:"answer-result-more",children:[(0,r.jsx)("span",{className:"answer-result-more-label",children:a("result.more",{count:d.length})}),(0,r.jsx)(it,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}function oy({summary:e,live:t=!1,onOpenFile:n}){let{ledger:a,subagents:s,toolResults:o}=(0,i.useContext)(sC),{st:l}=rQ(),c=(0,i.useMemo)(()=>t?[]:function(e){let t=[];for(let n of e){if(function(e){let t=e.toLowerCase().replace(/\\/g,"/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e];if(Object.hasOwn(ot,n)||n.startsWith(".next")||"doc"===n&&"history"===t[e+1])return!0}return!1}(n.filePath))continue;let e=function(e){let t=eW(e);return"html"===t||"htm"===t?"html":eO(e)?"document":eD(e)?"image":null}(n.filePath);e&&t.push({filePath:n.filePath,kind:e})}return t.map((e,t)=>({deliverable:e,index:t})).sort((e,t)=>on[e.deliverable.kind]-on[t.deliverable.kind]||e.index-t.index).map(({deliverable:e})=>e)}(e.files),[t,e.files]),[d,u]=(0,i.useState)(null),p=d??(e.latest&&0===c.length),h=(0,i.useId)(),f=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>iS(e,o.get(e.toolCallId))??[]).map(e=>iT(e,s,a)),[e.dispatchCalls,o,s,a]),m=(0,i.useMemo)(()=>f.map(e=>({startedAt:a.spawnedAt.get(e.member.key)??null,durationMs:a.durations.get(e.member.key)??null})),[f,a]),{flow:g,remaining:x}=e,v=e.checks.filter(e=>"failed"===e.state).length,y=e.checks.filter(e=>"failed"===e.state||"unobserved"===e.state).length,b=e.checks.filter(e=>e.compound?.failed).length,w=e.checks.filter(e=>"unverified"===e.state&&!e.compound?.failed).length,k=aE(g.steps).filter(e=>e.stale).length,j=y+f.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted").length;if(0===g.steps.length&&(t||0===e.files.length&&0===e.checks.length&&0===f.length&&!x?.length))return null;let S=[l(1===e.files.length?"summary.files.one":"summary.files",{count:e.files.length}),l(1===e.checks.length?"summary.checks.one":"summary.checks",{count:e.checks.length})];t&&S.unshift(l("summary.live")),v>0&&S.push(l("summary.checksFailed",{count:v})),b>0&&S.push(l("summary.compoundFailed",{count:b})),f.length>0&&S.push(l(1===f.length?"summary.makers.one":"summary.makers",{count:f.length})),x&&S.push(l("summary.remaining",{count:x.length})),!t&&j>0&&S.push(l("summary.unverified",{count:j})),w>0&&S.push(l(1===w?"summary.verdictUnverified.one":"summary.verdictUnverified",{count:w})),k>0&&S.push(l("summary.stale",{count:k}));let C=!t&&j>0||v>0||w>0||b>0||k>0;return(0,r.jsxs)("div",{className:"answer-summary","data-open":p?"":void 0,"data-live":t?"":void 0,"data-result":c.length>0?"":void 0,children:[c.length>0&&(0,r.jsx)(ov,{deliverables:c,onOpenFile:n}),(0,r.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":p,"aria-controls":h,title:l(p?"summary.collapse":"summary.expand"),onClick:()=>u(!p),children:[(0,r.jsx)("span",{className:"answer-summary-text","data-unverified":C?"":void 0,children:S.join(" \xb7 ")}),(0,r.jsx)("svg",{className:"answer-chevron",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)("polyline",{points:"6 9 12 15 18 9"})})]}),p&&(0,r.jsxs)("div",{className:"answer-summary-body",id:h,children:[g.steps.length>0&&(0,r.jsx)(oc,{summary:e,makers:f,timings:m,live:t,onOpenFile:n}),x&&(0,r.jsxs)("section",{className:"flow-remaining",children:[(0,r.jsx)("h4",{className:"flow-heading",children:l("summary.heading.remaining")}),0===x.length?(0,r.jsx)("p",{className:"answer-summary-empty",children:l("summary.todo.none")}):(0,r.jsx)("ul",{className:"flow-remaining-list",children:x.map((e,t)=>(0,r.jsxs)("li",{className:"answer-remaining","data-status":e.status,title:e.phase||void 0,children:[(0,r.jsx)("span",{className:"answer-remaining-status",children:l(`summary.todo.${e.status}`)}),(0,r.jsx)("span",{className:"answer-remaining-text",children:e.content}),e.blocker&&(0,r.jsx)("span",{className:"answer-remaining-blocker",children:l("summary.todo.blocker",{blocker:e.blocker})})]},`${e.phase}#${t}`))})]})]})]})}let ob=/^att_[0-9a-f]{32}$/,ow=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ok(e){return"string"==typeof e&&ob.test(e)}function oj(e){return"string"==typeof e&&ow.test(e)}class oS extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let oC={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},oN={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},oI={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function oT(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&&oN[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&oI[r]?"text":null}let oM={".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 oR(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?oM[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 oE(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function o$(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,...ok(i.attachmentId)?{attachmentId:i.attachmentId}:{}}),n+=i.size,r+=i.text.length))}}return t}async function oL(e){let t,n=oT(e);if(!n)throw new oS("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new oS("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await o_(e);else{try{t=await e.text()}catch(e){throw new oS("read_failed",e instanceof Error?e.message:String(e))}oB(t)}return{name:e.name,mimeType:oC[n],size:e.size,text:t}}function oP(e,t){let n=o$(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=`${oq}${JSON.stringify(r)}${oV}
@@ -16,7 +16,7 @@ Attached: ${n}`:`Attached: ${n}`}(g)).then(()=>{m(!0),setTimeout(()=>m(!1),1500)
16
16
  ${t}`)),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{if(void 0!==a)return;let n=!0;return(function(e,t){let n=`${e}
17
17
  ${t}`,r=eJ.get(n);if(void 0!==r)return Promise.resolve(r);let i=eZ.get(n);if(i)return i;let a=fetch(eV(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 eJ.set(n,r),r}).catch(()=>0).finally(()=>eZ.delete(n));return eZ.set(n,a),a})(e,t).then(e=>{n&&s(e)}),()=>{n=!1}},[a,e,t]),!a)return null;let u=Array.from({length:a},(e,t)=>t).filter(e=>!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:eV(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(i))})},i)),null!==o&&(0,r.jsx)(lr,{src:eV(e,t,o),fileName:`screen-${t.slice(-8)}-${o+1}`,onClose:()=>l(null)})]})}let ln={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function lr({src:e,fileName:t,onClose:n}){let{t:a}=(0,F.s)(),o=(0,i.useContext)(np),l=(0,i.useRef)(null),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),x=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=l.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{x.current?.abort(),document.body.style.overflow=t,e.open&&e.close()}},[]);let v=()=>{x.current?.abort(),n()},y=async()=>{let r,i;if(!o)return void p(a("toolImage.noComposer"));x.current?.abort();let s=new AbortController;x.current=s,d(!0),p(null);try{let n=await fetch(e,{signal:s.signal});if(!n.ok)throw Error(`HTTP ${n.status}`);let o=await n.blob(),l=ln[o.type];if(!l)throw Error(`unsupported ${o.type}`);if(0!==h.length&&m){let e=await nb(o,h);r=[new File([e.marked],`${t}-marked.png`,{type:"image/png"}),...e.crops.map((e,n)=>new File([e],`${t}-region-${n+1}.png`,{type:"image/png"}))];let n=1===h.length?"1":`1~${h.length}`;i=[a("toolImage.locatorIntro",{range:n}),...h.map((e,t)=>a("toolImage.locatorRegion",{n:t+1,x:e.x,y:e.y,w:e.w,h:e.h,width:m.width,height:m.height}))].join("\n")+"\n"}else r=[new File([o],`${t}.${l}`,{type:o.type})]}catch{if(s.signal.aborted)return;d(!1),p(a("toolImage.loadFailed"));return}if(!s.signal.aborted&&l.current?.open){if(!o(r,i)){d(!1),p(a("toolImage.noComposer"));return}n()}};return(0,_.createPortal)((0,r.jsxs)("dialog",{ref:l,className:"tool-image-dialog","aria-label":a("toolImage.dialogLabel"),onCancel:e=>{e.preventDefault(),v()},onClick:e=>{e.target===e.currentTarget&&v()},children:[(0,r.jsx)(nw,{src:e,regions:h,max:9,onAdd:e=>f(t=>t.length<9?[...t,e]:t),onNaturalSize:g,regionLabel:e=>a("toolImage.regionLabel",{n:e})}),u?(0,r.jsx)("p",{role:"alert",className:"tool-image-error",children:u}):(0,r.jsx)("p",{className:"tool-image-hint","data-hidden":h.length>0&&h.length<9?"true":void 0,children:h.length>=9?a("toolImage.markLimit",{count:9}):a("toolImage.markHint")}),(0,r.jsxs)("div",{className:"tool-image-actions",children:[(0,r.jsx)(s.r,{variant:"neutralSolid",size:"medium",loading:c,onClick:()=>void y(),title:a("toolImage.requestEditHint"),children:a("toolImage.requestEdit")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",disabled:0===h.length,onClick:()=>f([]),children:a("toolImage.clearMarks")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",onClick:v,children:a("i18n.close")})]})]}),document.body)}function li({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(o0,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function la({block:e,duration:t,sessionId:n,entryId:a,blockIndex:s}){let{t:o}=(0,F.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&&a?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=oQ.get(r);if(i)return oQ.delete(r),oQ.set(r,i),i;let a=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw oQ.delete(r),e});if(oQ.set(r,a),oQ.size>100){let e=oQ.keys().next().value;e&&oQ.delete(e)}return a})(n,a,s).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,s,a,n,o]);let f=e.deferred?l:e.thinking,m="string"==typeof f&&f.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}):m?(0,r.jsx)(nc,{className:"markdown-thinking-body",children:f}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&m&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function ls({block:e,result:t,duration:n,runStartedAt:a}){let s,{t:o}=(0,F.s)(),l=(0,i.useId)(),[c]=(0,i.useState)(()=>Date.now()),[d,u]=(0,i.useState)(null),p=e.toolName.toLowerCase(),h=JSON.stringify(e.input,null,2),f="todo"===p||p.endsWith(".todo")||p.endsWith("_todo"),m="bash"===p||p.startsWith("bash ")||p.endsWith(".bash")||p.endsWith("_bash"),g=t&&!t.isError?function(e){var t;let n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let i="string"==typeof n.diff?n.diff:null;return i?{text:i}:null}(t):null,x=f?"unknown"===(s=tb(e,t)).kind||0===s.phases.length?null:s.phases:null,v=g?g.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,y=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,b=null!==y&&("(no output)"===y.trim()||""===y.trim()),w=t?nS(t):null,k=t?t.isError||null!==w&&0!==w?"failed":"done":"running",j="failed"===k,S=d??j;if(f&&x)return(0,r.jsx)(lp,{phases:x});let C=m&&"string"==typeof e.input.command?e.input.command:"",N=!!(x||g),I=m?C.split(/\r?\n/,1)[0]??"":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(-120);if("file_path"in n)return String(n.file_path).slice(-120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let a=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==a)return String(a).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,x),T=!m&&/^\S+$/.test(I)&&/[\\/]/.test(I),M=v?o("toolRun.diffStats",{added:v.added,removed:v.removed}):"";return(0,r.jsxs)("div",{className:`tool-call-card ${j?"is-error":"running"===k?"is-running":"is-done"}${m?" is-shell":""}`,"aria-busy":"running"===k||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,r.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>u(!S),"aria-expanded":S,"aria-controls":S?l:void 0,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,r.jsx)(ld,{toolName:e.toolName}),(0,r.jsx)("span",{className:"tool-call-name",children:m?"bash":e.toolName}),m&&p.includes("(local)")&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"}),(0,r.jsx)("span",{className:`tool-call-target${T?" is-path":""}`,title:m?C:I,children:T?(0,r.jsx)("bdi",{dir:"ltr",children:I}):I}),v&&(0,r.jsxs)("span",{className:"tool-call-diffstats",title:M,"aria-label":M,children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",v.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",v.removed]})]}),(0,r.jsx)(lo,{state:k,duration:n,exitCode:w,startedAt:a??c}),(0,r.jsx)("svg",{className:"tool-call-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:S?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),S&&(0,r.jsx)("div",{id:l,className:"tool-call-body",children:m?(0,r.jsx)(lh,{command:C,output:y??"",pending:!t,isError:j}):(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(lf,{diff:g})}),t&&j&&(0,r.jsx)(ly,{text:y??"",isEmpty:b,isError:!0}),!N&&(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",maxHeight:400,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:h}),t&&!N&&!j&&(0,r.jsx)(ly,{text:y??"",isEmpty:b,isError:!1})]})})]})}function lo({state:e,duration:t,exitCode:n,startedAt:i}){let{t:a}=(0,F.s)();return"running"===e?(0,r.jsx)(ll,{startedAt:i}):(0,r.jsxs)(r.Fragment,{children:[void 0!==t&&(0,r.jsxs)("span",{className:"tool-run-duration",children:[t,"s"]}),"failed"===e&&(0,r.jsxs)("span",{className:"tool-run-failed",children:[(0,r.jsx)(nu.E,{tone:"critical",variant:"weak",size:"medium",children:a("toolRun.failed")}),null!==n&&(0,r.jsx)("span",{className:"tool-run-exit",children:a("toolRun.exitCode",{code:n})})]})]})}function ll({startedAt:e}){let{t}=(0,F.s)(),n=nd(500)-e;return n<400?null:(0,r.jsxs)("span",{className:"tool-run-running",children:[t("toolRun.running"),(0,r.jsxs)("span",{className:"tool-run-duration",children:[Math.floor(n/1e3),"s"]})]})}function lc(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function ld({toolName:e}){let t,n=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||lc(t,"edit")?"edit":lc(t,"read")||lc(t,"cat")?"read":lc(t,"write")||lc(t,"save")?"write":lc(t,"glob")||lc(t,"find")?"glob":lc(t,"grep")||lc(t,"search")?"grep":lc(t,"bash")||lc(t,"shell")||lc(t,"exec")?"bash":lc(t,"todo")?"todo":lc(t,"eval")?"eval":lc(t,"task")||lc(t,"agent")?"task":lc(t,"browser")||lc(t,"web_search")||lc(t,"fetch")?"browser":lc(t,"image")||lc(t,"inspect_image")?"image":"generic";return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:"var(--text-muted)"},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)(lu,{kind:n})})})}function lu({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 lp({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)(r4,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function lh({command:e,output:t,pending:n,isError:i}){let{isDark:a}=nr(),{t:s}=(0,F.s)(),o=e$(t.split(/\r?\n/)),l=1===o.length&&""===o[0]?[]:o;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)(tT.A,{className:"shell-command-code",language:"bash",style:a?tM.xJ:tM.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||" "})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsx)("div",{className:"shell-output-divider",children:(0,r.jsx)("span",{className:"shell-output-label",children:"Output"})}),(0,r.jsxs)("div",{className:"shell-output-body",children:[0===l.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:s("i18n.noOutput")}),l.map((e,t)=>{let n=eT(e).trimStart(),a=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${a}`.trim(),children:[eL(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)})]})]})]})}function lf({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(lm,{text:e.text})})}function lm({text:e}){let{t}=(0,F.s)(),n=(0,i.useMemo)(()=>r2(e),[e]);if(!n)return(0,r.jsx)(lv,{text:e});let a=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[a&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(lg,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(lg,{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)(lx,{cell:e.left,side:"left"}),(0,r.jsx)(lx,{cell:e.right,side:"right"})]},t))})]},n))})}function lg({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 lx({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:a,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function lv({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 ly({text:e,isEmpty:t,isError:n}){let{t:i}=(0,F.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 lb({message:e}){let{t}=(0,F.s)(),n=lS(e.content),a=(0,i.useMemo)(()=>{let e,t,r,i,a;return e=[],t=[],r=n.match(nN),i=r?.[1]??"",a=r?.index===void 0?n:n.slice(0,r.index),i.replace(nC,(n,r,i)=>{let a=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...a):t.push(...a),""}),{body:a.trim(),readFiles:e,modifiedFiles:t}},[n]),s=o4(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:nI(o)})}),s&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),a.body?(0,r.jsx)(nc,{className:"markdown-compaction-message",children:a.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(lw,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function lw({readFiles:e,modifiedFiles:t}){let{t:n}=(0,F.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)(lk,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(lk,{title:n("i18n.readFiles"),files:e})]})}function lk({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 lj({message:e,cwd:t,onOpenFile:n}){var a;let s,{t:o}=(0,F.s)(),l=!1===e.display,[c,d]=(0,i.useState)(!l),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1),m=lS(e.content),g="string"==typeof(a=e.content)?[]:a.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",y=e.customType||"extension",b=o4(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:y}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),b&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:b})]}),c?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!m},children:g.map((e,t)=>{let n=lC(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})}),m?(0,r.jsx)(nc,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:m}):(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:m?(s=m.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"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:[m||v?(0,r.jsx)("button",{onClick:()=>{ni(m||v).then(()=>{f(!0),setTimeout(()=>f(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children: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 lS(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function lC(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 lN({message:e,sessionId:t}){let[n,a]=(0,i.useState)(null),[s,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,f=n??e.output;async function m(){if(p){o(!0),c(null);try{let e=await fetch(p),t=await e.json();t.success?a(t.data?.output??""):c(t.error??"failed")}catch(e){c(String(e))}finally{o(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=d?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:f?[{type:"text",text:f}]:[],isError:u,details:void 0!==e.exitCode?{exitCode:e.exitCode}:void 0,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(ls,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:m,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,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,")"]})]})]})}n(21340);let lI="cuelo-chat-search",lT="cuelo-chat-search-active";function lM(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 lR({open:e,onClose:t,containerRef:n,index:a,renderedStart:s,renderedEnd:o,contentKey:l,onReveal:c,onProgrammaticScroll:d,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[f,m]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,y]=(0,i.useState)({index:-1,total:0}),b=(0,i.useDeferredValue)(f),w=e?b.trim().toLowerCase():"",k=(0,i.useRef)(g);k.current=g;let j=(0,i.useRef)([]),S=(0,i.useRef)({key:null,needle:"",rendered:!1});(0,i.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,i.useEffect)(()=>()=>{lM(lI,[]),lM(lT,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){lM(lI,[]),lM(lT,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},y(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),i=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let a=(e.textContent??"").toLowerCase(),s=n.get(i);s||(s=[],n.set(i,s));for(let n=a.indexOf(t);-1!==n;n=a.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),s.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,i){let a=[];if(!t)return a;for(let s=0;s<e.length;s++){let o=s>=r&&s<i?n.get(s)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[s],t);for(let e=0;e<o;e++)a.push({item:s,k:e})}return a}(a,w,n,s,o);j.current=r;let i=te(r,k.current);y(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(lM(lI,l),i<0){lM(lT,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=s&&u.item<o,f=S.current,m=f.needle!==w||f.key?.item!==u.item||f.key?.k!==u.k||!f.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){lM(lT,[]),m&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(lM(lT,g?[g]:[]),m)if(d(),g){let e,n;e=g.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,a,s,o,l,g,n,c,d]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=te(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=f.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,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:f,onChange:e=>m(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,r.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,r.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}function lE({questions:e,containerRef:t,layoutKey:n,onJump:a,label:s}){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,a=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,a=0,s=i.length-1,o=i.length-1;for(;a<=s;){let e=a+s>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(o=e,s=e-1):a=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)},s=()=>{r||(r=requestAnimationFrame(a))};return r=requestAnimationFrame(a),n.addEventListener("scroll",s,{passive:!0}),()=>{n.removeEventListener("scroll",s),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,i.useEffect)(()=>{let e=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,f=(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 m=e.some(e=>e.item===l)?l:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,r.jsx)("div",{ref:o,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(l$,{question:e,position:t,count:h,active:e.item===l,focusable:e.item===m,onJump:a,onMoveFocus:f},e.item))})})}let l$=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:a,onJump:s,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:a?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${l}`,title:l,onClick:()=>s(e.item),onKeyDown:e=>o(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function lL({label:e,tone:t,children:n}){return(0,r.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"run-status-label",children:e}),(0,r.jsx)("span",{className:"run-status-text",children:n})]})}let lP={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function lA({compaction:e,t}){let[n,a]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;a(Date.now());let t=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((n-e.startedAt)/1e3)),o=e.reason&&!0===lP[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(lL,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),o?` \xb7 ${o}`:""]})}function lF({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 lz=n(39092),lW=n.n(lz);let lD=["01","02","03"];function lO(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}function lH(e,t,n){if(e&&"streaming"!==t){let r=ru(e);if(r){let e="failed"===t?"failed":"done",i=nY(nJ(rd(r),r.id,e)?.stickers??[],null,()=>lO(n));return i?{src:i,alt:nO[e]}:null}}if(!e||"streaming"===t||!nz.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),a=nY(lD.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>lO(n));return a?{src:a,alt:nO[r]}:null}let lU=new Map,l_=(0,i.createContext)(lU);function lB({utterances:e,children:t}){return(0,r.jsx)(l_.Provider,{value:e,children:t})}function lq({turnIndex:e,turnEntryId:t,sessionId:n,cwd:a,onOpenFile:s}){let o=(0,i.useContext)(l_).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)(lV,{utterance:e,sessionId:n,cwd:a,onOpenFile:s},e.key))}):null}function lV({utterance:e,sessionId:t,cwd:n,onOpenFile:a}){let s=rZ(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(),f=s?.alias??h??rb(e.provider),m=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==m?`작업 \xb7 ${h}`:null,x=lH(s?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...s?{minHeight:40}:null},children:[s&&(0,r.jsx)(r0,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:f}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(nc,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:a,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(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-e0a9ca790f024efb inline-utterance-sticker"}),(0,r.jsx)(lW(),{id:"e0a9ca790f024efb",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 lK=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function lG(e,t,n,r){if("string"!=typeof n)return[];let i=lK.exec(n),a=i?.[1],s=i?.[2];return a&&s?[{toolCallId:e,...t?{name:t}:{},alias:a,model:s,batchSize:r}]:[]}function lJ(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(...lG(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(...lG(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function lZ(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 lY=/^agent:\/\/([^/?#]+)\/?$/i;function lX(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?lY.exec(e.path):null,a=i?.[1],s=e.content;if(!a||"string"!=typeof s)continue;let o=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:a,message:s,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return n}let lQ=["greeting","utterance","message","text"],l0=function(e){let t=(0,i.useMemo)(()=>ih(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let a of n.subagents){if(t.has(a.name))continue;let n=[...i].reverse().find(e=>e.name===a.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},a="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,s="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==a||void 0!==s)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==a?{resolvedModel:a,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),i}(a,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),a="string"==typeof t.task?lK.exec(t.task):null,s=a?.[1],o=a?.[2],l=i.find(e=>e.name===t.id)??(s&&o?r.requests.find(e=>e.alias===s&&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]),a=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),s=sS(a,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&a.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:a}=e,s="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",o="failed"===s,l=a?.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 a=t?.model.trim()??"",s=a.indexOf("/");return s>0?a.slice(0,s):n?.trim()||void 0}(i,a,n),d=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,f=0;if((t?.entries??[]).forEach((t,n)=>{var r;let m;if("irc"in t){let{from:n,message:r,truncated:a}=t.irc;if(a||"string"!=typeof n||"string"!=typeof r)return;for(let t=f;t<e.sends.length;t+=1){let a=e.sends[t];if(a.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(a.send,i.id)&&a.send.from===n){h=a.turnIndex,f=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||c;if(!g||o&&l&&g!==l)return;let x=((m=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?m:function(e){let t="";for(let 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",...lQ]){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:g,credentialId:t.message.credentialId,accountSessionId:null,label:o&&a?a.alias:d,text:x,status:s})}),0===p.length&&"settled"!==s&&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&&a?a.alias:d,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[r,s,e.sessionProvider])},l1="web6",l2=[],l8=[],l4=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let a=`${t}?sessionId=${encodeURIComponent(i)}`,s=await e(a,{signal:r});if(!s.ok)throw Error(`HTTP ${s.status}`);let o=await s.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:a,text:s,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 a&&""!==a?a:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof o&&""!==o?o:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(l8),a=(0,i.useRef)(""),s=e.sessionId??"",o=s.length>0;return(0,i.useEffect)(()=>{if(!o){a.current="",r(l8);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(s,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===a.current)return;a.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,o,s]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return l2;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 l2;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let a=t.error??"";0!==a.trim().length&&i.push({key:`${l1}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${l1}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return i.length>0?i:l2})(n,e.messages,s),[n,e.messages,s])},l5={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},l6={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function l3({rows:e,removeLabel:t,onRemove:n}){let a,{st:s}=rQ(),[o,l]=(0,i.useState)(!1),{rows:c,hidden:d}=(a=Math.max(0,e.length-4),o||0===a?{rows:e,hidden:a}:{rows:e.slice(a),hidden:a}),u=e.length>4;return(0,i.useEffect)(()=>{u||l(!1)},[u]),(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":o,onClick:()=>l(e=>!e),children:o?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:d})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:c.map(e=>{let i=oA(e.text),a=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?s(1===e.images?"delivery.images.one":"delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,r.jsx)("span",{className:"answer-delivery-kind",children:s(l5[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:s(l6[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${a}`,onClick:()=>n(e.kind,e.text),children:(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}let l7=(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"})]}),l9=(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 ce({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?l7:l9})})})}let ct=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),cn={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function cr(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(a),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},a=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}function ci(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let ca={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},cs=(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"})]}),co=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function cl({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:a}=(0,F.s)(),s=function(e,t,n){let{locale:r}=(0,F.s)(),[a,s]=(0,i.useState)("idle"),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),y=(0,i.useRef)(null),b=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{f("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,i.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,b.current?.close(),b.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let n=y.current;y.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,i.useCallback)((e,t)=>{l(e),d(t??null),j("error")},[j]),C=(0,i.useCallback)(async()=>{let i,a=k.current+1;k.current=a,l(null),d(null),g(!0),s("connecting");let o=e;if(!o&&t){try{o=await t()}catch{o=void 0}if(k.current!==a)return}if(!o){k.current===a&&(g(!1),S("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===a&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==a){for(let e of i.getTracks())e.stop();return}v.current=i;try{let e,t,l=new RTCPeerConnection;for(let e of(x.current=l,i.getTracks()))l.addTrack(e,i);let c=document.createElement("audio");if(c.autoplay=!0,y.current=c,l.ontrack=e=>{let[t]=e.streams;t&&(c.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await cr(l),k.current!==a)return;let d=l.localDescription?.sdp;if(!d)throw Error("The browser produced no offer SDP.");let u=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,sdp:d,locale:r})}),h=await u.json().catch(()=>({})),f="",m="";if(h&&"object"==typeof h&&("error"in h&&(e=h.error),"message"in h&&"string"==typeof h.message&&(t=h.message),"callId"in h&&"string"==typeof h.callId&&(f=h.callId),"sdp"in h&&"string"==typeof h.sdp&&(m=h.sdp)),!u.ok||!f||!m){k.current===a&&(g(!1),S(ci(u.status,e),t));return}if(k.current!==a)return void fetch(`/api/live/call/${encodeURIComponent(f)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:m}),k.current!==a){l.close(),fetch(`/api/live/call/${encodeURIComponent(f)}`,{method:"DELETE"}).catch(()=>{});return}w.current=f;let v=new EventSource(`/api/live/events?callId=${encodeURIComponent(f)}`);b.current=v,v.onmessage=e=>{let t;if(k.current===a){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;if("string"!=typeof t.state||(r=t.state,!0!==cn[r]))return;"closed"===t.state?j("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&n&&Promise.resolve().then(()=>n(o)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&ct.test(e)&&j("idle")}return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},v.onerror=()=>{k.current===a&&w.current&&S("failed")},s("live")}catch(e){k.current===a&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===a&&g(!1)}},[e,t,n,r,S,j]),N=(0,i.useCallback)(()=>{if("idle"===a||"closed"===a||"error"===a){m||C();return}j("idle")},[m,a,C,j]);return(0,i.useEffect)(()=>()=>j("closed"),[j]),{state:a,failure:o,detail:c,transcript:u,supported:h,toggle:N}}(e,t,n),o="connecting"===s.state||"live"===s.state||"working"===s.state,l="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,c=a(o?"chat.liveStop":"chat.liveStart"),d=!1===s.supported?ca.unsupported:s.failure?ca[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,r.jsxs)("div",{role:"group","aria-label":a("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[d&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:a(d)}),l&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a(l)}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":o,title:p?a(p):c,"aria-label":p?a(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?co:cs})})]})}let cc={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 cd({sessionId:e}){let{t}=(0,F.s)(),[n,a]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void a(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let s=Array.isArray(i.handles)?i.handles:[],o=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==o,a(o)}catch{}},s=async()=>{await i(),t||(n=window.setTimeout(()=>void s(),r?5e3:3e4))};return s(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:cc,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}let cu=new Map,cp="ompweb-drafts-for-reload-v1",ch=!1,cf=new Map,cm=new Map,cg="\0stale",cx=new Map,cv=0,cy=new Map,cb=new Map,cw=new Map,ck=new Map,cj=new Map,cS=(e,t,n)=>oU(e,t,n.length?{sentAttachmentIds:n}:{}),cC=null,cN=!1;function cI(){if(ch||"u"<typeof sessionStorage)return;ch=!0;let e=sessionStorage.getItem(cp);if(e){sessionStorage.removeItem(cp);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)&&(cu.set(e[0],cM(t)),"string"==typeof t.draftId&&t.draftId&&(cf.set(e[0],t.draftId),cm.set(t.draftId,cg)),cW(e[0]))}}catch{}}}function cT(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(cp,JSON.stringify([...cu.entries()].map(([e,t])=>{let n=cf.get(e);return[e,n?{...cM(t),draftId:n}:cM(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function cM(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function cR(e){return!e.value&&0===e.images.length&&0===e.documents.length}function cE(e){cI();let t=cu.get(e);return t?cM(t):null}function c$(e,t){cI(),cR(t)?cu.delete(e):cu.set(e,cM(t)),cW(e)}function cL(e){cu.delete(e),cW(e)}function cP(e,t,n,r,i,a=[]){let s=[...t??[],...r].filter(nj).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=o$([...i??[],...a]);return{value:e.trim()?n.trim()?`${e}
18
18
 
19
- ${n}`:e:n,images:s,documents:o}}function cA(e,t,n){if(e===t)return n?cM(n):cE(t);let r=cE(e),i=n&&!cR(n)?cM(n):r??(n?cM(n):null),a=cE(t),s=cf.get(e);if(cf.delete(e),s&&!cf.has(t)&&cf.set(t,s),cL(e),!i)return a;let o=a?cP(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return c$(t,o),cM(o)}function cF(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function cz(e){cI();let t=cf.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),cf.set(e,t)),t}function cW(e){let t=cF(cu.get(e)?.documents),n=t.length?cz(e):cf.get(e);for(let[e,n]of cb){for(let e of t)n.delete(e);0===n.size&&cb.delete(e)}let r=`${n??""}|${t.join(",")}`;ck.get(e)!==r&&(0!==t.length||n?ck.set(e,r):ck.delete(e),cq())}async function cD(e){let t=cz(e);cy.set(t,(cy.get(t)??0)+1),await cj.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(cy.get(t)??1)-1;if(r>0?cy.set(t,r):cy.delete(t),e){let n=cb.get(t)??new Set;n.add(e),cb.set(t,n)}cm.set(t,cg),cq()}}}function cO(e,t){let n=cw.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&cw.delete(e),[...n].sort()}async function cH(){if(!cS)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of cf)t(n,cF(cu.get(e)?.documents));for(let{draftId:e,ids:n}of cx.values())t(e,n);for(let[e,n]of cb)t(e,n);for(let e of cm.keys())t(e,[]);for(let e of cw.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(cy.has(e))return!1;let n=cm.get(e);return cO(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=cy.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=cO(r,i),a=cS(r,i,e).then(()=>{0===i.length?cm.delete(r):cm.set(r,i.join(","));let t=cw.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&cw.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});cj.set(r,a),await a,cj.get(r)===a&&cj.delete(r)}n?function(){if(cB)return;cB=!0;let e=setTimeout(()=>{cB=!1,cq()},c_);"object"==typeof e&&"unref"in e&&e.unref(),c_=Math.min(2*c_,6e4)}():c_=cU}let cU=5e3,c_=5e3,cB=!1;function cq(){if(cS){if(cC){cN=!0;return}cC=Promise.resolve().then(cH).finally(()=>{cC=null,cN&&(cN=!1,cq())})}}let cV=Math.floor(Number.MAX_SAFE_INTEGER/1048576),cK=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function cG(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=cV}async function cJ(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!cG(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:cG((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:cK.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:cK.autoCleanupEnabled,orphanGraceDays:7}}async function cZ(e={}){return cJ(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function cY(e){return cJ(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function cX(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 cQ(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function c0(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}function c1(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function c2(e,t,n){let r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`;return`${a}${s} `}let c8="omp-web:model-picks";function c4(){try{let e=JSON.parse(window.localStorage.getItem(c8)??"{}");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 c5(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*s)),c=Math.max(0,e-a-s),d=Math.max(0,n-t-a-s),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 c6(e,t,n){return Math.min(e*t,n)}function c3(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,i.useState)({side:c??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),d=c5(i.top,i.bottom,n,c6(n,r,a),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,s,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 c7=n(14755);let c9="omp-web:model-roles-expanded";async function de(e,t,n,r,i,a,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...dm,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(a&&(!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}}function dt(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let dn=["off","default","full"],dr={off:"none",default:"default",full:"full"},di=c7.IN.join(" \xb7 "),da=c7.C1.filter(e=>!c7.IN.includes(e)).join(" \xb7 ");function ds(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let dl=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),dc=0,dd={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function du(e,t){return dl.compare(e.name||e.modelId,t.name||t.modelId)||dl.compare(e.provider,t.provider)||dl.compare(e.modelId,t.modelId)}let dp=["auto","off","minimal","low","medium","high","xhigh","max"],dh=["low","medium","high","xhigh"],df={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},dm=[{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"}],dg=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],dx={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},dv={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function dy(e,t,n){let r=e.name.toLowerCase(),i=db(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function db(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function dw(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function dk(e){return{data:e.data,mimeType:e.mimeType}}function dj(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function dS(e){return(e??[]).filter(nj).slice(0,10).map(dj)}let dC=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,dN="\n\nTranscript of the audio ";function dI(e){return o$(e).map(e=>{let t=oD(e),n="audio"===t&&e.attachmentId&&!e.text.includes(dN)?dC.exec(e.text):null;return{...e,id:++dc,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function dT({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function dM(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class dR extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let dE="composer:unkeyed";async function d$(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new dR("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function dL(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function dP({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 dA({error:e}){return e?(0,r.jsx)(dP,{tone:"error",title:"Model error",body:e}):null}function dF({warnings:e}){return e&&0!==e.length?(0,r.jsx)(dP,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let dz=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:f,onMainPresetChange:m,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:y,onCompact:b,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:I,effectiveThinkingLevel:T,thinkingCeiling:M,onThinkingLevelChange:R,availableThinkingLevels:E,thinkingLevelMap:$,fastMode:L=null,fastModeBusy:P=!1,onFastModeToggle:A,retryInfo:z,deliveryRows:W=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,slashCommands:_,slashCommandsLoading:B,onLoadSlashCommands:q,onBuiltinCommand:V,soundEnabled:K,onSoundToggle:G,onAudioUnlock:J,onPromptWithStreamingBehavior:Z,draftKey:Y,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},en){let er,ei,ea,es,eo,el,ec,ed,eu,ep,{t:eh}=(0,F.s)();rY();let{st:ef}=rQ(),em=W.some(e=>e.removable),eg=U(),[ex,ev]=(0,i.useState)(()=>Y?cE(Y)?.value??"":""),[ey,eb]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{ey&&eN(c4())},[ey]);let[eI,eT]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(ey)try{eT("1"===window.localStorage.getItem(c9))}catch{}},[ey]);let eM=()=>{eT(e=>{let t=!e;try{window.localStorage.setItem(c9,t?"1":"0")}catch{}return t})},[eR,eE]=(0,i.useState)(!1),[e$,eL]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(!1),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(!1),[eU,e_]=(0,i.useState)(()=>Y?dS(cE(Y)?.images):[]),[eB,eq]=(0,i.useState)(()=>Y?dI(cE(Y)?.documents):[]),[eV,eK]=(0,i.useState)(null),eG=(0,i.useMemo)(()=>eB.filter(e=>"ready"===e.status),[eB]),eJ=eB.some(e=>"ready"!==e.status||dt(e)),eZ=eB.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(dN))),eY=ex.trimStart(),eX=0===eU.length&&0===eB.length&&eY.startsWith("!"),eQ=eX&&eY.startsWith("!!"),[e0,e1]=(0,i.useState)(!1),[e2,e8]=(0,i.useState)(0),[e4,e5]=(0,i.useState)(null),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(0),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(0),[ti,ta]=(0,i.useState)(null),[ts,to]=(0,i.useState)(!1),[tl,tc]=(0,i.useState)(null),[td,tu]=(0,i.useState)(null),tp=X&&td?.cwd===X?td.values:{},th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tm=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(null),tj=(0,i.useRef)(null),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(0),tN=(0,i.useRef)(!1),tI=(0,i.useRef)([]),tT=(0,i.useRef)([]),tM=(0,i.useRef)([]),tR=(0,i.useRef)(null),tE=(0,i.useRef)(null),t$=(0,i.useRef)(Y),tL=(0,i.useRef)(ex),tP=(0,i.useRef)(eU),tA=(0,i.useRef)(0),tF=(0,i.useRef)(eB);tL.current=ex,tP.current=eU,tF.current=eB,(0,i.useImperativeHandle)(en,()=>({insertIfEmpty(e){let t=th.current;(t?t.value:ex).trim()||(tL.current=e,ev(e),e5(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=th.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ex,tP.current.length,tA.current,tF.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"),oA(t)?.message??t),a=dS("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 nj(r)?[r]:[]})),s=dI((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),oA(n)?.documents??[]));tL.current=i,tP.current=a,tF.current=s,ev(i),e5(null),tt(!1),e_(e=>(e.forEach(dL),a)),eq(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(t$.current!==e)return void cA(e,t);let n={value:tL.current,images:tP.current.map(dk),documents:tF.current.filter(e=>"ready"===e.status).map(dT)},r=cA(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(t$.current=t,i)return;let a=dS(r.images),s=dM(dI(r.documents),tF.current),o=r.value;tL.current=o,tP.current=a,tF.current=s,ev(o),e_(e=>(e.forEach(dL),a)),eq(s),e5(null),tt(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=t$.current,a=r??i,s=a===i,o=!s&&a?cE(a):null,l=cP(e,t,s?tL.current:o?.value??"",s?tP.current.map(dk):o?.images??[],n,s?tF.current.filter(e=>"ready"===e.status).map(dT):o?.documents??[]);if(a&&c$(a,l),!s)return;let c=t?.length?[...dS(t).slice(0,Math.max(0,10-tP.current.length)),...tP.current].slice(0,10):tP.current,d=dM(dI(l.documents),tF.current);tL.current=l.value,tP.current=c,tF.current=d,ev(l.value),e5(null),tt(!1),t?.length&&e_(e=>{let n=Math.max(0,10-e.length),r=dS(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tP.current=i,i}),eq(d),requestAnimationFrame(()=>{let e=th.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=th.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",o=i+s+e+a;tL.current=o,ev(o),e5(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tX(e)}}));let tz=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tP.current.length-tA.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eK(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:oF(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eK(eh("chat.attachImageLimit",{count:10})),i.length){tA.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)})));e_(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(dL);let r=[...t,...n];return tP.current=r,r})}finally{tA.current-=i.length}}},[eh]),tW=(0,i.useCallback)(async e=>{for(let t of e){let e=oT(t);if(!e)continue;if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eK(eh("chat.attachTooLarge",{name:t.name,limit:oF(8388608)}));continue}if(tF.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eK(eh("chat.attachTotalTooLarge",{limit:oF(0x1000000)}));continue}let n={id:++dc,name:t.name,mimeType:oC[e],size:t.size,text:"",status:"extracting"},r=[...tF.current,n];tF.current=r,eq(r);try{let e=await oL(t);if(tF.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new oS("text_too_large","Total extracted text exceeds 240000 characters");let r=tF.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tF.current=r,eq(r)}catch(i){let e=tF.current.some(e=>e.id===n.id),r=tF.current.filter(e=>e.id!==n.id);if(tF.current=r,eq(r),!e)continue;i instanceof oS?"text_too_large"===i.code?eK(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eK(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eK(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eK(eh("chat.attachPasswordProtected",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tD=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.id===e))return!1;let n=t?tF.current.map(n=>n.id===e?t:n):tF.current.filter(t=>t.id!==e);return tF.current=n,eq(n),!0},[]),tO=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.attachmentId===e))return!1;let n=tF.current.map(n=>n.attachmentId===e?t(n):n);return tF.current=n,eq(n),!0},[]),tH=(0,i.useCallback)((e,t,n)=>{if(!e||e===t$.current)return;let r=cE(e);r?.documents.some(e=>e.attachmentId===t)&&c$(e,{...r,documents:dI(r.documents).map(e=>e.attachmentId===t?n(e):e).map(dT)})},[]),tU=(0,i.useRef)(new Map),t_=(0,i.useRef)(new Map),tB=(0,i.useRef)(new Set),tq=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=oO({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tV=(0,i.useCallback)(e=>e instanceof dR&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof dR&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tK=(0,i.useCallback)(async(e,t)=>{let n=t$.current,r=tF.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;t_.current.get(e)?.abort();let a=new AbortController;t_.current.set(e,a),tO(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await d$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new dR("Invalid transcription result",null,null,null);let i=r.transcript;tO(e,e=>tq(e,i,tF.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tH(n,e,e=>tq(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tO(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof dR&&"confirmation_required"===n.code)return void tG.current?.(e);let t=tV(n);tO(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t_.current.get(e)===a&&t_.current.delete(e)}},[eh,tV,tO,tH,tq]),tG=(0,i.useRef)(null),tJ=(0,i.useCallback)(async e=>{let t;t_.current.get(e)?.abort();let n=new AbortController;t_.current.set(e,n),tO(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new dR("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await d$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tO(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tV(t);tO(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t_.current.get(e)===n&&t_.current.delete(e)}t.requiresConfirmation?tO(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tK(e,!1)},[tK,tV,tO]);tG.current=tJ;let tZ=(0,i.useCallback)(e=>{let t=t_.current.get(e);t?t.abort():tO(e,e=>({...e,transcription:{state:"skipped"}}))},[tO]),tY=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++dc,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tF.current,i];tF.current=a,eq(a);let s=(e,t)=>{let n=tF.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?oE("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?oE("utf-16be",t.subarray(2)):t.includes(0)?null:oE("utf-8",t)??oE("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tD(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await cZ().catch(()=>cK)).uploadLimitMb),r.size>n){tD(i.id,null)&&eK(eh("chat.attachStoredTooLarge",{name:r.name,limit:oF(n)}));continue}let o={...i,stored:t,status:"uploading",size:0};if(!tD(i.id,o))continue;let l=t$.current??dE,c=await cD(l),d=null,u=new AbortController;tU.current.set(i.id,u);try{if(tB.current.has(i.id))continue;let e=await oH(r,{sessionId:Q,draftId:c.draftId,signal:u.signal}),n=tF.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=oO({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tD(i.id,null)&&eK(eh("chat.attachTotalTooLarge",{limit:oF(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tD(i.id,h))d=e.id;else if(!tB.current.has(i.id)&&l!==t$.current){let t=cE(l)??{value:"",images:[],documents:[]};c$(l,{...t,documents:[...t.documents,dT(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tD(i.id,null)&&eK(eh("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tU.current.delete(i.id),c.end(d)}d&&"audio"===t&&tF.current.some(e=>e.attachmentId===d)&&tJ(d)}},[tD,tJ,Q,eh]),tX=(0,i.useCallback)(async e=>{eK(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==oT(a)?n.push(a):oR(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tz(t),tW(n.filter(e=>e.size<=8388608)),tY(r,"audio"),tY([...i,...a],"file")])},[tW,tY,tz]),tQ=(0,i.useCallback)(e=>{e_(t=>{let n=[...t],[r]=n.splice(e,1);return r&&dL(r),tP.current=n,n})},[]),t0=(0,i.useCallback)(e=>{let t=tF.current.find(t=>t.id===e);if(tB.current.add(e),tU.current.get(e)?.abort(),t?.attachmentId){t_.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of cb)t.delete(n)&&(0===t.size&&cb.delete(e),cq())}let r=tF.current.filter(t=>t.id!==e);tF.current=r,eq(r)},[]),t1=(0,i.useCallback)(()=>{tP.current=[],e_(e=>(e.forEach(dL),[]))},[]),t2=(0,i.useCallback)(()=>{tF.current=[],eq([])},[]),t8=(0,i.useCallback)(()=>{tL.current="",ev(""),e5(null),tt(!1),Y&&cL(Y),t$.current&&t$.current!==Y&&cL(t$.current),t1(),t2(),eK(null),th.current&&(th.current.style.height="auto")},[t2,t1,Y]);(0,i.useEffect)(()=>{Y&&t$.current===Y&&c$(Y,{value:ex,images:eU.map(dk),documents:eG.map(dT)})},[eU,Y,eG,ex]),(0,i.useEffect)(()=>{let e=t$.current;if(e===Y)return;e&&c$(e,{value:tL.current,images:tP.current.map(dk),documents:tF.current.filter(e=>"ready"===e.status).map(dT)});let t=Y?cE(Y):null;t$.current=Y;let n=t?.value??"",r=dS(t?.images),i=dI(t?.documents);tL.current=n,tP.current=r,tF.current=i,ev(n),e5(null),tt(!1),e_(e=>(e.forEach(dL),r)),eq(i)},[Y]),(0,i.useEffect)(()=>{let e=th.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tP.current.forEach(dL)},[]);let t4=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=cF(t);if(0===n.length)return()=>{};let r=++cv;return cx.set(r,{draftId:cz(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=cx.get(r);if(t){if(cx.delete(r),"accepted"===e){let e=cw.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);cw.set(t.draftId,e)}cq()}}}(t$.current??dE,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t5=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eY.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eU.length&&!eG.length||o||eJ)return;J?.();let i=eU.length?eU:void 0,a=eG.length?eG:void 0;if(r.startsWith("/")){await de(r,_,V,t=>t4(a,()=>e(t,i,a)),eK,!!(i||a),q)&&t8();return}t8(),t4(a,()=>e(r,i,a))},[ex,eY,eU,eG,eJ,o,V,_,q,e,t8,J,t4]),t6=eY.startsWith("/")&&!/\s/.test(eY.slice(1))?eY.slice(1).toLowerCase():null,t3=(()=>{if(null===t6)return[];let e=[...o?[]:dm,..._??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=db(e,eh).toLowerCase();return t.includes(t6)||n.includes(t6)}).sort((e,t)=>{let n=dy(e,t6,eh)-dy(t,t6,eh);return 0!==n?n:dv[e.source]-dv[t.source]||dl.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t7,groups:t9}=(er=0,{commands:(ei=dg.map(e=>{let t=t3.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!dw(e,tp)),...t.filter(e=>dw(e,tp))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),ne=1===t3.length?eh(t6?"chat.match":"chat.command"):eh(t6?"chat.matches":"chat.commands",{count:t3.length}),nt=!!ex.trim(),nn=!eJ&&(nt||eU.length>0||eG.length>0),nr=(0,i.useCallback)((e,t)=>{if(!X)return void e5(null);let n=t??e.length;e5(cX(e.slice(0,n)))},[X]),ni=e4?.query??null,na=i.useMemo(()=>null!==ni&&ti&&ti.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:c0(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:c0(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||cQ(e.entry.path)-cQ(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(ti.entries,ni):[],[ni,ti,X]),ns=!!(ni&&ti?.truncated&&ti.cwd===X);(0,i.useEffect)(()=>{if(!ns||!X||!ni)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(ni)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tc({cwd:X,query:ni,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ns,ni,X]);let no=ns&&null!==tl&&tl.cwd===X&&tl.query===ni,nl=no?tl.matches:na,nc=null===e4?null:`${e4.start}:${+!!e4.quoted}:${e4.query}`;(0,i.useEffect)(()=>{if(null===nc){e3(!1),e9(0);return}e3(!0),e9(0)},[nc]);let nd=null!==e4,nu=c3(tk,te,{viewportFraction:.44,cap:360}),np=c3(tk,e0,{viewportFraction:.56,cap:460}),nh=c3(tk,e6,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!X)return;let e=tR.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tE.current===X||(tE.current=X,to(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{ta({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>cQ(e.path)-cQ(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tR.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tR.current=null}).finally(()=>{tE.current=null,to(!1)}))},[nd,X]);let nf=(0,i.useCallback)(e=>{if(!e4)return;let t=th.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e4.start),i=ex.slice(n);e4.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e4.quoted),s=r+a.text+i,o=r.length+a.cursorOffset;ev(s),e5(cX(s.slice(0,o))),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e4,ex]);(0,i.useEffect)(()=>{e7>=nl.length&&e9(Math.max(0,nl.length-1))},[nl.length,e7]),(0,i.useEffect)(()=>{tT.current.length=nl.length},[nl.length]),(0,i.useEffect)(()=>{e6&&tT.current[e7]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e7,e6]),(0,i.useEffect)(()=>{tn>=D.length&&tr(Math.max(0,D.length-1))},[D.length,tn]),(0,i.useEffect)(()=>{tM.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{te&&tM.current[tn]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tn,te]);let nm=(0,i.useCallback)(e=>{tL.current=e,ev(e),tt(!1),tr(0),e5(null),requestAnimationFrame(()=>{let t=th.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),ng=(0,i.useCallback)(e=>{let t=`/${e.name} `;tL.current=t,ev(t),e1(!1),e8(0),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eY.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eJ||!i&&0===eU.length&&0===eG.length?null:{message:i,images:eU.length?eU:void 0,documents:eG.length?eG:void 0};if(!s)return;J?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await de(i,_,V,e=>{if(!Z)throw Error("Cannot queue this command while the session is busy.");t4(s.documents,()=>Z(e,o,s.images,s.documents))},eK,!!(s.images?.length||s.documents?.length),q)&&t8();return}t8(),"steer"===e&&n?t4(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t4(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eY,eU,eG,eJ,_,q,V,Z,n,a,t8,J,t4]),nv=(0,i.useCallback)(e=>{let t=t7.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e2-1);if("right"===e)return Math.min(t,e2+1);let n=tI.current[e2];if(!n)return"down"===e?Math.min(t,e2+1):Math.max(0,e2-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===e2)continue;let t=tI.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-a;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<o&&(s=n,o=c)}return s>=0?s:"down"===e?Math.min(t,e2+1):Math.max(0,e2-1)},[t7.length,e2]),ny=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tC.current<100,s=tS.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(te&&!s){if("ArrowDown"===e.key){e.preventDefault(),tr(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tr(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tt(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[tn]){e.preventDefault(),nm(D[tn]);return}}if(e0&&null!==t6){if("ArrowDown"===e.key){e.preventDefault(),e8(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e8(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e8(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e8(nv("left"));return}if("Escape"===e.key){e.preventDefault(),e1(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t7[e2]){e.preventDefault(),ng(t7[e2]);return}}if(e6&&null!==e4&&!s){if("ArrowDown"===e.key){e.preventDefault(),e9(e=>Math.min(Math.max(0,nl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e9(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e3(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nl[e7]){e.preventDefault(),nf(nl[e7]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===ex.trim().length){e.preventDefault(),e1(!1),e3(!1),tr(D.length-1),tt(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(n||a)?nx(n?"steer":"followup"):t5())},[o,n,a,t,e0,t6,t7,e2,ng,nx,t5,nv,e6,e4,nl,e7,nf,te,D,tn,nm,ex]),nb=(0,i.useCallback)(()=>{let e=th.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nw=(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(),tX(t))},[tX]);(0,i.useEffect)(()=>{if(null===t6){e1(!1),e8(0),tN.current=!1;return}e1(!0),e8(0),!tN.current&&q&&(tN.current=!0,Promise.resolve(q()).catch(()=>{tN.current=!1}))},[t6,q]),(0,i.useEffect)(()=>{if(!e0||!X)return;let e=!1;return tu({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tu({cwd:X,values:n})}).catch(()=>{e||tu({cwd:X,values:{}})}),()=>{e=!0}},[e0,X]),(0,i.useEffect)(()=>{e2>=t7.length&&e8(Math.max(0,t7.length-1))},[t7.length,e2]),(0,i.useEffect)(()=>{tI.current.length=t7.length},[t7.length]),(0,i.useEffect)(()=>{e0&&tI.current[e2]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e2,e0]);let nk=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(du):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(du),nS=g??null,nC=n5.find(e=>e.alias===nS)?.provider??null,nN=nC?nk.filter(e=>e.provider===nC):nk,nT=(ea=ej.trim().toLocaleLowerCase())?nN.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):nN,nM=nN.length>8,nR=[];for(let e of nT){let t=nR.find(t=>t.provider===e.provider);t?t.options.push(e):nR.push({provider:e.provider,options:[e]})}let nE=nC?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),n$=l?nE.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,nL=ej.trim()?[]:nN.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nP=(e,t,n)=>{let i=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(eb(!1),eS(""),!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}(c4(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(c8,JSON.stringify(r))}catch{}eN(r),f?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nA=l?nk.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,nF=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nz=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${nI(S.tokensBefore)} -> ${nI(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:nI(nF)})})`:null,nW=e=>{let t=$?.[e];return null!=t&&t!==e?t:null},nD="auto"===(es=I??"auto")?M?`auto ≤ ${nW(M)??M}`:"auto":$?$[es]??es:es,nO=(I??"auto")==="auto"&&T&&"auto"!==T?$?.[T]??T:null,nH=R&&nO?eh("chat.currentReasoning",{level:nO}):null,nU=e=>!E||E.includes(e),n_=[{level:"auto",ceiling:null},...dh.filter(nU).map(e=>({level:"auto",ceiling:e})),...dp.filter(e=>"auto"!==e&&nU(e)).map(e=>({level:e,ceiling:null}))],nB=Object.entries(dr).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tf.current&&!tf.current.contains(e.target)&&tm.current&&!tm.current.contains(e.target)&&(eb(!1),eS("")),tg.current&&!tg.current.contains(e.target)&&tx.current&&!tx.current.contains(e.target)&&eE(!1),tv.current&&!tv.current.contains(e.target)&&eA(!1),ty.current&&!ty.current.contains(e.target)&&ez(!1),tb.current&&!tb.current.contains(e.target)&&eH(!1),!tw.current||tw.current.contains(e.target)||th.current?.contains(e.target)||tt(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eH(!1)},[eg]);let nq=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eU.length||eB.length?" is-active":""}`,onClick:()=>tj.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eU.length||eB.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=eU.length||eB.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eU.length||eB.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"})]})}),nV=m&&n5.length>0?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eR?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eL({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eR,onKeyDown:e=>{"Escape"===e.key&&eR&&(e.stopPropagation(),eE(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eg?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eR&&e$&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=c5(e$.top,e$.bottom,e,c6(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-e$.top+6}:{top:e$.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:e$.left,width:"max-content",minWidth:e$.width};return(0,r.jsx)("div",{ref:tx,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eE(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:n5.map(e=>{let t=e.alias===nS;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eE(!1),m({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:rv(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:rp(e.alias)}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,nK=R?(0,r.jsxs)("div",{ref:ty,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eF?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eD({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(!1),ez(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eF,onKeyDown:e=>{"Escape"===e.key&&eF&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level:nD}),"aria-label":eh("chat.changeReasoning",{level:nD}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eF?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eF?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nD})]}),eF&&eW&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=c5(eW.top,eW.bottom,e,c6(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eW.top+6}:{top:eW.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eW.left,width:"max-content",minWidth:Math.max(180,eW.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),ty.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:n_.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nW(i),s=t?`auto ≤ ${a??t}`:a??e,o=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(df[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{ez(!1),R(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,nG=A?(eo=P?eh("chat.fastModeBusy"):null===L?eh("chat.fastModeUnknown"):L.active?eh("chat.fastModeActive"):L.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),el=P||o||y,ec=L?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${L?.active?" is-active":""}`,onClick:A,disabled:el,"aria-pressed":null===L?void 0:L.enabled,"aria-busy":P||void 0,title:eo,"aria-label":eo,style:{flexShrink:0,opacity:o?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:L?.active?"var(--accent)":"none",stroke:ec?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===L?"3 2":void 0,style:{opacity:ec&&!L?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,nJ=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nx("steer"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nn?"var(--warning)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nZ=void 0!==G?(0,r.jsx)(ce,{soundEnabled:K??!0,onToggle:G}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tj,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tX(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(dA,{error:p}),(0,r.jsx)(dF,{warnings:h}),W.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ef("delivery.title",{count:W.length})}),O&&em&&(0,r.jsxs)("button",{onClick:O,title:eh("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(l3,{rows:W,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("steer"===e?"steering":"followUp",t):void 0})]}),z&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:z.attempt,max:z.maxAttempts}),z.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",z.errorMessage]})]}),nz&&(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"})}),nz]}),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}),eV&&(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:eV}),(0,r.jsx)("button",{type:"button",onClick:()=>eK(null),"aria-label":eh("i18n.close"),title:eh("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eU.length>0||eB.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eU.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tQ(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}`)),eB.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||dt(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):ie(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):dd[e.mimeType]," \xb7 ",oF(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t0(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eZ.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eZ.map(e=>{let t,n,i,a,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?eh("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:l?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:l.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,r.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[l.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tK(o,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tJ(o),children:eh(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tk,style:{position:"relative",minWidth:0},children:[te&&D.length>0&&(0,r.jsxs)("div",{ref:tw,style:{position:"absolute",left:0,right:0,...ds(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nu.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===tn;return(0,r.jsxs)("button",{ref:e=>{tM.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>tr(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}`)})})]}),e0&&null!==t6&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ds(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:B?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:ne})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:10},children:B||0!==t3.length?t9.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(dx[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===e2,i=dw(e,tp);return(0,r.jsxs)("button",{ref:e=>{tI.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ng(e)},onMouseEnter:()=>e8(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),db(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:db(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e6&&null!==e4&&(ed=ts&&(!ti||ti.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=ti?.truncated&&!no?e4.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ds(nh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nh.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ed?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nh.maxHeight-34),overflowY:"auto",padding:4},children:ed||0!==nl.length?nl.map((e,t)=>{let n=t===e7,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tT.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>e9(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)(r3,{size:14}):ie(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ns&&!no?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eX?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eX?"var(--tool-bg)":o&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:th,value:ex,onChange:e=>{tL.current=e.target.value,ev(e.target.value),tt(!1),nr(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nr(t.value,t.selectionStart)},onKeyDown:ny,onCompositionStart:()=>{tS.current=!0},onCompositionEnd:e=>{tS.current=!1,tC.current=Date.now();let t=e.currentTarget;nr(t.value,t.selectionStart)},onInput:nb,onPaste:nw,placeholder:o&&(n||a)?eh("chat.steerPlaceholder"):o?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),o?eg?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nJ}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t5,disabled:!nn,"aria-busy":eJ||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eJ?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:nn?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eX&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eQ?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eQ?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!o)&&nq,!eg&&nV,!(eg&&o)&&(nk.length>0||nA||p)&&f&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.jsxs)("button",{className:`composer-chip${ey?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(e=>(e&&eS(""),!e))},disabled:o||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:ey?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ey?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":nk.length>0?"Change model":"No available models",children:[y?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nA??(nk.length>0?"Select model":"No models")})]}),ey&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=c5(ew.top,ew.bottom,e,c6(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tm,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),eb(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nL.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),nL.map(({option:e,count:t})=>nP(e,"frequent",t))]}),nE.length>0&&!ej.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nL.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eI,"aria-controls":"model-role-rows",onClick:eM,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eI?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:eh("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nE.length}),n$&&(0,r.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:n$.tag??n$.role.toUpperCase()}),n$.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eI,children:nE.map(e=>{let t=n$?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{eb(!1),eS(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eh("chat.allModels")})]}),0===nR.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):nR.map((e,t)=>(0,r.jsxs)("div",{children:[nR.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=>nP(e,"all"))]},e.provider))]})]})})()]}),eg&&o&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nJ}),!eg&&nK,!eg&&nG,!eg&&nH&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nH}),(0,r.jsx)(cd,{sessionId:Q})]}),(0,r.jsxs)("div",{ref:tb,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eO?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eO?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eO?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eg&&(0,r.jsxs)(r.Fragment,{children:[o&&nq,nV,nK,nG]}),!o&&N&&(0,r.jsxs)("div",{ref:tv,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eP?" is-active":""}`,onClick:()=>!o&&eA(e=>!e),disabled:o,title:eh("chat.changeToolPreset")+`: ${nB}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eP?"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=eP?"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:nB})]}),eP&&(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:dn.map(e=>{let t=dr[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:di}):eh("chat.allBuiltInTools",{tools:`${di} + ${da}`});return(0,r.jsxs)("button",{onClick:()=>{eA(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!o&&b&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:b,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?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nZ,eO&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eA(!1),ez(!1),eH(!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:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(cl,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nZ]})]})]})]})});function dW({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=eT(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:eL(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function dD({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:s}=rQ(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=(0,i.useId)(),f=e??[],{currentPhase:m,activeTask:g,remaining:x,completed:v,total:y,percent:b}=tj(f),w=t.steps.length>0,k=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,s);if(0===y&&null===k)return null;let j=y>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${j?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:j?"✓":"›"}),k&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:k}),y>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!k&&m&&(0,r.jsx)("span",{className:"todo-strip-phase",children:m.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:j?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:j?a("todo.progressDone",{percent:b??0,completed:v,total:y}):a("todo.progress",{percent:b??0,completed:v,total:y,remaining:x})})]}),w&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",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)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&w&&(0,r.jsx)(sB,{flow:t,live:n,st:s,id:h}),o&&y>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[f.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[f.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(r4,{task:e},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function dO(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function dH(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function dU(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 d_ extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function dB(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 d_(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let dq="ompweb-update-client-id",dV="ompweb-update-resume-intent-v2",dK="ompweb-update-return-v1",dG="cuelo-restart-return-v1",dJ="ompweb-update-failure-return-v1",dZ="ompweb:update-wake";function dY(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function dX(){let e=sessionStorage.getItem(dq);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(dq,t),t}function dQ(){sessionStorage.removeItem(dV)}function d0(){let e=sessionStorage.getItem(dK);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 d1(e){let t=d0();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(dK,JSON.stringify(n))}catch{}return n}async function d2(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:dX(),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 d8(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=d0();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(dK,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),dQ();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(dZ,{detail:{sessionId:e.sessionId}}))}async function d4(e){let t=function(e){let t=sessionStorage.getItem(dJ);if(!t)return null;sessionStorage.removeItem(dJ);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(dQ(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(dZ,{detail:{sessionId:e.sessionId}})),"failed"):(await d8(e),"resumed")}function d5(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function d6(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 d3(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function d7(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function d9(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function ue(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 ut(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function un(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!e4(r??void 0))return{message:e[n],entryId:r}}return null}let ur=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class ui 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 ua(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function us(e){return new Promise(t=>setTimeout(t,e))}function uo(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ul(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:uo(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:uo(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=uo(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function uc(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 ud(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(uc).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function uu(e){return"user"===e.role?`user:${ud(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 up(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 uh(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function uf(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let um=!1,ug={width:0,height:0},ux=new Set,uv=null;function uy(){let e=window.visualViewport,t=uf();ug.width!==window.innerWidth?ug={width:window.innerWidth,height:window.innerHeight}:t||(ug.height=Math.max(ug.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:ug.height});if(n!==um)for(let e of(um=n,ux))e()}function ub(e){if(ux.add(e),!uv){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,uy()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),uy(),uv=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{ux.delete(e),0===ux.size&&uv&&(uv(),uv=null)}}function uw(){return(0,i.useSyncExternalStore)(ub,()=>um,()=>!1)}let uk={count:50,end:null};function uj(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function uS(e,t,n){let{startIndex:r,endIndex:i}=uj(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function uC({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:nO[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(lW(),{id:"71a4a7cebbc6c842",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 uN(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=(oA(t)?.message??t).trim();return n.length>0?n:null}function uI(e){return`omp-cues:${e}`}function uT(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(uI(e),JSON.stringify(n.slice(-200)))}catch{}}let uM=[];function uR(e){return`omp-web:interrupted-dismissed:${e}`}let uE=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:f,sessionId:m,main:g,process:x,dispatchSlots:v,compactedDispatch:y,openRequest:b,startIndex:w,endIndex:k,sentinelRef:j,laterSentinelRef:S,flashItem:C,t:N,onProcessLogChange:I,cues:T,cueFollowRef:M}){(0,i.useEffect)(()=>{I({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:m})},[I,x,e,t,n,a,s,m]);let R=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[o.idx];if(e?.role!=="assistant")continue;let s=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=e7(i.action);if(!0===e3[e]){let t={kind:"skill",action:e,name:e7(i.name)};n(JSON.stringify(t),t)}continue}let a=e7(i.memory),s=i.skill,o=s?{action:e7(s.action),name:e7(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:o}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...o?{skill:o}:{}})}}(o.blocks??e.content??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:e1,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,N]),E=(0,i.useMemo)(()=>{let r=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(r=t.idx);return function(e,t,n,r,i,a,s=[]){let o=function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&si(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:si(t,n),s=new Map;for(let[n,o]of(e.forEach((e,n)=>{"answer"===e.kind&&s.set(si(t,e.anchorIdx),n)}),s)){if(n===a)continue;let e=i.find(e=>e>n);r.set(o,{from:n+1,to:e??t.length})}return r}(e,t,n),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,n]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(ss(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let i=n.to-1;for(;i>=n.from&&e4(s[i]);)i-=1;if(s[i]!==a.throughEntryId)continue;let o=sn(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sa(t,r,n.from,n.to);c.set(e,{...a.summary,...p?{remaining:se(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,i,a=[]){let s=sn(e,n,r),o=sa(e,t,n,r);return{...st(s,t,i),remaining:o?se(o):null,span:so(e,n,r),flow:a7(s,t,!1,a,i,sr(e,n,r))}}(t,r,n.from,n.to,i,d),latest:e===l})}return c}(g,e,r,n,s,b,t)},[g,e,n,s,l,b,t]),$=w>0,L=k<g.length,P=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&e4(t[v]);)v-=1;let y="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,b=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(o5,{message:x,toolResults:n,modelNames:a,cwd:s,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:y,onEditContent:f,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:m,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${b}-view-${i}`)},A=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[$&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((a,l)=>{let c=w+l,d=y?.position===c?(0,r.jsx)(s3,{calls:y.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,f=p?p.idx:1/0,x=T.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<f}).map(e=>(0,r.jsx)(uC,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),b=h!==u,k=R.get(c),j=k?(0,r.jsx)(o5,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=b?(0,r.jsx)(lq,{turnIndex:u,turnEntryId:t[u],sessionId:m,cwd:s,onOpenFile:o}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx)),j,S,x]},`message-${a.idx}`);let C=tx(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=eH(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:E.get(c)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),y?.position===g.length&&k===g.length&&(0,r.jsx)(s3,{calls:y.calls}),L&&(0,r.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function u$({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsChange:m,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:y,onOpenWorkspaceView:b,onOpenSessionList:w,onOpenMaker:k,selectedMaker:j,onProcessLogChange:S,onOpenFile:C,transcriptReplacement:N,onComposerFocusChange:I,onSessionBusyChange:T,onWaitingChange:M,onAttentionChange:R,soundEnabled:E=!0,onSoundToggle:$,playCueSound:L=async()=>({sticker:null,text:null}),preloadCueSound:P,unlockAudio:A,jumpRequest:z=null,onJumpHandled:W}){var D,O;let H,B,q,{t:V}=(0,F.s)(),K=uw(),G=U(),J=(0,i.useRef)(L);J.current=L;let Z=(0,i.useRef)(null),Y=(0,i.useRef)(P);Y.current=P;let[Q,ee]=(0,i.useState)([]),et=(0,i.useRef)(Q);et.current=Q;let en=(0,i.useRef)(0),er=(0,i.useRef)([]),ei=(0,i.useRef)([]),ea=(0,i.useRef)(null),es=(0,i.useRef)(0),eo=(0,i.useRef)(-1),el=(0,i.useRef)(-1),ec=(0,i.useCallback)(()=>{let e=ea.current?.current;return e?{sessionId:e,turn:es.current}:null},[]),ed=(0,i.useCallback)(e=>ea.current?.current===e.sessionId&&es.current===e.turn,[]),eu=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;en.current=Math.max(en.current+1,Date.now());let i={id:en.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};ee(e=>{let t=[...e,a];return null!==a.anchorEntryId&&uT(n.sessionId,t),t})},[]),ep=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ed(n)&&("working"!==t||el.current!==n.turn);i()&&J.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&eu(e,t,n,r)}).catch(()=>{})},[ed,eu]),eh=(0,i.useCallback)(async(e,t,n)=>{let r=(await rJ(e,t,n))?.alias??null;return r&&Y.current?.(r),r},[]),ef=(0,i.useCallback)((e,t,n,r)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=nX(e[n]),a=0;for(let t=r;t<=n;t++)nX(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(er.current,ei.current);eh(t.sessionId,n,r).then(n=>{ep(n,e,t,i)})},[ep,eh]),[em,eg]=(0,i.useState)(0),ex=(0,i.useRef)([]),ev=(0,i.useCallback)(e=>{if(es.current+=1,null!==nB(e.outcome)){let t=e.sessionId;ex.current.push({completion:e,trigger:t?{sessionId:t,turn:es.current}:null}),eg(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ex.current.splice(0)){let n=nB(e.outcome),r="neutral"===n?null:n;t?ef(r,t,e.provider,e.credentialId):J.current(null,r).catch(()=>{})}},[em,ef]);let ey=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ew,messages:ek,entryIds:ej,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eI,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:e$,modelThinkingLevels:eL,modelThinkingLevelMaps:eP,modelRoles:eA,toolPreset:eF,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,fastMode:eO,fastModeBusy:eU,handleFastModeToggle:eV,retryInfo:eK,contextUsage:eJ,forkingEntryId:eZ,isCompacting:e1,compaction:e3,compactError:e7,compactResult:te,displayModel:tt,modelSwitching:tn,sessionStats:tr,runStateKnown:ti,compactedWork:ta,slashCommands:ts,slashCommandsLoading:to,deliveryRows:tl,subagents:tc,todoPhases:td,notices:tu,extensionDialog:tp,extensionResponse:th,extensionCustomUi:tf,extensionStatuses:tm,extensionWidgets:tg,respondToExtensionUi:tx,sendExtensionCustomInput:tv,isAutoModelSelection:ty,agentPhase:tb,isNew:tw,autoFollowPaused:tj,resumeAutoFollow:tS,pauseAutoFollow:tC,goalStatus:tI,sessionIdRef:tT,messagesEndRef:tM,scrollContainerRef:tR,handleSend:tE,handleAbort:t$,handleFork:tL,handleNavigate:tP,handleModelChange:tA,handleRoleModelChange:tF,handleMainPresetChange:tz,newSessionAccount:tW,handleCompact:tD,handleSteer:tO,handleFollowUp:tH,handlePromptWithStreamingBehavior:tU,handleAbortCompaction:t_,handleRecallQueue:tB,handleRemoveQueuedMessage:tq,handleBuiltinSlashCommand:tV,handleToolPresetChange:tK,handleThinkingLevelChange:tG,loadSlashCommands:tJ,ensureNewSession:tZ,refreshLiveTranscript:tY}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,f=null===t&&null!==r,m=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(m),[v,y]=(0,i.useState)(!f&&!m),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(m?.leafId??null),[S,C]=(0,i.useState)(m?.context.messages??[]),[N,I]=(0,i.useState)(m?.context.entryIds??[]),[T,M]=(0,i.useState)(m?.context.compactedWork??null),[R,E]=(0,i.useReducer)(d6,{isStreaming:!1,streamingMessage:null}),[$,L]=(0,i.useState)(!1),[P,A]=(0,i.useState)(!1),[F,z]=(0,i.useState)(null),[W,D]=(0,i.useState)({}),[O,H]=(0,i.useState)([]),[U,_]=(0,i.useState)(null),[B,q]=(0,i.useState)([]),[V,K]=(0,i.useState)({}),[G,J]=(0,i.useState)({}),[Z,Y]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,eo]=(0,i.useState)(()=>{let e=m?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[el,ec]=(0,i.useState)(),[ed,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[ey,eb]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(m?.contextUsage??null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)(null),[eI,eM]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(null),[e$,eL]=(0,i.useState)(!1),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(null),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(null),eU=(0,i.useRef)(null),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)([]),[eJ,eZ]=(0,i.useState)(!1),[eY,eX]=(0,i.useReducer)(ul,{visible:[],pending:[]}),[eQ,e1]=(0,i.useState)(null),[e2,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,to]=(0,i.useState)({steering:[],followUp:[]}),[tl,tc]=(0,i.useState)([]),[td,tu]=(0,i.useReducer)(iz,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{$||tu({type:"idle"})},[$]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iA(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${iP(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(td,ts),[td,ts]),[tf,tm]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(m?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tT=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),tR=(0,i.useRef)(!1),tE=(0,i.useRef)(-1),t$=(0,i.useRef)("unknown"),tL=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(0),tF=(0,i.useRef)(!1),tz=(0,i.useRef)(0),tW=(0,i.useRef)(null),tD=(0,i.useRef)(null),tO=(0,i.useRef)(null),tH=(0,i.useRef)(!1),tU=(0,i.useRef)(!0),[t_,tB]=(0,i.useState)(!1),[tq,tV]=(0,i.useState)(null),tK=(0,i.useRef)(void 0),tG=(0,i.useRef)(0),tJ=(0,i.useRef)(0),tZ=(0,i.useRef)(()=>{}),tY=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t8=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,no=eI??g?.context.model??eR??null,nl=f?X??en:no,nc=(0,i.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;s+=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:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nd=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nd.current+=1,tm(n=>n?.sid===e&&ue(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nd.current===n&&Array.isArray(t)&&tm(n=>n?.sid===e&&ue(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nf=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),nm=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&y(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=e5(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(s.messages),nf(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let o=!n&&t5.current===e;if(o||(eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&y(!1),!n){if(o)try{let t=t6.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t6.current===t&&(r.state?.thinkingLevel!==void 0?(eo(r.state.configuredThinkingLevel??r.state.thinkingLevel),ec(r.state.thinkingLevel)):r.running||(t5.current=null,eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nd.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eS(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t5.current=e,eo(i.configuredThinkingLevel??i.thinkingLevel),ec(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&to(d3(i.queuedMessages)),void 0!==i.subagents&&tc(e=>d5(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||to({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&&y(!1)}},[np,nf,nh]),ng=(0,i.useCallback)(e=>{let t=na.current.then(async()=>{tj.current===e&&await nm(e)});return na.current=t.catch(()=>{}),t},[nm]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let o=e5(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(o.messages),nf(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nf,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await dB(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),ny=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;f&&r&&n&&!t1.current&&(t1.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}))},[f,r,l]),nb=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!f||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t4.current,i=t8.current;e&&eE(e);let a={cwd:r,type:"ensure_session",toolNames:(0,c7.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),o=t0.current,l=o?.body===s?o.createRequestId:ua();t0.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:l})});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();t0.current=null,t=d.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),d.model&&t2.current===e&&(eE(d.model),e||er(d.model)),d.thinkingLevel&&t4.current===n&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await dB(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[f,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await nb();if(!e)return eG([]),[];eZ(!0);try{let t=await dB(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[nb]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,tb.current&&(clearTimeout(tb.current),tb.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{ty.current?.close(),ty.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);ty.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tW.current?.(n):"agent_start"===n.type&&tD.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tW.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nI=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new ui(n.status)},[nN]),nT=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await dB(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e6(t=>t?.id===e.id?null:t)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await dB(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nR=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??ua(),message:t,type:e.type??"info"}})},[]),nE=(0,i.useCallback)(e=>{let t={role:"custom",customType:e0,content:eT(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!e4(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${e8}${n.seq}`,baseEntryId:a,message:t});let s=e5(tC.current,tN.current,n.outputs);nh(s.messages),nf(s.entryIds)},[nh,nf]),n$=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e6(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(dH(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":nR({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ta(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[nR,o,e.chatInputRef]),nL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eV(null),eb(null),E({type:"end"}),e},[]),nP=(0,i.useCallback)(()=>{t$.current="unknown",tL.current=null;let e=un(tC.current,tN.current);tP.current=e?{entryId:e.entryId,key:uu(e.message)}:null,tA.current+=1},[]),nA=(0,i.useCallback)(()=>{let e=t$.current,t=tL.current;if("unknown"===e){let n=un(tC.current,tN.current),r=n?.message,i=tP.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:uu(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=ut(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nF=(0,i.useCallback)(e=>{let t=nA();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===n;s?.(e?nA():t)})},[s,nA]),nz=(0,i.useCallback)((e,t)=>tE.current!==e&&(tE.current=e,nF(t),!0),[nF]),nW=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nd.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(tc(e=>d5(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,tb.current=null,tM.current=!!s?.isStreaming,tR.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eH(d9(s)),tb.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){tb.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,tb.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;tb.current=setTimeout(()=>void n(),600)}};tb.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),nD=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nm(e)}finally{if(nt.current!==t)return;let n=tR.current,r=tM.current;tR.current=!1,tM.current=!1,nr.current=null;let i=nL();n?nz(t):r&&i&&nF(),e&&nW(e)}},[nm,nF,nz,nW,nL]),nO=(0,i.useCallback)(async(e,t)=>{await us(800);let n=Date.now();for(;tT.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nD(e,t)}}catch{}await us(600)}},[nD]),nH=(0,i.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;tF.current&&tz.current===t&&tj.current===e;){await us(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 nm(e),tz.current!==t||tj.current!==e)return;tF.current=!1,A(!1),z(null);return}catch{}}},[nm]),nU=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=nt.current;try{let n=nd.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let a=i.state;if(eA(a?.isCompacting??!1),eH(d9(a)),to(d3(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),tc(e=>d5(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eS(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await nD(e,t)}catch{}},[np,nD]),n_=(0,i.useCallback)(async e=>{let t=await nm(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tT.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,tR.current=!!n.isPromptRunning,tT.current=!0,L(!0),eV(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nO(e),!0)},[nN,nm,nO]),nB=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eP){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eP]),(0,i.useEffect)(()=>{if(!$&&!eP)return;let e=()=>{let e=tj.current;e&&nB(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[$,eP,nB]),(0,i.useEffect)(()=>{if(!$)return;let e=()=>{let e=tj.current;e&&nU(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)}},[$,nU]),(0,i.useEffect)(()=>{if($)return;let e=()=>{let e=tj.current;e&&!tT.current&&n_(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tT.current&&n_(t).then(e=>{e||tj.current!==t||tT.current||nm(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(dZ,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(dZ,n)}},[$,n_,nm]),tD.current=e=>{if(tj.current!==e||tT.current||tg.current||tO.current)return;let t=n_(e).then(async t=>{t||tj.current!==e||tT.current||await nm(e)}).catch(()=>{}).finally(()=>{tO.current===t&&(tO.current=null)});tO.current=t},(0,i.useEffect)(()=>{tT.current=$},[$]),tW.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=uu(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=uu(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=uu(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let n=e5(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);nh(n.messages),nf(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;nk(),e&&nP(),tM.current=!0,tT.current=!0,L(!0),eV({kind:"waiting_model"}),E({type:"start"});break}case"agent_end":if(!tT.current)break;if(eV(null),eb(null),E({type:"end"}),tj.current){nm(tj.current);let e=nd.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eS(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>d5(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tV(t.state.goal??null),to(d3(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tV(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||tR.current)break;let t=tj.current,n=nL();eA(!1);let r=t?nm(t):void 0;t&&nW(t),n&&nF(r);break}case"prompt_done":{let e=nt.current,t=tR.current;tR.current=!1,nr.current=null;let n=tE.current!==e;if(!t&&!n)break;let r=tj.current;nz(e,r?nm(r):void 0),!tM.current&&(nL(),r&&nW(r))}break;case"prompt_error":t$.current="failed",nR({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t$.current="failed",nR({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tT.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&E({type:"update",message:sy(t)}),eV(null);break}case"message_end":{if(!tT.current)break;let t=e.message;if(t?.role==="assistant"&&(tL.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},t$.current=ut(t)),t&&"user"===t.role){let e=sy(t),n=ud(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ud(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tu({type:"user-message",kind:iD(e),text:iW(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nh(e=>[...e,sy(t)]);let n=tj.current;n&&nB(n),E({type:"reset"}),eV({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t5.current=t,t6.current+=1,eo(e.configured??n),ec(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eV(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;eV(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";tc(n=>{let r=n.find(e=>e.id===t.id);return d5(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()};tc(e=>d5(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};tc(e=>d5(e,[r]));break}case"queue_update":to({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eb({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eb(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}eA(!0),ez(null),eD(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)ez(e.errorMessage),eD(null);else if(!e.aborted){eD(up(e.result,e.reason??"auto"));let t=tj.current;t&&(nm(t),nB(t))}break;case"extension_ui_request":n$(e)}},[nR,nu,np,nk,n$,nm,nF,nz,nB,nP,nW,nL,nf,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tF.current||ni.current)return"unknown";let o=oP(n,a??[]),l=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tK.current?.(t,e),"accepted"):"unknown"}nP();let c=nt.current+1;nk(),tR.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()};nh(e=>[...e,u]),nr.current=ud(u),nt.current=c,tT.current=!0,L(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),tZ.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,m=!1,g="unknown";try{if(f&&r){let e=tj.current??await tQ.current,t=await nb();t&&(h=t,X&&(eE(X),e&&await dB(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),m=!0,await dB(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),ny(1,n),g="accepted")}else t&&(h=t.id,await nI(t.id),m=!0,await dB(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&nO(h,c),g}catch(o){console.error("Failed to send message:",o);let r=o instanceof d_&&"update_draining"===o.code&&!1===o.accepted;if(!(!m||o instanceof d_&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return nO(h,c),"unknown";tR.current=!1,tT.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&ud(t)===s?e.slice(0,-1):e}),nR({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,uh(i),a,t?.id??h??void 0),nr.current=null,L(!1),eV(null),E({type:"end"}),"returned"}},[f,r,X,t,nb,nI,ny,nO,nR,nk,nj,e.chatInputRef,nP,nh]);tK.current=(0,i.useCallback)(async(n,r)=>{if(tT.current||tF.current)return;let i=`${r?"!!":"!"}${n}`;tF.current=!0,tZ.current(!0),z({command:n,excludeFromContext:r}),A(!0);try{let e=tj.current??t?.id??await nb();if(!e)throw Error("Unable to create a session for the shell command");await dB(e,{type:"bash",command:n,excludeFromContext:r}),await nm(e),ny(1,i)}catch(t){console.error("Failed to execute shell command:",t),nR({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tF.current=!1,z(null),A(!1)}},[nR,nb,nm,e.chatInputRef,ny,t]);let nV=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tF.current){try{await dB(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await dB(e,{type:"abort"}),t$.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nK=(0,i.useCallback)(async e=>{if(tF.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eN(e??null);try{let{cancelled:n,newSessionId:r}=await dB(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{eN(null)}},[c]),nG=(0,i.useCallback)(async e=>{if(tF.current)return;let t=tj.current;t&&(dB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nJ=(0,i.useCallback)(async e=>{if(tF.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&dB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nZ=(0,i.useCallback)(async(e,t)=>{if(f){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t8.current=null,et(null)),Q(n),eE(n);let i=tj.current??await tQ.current;if(!i)return;try{await dB(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await dB(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nm(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eI),nR({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nm(n)}finally{ni.current=!1,eL(!1)}}},[nR,eI,f,nm,Q]),nY=(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(f){if(ni.current)return!1;ni.current=!0,eL(!0);let e=t2.current,a=t8.current,s=t4.current;try{t2.current=t,t8.current=n??null,t4.current="auto";let e=tj.current??await tQ.current;return e&&await dB(e,r),Q(t),et(n??null),eE(t),eo("auto"),ec(void 0),e&&await nm(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t8.current=a,t4.current=s,nR({type:"error",message:i(n)});let t=tj.current;return t&&await nm(t),!1}finally{ni.current=!1,eL(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await dB(a,r),await nm(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eI),nR({type:"error",message:i(e)}),await nm(a),!1}finally{ni.current=!1,eL(!1)}},[nR,eI,el,f,nm,Q,es]),nX=(0,i.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(f){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t4.current=t??null,eo(t??"auto"),ec(void 0),t2.current=e,t8.current=null,et(null),Q(e),eE(e)}let r=tj.current??(f?await tQ.current:null);if(r)try{await dB(r,{type:"set_role_model",role:e}),f||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Z,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eP){eU.current="manual",eA(!0),ez(null),eD(null);try{let t=await dB(e,{type:"compact"});eD(up(t,"manual")),await nm(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eD(null)}finally{eA(!1)}}},[eP,nm]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();D(s.models),_(s.modelError??null),q(s.modelScopeWarnings??[]),K(s.thinkingLevels??{}),J(s.thinkingLevelMaps??{}),Y(s.roles??[]);let o=s.modelList??[];if(H(o),f&&!tj.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t4.current&&eo(t??"auto")}},[f,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await nb(),s=e=>(e.handled&&(e.error?nR({type:"error",message:e.error}):"openSessionStats"!==e.action&&nR({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eP)return s({handled:!0,error:"No active session to compact"});eU.current="manual",eA(!0),ez(null),eD(null);let e=await dB(a,{type:"compact",...i?{customInstructions:i}:{}});return eD(up(e,"manual")),await nm(a,!0)&&ny(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await dB(a,{type:"reload"}),await Promise.all([nm(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await dB(a,{type:"set_session_name",name:i}),await nm(a)&&ny(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await dB(a,{type:"get_session_stats"});return e&&e1(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await dB(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nK();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await dB(a,{type:"goal",args:i});if(tV(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nE(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nR({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tF.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eV({kind:"running_command"});try{await nI(a);let e=await dB(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nm(a,!0)&&ny(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eV(null),tj.current===a&&nW(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await dB(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nE(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[nR,nE,nI,nb,nK,eP,n0,nm,nw,nv,ny,h,nW]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r),"returned";let a=oP(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:a,images:s?.length??0});try{return await dB(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to steer:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r,i),"returned"}},[nR,e.chatInputRef]),n8=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(r),i),"returned";let s=oP(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:n,text:s,images:o?.length??0});try{return await dB(a,{type:"prompt",message:s,streamingBehavior:n,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(n){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",n),nR({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(r),i,a),"returned"}},[nR,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r),"returned";let a=oP(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:a,images:s?.length??0});try{return await dB(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to follow up:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r,i),"returned"}},[nR,e.chatInputRef]),n5=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await dB(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await dB(t,{type:"clear_queue"});tu({type:"withdraw"}),to({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),nR({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nR]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await dB(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nR({type:"error",message:"Failed to remove queued message"})}},[nR]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ed;eo(e),eu(n),f&&(!tj.current||t7.current===tj.current)&&(t4.current=e,t3.current=n),ec(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await nb():r&&await dB(i,{type:"set_thinking_ceiling",ceiling:n}),await dB(i,{type:"set_thinking_level",level:e}),await nm(i)}catch(e){console.error("Failed to set thinking level:",e),nR({type:"error",message:"Failed to set thinking level"}),await nm(i)}},[f,nm,nR,ed,nb]);ev.current=nl?`${nl.provider}/${nl.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!$&&!e$&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?d7(t.state):void 0)??null})}).catch(()=>{})},[rt,$,e$]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await nb(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};em(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=d7(await dB(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await dB(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nR({type:"error",message:t instanceof Error?t.message:String(t)});try{i(d7(await dB(e,{type:"get_state"}))??null)}catch{i(null)}}finally{em(!1)}},[nb,ep,nR]),ri=(0,i.useCallback)(async e=>{let t=(0,c7.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await dB(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),ra=(0,i.useCallback)(e=>{tU.current=e,tB(t=>!e===t?t:!e)},[]);tZ.current=ra;let rs=(0,i.useCallback)((e="smooth")=>{tJ.current=Date.now()+700,tY.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tG.current=0,ra(!0),rs("smooth")},[rs,ra]),rl=(0,i.useCallback)(()=>{tG.current=0,ra(!1)},[ra]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!ur.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tG.current=Date.now()+1200)},[]),rd=(0,i.useCallback)(()=>{if(!tT.current&&!tF.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tG.current;!t&&Date.now()<tJ.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?ra(!0):t&&ra(!1))},[ra]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&nm(t.id,!m,!0,m).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,tR.current=!!e.state.isPromptRunning,tT.current=!0,L(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nO(t.id)),e.state?.isBashRunning&&(tF.current=!0,A(!0),nH(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eA(n.isCompacting),eH(d9(n)),void 0!==n.contextUsage&&ek(n.contextUsage??null),void 0!==n.systemPrompt&&eS(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t5.current=t.id,eo(n.configuredThinkingLevel??n.thinkingLevel),ec(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&to(d3(n.queuedMessages)),void 0!==n.subagents&&tc(e=>d5(e,n.subagents??[])),void 0!==n.goal&&tV(n.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(ej)},[ej,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nJ)},[g?.tree,k,nJ,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rc),()=>{window.removeEventListener("keydown",rc)}),[rc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rc,{passive:!0}),e.addEventListener("wheel",rc,{passive:!0}),e.addEventListener("touchstart",rc,{passive:!0}),e.addEventListener("scroll",rd,{passive:!0}),()=>{e.removeEventListener("pointerdown",rc),e.removeEventListener("wheel",rc),e.removeEventListener("touchstart",rc),e.removeEventListener("scroll",rd)}},[S.length,v,rd,rc]),(0,i.useEffect)(()=>{if(t9.current||!$&&!P||!tU.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tJ.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[$,P,S.length,R.streamingMessage,eq,F,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,rs("instant");return}if(!t9.current&&tU.current){let e=Date.now()-ne.current<1500;rs(tT.current||tF.current||e?"instant":"smooth")}}},[S.length,$,P,rs,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,d]),(0,i.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[eW]),(0,i.useEffect)(()=>{if(0===eY.visible.length)return;let e=eY.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eY.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eY.visible]),(0,i.useEffect)(()=>{e1(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:b,activeLeafId:k,messages:S,entryIds:N,streamState:R,agentRunning:$,modelNames:W,modelList:O,modelError:U,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:el,thinkingCeiling:ed,retryInfo:ey,contextUsage:ew,systemPrompt:ej,forkingEntryId:eC,isCompacting:eP,compaction:eO,compactError:eF,compactResult:eW,currentModel:no,displayModel:nl,modelSwitching:e$,sessionStats:nc,runStateKnown:e_,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:ts,deliveryRows:th,subagents:tl,todoPhases:tf&&tf.sid===tj.current?tf.phases:null,compactedWork:T,notices:eY.visible,extensionDialog:e2,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nT,sendExtensionCustomInput:nM,isAutoModelSelection:f&&null===X,agentPhase:eq,isNew:f,autoFollowPaused:t_,resumeAutoFollow:ro,pauseAutoFollow:rl,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tY,scrollContainerRef:tX,handleSend:nq,handleAbort:nV,handleFork:nK,handleNavigate:nG,handleModelChange:nZ,handleRoleModelChange:nX,handleMainPresetChange:nY,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n4,handlePromptWithStreamingBehavior:n8,handleAbortCompaction:n5,handleRecallQueue:n6,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:ef,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:nb,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:E,setAgentRunning:L,setForkingEntryId:eN,bashRunning:P,pendingBash:F,handleAgentEventRef:tW}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ev,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsPanelOpen:g}),tX=(0,i.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=eQ(i);if(!a||"custom"!==i.role)continue;t??=[...e];let s=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&s.push(t);continue}let i=n.get(t);void 0===i&&(i=function(e){let t=eX(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,i)),i===a.sourceHash&&s.push(t)}s.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===a.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[r]={...i,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(eY)?{kind:"translated",text:n.slice(eY.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(i,eX(o.content??[]))}}return t??e})(ek),[ek]),tQ=rZ(e?.id,tt?.provider,void 0),t0=tQ?.alias;(0,i.useEffect)(()=>{t0&&Y.current?.(t0)},[t0]);let t1=(0,i.useMemo)(()=>{if(!tt)return null;let e=tw?tW:n5.find(e=>e.alias===tQ?.alias)?.oauthPosition;return n5.find(t=>t.provider===tt.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[tt,tw,tW,tQ]),t2=eC||eN,t8=e?.id;er.current=tX,ei.current=ej,ea.current=tT;let t4=(0,i.useRef)(!0);t4.current=!tj;let t5=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t5.current&&(es.current+=1),t5.current=eC},[eC]),(0,i.useEffect)(()=>()=>{es.current+=1},[]),(0,i.useEffect)(()=>{ee(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(uI(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[]}}(t8),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t8)])},[t8]),(0,i.useEffect)(()=>{let e=tT.current;e&&et.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&ee(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(nX(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,tX,ej);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(uT(e,r),r):t})},[tX,ej,tT]);let t6=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tT.current,t=t6.current;if(t6.current=e?{sessionId:e,entryIds:ej}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===n0&&r.push(t[a])}return r}(t.entryIds,ej,tX),r=ec();if(0===n.length||!r)return;let i=rG(e,"web6",void 0)?.alias??null;for(let e of n)et.current.some(t=>t.anchorEntryId===e)||ep(i,"done",r,{kind:"entry",entryId:e})},[ej,tX,tT,ec,ep]);let t3=eC&&tb?.kind==="running_tools"&&tb.tools.length>0&&tb.tools.every(e=>"wait"===e.name),t7=eb||s,{hideThinkingBlock:t9}=(D=t??e?.cwd??null,H=nF(),(0,i.useEffect)(()=>{nA(D).catch(()=>{})},[D]),H),ne=(0,i.useMemo)(()=>({hideThinking:t9}),[t9]);(0,i.useEffect)(()=>{var e;if(!tp||Z.current===tp.id)return;Z.current=tp.id;let t=ec();if(!t)return;el.current=t.turn;let n=eS.streamingMessage?.role==="assistant"?eS.streamingMessage:null,r=nQ(er.current,n,tt?.provider);ef("select"===(e=tp.method)||"ask"===e?"choice":"approval",t,r.provider,r.credentialId)},[tp,eS.streamingMessage,tt?.provider,ec,ef]),(0,i.useEffect)(()=>(v=t2?t$:null,()=>void(v=null)),[t2,t$]),(0,i.useEffect)(()=>{T?.(t2)},[T,t2]),(0,i.useEffect)(()=>()=>T?.(!1),[T]),(0,i.useEffect)(()=>{M?.(t3)},[t3,M]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{R?.(null!==tp)},[R,tp]),(0,i.useEffect)(()=>()=>R?.(!1),[R]);let{main:nt,process:nn}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,o=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),o=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:o});a.messageCount+=t.length,a.toolCallCount+=n},l=eG(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:a,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(),a=i.idx,r.push(i);continue}if(e2(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===eQ(t)&&o(a,[{idx:i.idx}],0);continue}let s=eB(t,n),c=!1;for(let e of s){if("answer"===e.kind){d(i.idx,e.blocks),c=!0;continue}o(a,[{idx:i.idx,blocks:e.blocks}],eq(e.blocks)),l.collect(i.idx,e.blocks)}!c&&e_(t,n)&&d(i.idx,[])}return u(),{main:r,process:i}})(tX,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(e6(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!e6(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!e6(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,o=[],l=0,c=0,d=eG(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex: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(null!==eQ(n))continue;if(e2(n)){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:l});continue}let c=eB(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(a.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eq(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&e_(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 f=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=f);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(tX,{sessionBusy:t2,isStreaming:eS.isStreaming,hideThinking:ne.hideThinking}),ne),[tX,t2,eS.isStreaming,ne]),nr=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=iE(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=r.get(l.position);e?e.calls.push(...n):r.set(l.position,{calls:[...n],placement:o?"after":"before"})}}"user"===e.role&&(a=t),e6(e)&&(s=t)});let{continuing:o}=i$(e,t,n);if(o){let e=r.get(o.position);e?e.calls.unshift(...o.calls):r.set(o.position,{calls:o.calls,placement:"before"})}return r})(nt,tX,ta?.messages),[nt,tX,ta]),ni=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=i$(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i);return{position:-1===a?e.length:a,calls:r}})(nt,tX,ta?.messages),[nt,tX,ta]),[na,ns]=(0,i.useState)(uk),{startIndex:no,endIndex:nl,hasLater:nc}=uj(nt.length,na),nd=null!==na.end&&nc,nu=(0,i.useRef)(nt.length);nu.current=nt.length;let np=(0,i.useRef)(null),nh=(0,i.useRef)(null),nf=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==na.end&&na.end>=nt.length&&ns(e=>({count:e.count,end:null}))},[na.end,nt.length]),(0,i.useEffect)(()=>{let e=np.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nf.current=t.scrollHeight-t.scrollTop,ns(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]),(0,i.useEffect)(()=>{if(null==nf.current)return;let e=tR.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nf.current),nf.current=null}},[na.count,tR]),(0,i.useEffect)(()=>{let e=nh.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ns(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=uj(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nu.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]);let[nm,ng]=(0,i.useState)(null),[nx,nv]=(0,i.useState)(0),ny=(0,i.useRef)(null),nb=(0,i.useCallback)(e=>{tC(),ny.current=e,ng(null),ns(t=>uS(nu.current,e,t)),nv(e=>e+1)},[tC]);(0,i.useLayoutEffect)(()=>{let e=ny.current,t=tR.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;ny.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,ng(e)},[nx,na,nt,tR]),(0,i.useEffect)(()=>{if(null===nm)return;let e=setTimeout(()=>ng(null),1800);return()=>clearTimeout(e)},[nm]);let nw=(0,i.useCallback)(()=>{(0,_.flushSync)(()=>ns(uk));let e=tR.current;e&&(e.scrollTop=e.scrollHeight)},[tR]),nk=(0,i.useCallback)(()=>{nd&&nw(),tS()},[nd,nw,tS]),nj=(0,i.useRef)(null),[nS,nC]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!z||nj.current===z.id||z.sessionId!==e?.id||eb||0===tX.length)return;nj.current=z.id,W?.(z.id);let t=ej.indexOf(z.entryId);if(t<0)return void nC(!0);let n=0;for(let e=0;e<nt.length;e++){let r=nt[e].idx;if(r>t||(n=e,r===t))break}nb(n)},[z,e?.id,eb,tX.length,ej,nt,nb,W]),(0,i.useEffect)(()=>{if(!nS)return;let e=setTimeout(()=>nC(!1),6e3);return()=>clearTimeout(e)},[nS]);let[nN,nI]=(0,i.useState)(!1),[nT,nM]=(0,i.useState)(0),nR=(0,i.useMemo)(()=>nN?nt.map(e=>(function(e,t){if("answer"===e.kind)return e9(e.blocks);let n=t[e.idx];return n&&"content"in n?e9(n.content):""})(e,tX).toLowerCase()):uM,[nN,nt,tX]),nE=(0,i.useCallback)(e=>{tC(),ns(t=>uS(nu.current,e,t))},[tC]),n$=(0,i.useCallback)(()=>nI(!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=tR.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(),nI(!0),nM(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tR]);let nL=(0,i.useMemo)(()=>{let e=[];return nt.forEach((t,n)=>{if("message"!==t.kind)return;let r=uN(tX[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nt,tX]),nP=`${no}:${nl}`,nz=ej.length>0?ej[ej.length-1]:null,[nW,nD]=(0,i.useState)(null),nO=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nO.current||!ti||eb||!e?.id||(nO.current=!0,t2||!nz||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(tX)||function(e){try{return window.localStorage.getItem(uR(e))}catch{return null}}(e.id)!==nz&&nD(nz))},[ti,eb,e?.id,t2,nz,tX]);let nH=(0,i.useCallback)(()=>{e?.id&&nW&&function(e,t){try{window.localStorage.setItem(uR(e),t)}catch{}}(e.id,nW),nD(null)},[e?.id,nW]),nU=null!==nW&&nW===nz&&!t2&&!nd,n_=tr?[tr.sessionId,tr.sessionFile??"",tr.sessionName??"",tr.userMessages,tr.assistantMessages,tr.toolCalls,tr.toolResults,tr.totalMessages,tr.tokens.input,tr.tokens.output,tr.tokens.cacheRead,tr.tokens.cacheWrite,tr.tokens.total,tr.cost??0,tr.totalActiveMs??0].join("|"):null,nq=(0,i.useRef)(tr);nq.current=tr,(0,i.useEffect)(()=>{m?.(nq.current)},[n_,m]),(0,i.useEffect)(()=>()=>{m?.(null)},[m]);let nV=eJ?`${eJ.percent??"null"}|${eJ.contextWindow}|${eJ.tokens??"null"}`:null,nK=(0,i.useRef)(eJ);nK.current=eJ,(0,i.useEffect)(()=>{x?.(nK.current)},[nV,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{y?.(tc)},[y,tc]),(0,i.useEffect)(()=>()=>{y?.([])},[y]);let{isDragOver:nG,handleDragEnter:nJ,handleDragOver:nZ,handleDragLeave:nY,handleDrop:n1}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t2||p?.current?.addAttachments(e)},[t2,p])),n2=(0,i.useMemo)(()=>{var e;return e=ta?.messages,e&&e.length>0?[...e,...tX]:tX},[ta,tX]),n8=(0,i.useMemo)(()=>{let e=new Map;for(let t of n2)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[n2]),n4=(0,i.useMemo)(()=>{let e,t,n,r,i,a,s,o,l,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,i=new Map,a=new Map,s=new Map,o=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},l=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=ik(e.status);if(!r||l.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;l.add(r);let s=iw(e);null!==s&&i.set(r,s)},d=(e,t,r)=>{let i=t?n.get(t):void 0,a=iw(e);i&&"number"==typeof r&&null!==a&&"running"===ik(e.status)&&s.set(i,Math.max(s.get(i)??-1/0,r-a))},n2.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=n8.get(e.toolCallId);if(t)for(let i of iS(e,t)??[])n.set(i.agentId,i.key),"number"==typeof t.timestamp&&r.set(i.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(ij(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=ib(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:ib(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of iy(t.details?.jobs)){if("task"!==r.type)continue;let a=ib(r.id);if(a&&o(a,ik(r.status),i),c(r,a),d(r,a,t.timestamp),a&&"running"===ik(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of ij(t.content).matchAll(iC)){let t=Object.fromEntries([...e[1].matchAll(iN)].map(e=>[e[1],e[2]]));t.id&&o(t.id,ik(t.status),i)}for(let e of iy(t.details?.jobs))"task"===e.type&&c(e,ib(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:i,parallelWith:a,runStartedAt:s}},[n2,n8]),n6=(0,i.useMemo)(()=>({ledger:n4,subagents:tc,toolResults:n8,onOpenPanel:b,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:k,selectedMaker:j}),[n4,tc,n8,b,e?.id,e?.cwd,t,k,j]),n3=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=tX.length-1;n>=0;n-=1){let r=uN(tX[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[tX]),n7=(0,i.useMemo)(()=>tk(tX,n8,td,ta?.todoPhases??null),[tX,n8,td,ta]),n9=(0,i.useMemo)(()=>lZ(eS.streamingMessage).join("|"),[eS.streamingMessage]),re=(0,i.useMemo)(()=>JSON.stringify(lJ(eS.streamingMessage)),[eS.streamingMessage]),rt=(0,i.useMemo)(()=>JSON.stringify(lX(eS.streamingMessage)),[eS.streamingMessage]),rn=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],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=lZ(r),c=lX(r,a);if(0===i.length&&0===c.length||l<0)continue;let d=lJ(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.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 a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=o.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(a,e),s.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 s.sort((e,t)=>e.index-t.index)})(tX,ej,n9.length>0?n9.split("|"):[],JSON.parse(re),JSON.parse(rt)),[tX,ej,n9,re,rt]),rr=e?.id??tT.current??void 0,ri=(B=l0(O=(0,i.useMemo)(()=>({sessionId:rr,sessionProvider:tt?.provider,turns:rn,messages:tX,subagents:tc}),[rr,tt?.provider,rn,tX,tc])),q=l4(O),(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}([...B,...q])),[B,q])),ra=tw&&0===tX.length&&!eS.isStreaming&&!t2,rs=e?.cwd??t??void 0,ro=tt?eL[`${tt.provider}:${tt.modelId}`]??null:null,rl=tt?eP[`${tt.provider}:${tt.modelId}`]??null:null,rc=(0,i.useRef)(null),rd=(0,i.useRef)(null),ru=(0,i.useCallback)(()=>{rc.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(I?.(ru),()=>I?.(null)),[ru,I]),(0,i.useLayoutEffect)(()=>{let e=rd.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tR.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tR.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[eb,tR]);let rp=(0,i.useCallback)((...e)=>(null!==na.end&&nw(),tE(...e)),[tE,na.end,nw]),rh=(0,r.jsx)("div",{ref:rc,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(dz,{ref:p,sessionId:e?.id??tT.current??void 0,onEnsureSession:tw&&t?tZ:void 0,onLiveTranscriptPersisted:tY,onSend:rp,onAbort:t$,onSteer:eC?tO:void 0,onFollowUp:eC?tH:void 0,onPromptWithStreamingBehavior:eC?tU:void 0,isStreaming:t2,model:tt,isAutoModelSelection:ty,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:e$,onModelChange:tA,onMainPresetChange:e||tw?tz:void 0,mainPresetActiveAlias:t1,modelRoles:eA,onRoleModelChange:tF,modelSwitching:tn,onCompact:e||tw?tD:void 0,onAbortCompaction:t_,isCompacting:e1,compactError:e7,compactResult:te,toolPreset:eF,onToolPresetChange:e||tw?tK:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,onThinkingLevelChange:e||tw?tG:void 0,fastMode:eO,fastModeBusy:eU,onFastModeToggle:e||tw?eV:void 0,availableThinkingLevels:ro,thinkingLevelMap:rl,retryInfo:eK,deliveryRows:tl,inputHistory:n3,onRecallQueue:tB,onRemoveQueuedMessage:tq,slashCommands:ts,slashCommandsLoading:to,onLoadSlashCommands:tJ,onBuiltinCommand:tV,soundEnabled:E,onSoundToggle:$,onAudioUnlock:A,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rf=eS.streamingMessage,rm=(0,i.useMemo)(()=>rf?eB(rf,{isStreaming:!0}):[],[rf]),rg=(0,i.useMemo)(()=>rm.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rm]),rx=(0,i.useMemo)(()=>rm.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rm]),rv=rf?.role==="assistant"?rf:null,ry=(0,i.useMemo)(()=>{let e=-1;for(let t=tX.length-1;t>=0;t-=1)if("user"===tX[t].role){e=t;break}let t=e<0?-1:si(tX,e);return{start:t,blocks:sn(tX,t+1,tX.length),priorCiHeads:ss(tX,n8,t+1),jobNotices:sr(tX,t+1,tX.length)}},[tX,n8]),rb=(0,i.useMemo)(()=>a7(rv?[...ry.blocks,...rv.content??[]]:ry.blocks,n8,t2,ry.priorCiHeads,rs,ry.jobNotices),[ry,rv,n8,t2,rs]),rw=(0,i.useMemo)(()=>t2?{...st(ry.blocks,n8,rs),span:so(tX,ry.start+1,tX.length)}:null,[t2,ry,n8,rs,tX]),rk=(0,i.useMemo)(()=>rw?{...rw,flow:rb,latest:!0}:null,[rw,rb]),rj=eC&&(tb?.kind==="running_tools"||(rv?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rS=nQ(tX,rv,tt?.provider),rC=rS.provider,rN=rS.credentialId;(0,i.useEffect)(()=>{if(!rj)return;let e=ec();e&&eo.current!==e.turn&&el.current!==e.turn&&(eo.current=e.turn,ef("working",e,rC,rN))},[rj,rC,rN,ec,ef]);let[rI,rT]=(0,i.useState)(null),rM=(0,i.useCallback)(e=>{rT(e)},[]),rR=(0,i.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),rE=(0,i.useMemo)(()=>{let e=[eC&&!rf&&tb?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}(tb,V):null,eN&&!eI?V("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eC,rf,tb,eN,eI,V]);(0,i.useEffect)(()=>{if(!rI)return void S?.(null);let e=[],t=[],n=0;if(rf&&rx.length>0){let r=rI.messages.length+e.length;for(let i of(e.push(rf),rx))t.push({idx:r,blocks:i}),n+=eq(i)}if(rR&&(t.push({idx:rI.messages.length+e.length}),e.push(rR)),0===t.length)return void S?.(rE?{...rI,status:rE}:rI);let r=-1;for(let e=rI.messages.length-1;e>=0;e--)if(e6(rI.messages[e])){r=e;break}let i=rI.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),S?.({...rI,groups:i,messages:[...rI.messages,...e],status:rE})},[rI,rx,rf,rR,rE,S]),(0,i.useEffect)(()=>()=>S?.(null),[S]);let r$=tg.filter(e=>"belowEditor"!==e.placement),rL=tg.filter(e=>"belowEditor"===e.placement);return ew?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ew}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":t7,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nJ,onDragOver:nZ,onDragLeave:nY,onDrop:n1,children:[t7?(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:V("chat.loadingSession")})}):null,nG&&!t2&&(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:V("chat.attachFile")})}),tf&&(0,r.jsx)(uW,{request:tf,onInput:tv}),ra&&!N?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[860px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(X,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.63"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.12.6"]})]})]})]}),rs&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":V("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:V("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tN(rs)||rs}),(0,r.jsx)("code",{title:rs,children:rs}),(0,r.jsx)("p",{children:V("chat.emptyProjectHint")})]}),w&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:w,children:V("chat.openSessionList")})]}),(0,r.jsx)(uA,{notices:tu,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[N&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:N}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!N,style:{display:N?"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:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(lR,{open:nN,onClose:n$,containerRef:tR,index:nR,renderedStart:no,renderedEnd:nl,contentKey:tX,onReveal:nE,onProgrammaticScroll:tC,focusRequest:nT,t:V}),nS&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:V("chat.jumpMissing")}),(0,r.jsx)(uA,{notices:tu,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tR,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(uP,{widgets:r$}),(0,r.jsxs)(sC.Provider,{value:n6,children:[(0,r.jsx)(lB,{utterances:ri,children:(0,r.jsx)(uE,{messages:tX,entryIds:ej,toolResultsMap:n8,modelNames:eM,messageCwd:rs,onOpenFile:C,sessionBusy:t2,isNew:tw,isStreaming:eS.isStreaming,handleFork:tL,forkingEntryId:eZ,handleNavigate:tP,handleEditContent:ey,sessionId:e?.id??tT.current??void 0,main:nt,dispatchSlots:nr,compactedDispatch:ni,openRequest:ta?.openRequest??null,process:nn,startIndex:no,endIndex:nl,sentinelRef:np,laterSentinelRef:nh,flashItem:nm,t:V,cues:Q,cueFollowRef:t4,onProcessLogChange:rM})}),!nd&&eS.isStreaming&&eS.streamingMessage&&rg.length>0&&(0,r.jsx)(o5,{message:eH(eS.streamingMessage,rg),sessionId:e?.id??tT.current??void 0,isStreaming:!0,modelNames:eM,cwd:rs,onOpenFile:C}),!nd&&rk&&(0,r.jsx)(oy,{summary:rk,live:!0,onOpenFile:C})]}),nU&&(0,r.jsx)(lF,{onDismiss:nH,t:V}),(0,r.jsx)("div",{ref:tM})]})})}),(0,r.jsx)(lE,{questions:nL,containerRef:tR,layoutKey:nP,onJump:nb,label:V("chat.questionRail")}),(t2&&tj||nd)&&(0,r.jsxs)("button",{type:"button",onClick:nk,"aria-label":V("chat.jumpToBottom"),title:V("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:G?44:void 0,borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),V("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rd,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tp&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,r.jsx)(uz,{request:tp,onRespond:tx,onActivity:e=>void tv(e,"activity"),delivery:th})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(lA,{compaction:e3,t:V}),(0,r.jsx)(uL,{goal:tI,t:V}),(0,r.jsx)(uP,{widgets:rL}),(n7||rb.steps.length>0)&&!(K&&G)&&(0,r.jsx)(dD,{phases:n7,flow:rb,busy:t2})]})}),rh,(0,r.jsx)(dW,{statuses:tm})]})]})}function uL({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nI(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nI(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 uP({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 uA({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function uF({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,F.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:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:a},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 uz({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),f=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let m=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(uF,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{f(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},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:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{f();let n=e.target.value;d(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(uF,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(nc,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(uF,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m()},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&&m()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function uW({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),o=e$(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eA[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":" ":eP[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eL(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function uD({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,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"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),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"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var uO=n(50640),uH=n(73620);let uU=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function u_(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 uB=["tags","categories","keywords","tag","category"];function uq({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=uB.find(t=>Array.isArray(e[t])),s=a?e[a].map(u_).filter(Boolean):[],o=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),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=u_(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))})]})}var uV=n(8745);let uK=(0,i.createContext)(null),uG=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),uJ=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),uZ=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10 3-5 5 5 5"})}),uY=(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"})}),uX=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function uQ({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:f}){let{t:m}=(0,F.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uZ})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,l&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:l})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(uV.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,r.jsxs)(uV.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(uV.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(uV.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":m("panel.more"),title:m("panel.more"),children:(0,r.jsx)(o.In,{size:"16px",svg:uX})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":m("panel.more"),children:(0,r.jsx)(c.k.ScrollArea,{children:(0,r.jsx)(c.k.Group,{children:h.map(e=>(0,r.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(u0,{}),f&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:f.onClick,"aria-label":f.label,title:f.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uY})})]})}function u0({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,i.useContext)(uK);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(o.In,{size:"16px",svg:n.expanded?uJ:uG})})}let u1="cuelo-html-pick",u2="cuelo-html-pick-exit";function u8(e,t){return"string"==typeof e&&e.length<=t}function u4(e){return"number"==typeof e&&Number.isFinite(e)}function u5({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:o}){let{t:l}=(0,F.s)(),c=(0,i.useRef)(null),d=(0,i.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
19
+ ${n}`:e:n,images:s,documents:o}}function cA(e,t,n){if(e===t)return n?cM(n):cE(t);let r=cE(e),i=n&&!cR(n)?cM(n):r??(n?cM(n):null),a=cE(t),s=cf.get(e);if(cf.delete(e),s&&!cf.has(t)&&cf.set(t,s),cL(e),!i)return a;let o=a?cP(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return c$(t,o),cM(o)}function cF(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function cz(e){cI();let t=cf.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),cf.set(e,t)),t}function cW(e){let t=cF(cu.get(e)?.documents),n=t.length?cz(e):cf.get(e);for(let[e,n]of cb){for(let e of t)n.delete(e);0===n.size&&cb.delete(e)}let r=`${n??""}|${t.join(",")}`;ck.get(e)!==r&&(0!==t.length||n?ck.set(e,r):ck.delete(e),cq())}async function cD(e){let t=cz(e);cy.set(t,(cy.get(t)??0)+1),await cj.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(cy.get(t)??1)-1;if(r>0?cy.set(t,r):cy.delete(t),e){let n=cb.get(t)??new Set;n.add(e),cb.set(t,n)}cm.set(t,cg),cq()}}}function cO(e,t){let n=cw.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&cw.delete(e),[...n].sort()}async function cH(){if(!cS)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of cf)t(n,cF(cu.get(e)?.documents));for(let{draftId:e,ids:n}of cx.values())t(e,n);for(let[e,n]of cb)t(e,n);for(let e of cm.keys())t(e,[]);for(let e of cw.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(cy.has(e))return!1;let n=cm.get(e);return cO(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=cy.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=cO(r,i),a=cS(r,i,e).then(()=>{0===i.length?cm.delete(r):cm.set(r,i.join(","));let t=cw.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&cw.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});cj.set(r,a),await a,cj.get(r)===a&&cj.delete(r)}n?function(){if(cB)return;cB=!0;let e=setTimeout(()=>{cB=!1,cq()},c_);"object"==typeof e&&"unref"in e&&e.unref(),c_=Math.min(2*c_,6e4)}():c_=cU}let cU=5e3,c_=5e3,cB=!1;function cq(){if(cS){if(cC){cN=!0;return}cC=Promise.resolve().then(cH).finally(()=>{cC=null,cN&&(cN=!1,cq())})}}let cV=Math.floor(Number.MAX_SAFE_INTEGER/1048576),cK=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function cG(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=cV}async function cJ(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!cG(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:cG((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:cK.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:cK.autoCleanupEnabled,orphanGraceDays:7}}async function cZ(e={}){return cJ(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function cY(e){return cJ(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function cX(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 cQ(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function c0(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}function c1(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function c2(e,t,n){let r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`;return`${a}${s} `}let c8="omp-web:model-picks";function c4(){try{let e=JSON.parse(window.localStorage.getItem(c8)??"{}");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 c5(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*s)),c=Math.max(0,e-a-s),d=Math.max(0,n-t-a-s),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 c6(e,t,n){return Math.min(e*t,n)}function c3(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,i.useState)({side:c??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),d=c5(i.top,i.bottom,n,c6(n,r,a),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,s,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 c7=n(14755);let c9="omp-web:model-roles-expanded";async function de(e,t,n,r,i,a,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...dm,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(a&&(!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}}function dt(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let dn=["off","default","full"],dr={off:"none",default:"default",full:"full"},di=c7.IN.join(" \xb7 "),da=c7.C1.filter(e=>!c7.IN.includes(e)).join(" \xb7 ");function ds(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let dl=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),dc=0,dd={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function du(e,t){return dl.compare(e.name||e.modelId,t.name||t.modelId)||dl.compare(e.provider,t.provider)||dl.compare(e.modelId,t.modelId)}let dp=["auto","off","minimal","low","medium","high","xhigh","max"],dh=["low","medium","high","xhigh"],df={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},dm=[{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"}],dg=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],dx={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},dv={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function dy(e,t,n){let r=e.name.toLowerCase(),i=db(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function db(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function dw(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function dk(e){return{data:e.data,mimeType:e.mimeType}}function dj(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function dS(e){return(e??[]).filter(nj).slice(0,10).map(dj)}let dC=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,dN="\n\nTranscript of the audio ";function dI(e){return o$(e).map(e=>{let t=oD(e),n="audio"===t&&e.attachmentId&&!e.text.includes(dN)?dC.exec(e.text):null;return{...e,id:++dc,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function dT({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function dM(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class dR extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let dE="composer:unkeyed";async function d$(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new dR("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function dL(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function dP({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 dA({error:e}){return e?(0,r.jsx)(dP,{tone:"error",title:"Model error",body:e}):null}function dF({warnings:e}){return e&&0!==e.length?(0,r.jsx)(dP,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let dz=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:f,onMainPresetChange:m,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:y,onCompact:b,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:I,effectiveThinkingLevel:T,thinkingCeiling:M,onThinkingLevelChange:R,availableThinkingLevels:E,thinkingLevelMap:$,fastMode:L=null,fastModeBusy:P=!1,onFastModeToggle:A,retryInfo:z,deliveryRows:W=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,slashCommands:_,slashCommandsLoading:B,onLoadSlashCommands:q,onBuiltinCommand:V,soundEnabled:K,onSoundToggle:G,onAudioUnlock:J,onPromptWithStreamingBehavior:Z,draftKey:Y,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},en){let er,ei,ea,es,eo,el,ec,ed,eu,ep,{t:eh}=(0,F.s)();rY();let{st:ef}=rQ(),em=W.some(e=>e.removable),eg=U(),[ex,ev]=(0,i.useState)(()=>Y?cE(Y)?.value??"":""),[ey,eb]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{ey&&eN(c4())},[ey]);let[eI,eT]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(ey)try{eT("1"===window.localStorage.getItem(c9))}catch{}},[ey]);let eM=()=>{eT(e=>{let t=!e;try{window.localStorage.setItem(c9,t?"1":"0")}catch{}return t})},[eR,eE]=(0,i.useState)(!1),[e$,eL]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(!1),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(!1),[eU,e_]=(0,i.useState)(()=>Y?dS(cE(Y)?.images):[]),[eB,eq]=(0,i.useState)(()=>Y?dI(cE(Y)?.documents):[]),[eV,eK]=(0,i.useState)(null),eG=(0,i.useMemo)(()=>eB.filter(e=>"ready"===e.status),[eB]),eJ=eB.some(e=>"ready"!==e.status||dt(e)),eZ=eB.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(dN))),eY=ex.trimStart(),eX=0===eU.length&&0===eB.length&&eY.startsWith("!"),eQ=eX&&eY.startsWith("!!"),[e0,e1]=(0,i.useState)(!1),[e2,e8]=(0,i.useState)(0),[e4,e5]=(0,i.useState)(null),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(0),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(0),[ti,ta]=(0,i.useState)(null),[ts,to]=(0,i.useState)(!1),[tl,tc]=(0,i.useState)(null),[td,tu]=(0,i.useState)(null),tp=X&&td?.cwd===X?td.values:{},th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tm=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(null),tj=(0,i.useRef)(null),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(0),tN=(0,i.useRef)(!1),tI=(0,i.useRef)([]),tT=(0,i.useRef)([]),tM=(0,i.useRef)([]),tR=(0,i.useRef)(null),tE=(0,i.useRef)(null),t$=(0,i.useRef)(Y),tL=(0,i.useRef)(ex),tP=(0,i.useRef)(eU),tA=(0,i.useRef)(0),tF=(0,i.useRef)(eB);tL.current=ex,tP.current=eU,tF.current=eB,(0,i.useImperativeHandle)(en,()=>({insertIfEmpty(e){let t=th.current;(t?t.value:ex).trim()||(tL.current=e,ev(e),e5(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=th.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ex,tP.current.length,tA.current,tF.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"),oA(t)?.message??t),a=dS("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 nj(r)?[r]:[]})),s=dI((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),oA(n)?.documents??[]));tL.current=i,tP.current=a,tF.current=s,ev(i),e5(null),tt(!1),e_(e=>(e.forEach(dL),a)),eq(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(t$.current!==e)return void cA(e,t);let n={value:tL.current,images:tP.current.map(dk),documents:tF.current.filter(e=>"ready"===e.status).map(dT)},r=cA(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(t$.current=t,i)return;let a=dS(r.images),s=dM(dI(r.documents),tF.current),o=r.value;tL.current=o,tP.current=a,tF.current=s,ev(o),e_(e=>(e.forEach(dL),a)),eq(s),e5(null),tt(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=t$.current,a=r??i,s=a===i,o=!s&&a?cE(a):null,l=cP(e,t,s?tL.current:o?.value??"",s?tP.current.map(dk):o?.images??[],n,s?tF.current.filter(e=>"ready"===e.status).map(dT):o?.documents??[]);if(a&&c$(a,l),!s)return;let c=t?.length?[...dS(t).slice(0,Math.max(0,10-tP.current.length)),...tP.current].slice(0,10):tP.current,d=dM(dI(l.documents),tF.current);tL.current=l.value,tP.current=c,tF.current=d,ev(l.value),e5(null),tt(!1),t?.length&&e_(e=>{let n=Math.max(0,10-e.length),r=dS(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tP.current=i,i}),eq(d),requestAnimationFrame(()=>{let e=th.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=th.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",o=i+s+e+a;tL.current=o,ev(o),e5(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tX(e)}}));let tz=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tP.current.length-tA.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eK(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:oF(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eK(eh("chat.attachImageLimit",{count:10})),i.length){tA.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)})));e_(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(dL);let r=[...t,...n];return tP.current=r,r})}finally{tA.current-=i.length}}},[eh]),tW=(0,i.useCallback)(async e=>{for(let t of e){let e=oT(t);if(!e)continue;if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eK(eh("chat.attachTooLarge",{name:t.name,limit:oF(8388608)}));continue}if(tF.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eK(eh("chat.attachTotalTooLarge",{limit:oF(0x1000000)}));continue}let n={id:++dc,name:t.name,mimeType:oC[e],size:t.size,text:"",status:"extracting"},r=[...tF.current,n];tF.current=r,eq(r);try{let e=await oL(t);if(tF.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new oS("text_too_large","Total extracted text exceeds 240000 characters");let r=tF.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tF.current=r,eq(r)}catch(i){let e=tF.current.some(e=>e.id===n.id),r=tF.current.filter(e=>e.id!==n.id);if(tF.current=r,eq(r),!e)continue;i instanceof oS?"text_too_large"===i.code?eK(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eK(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eK(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eK(eh("chat.attachPasswordProtected",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tD=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.id===e))return!1;let n=t?tF.current.map(n=>n.id===e?t:n):tF.current.filter(t=>t.id!==e);return tF.current=n,eq(n),!0},[]),tO=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.attachmentId===e))return!1;let n=tF.current.map(n=>n.attachmentId===e?t(n):n);return tF.current=n,eq(n),!0},[]),tH=(0,i.useCallback)((e,t,n)=>{if(!e||e===t$.current)return;let r=cE(e);r?.documents.some(e=>e.attachmentId===t)&&c$(e,{...r,documents:dI(r.documents).map(e=>e.attachmentId===t?n(e):e).map(dT)})},[]),tU=(0,i.useRef)(new Map),t_=(0,i.useRef)(new Map),tB=(0,i.useRef)(new Set),tq=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=oO({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tV=(0,i.useCallback)(e=>e instanceof dR&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof dR&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tK=(0,i.useCallback)(async(e,t)=>{let n=t$.current,r=tF.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;t_.current.get(e)?.abort();let a=new AbortController;t_.current.set(e,a),tO(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await d$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new dR("Invalid transcription result",null,null,null);let i=r.transcript;tO(e,e=>tq(e,i,tF.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tH(n,e,e=>tq(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tO(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof dR&&"confirmation_required"===n.code)return void tG.current?.(e);let t=tV(n);tO(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t_.current.get(e)===a&&t_.current.delete(e)}},[eh,tV,tO,tH,tq]),tG=(0,i.useRef)(null),tJ=(0,i.useCallback)(async e=>{let t;t_.current.get(e)?.abort();let n=new AbortController;t_.current.set(e,n),tO(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new dR("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await d$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tO(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tV(t);tO(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t_.current.get(e)===n&&t_.current.delete(e)}t.requiresConfirmation?tO(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tK(e,!1)},[tK,tV,tO]);tG.current=tJ;let tZ=(0,i.useCallback)(e=>{let t=t_.current.get(e);t?t.abort():tO(e,e=>({...e,transcription:{state:"skipped"}}))},[tO]),tY=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++dc,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tF.current,i];tF.current=a,eq(a);let s=(e,t)=>{let n=tF.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?oE("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?oE("utf-16be",t.subarray(2)):t.includes(0)?null:oE("utf-8",t)??oE("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tD(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await cZ().catch(()=>cK)).uploadLimitMb),r.size>n){tD(i.id,null)&&eK(eh("chat.attachStoredTooLarge",{name:r.name,limit:oF(n)}));continue}let o={...i,stored:t,status:"uploading",size:0};if(!tD(i.id,o))continue;let l=t$.current??dE,c=await cD(l),d=null,u=new AbortController;tU.current.set(i.id,u);try{if(tB.current.has(i.id))continue;let e=await oH(r,{sessionId:Q,draftId:c.draftId,signal:u.signal}),n=tF.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=oO({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tD(i.id,null)&&eK(eh("chat.attachTotalTooLarge",{limit:oF(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tD(i.id,h))d=e.id;else if(!tB.current.has(i.id)&&l!==t$.current){let t=cE(l)??{value:"",images:[],documents:[]};c$(l,{...t,documents:[...t.documents,dT(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tD(i.id,null)&&eK(eh("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tU.current.delete(i.id),c.end(d)}d&&"audio"===t&&tF.current.some(e=>e.attachmentId===d)&&tJ(d)}},[tD,tJ,Q,eh]),tX=(0,i.useCallback)(async e=>{eK(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==oT(a)?n.push(a):oR(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tz(t),tW(n.filter(e=>e.size<=8388608)),tY(r,"audio"),tY([...i,...a],"file")])},[tW,tY,tz]),tQ=(0,i.useCallback)(e=>{e_(t=>{let n=[...t],[r]=n.splice(e,1);return r&&dL(r),tP.current=n,n})},[]),t0=(0,i.useCallback)(e=>{let t=tF.current.find(t=>t.id===e);if(tB.current.add(e),tU.current.get(e)?.abort(),t?.attachmentId){t_.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of cb)t.delete(n)&&(0===t.size&&cb.delete(e),cq())}let r=tF.current.filter(t=>t.id!==e);tF.current=r,eq(r)},[]),t1=(0,i.useCallback)(()=>{tP.current=[],e_(e=>(e.forEach(dL),[]))},[]),t2=(0,i.useCallback)(()=>{tF.current=[],eq([])},[]),t8=(0,i.useCallback)(()=>{tL.current="",ev(""),e5(null),tt(!1),Y&&cL(Y),t$.current&&t$.current!==Y&&cL(t$.current),t1(),t2(),eK(null),th.current&&(th.current.style.height="auto")},[t2,t1,Y]);(0,i.useEffect)(()=>{Y&&t$.current===Y&&c$(Y,{value:ex,images:eU.map(dk),documents:eG.map(dT)})},[eU,Y,eG,ex]),(0,i.useEffect)(()=>{let e=t$.current;if(e===Y)return;e&&c$(e,{value:tL.current,images:tP.current.map(dk),documents:tF.current.filter(e=>"ready"===e.status).map(dT)});let t=Y?cE(Y):null;t$.current=Y;let n=t?.value??"",r=dS(t?.images),i=dI(t?.documents);tL.current=n,tP.current=r,tF.current=i,ev(n),e5(null),tt(!1),e_(e=>(e.forEach(dL),r)),eq(i)},[Y]),(0,i.useEffect)(()=>{let e=th.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tP.current.forEach(dL)},[]);let t4=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=cF(t);if(0===n.length)return()=>{};let r=++cv;return cx.set(r,{draftId:cz(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=cx.get(r);if(t){if(cx.delete(r),"accepted"===e){let e=cw.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);cw.set(t.draftId,e)}cq()}}}(t$.current??dE,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t5=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eY.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eU.length&&!eG.length||o||eJ)return;J?.();let i=eU.length?eU:void 0,a=eG.length?eG:void 0;if(r.startsWith("/")){await de(r,_,V,t=>t4(a,()=>e(t,i,a)),eK,!!(i||a),q)&&t8();return}t8(),t4(a,()=>e(r,i,a))},[ex,eY,eU,eG,eJ,o,V,_,q,e,t8,J,t4]),t6=eY.startsWith("/")&&!/\s/.test(eY.slice(1))?eY.slice(1).toLowerCase():null,t3=(()=>{if(null===t6)return[];let e=[...o?[]:dm,..._??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=db(e,eh).toLowerCase();return t.includes(t6)||n.includes(t6)}).sort((e,t)=>{let n=dy(e,t6,eh)-dy(t,t6,eh);return 0!==n?n:dv[e.source]-dv[t.source]||dl.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t7,groups:t9}=(er=0,{commands:(ei=dg.map(e=>{let t=t3.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!dw(e,tp)),...t.filter(e=>dw(e,tp))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),ne=1===t3.length?eh(t6?"chat.match":"chat.command"):eh(t6?"chat.matches":"chat.commands",{count:t3.length}),nt=!!ex.trim(),nn=!eJ&&(nt||eU.length>0||eG.length>0),nr=(0,i.useCallback)((e,t)=>{if(!X)return void e5(null);let n=t??e.length;e5(cX(e.slice(0,n)))},[X]),ni=e4?.query??null,na=i.useMemo(()=>null!==ni&&ti&&ti.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:c0(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:c0(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||cQ(e.entry.path)-cQ(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(ti.entries,ni):[],[ni,ti,X]),ns=!!(ni&&ti?.truncated&&ti.cwd===X);(0,i.useEffect)(()=>{if(!ns||!X||!ni)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(ni)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tc({cwd:X,query:ni,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ns,ni,X]);let no=ns&&null!==tl&&tl.cwd===X&&tl.query===ni,nl=no?tl.matches:na,nc=null===e4?null:`${e4.start}:${+!!e4.quoted}:${e4.query}`;(0,i.useEffect)(()=>{if(null===nc){e3(!1),e9(0);return}e3(!0),e9(0)},[nc]);let nd=null!==e4,nu=c3(tk,te,{viewportFraction:.44,cap:360}),np=c3(tk,e0,{viewportFraction:.56,cap:460}),nh=c3(tk,e6,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!X)return;let e=tR.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tE.current===X||(tE.current=X,to(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{ta({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>cQ(e.path)-cQ(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tR.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tR.current=null}).finally(()=>{tE.current=null,to(!1)}))},[nd,X]);let nf=(0,i.useCallback)(e=>{if(!e4)return;let t=th.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e4.start),i=ex.slice(n);e4.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e4.quoted),s=r+a.text+i,o=r.length+a.cursorOffset;ev(s),e5(cX(s.slice(0,o))),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e4,ex]);(0,i.useEffect)(()=>{e7>=nl.length&&e9(Math.max(0,nl.length-1))},[nl.length,e7]),(0,i.useEffect)(()=>{tT.current.length=nl.length},[nl.length]),(0,i.useEffect)(()=>{e6&&tT.current[e7]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e7,e6]),(0,i.useEffect)(()=>{tn>=D.length&&tr(Math.max(0,D.length-1))},[D.length,tn]),(0,i.useEffect)(()=>{tM.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{te&&tM.current[tn]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tn,te]);let nm=(0,i.useCallback)(e=>{tL.current=e,ev(e),tt(!1),tr(0),e5(null),requestAnimationFrame(()=>{let t=th.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),ng=(0,i.useCallback)(e=>{let t=`/${e.name} `;tL.current=t,ev(t),e1(!1),e8(0),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eY.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eJ||!i&&0===eU.length&&0===eG.length?null:{message:i,images:eU.length?eU:void 0,documents:eG.length?eG:void 0};if(!s)return;J?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await de(i,_,V,e=>{if(!Z)throw Error("Cannot queue this command while the session is busy.");t4(s.documents,()=>Z(e,o,s.images,s.documents))},eK,!!(s.images?.length||s.documents?.length),q)&&t8();return}t8(),"steer"===e&&n?t4(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t4(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eY,eU,eG,eJ,_,q,V,Z,n,a,t8,J,t4]),nv=(0,i.useCallback)(e=>{let t=t7.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e2-1);if("right"===e)return Math.min(t,e2+1);let n=tI.current[e2];if(!n)return"down"===e?Math.min(t,e2+1):Math.max(0,e2-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===e2)continue;let t=tI.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-a;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<o&&(s=n,o=c)}return s>=0?s:"down"===e?Math.min(t,e2+1):Math.max(0,e2-1)},[t7.length,e2]),ny=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tC.current<100,s=tS.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(te&&!s){if("ArrowDown"===e.key){e.preventDefault(),tr(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tr(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tt(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[tn]){e.preventDefault(),nm(D[tn]);return}}if(e0&&null!==t6){if("ArrowDown"===e.key){e.preventDefault(),e8(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e8(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e8(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e8(nv("left"));return}if("Escape"===e.key){e.preventDefault(),e1(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t7[e2]){e.preventDefault(),ng(t7[e2]);return}}if(e6&&null!==e4&&!s){if("ArrowDown"===e.key){e.preventDefault(),e9(e=>Math.min(Math.max(0,nl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e9(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e3(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nl[e7]){e.preventDefault(),nf(nl[e7]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===ex.trim().length){e.preventDefault(),e1(!1),e3(!1),tr(D.length-1),tt(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(n||a)?nx(n?"steer":"followup"):t5())},[o,n,a,t,e0,t6,t7,e2,ng,nx,t5,nv,e6,e4,nl,e7,nf,te,D,tn,nm,ex]),nb=(0,i.useCallback)(()=>{let e=th.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nw=(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(),tX(t))},[tX]);(0,i.useEffect)(()=>{if(null===t6){e1(!1),e8(0),tN.current=!1;return}e1(!0),e8(0),!tN.current&&q&&(tN.current=!0,Promise.resolve(q()).catch(()=>{tN.current=!1}))},[t6,q]),(0,i.useEffect)(()=>{if(!e0||!X)return;let e=!1;return tu({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tu({cwd:X,values:n})}).catch(()=>{e||tu({cwd:X,values:{}})}),()=>{e=!0}},[e0,X]),(0,i.useEffect)(()=>{e2>=t7.length&&e8(Math.max(0,t7.length-1))},[t7.length,e2]),(0,i.useEffect)(()=>{tI.current.length=t7.length},[t7.length]),(0,i.useEffect)(()=>{e0&&tI.current[e2]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e2,e0]);let nk=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(du):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(du),nS=g??null,nC=n5.find(e=>e.alias===nS)?.provider??null,nN=nC?nk.filter(e=>e.provider===nC):nk,nT=(ea=ej.trim().toLocaleLowerCase())?nN.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):nN,nM=nN.length>8,nR=[];for(let e of nT){let t=nR.find(t=>t.provider===e.provider);t?t.options.push(e):nR.push({provider:e.provider,options:[e]})}let nE=nC?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),n$=l?nE.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,nL=ej.trim()?[]:nN.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nP=(e,t,n)=>{let i=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(eb(!1),eS(""),!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}(c4(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(c8,JSON.stringify(r))}catch{}eN(r),f?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nA=l?nk.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,nF=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nz=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${nI(S.tokensBefore)} -> ${nI(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:nI(nF)})})`:null,nW=e=>{let t=$?.[e];return null!=t&&t!==e?t:null},nD="auto"===(es=I??"auto")?M?`auto ≤ ${nW(M)??M}`:"auto":$?$[es]??es:es,nO=(I??"auto")==="auto"&&T&&"auto"!==T?$?.[T]??T:null,nH=R&&nO?eh("chat.currentReasoning",{level:nO}):null,nU=e=>!E||E.includes(e),n_=[{level:"auto",ceiling:null},...dh.filter(nU).map(e=>({level:"auto",ceiling:e})),...dp.filter(e=>"auto"!==e&&nU(e)).map(e=>({level:e,ceiling:null}))],nB=Object.entries(dr).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tf.current&&!tf.current.contains(e.target)&&tm.current&&!tm.current.contains(e.target)&&(eb(!1),eS("")),tg.current&&!tg.current.contains(e.target)&&tx.current&&!tx.current.contains(e.target)&&eE(!1),tv.current&&!tv.current.contains(e.target)&&eA(!1),ty.current&&!ty.current.contains(e.target)&&ez(!1),tb.current&&!tb.current.contains(e.target)&&eH(!1),!tw.current||tw.current.contains(e.target)||th.current?.contains(e.target)||tt(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eH(!1)},[eg]);let nq=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eU.length||eB.length?" is-active":""}`,onClick:()=>tj.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eU.length||eB.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=eU.length||eB.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eU.length||eB.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"})]})}),nV=m&&n5.length>0?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eR?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eL({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eR,onKeyDown:e=>{"Escape"===e.key&&eR&&(e.stopPropagation(),eE(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eg?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eR&&e$&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=c5(e$.top,e$.bottom,e,c6(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-e$.top+6}:{top:e$.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:e$.left,width:"max-content",minWidth:e$.width};return(0,r.jsx)("div",{ref:tx,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eE(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:n5.map(e=>{let t=e.alias===nS;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eE(!1),m({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:rv(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:rp(e.alias)}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,nK=R?(0,r.jsxs)("div",{ref:ty,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eF?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eD({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(!1),ez(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eF,onKeyDown:e=>{"Escape"===e.key&&eF&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level:nD}),"aria-label":eh("chat.changeReasoning",{level:nD}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eF?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eF?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nD})]}),eF&&eW&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=c5(eW.top,eW.bottom,e,c6(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eW.top+6}:{top:eW.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eW.left,width:"max-content",minWidth:Math.max(180,eW.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),ty.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:n_.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nW(i),s=t?`auto ≤ ${a??t}`:a??e,o=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(df[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{ez(!1),R(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,nG=A?(eo=P?eh("chat.fastModeBusy"):null===L?eh("chat.fastModeUnknown"):L.active?eh("chat.fastModeActive"):L.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),el=P||o||y,ec=L?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${L?.active?" is-active":""}`,onClick:A,disabled:el,"aria-pressed":null===L?void 0:L.enabled,"aria-busy":P||void 0,title:eo,"aria-label":eo,style:{flexShrink:0,opacity:o?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:L?.active?"var(--accent)":"none",stroke:ec?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===L?"3 2":void 0,style:{opacity:ec&&!L?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,nJ=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nx("steer"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nn?"var(--warning)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nZ=void 0!==G?(0,r.jsx)(ce,{soundEnabled:K??!0,onToggle:G}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tj,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tX(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(dA,{error:p}),(0,r.jsx)(dF,{warnings:h}),W.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ef("delivery.title",{count:W.length})}),O&&em&&(0,r.jsxs)("button",{onClick:O,title:eh("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(l3,{rows:W,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("steer"===e?"steering":"followUp",t):void 0})]}),z&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:z.attempt,max:z.maxAttempts}),z.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",z.errorMessage]})]}),nz&&(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"})}),nz]}),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}),eV&&(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:eV}),(0,r.jsx)("button",{type:"button",onClick:()=>eK(null),"aria-label":eh("i18n.close"),title:eh("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eU.length>0||eB.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eU.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tQ(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}`)),eB.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||dt(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):ie(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):dd[e.mimeType]," \xb7 ",oF(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t0(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eZ.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eZ.map(e=>{let t,n,i,a,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?eh("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:l?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:l.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,r.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[l.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tK(o,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tJ(o),children:eh(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tk,style:{position:"relative",minWidth:0},children:[te&&D.length>0&&(0,r.jsxs)("div",{ref:tw,style:{position:"absolute",left:0,right:0,...ds(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nu.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===tn;return(0,r.jsxs)("button",{ref:e=>{tM.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>tr(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}`)})})]}),e0&&null!==t6&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ds(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:B?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:ne})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:10},children:B||0!==t3.length?t9.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(dx[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===e2,i=dw(e,tp);return(0,r.jsxs)("button",{ref:e=>{tI.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ng(e)},onMouseEnter:()=>e8(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),db(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:db(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e6&&null!==e4&&(ed=ts&&(!ti||ti.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=ti?.truncated&&!no?e4.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ds(nh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nh.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ed?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nh.maxHeight-34),overflowY:"auto",padding:4},children:ed||0!==nl.length?nl.map((e,t)=>{let n=t===e7,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tT.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>e9(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)(r3,{size:14}):ie(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ns&&!no?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eX?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eX?"var(--tool-bg)":o&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:th,value:ex,onChange:e=>{tL.current=e.target.value,ev(e.target.value),tt(!1),nr(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nr(t.value,t.selectionStart)},onKeyDown:ny,onCompositionStart:()=>{tS.current=!0},onCompositionEnd:e=>{tS.current=!1,tC.current=Date.now();let t=e.currentTarget;nr(t.value,t.selectionStart)},onInput:nb,onPaste:nw,placeholder:o&&(n||a)?eh("chat.steerPlaceholder"):o?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),o?eg?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nJ}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t5,disabled:!nn,"aria-busy":eJ||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eJ?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:nn?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eX&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eQ?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eQ?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!o)&&nq,!eg&&nV,!(eg&&o)&&(nk.length>0||nA||p)&&f&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.jsxs)("button",{className:`composer-chip${ey?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(e=>(e&&eS(""),!e))},disabled:o||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:ey?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ey?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":nk.length>0?"Change model":"No available models",children:[y?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nA??(nk.length>0?"Select model":"No models")})]}),ey&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=c5(ew.top,ew.bottom,e,c6(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tm,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),eb(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nL.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),nL.map(({option:e,count:t})=>nP(e,"frequent",t))]}),nE.length>0&&!ej.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nL.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eI,"aria-controls":"model-role-rows",onClick:eM,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eI?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:eh("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nE.length}),n$&&(0,r.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:n$.tag??n$.role.toUpperCase()}),n$.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eI,children:nE.map(e=>{let t=n$?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{eb(!1),eS(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eh("chat.allModels")})]}),0===nR.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):nR.map((e,t)=>(0,r.jsxs)("div",{children:[nR.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=>nP(e,"all"))]},e.provider))]})]})})()]}),eg&&o&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nJ}),!eg&&nK,!eg&&nG,!eg&&nH&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nH}),(0,r.jsx)(cd,{sessionId:Q})]}),(0,r.jsxs)("div",{ref:tb,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eO?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eO?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eO?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eg&&(0,r.jsxs)(r.Fragment,{children:[o&&nq,nV,nK,nG]}),!o&&N&&(0,r.jsxs)("div",{ref:tv,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eP?" is-active":""}`,onClick:()=>!o&&eA(e=>!e),disabled:o,title:eh("chat.changeToolPreset")+`: ${nB}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eP?"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=eP?"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:nB})]}),eP&&(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:dn.map(e=>{let t=dr[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:di}):eh("chat.allBuiltInTools",{tools:`${di} + ${da}`});return(0,r.jsxs)("button",{onClick:()=>{eA(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!o&&b&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:b,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?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nZ,eO&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eA(!1),ez(!1),eH(!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:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(cl,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nZ]})]})]})]})});function dW({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=eT(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:eL(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function dD({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:s}=rQ(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=(0,i.useId)(),f=e??[],{currentPhase:m,activeTask:g,remaining:x,completed:v,total:y,percent:b}=tj(f),w=t.steps.length>0,k=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,s);if(0===y&&null===k)return null;let j=y>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${j?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:j?"✓":"›"}),k&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:k}),y>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!k&&m&&(0,r.jsx)("span",{className:"todo-strip-phase",children:m.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:j?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:j?a("todo.progressDone",{percent:b??0,completed:v,total:y}):a("todo.progress",{percent:b??0,completed:v,total:y,remaining:x})})]}),w&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",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)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&w&&(0,r.jsx)(sB,{flow:t,live:n,st:s,id:h}),o&&y>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[f.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[f.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(r4,{task:e},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function dO(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function dH(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function dU(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 d_ extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function dB(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 d_(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let dq="ompweb-update-client-id",dV="ompweb-update-resume-intent-v2",dK="ompweb-update-return-v1",dG="cuelo-restart-return-v1",dJ="ompweb-update-failure-return-v1",dZ="ompweb:update-wake";function dY(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function dX(){let e=sessionStorage.getItem(dq);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(dq,t),t}function dQ(){sessionStorage.removeItem(dV)}function d0(){let e=sessionStorage.getItem(dK);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 d1(e){let t=d0();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(dK,JSON.stringify(n))}catch{}return n}async function d2(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:dX(),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 d8(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=d0();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(dK,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),dQ();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(dZ,{detail:{sessionId:e.sessionId}}))}async function d4(e){let t=function(e){let t=sessionStorage.getItem(dJ);if(!t)return null;sessionStorage.removeItem(dJ);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(dQ(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(dZ,{detail:{sessionId:e.sessionId}})),"failed"):(await d8(e),"resumed")}function d5(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function d6(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 d3(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function d7(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function d9(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function ue(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 ut(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function un(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!e4(r??void 0))return{message:e[n],entryId:r}}return null}let ur=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class ui 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 ua(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function us(e){return new Promise(t=>setTimeout(t,e))}function uo(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ul(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:uo(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:uo(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=uo(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function uc(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 ud(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(uc).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function uu(e){return"user"===e.role?`user:${ud(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 up(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 uh(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function uf(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let um=!1,ug={width:0,height:0},ux=new Set,uv=null;function uy(){let e=window.visualViewport,t=uf();ug.width!==window.innerWidth?ug={width:window.innerWidth,height:window.innerHeight}:t||(ug.height=Math.max(ug.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:ug.height});if(n!==um)for(let e of(um=n,ux))e()}function ub(e){if(ux.add(e),!uv){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,uy()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),uy(),uv=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{ux.delete(e),0===ux.size&&uv&&(uv(),uv=null)}}function uw(){return(0,i.useSyncExternalStore)(ub,()=>um,()=>!1)}let uk={count:50,end:null};function uj(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function uS(e,t,n){let{startIndex:r,endIndex:i}=uj(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function uC({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:nO[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(lW(),{id:"71a4a7cebbc6c842",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 uN(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=(oA(t)?.message??t).trim();return n.length>0?n:null}function uI(e){return`omp-cues:${e}`}function uT(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(uI(e),JSON.stringify(n.slice(-200)))}catch{}}let uM=[];function uR(e){return`omp-web:interrupted-dismissed:${e}`}let uE=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:f,sessionId:m,main:g,process:x,dispatchSlots:v,compactedDispatch:y,openRequest:b,startIndex:w,endIndex:k,sentinelRef:j,laterSentinelRef:S,flashItem:C,t:N,onProcessLogChange:I,cues:T,cueFollowRef:M}){(0,i.useEffect)(()=>{I({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:m})},[I,x,e,t,n,a,s,m]);let R=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[o.idx];if(e?.role!=="assistant")continue;let s=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=e7(i.action);if(!0===e3[e]){let t={kind:"skill",action:e,name:e7(i.name)};n(JSON.stringify(t),t)}continue}let a=e7(i.memory),s=i.skill,o=s?{action:e7(s.action),name:e7(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:o}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...o?{skill:o}:{}})}}(o.blocks??e.content??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:e1,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,N]),E=(0,i.useMemo)(()=>{let r=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(r=t.idx);return function(e,t,n,r,i,a,s=[]){let o=function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&si(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:si(t,n),s=new Map;for(let[n,o]of(e.forEach((e,n)=>{"answer"===e.kind&&s.set(si(t,e.anchorIdx),n)}),s)){if(n===a)continue;let e=i.find(e=>e>n);r.set(o,{from:n+1,to:e??t.length})}return r}(e,t,n),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,n]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(ss(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let i=n.to-1;for(;i>=n.from&&e4(s[i]);)i-=1;if(s[i]!==a.throughEntryId)continue;let o=sn(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sa(t,r,n.from,n.to);c.set(e,{...a.summary,...p?{remaining:se(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,i,a=[]){let s=sn(e,n,r),o=sa(e,t,n,r);return{...st(s,t,i),remaining:o?se(o):null,span:so(e,n,r),flow:a7(s,t,!1,a,i,sr(e,n,r))}}(t,r,n.from,n.to,i,d),latest:e===l})}return c}(g,e,r,n,s,b,t)},[g,e,n,s,l,b,t]),$=w>0,L=k<g.length,P=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&e4(t[v]);)v-=1;let y="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,b=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(o5,{message:x,toolResults:n,modelNames:a,cwd:s,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:y,onEditContent:f,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:m,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${b}-view-${i}`)},A=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[$&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((a,l)=>{let c=w+l,d=y?.position===c?(0,r.jsx)(s3,{calls:y.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,f=p?p.idx:1/0,x=T.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<f}).map(e=>(0,r.jsx)(uC,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),b=h!==u,k=R.get(c),j=k?(0,r.jsx)(o5,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=b?(0,r.jsx)(lq,{turnIndex:u,turnEntryId:t[u],sessionId:m,cwd:s,onOpenFile:o}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx)),j,S,x]},`message-${a.idx}`);let C=tx(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=eH(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:E.get(c)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),y?.position===g.length&&k===g.length&&(0,r.jsx)(s3,{calls:y.calls}),L&&(0,r.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function u$({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsChange:m,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:y,onOpenWorkspaceView:b,onOpenSessionList:w,onOpenMaker:k,selectedMaker:j,onProcessLogChange:S,onOpenFile:C,transcriptReplacement:N,onComposerFocusChange:I,onSessionBusyChange:T,onWaitingChange:M,onAttentionChange:R,soundEnabled:E=!0,onSoundToggle:$,playCueSound:L=async()=>({sticker:null,text:null}),preloadCueSound:P,unlockAudio:A,jumpRequest:z=null,onJumpHandled:W}){var D,O;let H,B,q,{t:V}=(0,F.s)(),K=uw(),G=U(),J=(0,i.useRef)(L);J.current=L;let Z=(0,i.useRef)(null),Y=(0,i.useRef)(P);Y.current=P;let[Q,ee]=(0,i.useState)([]),et=(0,i.useRef)(Q);et.current=Q;let en=(0,i.useRef)(0),er=(0,i.useRef)([]),ei=(0,i.useRef)([]),ea=(0,i.useRef)(null),es=(0,i.useRef)(0),eo=(0,i.useRef)(-1),el=(0,i.useRef)(-1),ec=(0,i.useCallback)(()=>{let e=ea.current?.current;return e?{sessionId:e,turn:es.current}:null},[]),ed=(0,i.useCallback)(e=>ea.current?.current===e.sessionId&&es.current===e.turn,[]),eu=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;en.current=Math.max(en.current+1,Date.now());let i={id:en.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};ee(e=>{let t=[...e,a];return null!==a.anchorEntryId&&uT(n.sessionId,t),t})},[]),ep=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ed(n)&&("working"!==t||el.current!==n.turn);i()&&J.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&eu(e,t,n,r)}).catch(()=>{})},[ed,eu]),eh=(0,i.useCallback)(async(e,t,n)=>{let r=(await rJ(e,t,n))?.alias??null;return r&&Y.current?.(r),r},[]),ef=(0,i.useCallback)((e,t,n,r)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=nX(e[n]),a=0;for(let t=r;t<=n;t++)nX(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(er.current,ei.current);eh(t.sessionId,n,r).then(n=>{ep(n,e,t,i)})},[ep,eh]),[em,eg]=(0,i.useState)(0),ex=(0,i.useRef)([]),ev=(0,i.useCallback)(e=>{if(es.current+=1,null!==nB(e.outcome)){let t=e.sessionId;ex.current.push({completion:e,trigger:t?{sessionId:t,turn:es.current}:null}),eg(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ex.current.splice(0)){let n=nB(e.outcome),r="neutral"===n?null:n;t?ef(r,t,e.provider,e.credentialId):J.current(null,r).catch(()=>{})}},[em,ef]);let ey=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ew,messages:ek,entryIds:ej,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eI,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:e$,modelThinkingLevels:eL,modelThinkingLevelMaps:eP,modelRoles:eA,toolPreset:eF,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,fastMode:eO,fastModeBusy:eU,handleFastModeToggle:eV,retryInfo:eK,contextUsage:eJ,forkingEntryId:eZ,isCompacting:e1,compaction:e3,compactError:e7,compactResult:te,displayModel:tt,modelSwitching:tn,sessionStats:tr,runStateKnown:ti,compactedWork:ta,slashCommands:ts,slashCommandsLoading:to,deliveryRows:tl,subagents:tc,todoPhases:td,notices:tu,extensionDialog:tp,extensionResponse:th,extensionCustomUi:tf,extensionStatuses:tm,extensionWidgets:tg,respondToExtensionUi:tx,sendExtensionCustomInput:tv,isAutoModelSelection:ty,agentPhase:tb,isNew:tw,autoFollowPaused:tj,resumeAutoFollow:tS,pauseAutoFollow:tC,goalStatus:tI,sessionIdRef:tT,messagesEndRef:tM,scrollContainerRef:tR,handleSend:tE,handleAbort:t$,handleFork:tL,handleNavigate:tP,handleModelChange:tA,handleRoleModelChange:tF,handleMainPresetChange:tz,newSessionAccount:tW,handleCompact:tD,handleSteer:tO,handleFollowUp:tH,handlePromptWithStreamingBehavior:tU,handleAbortCompaction:t_,handleRecallQueue:tB,handleRemoveQueuedMessage:tq,handleBuiltinSlashCommand:tV,handleToolPresetChange:tK,handleThinkingLevelChange:tG,loadSlashCommands:tJ,ensureNewSession:tZ,refreshLiveTranscript:tY}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,f=null===t&&null!==r,m=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(m),[v,y]=(0,i.useState)(!f&&!m),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(m?.leafId??null),[S,C]=(0,i.useState)(m?.context.messages??[]),[N,I]=(0,i.useState)(m?.context.entryIds??[]),[T,M]=(0,i.useState)(m?.context.compactedWork??null),[R,E]=(0,i.useReducer)(d6,{isStreaming:!1,streamingMessage:null}),[$,L]=(0,i.useState)(!1),[P,A]=(0,i.useState)(!1),[F,z]=(0,i.useState)(null),[W,D]=(0,i.useState)({}),[O,H]=(0,i.useState)([]),[U,_]=(0,i.useState)(null),[B,q]=(0,i.useState)([]),[V,K]=(0,i.useState)({}),[G,J]=(0,i.useState)({}),[Z,Y]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,eo]=(0,i.useState)(()=>{let e=m?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[el,ec]=(0,i.useState)(),[ed,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[ey,eb]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(m?.contextUsage??null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)(null),[eI,eM]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(null),[e$,eL]=(0,i.useState)(!1),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(null),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(null),eU=(0,i.useRef)(null),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)([]),[eJ,eZ]=(0,i.useState)(!1),[eY,eX]=(0,i.useReducer)(ul,{visible:[],pending:[]}),[eQ,e1]=(0,i.useState)(null),[e2,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,to]=(0,i.useState)({steering:[],followUp:[]}),[tl,tc]=(0,i.useState)([]),[td,tu]=(0,i.useReducer)(iz,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{$||tu({type:"idle"})},[$]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${iA(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${iP(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(td,ts),[td,ts]),[tf,tm]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(m?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tT=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),tR=(0,i.useRef)(!1),tE=(0,i.useRef)(-1),t$=(0,i.useRef)("unknown"),tL=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(0),tF=(0,i.useRef)(!1),tz=(0,i.useRef)(0),tW=(0,i.useRef)(null),tD=(0,i.useRef)(null),tO=(0,i.useRef)(null),tH=(0,i.useRef)(!1),tU=(0,i.useRef)(!0),[t_,tB]=(0,i.useState)(!1),[tq,tV]=(0,i.useState)(null),tK=(0,i.useRef)(void 0),tG=(0,i.useRef)(0),tJ=(0,i.useRef)(0),tZ=(0,i.useRef)(()=>{}),tY=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t8=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,no=eI??g?.context.model??eR??null,nl=f?X??en:no,nc=(0,i.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;s+=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:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nd=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nd.current+=1,tm(n=>n?.sid===e&&ue(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nd.current===n&&Array.isArray(t)&&tm(n=>n?.sid===e&&ue(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nf=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),nm=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&y(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=e5(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(s.messages),nf(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let o=!n&&t5.current===e;if(o||(eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&y(!1),!n){if(o)try{let t=t6.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t6.current===t&&(r.state?.thinkingLevel!==void 0?(eo(r.state.configuredThinkingLevel??r.state.thinkingLevel),ec(r.state.thinkingLevel)):r.running||(t5.current=null,eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nd.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eS(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t5.current=e,eo(i.configuredThinkingLevel??i.thinkingLevel),ec(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&to(d3(i.queuedMessages)),void 0!==i.subagents&&tc(e=>d5(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||to({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&&y(!1)}},[np,nf,nh]),ng=(0,i.useCallback)(e=>{let t=na.current.then(async()=>{tj.current===e&&await nm(e)});return na.current=t.catch(()=>{}),t},[nm]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let o=e5(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(o.messages),nf(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nf,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await dB(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),ny=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;f&&r&&n&&!t1.current&&(t1.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}))},[f,r,l]),nb=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!f||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t4.current,i=t8.current;e&&eE(e);let a={cwd:r,type:"ensure_session",toolNames:(0,c7.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),o=t0.current,l=o?.body===s?o.createRequestId:ua();t0.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:l})});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();t0.current=null,t=d.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),d.model&&t2.current===e&&(eE(d.model),e||er(d.model)),d.thinkingLevel&&t4.current===n&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await dB(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[f,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await nb();if(!e)return eG([]),[];eZ(!0);try{let t=await dB(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[nb]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,tb.current&&(clearTimeout(tb.current),tb.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{ty.current?.close(),ty.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);ty.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tW.current?.(n):"agent_start"===n.type&&tD.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tW.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nI=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new ui(n.status)},[nN]),nT=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await dB(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e6(t=>t?.id===e.id?null:t)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await dB(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nR=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??ua(),message:t,type:e.type??"info"}})},[]),nE=(0,i.useCallback)(e=>{let t={role:"custom",customType:e0,content:eT(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!e4(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${e8}${n.seq}`,baseEntryId:a,message:t});let s=e5(tC.current,tN.current,n.outputs);nh(s.messages),nf(s.entryIds)},[nh,nf]),n$=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e6(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(dH(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":nR({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ta(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[nR,o,e.chatInputRef]),nL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eV(null),eb(null),E({type:"end"}),e},[]),nP=(0,i.useCallback)(()=>{t$.current="unknown",tL.current=null;let e=un(tC.current,tN.current);tP.current=e?{entryId:e.entryId,key:uu(e.message)}:null,tA.current+=1},[]),nA=(0,i.useCallback)(()=>{let e=t$.current,t=tL.current;if("unknown"===e){let n=un(tC.current,tN.current),r=n?.message,i=tP.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:uu(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=ut(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nF=(0,i.useCallback)(e=>{let t=nA();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===n;s?.(e?nA():t)})},[s,nA]),nz=(0,i.useCallback)((e,t)=>tE.current!==e&&(tE.current=e,nF(t),!0),[nF]),nW=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nd.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(tc(e=>d5(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,tb.current=null,tM.current=!!s?.isStreaming,tR.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eH(d9(s)),tb.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){tb.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,tb.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;tb.current=setTimeout(()=>void n(),600)}};tb.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),nD=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nm(e)}finally{if(nt.current!==t)return;let n=tR.current,r=tM.current;tR.current=!1,tM.current=!1,nr.current=null;let i=nL();n?nz(t):r&&i&&nF(),e&&nW(e)}},[nm,nF,nz,nW,nL]),nO=(0,i.useCallback)(async(e,t)=>{await us(800);let n=Date.now();for(;tT.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nD(e,t)}}catch{}await us(600)}},[nD]),nH=(0,i.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;tF.current&&tz.current===t&&tj.current===e;){await us(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 nm(e),tz.current!==t||tj.current!==e)return;tF.current=!1,A(!1),z(null);return}catch{}}},[nm]),nU=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=nt.current;try{let n=nd.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let a=i.state;if(eA(a?.isCompacting??!1),eH(d9(a)),to(d3(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),tc(e=>d5(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eS(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await nD(e,t)}catch{}},[np,nD]),n_=(0,i.useCallback)(async e=>{let t=await nm(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tT.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,tR.current=!!n.isPromptRunning,tT.current=!0,L(!0),eV(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nO(e),!0)},[nN,nm,nO]),nB=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eP){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eP]),(0,i.useEffect)(()=>{if(!$&&!eP)return;let e=()=>{let e=tj.current;e&&nB(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[$,eP,nB]),(0,i.useEffect)(()=>{if(!$)return;let e=()=>{let e=tj.current;e&&nU(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)}},[$,nU]),(0,i.useEffect)(()=>{if($)return;let e=()=>{let e=tj.current;e&&!tT.current&&n_(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tT.current&&n_(t).then(e=>{e||tj.current!==t||tT.current||nm(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(dZ,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(dZ,n)}},[$,n_,nm]),tD.current=e=>{if(tj.current!==e||tT.current||tg.current||tO.current)return;let t=n_(e).then(async t=>{t||tj.current!==e||tT.current||await nm(e)}).catch(()=>{}).finally(()=>{tO.current===t&&(tO.current=null)});tO.current=t},(0,i.useEffect)(()=>{tT.current=$},[$]),tW.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=uu(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=uu(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=uu(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let n=e5(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);nh(n.messages),nf(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;nk(),e&&nP(),tM.current=!0,tT.current=!0,L(!0),eV({kind:"waiting_model"}),E({type:"start"});break}case"agent_end":if(!tT.current)break;if(eV(null),eb(null),E({type:"end"}),tj.current){nm(tj.current);let e=nd.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eS(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>d5(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tV(t.state.goal??null),to(d3(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tV(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||tR.current)break;let t=tj.current,n=nL();eA(!1);let r=t?nm(t):void 0;t&&nW(t),n&&nF(r);break}case"prompt_done":{let e=nt.current,t=tR.current;tR.current=!1,nr.current=null;let n=tE.current!==e;if(!t&&!n)break;let r=tj.current;nz(e,r?nm(r):void 0),!tM.current&&(nL(),r&&nW(r))}break;case"prompt_error":t$.current="failed",nR({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t$.current="failed",nR({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tT.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&E({type:"update",message:sy(t)}),eV(null);break}case"message_end":{if(!tT.current)break;let t=e.message;if(t?.role==="assistant"&&(tL.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},t$.current=ut(t)),t&&"user"===t.role){let e=sy(t),n=ud(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ud(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tu({type:"user-message",kind:iD(e),text:iW(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nh(e=>[...e,sy(t)]);let n=tj.current;n&&nB(n),E({type:"reset"}),eV({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t5.current=t,t6.current+=1,eo(e.configured??n),ec(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eV(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;eV(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";tc(n=>{let r=n.find(e=>e.id===t.id);return d5(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()};tc(e=>d5(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};tc(e=>d5(e,[r]));break}case"queue_update":to({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eb({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eb(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}eA(!0),ez(null),eD(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)ez(e.errorMessage),eD(null);else if(!e.aborted){eD(up(e.result,e.reason??"auto"));let t=tj.current;t&&(nm(t),nB(t))}break;case"extension_ui_request":n$(e)}},[nR,nu,np,nk,n$,nm,nF,nz,nB,nP,nW,nL,nf,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tF.current||ni.current)return"unknown";let o=oP(n,a??[]),l=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tK.current?.(t,e),"accepted"):"unknown"}nP();let c=nt.current+1;nk(),tR.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()};nh(e=>[...e,u]),nr.current=ud(u),nt.current=c,tT.current=!0,L(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),tZ.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,m=!1,g="unknown";try{if(f&&r){let e=tj.current??await tQ.current,t=await nb();t&&(h=t,X&&(eE(X),e&&await dB(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),m=!0,await dB(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),ny(1,n),g="accepted")}else t&&(h=t.id,await nI(t.id),m=!0,await dB(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&nO(h,c),g}catch(o){console.error("Failed to send message:",o);let r=o instanceof d_&&"update_draining"===o.code&&!1===o.accepted;if(!(!m||o instanceof d_&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return nO(h,c),"unknown";tR.current=!1,tT.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&ud(t)===s?e.slice(0,-1):e}),nR({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,uh(i),a,t?.id??h??void 0),nr.current=null,L(!1),eV(null),E({type:"end"}),"returned"}},[f,r,X,t,nb,nI,ny,nO,nR,nk,nj,e.chatInputRef,nP,nh]);tK.current=(0,i.useCallback)(async(n,r)=>{if(tT.current||tF.current)return;let i=`${r?"!!":"!"}${n}`;tF.current=!0,tZ.current(!0),z({command:n,excludeFromContext:r}),A(!0);try{let e=tj.current??t?.id??await nb();if(!e)throw Error("Unable to create a session for the shell command");await dB(e,{type:"bash",command:n,excludeFromContext:r}),await nm(e),ny(1,i)}catch(t){console.error("Failed to execute shell command:",t),nR({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tF.current=!1,z(null),A(!1)}},[nR,nb,nm,e.chatInputRef,ny,t]);let nV=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tF.current){try{await dB(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await dB(e,{type:"abort"}),t$.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nK=(0,i.useCallback)(async e=>{if(tF.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eN(e??null);try{let{cancelled:n,newSessionId:r}=await dB(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{eN(null)}},[c]),nG=(0,i.useCallback)(async e=>{if(tF.current)return;let t=tj.current;t&&(dB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nJ=(0,i.useCallback)(async e=>{if(tF.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&dB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nZ=(0,i.useCallback)(async(e,t)=>{if(f){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t8.current=null,et(null)),Q(n),eE(n);let i=tj.current??await tQ.current;if(!i)return;try{await dB(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await dB(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nm(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eI),nR({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nm(n)}finally{ni.current=!1,eL(!1)}}},[nR,eI,f,nm,Q]),nY=(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(f){if(ni.current)return!1;ni.current=!0,eL(!0);let e=t2.current,a=t8.current,s=t4.current;try{t2.current=t,t8.current=n??null,t4.current="auto";let e=tj.current??await tQ.current;return e&&await dB(e,r),Q(t),et(n??null),eE(t),eo("auto"),ec(void 0),e&&await nm(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t8.current=a,t4.current=s,nR({type:"error",message:i(n)});let t=tj.current;return t&&await nm(t),!1}finally{ni.current=!1,eL(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await dB(a,r),await nm(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eI),nR({type:"error",message:i(e)}),await nm(a),!1}finally{ni.current=!1,eL(!1)}},[nR,eI,el,f,nm,Q,es]),nX=(0,i.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(f){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t4.current=t??null,eo(t??"auto"),ec(void 0),t2.current=e,t8.current=null,et(null),Q(e),eE(e)}let r=tj.current??(f?await tQ.current:null);if(r)try{await dB(r,{type:"set_role_model",role:e}),f||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Z,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eP){eU.current="manual",eA(!0),ez(null),eD(null);try{let t=await dB(e,{type:"compact"});eD(up(t,"manual")),await nm(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eD(null)}finally{eA(!1)}}},[eP,nm]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();D(s.models),_(s.modelError??null),q(s.modelScopeWarnings??[]),K(s.thinkingLevels??{}),J(s.thinkingLevelMaps??{}),Y(s.roles??[]);let o=s.modelList??[];if(H(o),f&&!tj.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t4.current&&eo(t??"auto")}},[f,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await nb(),s=e=>(e.handled&&(e.error?nR({type:"error",message:e.error}):"openSessionStats"!==e.action&&nR({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eP)return s({handled:!0,error:"No active session to compact"});eU.current="manual",eA(!0),ez(null),eD(null);let e=await dB(a,{type:"compact",...i?{customInstructions:i}:{}});return eD(up(e,"manual")),await nm(a,!0)&&ny(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await dB(a,{type:"reload"}),await Promise.all([nm(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await dB(a,{type:"set_session_name",name:i}),await nm(a)&&ny(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await dB(a,{type:"get_session_stats"});return e&&e1(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await dB(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nK();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await dB(a,{type:"goal",args:i});if(tV(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nE(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nR({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tF.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eV({kind:"running_command"});try{await nI(a);let e=await dB(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nm(a,!0)&&ny(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eV(null),tj.current===a&&nW(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await dB(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nE(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[nR,nE,nI,nb,nK,eP,n0,nm,nw,nv,ny,h,nW]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r),"returned";let a=oP(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:a,images:s?.length??0});try{return await dB(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to steer:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r,i),"returned"}},[nR,e.chatInputRef]),n8=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(r),i),"returned";let s=oP(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:n,text:s,images:o?.length??0});try{return await dB(a,{type:"prompt",message:s,streamingBehavior:n,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(n){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",n),nR({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(r),i,a),"returned"}},[nR,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r),"returned";let a=oP(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:a,images:s?.length??0});try{return await dB(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to follow up:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,uh(n),r,i),"returned"}},[nR,e.chatInputRef]),n5=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await dB(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await dB(t,{type:"clear_queue"});tu({type:"withdraw"}),to({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),nR({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nR]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await dB(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nR({type:"error",message:"Failed to remove queued message"})}},[nR]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ed;eo(e),eu(n),f&&(!tj.current||t7.current===tj.current)&&(t4.current=e,t3.current=n),ec(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await nb():r&&await dB(i,{type:"set_thinking_ceiling",ceiling:n}),await dB(i,{type:"set_thinking_level",level:e}),await nm(i)}catch(e){console.error("Failed to set thinking level:",e),nR({type:"error",message:"Failed to set thinking level"}),await nm(i)}},[f,nm,nR,ed,nb]);ev.current=nl?`${nl.provider}/${nl.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!$&&!e$&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?d7(t.state):void 0)??null})}).catch(()=>{})},[rt,$,e$]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await nb(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};em(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=d7(await dB(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await dB(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nR({type:"error",message:t instanceof Error?t.message:String(t)});try{i(d7(await dB(e,{type:"get_state"}))??null)}catch{i(null)}}finally{em(!1)}},[nb,ep,nR]),ri=(0,i.useCallback)(async e=>{let t=(0,c7.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await dB(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),ra=(0,i.useCallback)(e=>{tU.current=e,tB(t=>!e===t?t:!e)},[]);tZ.current=ra;let rs=(0,i.useCallback)((e="smooth")=>{tJ.current=Date.now()+700,tY.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tG.current=0,ra(!0),rs("smooth")},[rs,ra]),rl=(0,i.useCallback)(()=>{tG.current=0,ra(!1)},[ra]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!ur.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tG.current=Date.now()+1200)},[]),rd=(0,i.useCallback)(()=>{if(!tT.current&&!tF.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tG.current;!t&&Date.now()<tJ.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?ra(!0):t&&ra(!1))},[ra]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&nm(t.id,!m,!0,m).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,tR.current=!!e.state.isPromptRunning,tT.current=!0,L(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nO(t.id)),e.state?.isBashRunning&&(tF.current=!0,A(!0),nH(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eA(n.isCompacting),eH(d9(n)),void 0!==n.contextUsage&&ek(n.contextUsage??null),void 0!==n.systemPrompt&&eS(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t5.current=t.id,eo(n.configuredThinkingLevel??n.thinkingLevel),ec(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&to(d3(n.queuedMessages)),void 0!==n.subagents&&tc(e=>d5(e,n.subagents??[])),void 0!==n.goal&&tV(n.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(ej)},[ej,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nJ)},[g?.tree,k,nJ,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rc),()=>{window.removeEventListener("keydown",rc)}),[rc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rc,{passive:!0}),e.addEventListener("wheel",rc,{passive:!0}),e.addEventListener("touchstart",rc,{passive:!0}),e.addEventListener("scroll",rd,{passive:!0}),()=>{e.removeEventListener("pointerdown",rc),e.removeEventListener("wheel",rc),e.removeEventListener("touchstart",rc),e.removeEventListener("scroll",rd)}},[S.length,v,rd,rc]),(0,i.useEffect)(()=>{if(t9.current||!$&&!P||!tU.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tJ.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[$,P,S.length,R.streamingMessage,eq,F,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,rs("instant");return}if(!t9.current&&tU.current){let e=Date.now()-ne.current<1500;rs(tT.current||tF.current||e?"instant":"smooth")}}},[S.length,$,P,rs,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,d]),(0,i.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[eW]),(0,i.useEffect)(()=>{if(0===eY.visible.length)return;let e=eY.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eY.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eY.visible]),(0,i.useEffect)(()=>{e1(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:b,activeLeafId:k,messages:S,entryIds:N,streamState:R,agentRunning:$,modelNames:W,modelList:O,modelError:U,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:el,thinkingCeiling:ed,retryInfo:ey,contextUsage:ew,systemPrompt:ej,forkingEntryId:eC,isCompacting:eP,compaction:eO,compactError:eF,compactResult:eW,currentModel:no,displayModel:nl,modelSwitching:e$,sessionStats:nc,runStateKnown:e_,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:ts,deliveryRows:th,subagents:tl,todoPhases:tf&&tf.sid===tj.current?tf.phases:null,compactedWork:T,notices:eY.visible,extensionDialog:e2,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nT,sendExtensionCustomInput:nM,isAutoModelSelection:f&&null===X,agentPhase:eq,isNew:f,autoFollowPaused:t_,resumeAutoFollow:ro,pauseAutoFollow:rl,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tY,scrollContainerRef:tX,handleSend:nq,handleAbort:nV,handleFork:nK,handleNavigate:nG,handleModelChange:nZ,handleRoleModelChange:nX,handleMainPresetChange:nY,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n4,handlePromptWithStreamingBehavior:n8,handleAbortCompaction:n5,handleRecallQueue:n6,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:ef,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:nb,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:E,setAgentRunning:L,setForkingEntryId:eN,bashRunning:P,pendingBash:F,handleAgentEventRef:tW}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ev,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsPanelOpen:g}),tX=(0,i.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=eQ(i);if(!a||"custom"!==i.role)continue;t??=[...e];let s=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&s.push(t);continue}let i=n.get(t);void 0===i&&(i=function(e){let t=eX(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,i)),i===a.sourceHash&&s.push(t)}s.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===a.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[r]={...i,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(eY)?{kind:"translated",text:n.slice(eY.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(i,eX(o.content??[]))}}return t??e})(ek),[ek]),tQ=rZ(e?.id,tt?.provider,void 0),t0=tQ?.alias;(0,i.useEffect)(()=>{t0&&Y.current?.(t0)},[t0]);let t1=(0,i.useMemo)(()=>{if(!tt)return null;let e=tw?tW:n5.find(e=>e.alias===tQ?.alias)?.oauthPosition;return n5.find(t=>t.provider===tt.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[tt,tw,tW,tQ]),t2=eC||eN,t8=e?.id;er.current=tX,ei.current=ej,ea.current=tT;let t4=(0,i.useRef)(!0);t4.current=!tj;let t5=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t5.current&&(es.current+=1),t5.current=eC},[eC]),(0,i.useEffect)(()=>()=>{es.current+=1},[]),(0,i.useEffect)(()=>{ee(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(uI(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[]}}(t8),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t8)])},[t8]),(0,i.useEffect)(()=>{let e=tT.current;e&&et.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&ee(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(nX(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,tX,ej);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(uT(e,r),r):t})},[tX,ej,tT]);let t6=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tT.current,t=t6.current;if(t6.current=e?{sessionId:e,entryIds:ej}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===n0&&r.push(t[a])}return r}(t.entryIds,ej,tX),r=ec();if(0===n.length||!r)return;let i=rG(e,"web6",void 0)?.alias??null;for(let e of n)et.current.some(t=>t.anchorEntryId===e)||ep(i,"done",r,{kind:"entry",entryId:e})},[ej,tX,tT,ec,ep]);let t3=eC&&tb?.kind==="running_tools"&&tb.tools.length>0&&tb.tools.every(e=>"wait"===e.name),t7=eb||s,{hideThinkingBlock:t9}=(D=t??e?.cwd??null,H=nF(),(0,i.useEffect)(()=>{nA(D).catch(()=>{})},[D]),H),ne=(0,i.useMemo)(()=>({hideThinking:t9}),[t9]);(0,i.useEffect)(()=>{var e;if(!tp||Z.current===tp.id)return;Z.current=tp.id;let t=ec();if(!t)return;el.current=t.turn;let n=eS.streamingMessage?.role==="assistant"?eS.streamingMessage:null,r=nQ(er.current,n,tt?.provider);ef("select"===(e=tp.method)||"ask"===e?"choice":"approval",t,r.provider,r.credentialId)},[tp,eS.streamingMessage,tt?.provider,ec,ef]),(0,i.useEffect)(()=>(v=t2?t$:null,()=>void(v=null)),[t2,t$]),(0,i.useEffect)(()=>{T?.(t2)},[T,t2]),(0,i.useEffect)(()=>()=>T?.(!1),[T]),(0,i.useEffect)(()=>{M?.(t3)},[t3,M]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{R?.(null!==tp)},[R,tp]),(0,i.useEffect)(()=>()=>R?.(!1),[R]);let{main:nt,process:nn}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,o=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),o=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:o});a.messageCount+=t.length,a.toolCallCount+=n},l=eG(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:a,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(),a=i.idx,r.push(i);continue}if(e2(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===eQ(t)&&o(a,[{idx:i.idx}],0);continue}let s=eB(t,n),c=!1;for(let e of s){if("answer"===e.kind){d(i.idx,e.blocks),c=!0;continue}o(a,[{idx:i.idx,blocks:e.blocks}],eq(e.blocks)),l.collect(i.idx,e.blocks)}!c&&e_(t,n)&&d(i.idx,[])}return u(),{main:r,process:i}})(tX,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(e6(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!e6(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!e6(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,o=[],l=0,c=0,d=eG(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex: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(null!==eQ(n))continue;if(e2(n)){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:l});continue}let c=eB(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(a.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eq(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&e_(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 f=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=f);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(tX,{sessionBusy:t2,isStreaming:eS.isStreaming,hideThinking:ne.hideThinking}),ne),[tX,t2,eS.isStreaming,ne]),nr=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=iE(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=r.get(l.position);e?e.calls.push(...n):r.set(l.position,{calls:[...n],placement:o?"after":"before"})}}"user"===e.role&&(a=t),e6(e)&&(s=t)});let{continuing:o}=i$(e,t,n);if(o){let e=r.get(o.position);e?e.calls.unshift(...o.calls):r.set(o.position,{calls:o.calls,placement:"before"})}return r})(nt,tX,ta?.messages),[nt,tX,ta]),ni=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=i$(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i);return{position:-1===a?e.length:a,calls:r}})(nt,tX,ta?.messages),[nt,tX,ta]),[na,ns]=(0,i.useState)(uk),{startIndex:no,endIndex:nl,hasLater:nc}=uj(nt.length,na),nd=null!==na.end&&nc,nu=(0,i.useRef)(nt.length);nu.current=nt.length;let np=(0,i.useRef)(null),nh=(0,i.useRef)(null),nf=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==na.end&&na.end>=nt.length&&ns(e=>({count:e.count,end:null}))},[na.end,nt.length]),(0,i.useEffect)(()=>{let e=np.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nf.current=t.scrollHeight-t.scrollTop,ns(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]),(0,i.useEffect)(()=>{if(null==nf.current)return;let e=tR.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nf.current),nf.current=null}},[na.count,tR]),(0,i.useEffect)(()=>{let e=nh.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ns(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=uj(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nu.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]);let[nm,ng]=(0,i.useState)(null),[nx,nv]=(0,i.useState)(0),ny=(0,i.useRef)(null),nb=(0,i.useCallback)(e=>{tC(),ny.current=e,ng(null),ns(t=>uS(nu.current,e,t)),nv(e=>e+1)},[tC]);(0,i.useLayoutEffect)(()=>{let e=ny.current,t=tR.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;ny.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,ng(e)},[nx,na,nt,tR]),(0,i.useEffect)(()=>{if(null===nm)return;let e=setTimeout(()=>ng(null),1800);return()=>clearTimeout(e)},[nm]);let nw=(0,i.useCallback)(()=>{(0,_.flushSync)(()=>ns(uk));let e=tR.current;e&&(e.scrollTop=e.scrollHeight)},[tR]),nk=(0,i.useCallback)(()=>{nd&&nw(),tS()},[nd,nw,tS]),nj=(0,i.useRef)(null),[nS,nC]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!z||nj.current===z.id||z.sessionId!==e?.id||eb||0===tX.length)return;nj.current=z.id,W?.(z.id);let t=ej.indexOf(z.entryId);if(t<0)return void nC(!0);let n=0;for(let e=0;e<nt.length;e++){let r=nt[e].idx;if(r>t||(n=e,r===t))break}nb(n)},[z,e?.id,eb,tX.length,ej,nt,nb,W]),(0,i.useEffect)(()=>{if(!nS)return;let e=setTimeout(()=>nC(!1),6e3);return()=>clearTimeout(e)},[nS]);let[nN,nI]=(0,i.useState)(!1),[nT,nM]=(0,i.useState)(0),nR=(0,i.useMemo)(()=>nN?nt.map(e=>(function(e,t){if("answer"===e.kind)return e9(e.blocks);let n=t[e.idx];return n&&"content"in n?e9(n.content):""})(e,tX).toLowerCase()):uM,[nN,nt,tX]),nE=(0,i.useCallback)(e=>{tC(),ns(t=>uS(nu.current,e,t))},[tC]),n$=(0,i.useCallback)(()=>nI(!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=tR.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(),nI(!0),nM(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tR]);let nL=(0,i.useMemo)(()=>{let e=[];return nt.forEach((t,n)=>{if("message"!==t.kind)return;let r=uN(tX[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nt,tX]),nP=`${no}:${nl}`,nz=ej.length>0?ej[ej.length-1]:null,[nW,nD]=(0,i.useState)(null),nO=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nO.current||!ti||eb||!e?.id||(nO.current=!0,t2||!nz||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(tX)||function(e){try{return window.localStorage.getItem(uR(e))}catch{return null}}(e.id)!==nz&&nD(nz))},[ti,eb,e?.id,t2,nz,tX]);let nH=(0,i.useCallback)(()=>{e?.id&&nW&&function(e,t){try{window.localStorage.setItem(uR(e),t)}catch{}}(e.id,nW),nD(null)},[e?.id,nW]),nU=null!==nW&&nW===nz&&!t2&&!nd,n_=tr?[tr.sessionId,tr.sessionFile??"",tr.sessionName??"",tr.userMessages,tr.assistantMessages,tr.toolCalls,tr.toolResults,tr.totalMessages,tr.tokens.input,tr.tokens.output,tr.tokens.cacheRead,tr.tokens.cacheWrite,tr.tokens.total,tr.cost??0,tr.totalActiveMs??0].join("|"):null,nq=(0,i.useRef)(tr);nq.current=tr,(0,i.useEffect)(()=>{m?.(nq.current)},[n_,m]),(0,i.useEffect)(()=>()=>{m?.(null)},[m]);let nV=eJ?`${eJ.percent??"null"}|${eJ.contextWindow}|${eJ.tokens??"null"}`:null,nK=(0,i.useRef)(eJ);nK.current=eJ,(0,i.useEffect)(()=>{x?.(nK.current)},[nV,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{y?.(tc)},[y,tc]),(0,i.useEffect)(()=>()=>{y?.([])},[y]);let{isDragOver:nG,handleDragEnter:nJ,handleDragOver:nZ,handleDragLeave:nY,handleDrop:n1}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t2||p?.current?.addAttachments(e)},[t2,p])),n2=(0,i.useMemo)(()=>{var e;return e=ta?.messages,e&&e.length>0?[...e,...tX]:tX},[ta,tX]),n8=(0,i.useMemo)(()=>{let e=new Map;for(let t of n2)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[n2]),n4=(0,i.useMemo)(()=>{let e,t,n,r,i,a,s,o,l,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,i=new Map,a=new Map,s=new Map,o=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},l=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=ik(e.status);if(!r||l.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;l.add(r);let s=iw(e);null!==s&&i.set(r,s)},d=(e,t,r)=>{let i=t?n.get(t):void 0,a=iw(e);i&&"number"==typeof r&&null!==a&&"running"===ik(e.status)&&s.set(i,Math.max(s.get(i)??-1/0,r-a))},n2.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=n8.get(e.toolCallId);if(t)for(let i of iS(e,t)??[])n.set(i.agentId,i.key),"number"==typeof t.timestamp&&r.set(i.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(ij(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=ib(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:ib(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of iy(t.details?.jobs)){if("task"!==r.type)continue;let a=ib(r.id);if(a&&o(a,ik(r.status),i),c(r,a),d(r,a,t.timestamp),a&&"running"===ik(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of ij(t.content).matchAll(iC)){let t=Object.fromEntries([...e[1].matchAll(iN)].map(e=>[e[1],e[2]]));t.id&&o(t.id,ik(t.status),i)}for(let e of iy(t.details?.jobs))"task"===e.type&&c(e,ib(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:i,parallelWith:a,runStartedAt:s}},[n2,n8]),n6=(0,i.useMemo)(()=>({ledger:n4,subagents:tc,toolResults:n8,onOpenPanel:b,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:k,selectedMaker:j}),[n4,tc,n8,b,e?.id,e?.cwd,t,k,j]),n3=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=tX.length-1;n>=0;n-=1){let r=uN(tX[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[tX]),n7=(0,i.useMemo)(()=>tk(tX,n8,td,ta?.todoPhases??null),[tX,n8,td,ta]),n9=(0,i.useMemo)(()=>lZ(eS.streamingMessage).join("|"),[eS.streamingMessage]),re=(0,i.useMemo)(()=>JSON.stringify(lJ(eS.streamingMessage)),[eS.streamingMessage]),rt=(0,i.useMemo)(()=>JSON.stringify(lX(eS.streamingMessage)),[eS.streamingMessage]),rn=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],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=lZ(r),c=lX(r,a);if(0===i.length&&0===c.length||l<0)continue;let d=lJ(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.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 a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=o.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(a,e),s.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 s.sort((e,t)=>e.index-t.index)})(tX,ej,n9.length>0?n9.split("|"):[],JSON.parse(re),JSON.parse(rt)),[tX,ej,n9,re,rt]),rr=e?.id??tT.current??void 0,ri=(B=l0(O=(0,i.useMemo)(()=>({sessionId:rr,sessionProvider:tt?.provider,turns:rn,messages:tX,subagents:tc}),[rr,tt?.provider,rn,tX,tc])),q=l4(O),(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}([...B,...q])),[B,q])),ra=tw&&0===tX.length&&!eS.isStreaming&&!t2,rs=e?.cwd??t??void 0,ro=tt?eL[`${tt.provider}:${tt.modelId}`]??null:null,rl=tt?eP[`${tt.provider}:${tt.modelId}`]??null:null,rc=(0,i.useRef)(null),rd=(0,i.useRef)(null),ru=(0,i.useCallback)(()=>{rc.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(I?.(ru),()=>I?.(null)),[ru,I]),(0,i.useLayoutEffect)(()=>{let e=rd.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tR.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tR.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[eb,tR]);let rp=(0,i.useCallback)((...e)=>(null!==na.end&&nw(),tE(...e)),[tE,na.end,nw]),rh=(0,r.jsx)("div",{ref:rc,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(dz,{ref:p,sessionId:e?.id??tT.current??void 0,onEnsureSession:tw&&t?tZ:void 0,onLiveTranscriptPersisted:tY,onSend:rp,onAbort:t$,onSteer:eC?tO:void 0,onFollowUp:eC?tH:void 0,onPromptWithStreamingBehavior:eC?tU:void 0,isStreaming:t2,model:tt,isAutoModelSelection:ty,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:e$,onModelChange:tA,onMainPresetChange:e||tw?tz:void 0,mainPresetActiveAlias:t1,modelRoles:eA,onRoleModelChange:tF,modelSwitching:tn,onCompact:e||tw?tD:void 0,onAbortCompaction:t_,isCompacting:e1,compactError:e7,compactResult:te,toolPreset:eF,onToolPresetChange:e||tw?tK:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,onThinkingLevelChange:e||tw?tG:void 0,fastMode:eO,fastModeBusy:eU,onFastModeToggle:e||tw?eV:void 0,availableThinkingLevels:ro,thinkingLevelMap:rl,retryInfo:eK,deliveryRows:tl,inputHistory:n3,onRecallQueue:tB,onRemoveQueuedMessage:tq,slashCommands:ts,slashCommandsLoading:to,onLoadSlashCommands:tJ,onBuiltinCommand:tV,soundEnabled:E,onSoundToggle:$,onAudioUnlock:A,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rf=eS.streamingMessage,rm=(0,i.useMemo)(()=>rf?eB(rf,{isStreaming:!0}):[],[rf]),rg=(0,i.useMemo)(()=>rm.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rm]),rx=(0,i.useMemo)(()=>rm.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rm]),rv=rf?.role==="assistant"?rf:null,ry=(0,i.useMemo)(()=>{let e=-1;for(let t=tX.length-1;t>=0;t-=1)if("user"===tX[t].role){e=t;break}let t=e<0?-1:si(tX,e);return{start:t,blocks:sn(tX,t+1,tX.length),priorCiHeads:ss(tX,n8,t+1),jobNotices:sr(tX,t+1,tX.length)}},[tX,n8]),rb=(0,i.useMemo)(()=>a7(rv?[...ry.blocks,...rv.content??[]]:ry.blocks,n8,t2,ry.priorCiHeads,rs,ry.jobNotices),[ry,rv,n8,t2,rs]),rw=(0,i.useMemo)(()=>t2?{...st(ry.blocks,n8,rs),span:so(tX,ry.start+1,tX.length)}:null,[t2,ry,n8,rs,tX]),rk=(0,i.useMemo)(()=>rw?{...rw,flow:rb,latest:!0}:null,[rw,rb]),rj=eC&&(tb?.kind==="running_tools"||(rv?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rS=nQ(tX,rv,tt?.provider),rC=rS.provider,rN=rS.credentialId;(0,i.useEffect)(()=>{if(!rj)return;let e=ec();e&&eo.current!==e.turn&&el.current!==e.turn&&(eo.current=e.turn,ef("working",e,rC,rN))},[rj,rC,rN,ec,ef]);let[rI,rT]=(0,i.useState)(null),rM=(0,i.useCallback)(e=>{rT(e)},[]),rR=(0,i.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),rE=(0,i.useMemo)(()=>{let e=[eC&&!rf&&tb?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}(tb,V):null,eN&&!eI?V("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eC,rf,tb,eN,eI,V]);(0,i.useEffect)(()=>{if(!rI)return void S?.(null);let e=[],t=[],n=0;if(rf&&rx.length>0){let r=rI.messages.length+e.length;for(let i of(e.push(rf),rx))t.push({idx:r,blocks:i}),n+=eq(i)}if(rR&&(t.push({idx:rI.messages.length+e.length}),e.push(rR)),0===t.length)return void S?.(rE?{...rI,status:rE}:rI);let r=-1;for(let e=rI.messages.length-1;e>=0;e--)if(e6(rI.messages[e])){r=e;break}let i=rI.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),S?.({...rI,groups:i,messages:[...rI.messages,...e],status:rE})},[rI,rx,rf,rR,rE,S]),(0,i.useEffect)(()=>()=>S?.(null),[S]);let r$=tg.filter(e=>"belowEditor"!==e.placement),rL=tg.filter(e=>"belowEditor"===e.placement);return ew?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ew}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":t7,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nJ,onDragOver:nZ,onDragLeave:nY,onDrop:n1,children:[t7?(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:V("chat.loadingSession")})}):null,nG&&!t2&&(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:V("chat.attachFile")})}),tf&&(0,r.jsx)(uW,{request:tf,onInput:tv}),ra&&!N?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[860px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(X,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.64"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.12.6"]})]})]})]}),rs&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":V("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:V("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tN(rs)||rs}),(0,r.jsx)("code",{title:rs,children:rs}),(0,r.jsx)("p",{children:V("chat.emptyProjectHint")})]}),w&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:w,children:V("chat.openSessionList")})]}),(0,r.jsx)(uA,{notices:tu,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[N&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:N}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!N,style:{display:N?"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:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(lR,{open:nN,onClose:n$,containerRef:tR,index:nR,renderedStart:no,renderedEnd:nl,contentKey:tX,onReveal:nE,onProgrammaticScroll:tC,focusRequest:nT,t:V}),nS&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:V("chat.jumpMissing")}),(0,r.jsx)(uA,{notices:tu,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tR,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(uP,{widgets:r$}),(0,r.jsxs)(sC.Provider,{value:n6,children:[(0,r.jsx)(lB,{utterances:ri,children:(0,r.jsx)(uE,{messages:tX,entryIds:ej,toolResultsMap:n8,modelNames:eM,messageCwd:rs,onOpenFile:C,sessionBusy:t2,isNew:tw,isStreaming:eS.isStreaming,handleFork:tL,forkingEntryId:eZ,handleNavigate:tP,handleEditContent:ey,sessionId:e?.id??tT.current??void 0,main:nt,dispatchSlots:nr,compactedDispatch:ni,openRequest:ta?.openRequest??null,process:nn,startIndex:no,endIndex:nl,sentinelRef:np,laterSentinelRef:nh,flashItem:nm,t:V,cues:Q,cueFollowRef:t4,onProcessLogChange:rM})}),!nd&&eS.isStreaming&&eS.streamingMessage&&rg.length>0&&(0,r.jsx)(o5,{message:eH(eS.streamingMessage,rg),sessionId:e?.id??tT.current??void 0,isStreaming:!0,modelNames:eM,cwd:rs,onOpenFile:C}),!nd&&rk&&(0,r.jsx)(oy,{summary:rk,live:!0,onOpenFile:C})]}),nU&&(0,r.jsx)(lF,{onDismiss:nH,t:V}),(0,r.jsx)("div",{ref:tM})]})})}),(0,r.jsx)(lE,{questions:nL,containerRef:tR,layoutKey:nP,onJump:nb,label:V("chat.questionRail")}),(t2&&tj||nd)&&(0,r.jsxs)("button",{type:"button",onClick:nk,"aria-label":V("chat.jumpToBottom"),title:V("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:G?44:void 0,borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),V("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rd,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tp&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,r.jsx)(uz,{request:tp,onRespond:tx,onActivity:e=>void tv(e,"activity"),delivery:th})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(lA,{compaction:e3,t:V}),(0,r.jsx)(uL,{goal:tI,t:V}),(0,r.jsx)(uP,{widgets:rL}),(n7||rb.steps.length>0)&&!(K&&G)&&(0,r.jsx)(dD,{phases:n7,flow:rb,busy:t2})]})}),rh,(0,r.jsx)(dW,{statuses:tm})]})]})}function uL({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nI(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nI(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 uP({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 uA({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function uF({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,F.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:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:a},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 uz({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),f=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let m=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(uF,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{f(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},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:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{f();let n=e.target.value;d(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(uF,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(nc,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(uF,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m()},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&&m()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function uW({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),o=e$(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eA[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":" ":eP[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eL(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function uD({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,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"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),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"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var uO=n(50640),uH=n(73620);let uU=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function u_(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 uB=["tags","categories","keywords","tag","category"];function uq({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=uB.find(t=>Array.isArray(e[t])),s=a?e[a].map(u_).filter(Boolean):[],o=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),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=u_(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))})]})}var uV=n(8745);let uK=(0,i.createContext)(null),uG=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),uJ=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),uZ=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10 3-5 5 5 5"})}),uY=(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"})}),uX=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function uQ({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:f}){let{t:m}=(0,F.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uZ})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,l&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:l})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(uV.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,r.jsxs)(uV.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(uV.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(uV.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":m("panel.more"),title:m("panel.more"),children:(0,r.jsx)(o.In,{size:"16px",svg:uX})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":m("panel.more"),children:(0,r.jsx)(c.k.ScrollArea,{children:(0,r.jsx)(c.k.Group,{children:h.map(e=>(0,r.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(u0,{}),f&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:f.onClick,"aria-label":f.label,title:f.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uY})})]})}function u0({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,i.useContext)(uK);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(o.In,{size:"16px",svg:n.expanded?uJ:uG})})}let u1="cuelo-html-pick",u2="cuelo-html-pick-exit";function u8(e,t){return"string"==typeof e&&e.length<=t}function u4(e){return"number"==typeof e&&Number.isFinite(e)}function u5({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:o}){let{t:l}=(0,F.s)(),c=(0,i.useRef)(null),d=(0,i.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
20
20
  var NONCE=${JSON.stringify(n)},TYPE=${JSON.stringify(u1)},EXIT=${JSON.stringify(u2)};
21
21
  var host=window.parent;
22
22
  if(document.currentScript)document.currentScript.remove();
@@ -71,4 +71,4 @@ ${w.model??"모델 미확인"} \xb7 ${j}
71
71
  ${p.title}${f?`
72
72
  현재 단계: ${f}`:""}${g?`
73
73
  ${g}`:""}${x?`
74
- ${x}`:""}`,"aria-label":`${S} ${v}, 업무 ${p.title}${f?`, 현재 단계 ${f}`:""}${g?`, ${g}`:""}${x?`, ${x}`:""}, ${d?d.status:u?.status??"미확인"}, 모델 ${w.model??"미확인"}, 추론 ${j}`,"aria-describedby":m&&d?c:void 0,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"===b.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":b.agent,title:`${b.agent} \xb7 ${fd[b.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),b.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:p.title})]}),d?(0,r.jsx)("span",{style:{color:fl(d),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:d.status}):u?(0,r.jsx)("span",{style:{color:"failed"===u.status?"var(--danger)":"aborted"===u.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:u.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),f&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${f}`,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 ",f]}),m?.phase&&(0,r.jsxs)("span",{className:"subagent-phase-line",style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[(0,r.jsx)(sG,{phase:m.phase}),x&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle)"},title:x,children:` \xb7 ${x}`})]}),m&&d&&(0,r.jsx)("span",{className:"subagent-eta-line",style:{gridColumn:"1 / -1",minWidth:0,color:"var(--seed-color-fg-neutral)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)(sQ,{snapshot:d,view:m,id:c})}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":w.model?w.effort?"both":"model":w.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[k,w.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",j]})]}),(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:v}),(0,r.jsx)("span",{children:y})]}),(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:[d?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",d.progress.toolCount]}),(0,r.jsxs)("span",{children:[d.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}분`}(d.progress.durationMs)})]}),u&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===u.messages?"메시지 수 미확인":`메시지 ${u.messages}`}),(0,r.jsxs)("span",{children:[(u.bytes/1024).toFixed(+(u.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)}일 전`}(u.modified)})]})]})]})})}function fv({title:e,sessionId:t,sessionPath:n,sessionCwd:a,liveSubagents:s,client:o,visible:l=!0,onClose:c,onReturnFocus:d,selection:u,onSelectionChange:p,onReturnToOrigin:h,onOpenFile:f}){let{t:m}=(0,F.s)(),g=(0,i.useMemo)(()=>o??ih(),[o]),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)({kind:"loading"}),[w,k]=(0,i.useState)({kind:"loading"}),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(null),I=p?u??null:C,T=p??N,[M,R]=(0,i.useState)(0),E=(0,i.useRef)(null),$=(0,i.useRef)(null);(0,i.useEffect)(()=>{v([]),b({kind:"loading"}),k({kind:"loading"}),S(!1),N(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,a]=await Promise.allSettled([g.getLiveSnapshots(t,r.signal),g.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===i.status)v(i.value.subagents),b(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=sj(i.reason);b("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===a.status)S(!0===a.value.listTruncated),k(a.value.subagents.length>0?{kind:"ready",data:a.value.subagents}:{kind:"empty",data:[]});else{let e=sj(a.reason);k("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};i();let a=setInterval(()=>void i(),3e3),s=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",s),()=>{e=!0,r?.abort(),clearInterval(a),document.removeEventListener("visibilitychange",s)}},[M,g,t,l]);let L=(0,i.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let i of[...e,...t]){let e=n.get(i.id);if(!e){r.push(i.id),n.set(i.id,i);continue}let[t,a]=fu(i)>=fu(e)?[i,e]:[e,i];n.set(i.id,{...t,assignment:t.assignment??a.assignment,description:t.description??a.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(s,x),[s,x]),P="ready"===w.kind||"empty"===w.kind?w.data:[],A=(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})(L,P),[P,L]),z=I?A.find(e=>e.key===I.key)??null:null,W=z&&I?.toolCallId&&z.live?.parentToolCallId!==I.toolCallId?null:z,D=sq({sessionId:t,snapshots:L,client:g,enabled:l&&!I,cwd:a??void 0});if((0,i.useEffect)(()=>{let e=$.current;if(I||!e)return;$.current=null;let t=[...E.current?.querySelectorAll("[data-subagent-key]")??[]].find(t=>t.dataset.subagentKey===e);t?.focus({preventScroll:!1})}),I&&t)return(0,r.jsx)(fg,{sessionId:t,sessionCwd:a,record:W,selection:I,client:g,visible:l,onOpenFile:f,onBack:()=>{T(null),I.origin&&h?h(I.origin):$.current=I.key}});let O=0===A.length&&"loading"===y.kind&&"loading"===w.kind,H=0===A.length&&("empty"===y.kind||0===s.length)&&"empty"===w.kind;return(0,r.jsxs)("section",{ref:E,"aria-label":"Subagent 기록","data-state":O?"loading":H?"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.jsx)(uQ,{title:e,titleTooltip:n??void 0,subtitle:O||!t?void 0:m("panel.subagentsCount",{count:A.length}),actions:[{id:"refresh",label:m("panel.refresh"),icon:fp,onClick:()=>R(e=>e+1)}],close:c?{label:m("panel.close"),onClick:()=>{c?.(),d?.()}}:void 0}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?O?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):H?(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:A.map(e=>(0,r.jsx)(fx,{record:e,view:e.live?D.get(e.live.id):void 0,onSelect:()=>T({key:e.key})},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!O&&"loading"===y.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!O&&"loading"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===y.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:y.message}),"error"===y.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:y.message}),"unreachable"===w.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:w.message}),"error"===w.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:w.message}),j&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let fy=new Set(["efficiency","sidechat","resource"]),fb=["process","efficiency","subagents","files","resource","sidechat"];function fw({activeView:e,onViewChange:t,viewLabels:n,sessionId:i,sessionPath:a,sessionName:l,sessionCwd:c,liveSubagents:d,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:f,resourceSlot:m,efficiencySlot:g,visible:x=!0,onClose:v,onReturnFocus:y,expand:b=null,selectedMaker:w,onSelectMaker:k,onReturnToDispatch:j,onOpenFile:S,fileOpen:C=!1}){return(0,r.jsx)(uK.Provider,{value:b,children:(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":e,"data-expanded":b?.expanded?"true":void 0,children:(0,r.jsxs)(fs.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)(fs.J.List,{"aria-label":"보조 패널 보기",children:[fb.map(e=>{let t="subagents"===e?d.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(fs.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)(nu.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,r.jsx)(fs.J.Indicator,{})]}),(fy.has(e)||"files"===e&&!C)&&(0,r.jsx)(u0,{className:"auxiliary-deck-expand"}),v&&(0,r.jsx)(s.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{v?.(),y?.()},"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)(fs.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(fs.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(fs.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(fv,{title:n.subagents,sessionId:i,sessionPath:a,sessionCwd:c,liveSubagents:d,client:u,visible:x&&"subagents"===e,selection:w,onSelectionChange:k,onReturnToOrigin:j,onOpenFile:S})}),(0,r.jsx)(fs.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,r.jsx)(fs.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:f}),(0,r.jsx)(fs.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:m})]})})})}function fk({title:e,data:t,onOpenFile:n}){let{t:a}=(0,F.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.jsx)(uQ,{title:`${o.length} ${a(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:a("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} ${a(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${a(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(s.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!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?a("chat.expandProcess"):a("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:d??a("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,a)=>{let s=t?.messages[i.idx];return s?(0,r.jsx)(o5,{message:i.blocks?eH(s,i.blocks,{omitUsage:!0}):s,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[i.idx],sessionId:t?.sessionId,showTimestamp:!1},`process-${e.anchorIdx}-${a}`):null})})]},`turn-${e.anchorIdx}-${i}`)})]})]})}let fj=6,fS="omp-btw-log:",fC="omp-btw-log-index";function fN(e){return e.trim().toLowerCase()}function fI(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function fT(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 fM(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function fR(e,t={}){let n=t.now??Date.now,r=new Map,i=new Set,a=!1,s=[],o=t=>{if(e)try{e.removeItem(t)}catch{}},l=e=>{r.delete(e),i.delete(e),o(fS+e)},c=()=>{let e=new Set,t=[];for(let n of(s.sort((e,t)=>t.updatedAt-e.updatedAt),s))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):l(n.id));s=t},d=()=>{if(!a){if(a=!0,e)try{let t=e.getItem(fC),n=t?JSON.parse(t):[];Array.isArray(n)&&(s=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:fN(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{s=[]}c()}},u=e=>{d();for(let t=s.length-1;t>=0;t-=1){if(s[t].id===e)continue;let[n]=s.splice(t,1);return l(n.id),!0}return!1},p=t=>{if(e){try{e.setItem(fC,JSON.stringify(s));return}catch(e){if(!fM(e)||!u(t))return}try{e.setItem(fC,JSON.stringify(s))}catch{}}},h=t=>{let n=fN(t);if(!n)return[];if(i.has(n))return fI(r.get(n)??[]);if(e)try{let t=e.getItem(fS+n);if(t){let e=JSON.parse(t),i=fT(e?.entries);return r.set(n,i),fI(i)}}catch{}return fI(r.get(n)??[])},f=e=>{let t=fN(e);t&&(d(),s=s.filter(e=>e.id!==t),l(t),p(null))};return{read:h,append:(t,a)=>((t,a)=>{let o=fN(t);if(!o)return[];let l=fT(a),h=n();if(r.set(o,fI(l)),d(),(s=s.filter(e=>e.id!==o)).unshift({id:o,updatedAt:h}),c(),p(o),!e)return fI(l);let f=JSON.stringify({updatedAt:h,entries:l});try{return e.setItem(fS+o,f),i.delete(o),fI(l)}catch(e){if(!fM(e)||!u(o))return i.add(o),fI(l)}p(o);try{e.setItem(fS+o,f),i.delete(o)}catch{i.add(o)}return fI(l)})(t,[...h(t),a]),history:(e,t=fj)=>h(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:f,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=fN(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);i.set(t,Number.isFinite(n)?n:0)}let a=r?fN(r):null,l=n();for(let e of[...s])if(e.id!==a){if(!i.has(e.id)){f(e.id);continue}l-Math.max(i.get(e.id)??0,e.updatedAt)>6048e5&&f(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(fS))continue;let r=fN(n.slice(fS.length));i.has(r)||r===a||c.push(n)}}catch{return}for(let e of c)o(e)}}}function fE(){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 f$ extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function fL(e){let t;try{t=JSON.parse(e)}catch{throw new f$("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new f$("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new f$("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class fP{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()?[fL(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[fL(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function fA(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 fF(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 fz({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 fW({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)(nc,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function fD({identity:e,status:t,utteranceKey:n,children:i}){let a=rZ(e?.sessionId,e?.provider,e?.credentialId),s=lH(a?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[a&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(r0,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:a.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[i,s&&(0,r.jsx)("img",{src:s.src,alt:s.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function fO({title:e,sessionId:t,sessionPath:n,sessionName:a,historyStore:s,flights:o,sessionCensus:l,client:c,visible:d=!0,onClose:u,onReturnFocus:p}){let h,f,m=(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(-fj)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new f$("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new f$("http",await fA(r),r.status);if(!r.body)throw new f$("stream","사이드채팅 스트림을 열 수 없습니다.");let i=r.body.getReader(),a=new fP,s="",o=null,l=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)s+=t.v;else if("done"===t.t)s=t.v||s;else if("m"===t.t)o=t.v;else throw new f$("server",t.v)};try{for(;;){let e=await i.read();if(e.done)break;l(a.push(e.value))}l(a.finish())}catch(e){if(n.signal?.aborted||e instanceof f$)throw e;throw new f$("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{i.releaseLock()}if(!s)throw new f$("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:s,model:o}}}}(),[c]),g=t?.toLowerCase()??null,[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)({}),w=g??"",k=y[w]??"",j=(e,t)=>{b(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,i.useState)(0),[N,I]=(0,i.useState)({}),[T,M]=(0,i.useState)({}),[R,E]=(0,i.useState)({}),[$,L]=(0,i.useState)(null),[P,A]=(0,i.useState)(null),[F,z]=(0,i.useState)({}),[W,D]=(0,i.useState)({}),[O,H]=(0,i.useState)({}),U=(0,i.useRef)((h=new Set,f=new Set,{claim:e=>!(!e||h.has(e)||f.has(e))&&(h.add(e),!0),markSent(e){h.delete(e),f.add(e)},release(e){h.delete(e)}})),_=(0,i.useRef)(!0),B=(0,i.useRef)(g),q=(0,i.useRef)(d),V=(0,i.useRef)(null),K=(0,i.useRef)(!1),G=(0,i.useRef)(0),J=(0,i.useRef)(null);B.current=g,q.current=d,(0,i.useEffect)(()=>(_.current=!0,()=>{_.current=!1}),[]),(0,i.useEffect)(()=>{v(g?s.read(g):[])},[s,g]);let Z=(0,i.useRef)(null);(0,i.useEffect)(()=>{L(null),Z.current=null},[g]),(0,i.useEffect)(()=>{if(!d||!g||Z.current===g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0;return{provider:t.provider,..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&(Z.current=g,L(t?{...t,sessionId:g}:null))}).catch(()=>{e&&(Z.current=g,L(null))}),()=>{e=!1}},[g,d]),(0,i.useEffect)(()=>{if(!g)return;let e=()=>{if(!_.current||B.current!==g)return;let e=o.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)I(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),b(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;E(e=>({...e,[g]:t}))}v(s.read(g))}else null===o.read(g)&&v(s.read(g));C(e=>e+1)},t=o.subscribe(g,e);return e(),t},[o,s,g]),(0,i.useEffect)(()=>{l&&s.cleanup(l,g)},[s,g,l]),(0,i.useEffect)(()=>{d&&V.current?.focus()},[d,g]),(0,i.useEffect)(()=>{if(!d)return;let e=requestAnimationFrame(()=>{let e=J.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,d]);let Y=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=o.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await m.ask({sessionPath:n,question:e,history:s.history(g),signal:r,onEvent:e=>o.ingest(g,e)});s.append(g,{q:e,a:t.text,at:Date.now()}),o.finish(g,{kind:"done",model:t.model})}catch(n){let t=o.read(g)?.text??"";if(r.aborted){let n=!1;t&&(s.append(g,{q:e,a:t,at:Date.now()}),n=!0),o.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof f$?n.kind:"unknown",i=n instanceof Error?n.message:String(n);o.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:i})}}finally{_.current&&q.current&&V.current?.focus()}},X=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(U.current.claim(r)){D(e=>({...e,[r]:"sending"})),H(e=>{let t={...e};return delete t[r],t});try{var i,a;let t,s=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),o=null;try{o=await s.json()}catch{}if(!s.ok){if(o&&"object"==typeof o&&"error"in o&&"string"==typeof o.error)throw Error(o.error);throw Error(`HTTP ${s.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,a=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",i,"","[사이드채팅 답변]",a,...t?["","[추가 지시]",t]:[]].join("\n"));await dB(g,{type:l?"steer":"prompt",message:c}),U.current.markSent(r),D(e=>({...e,[r]:"sent"}))}catch(e){U.current.release(r),D(e=>{let t={...e};return delete t[r],t}),H(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},Q=()=>{if(g&&null!==o.read(g))return void o.abort(g);let e=k.trim();e&&(j(w,""),Y(e))},ee=N[g??""]??[],et=T[g??""],en=g?o.read(g):null,er=x.length>0||ee.length>0||null!==en,ei=en?.model??R[g??""],ea=!g||!n,es=null!==en,eo=!es&&!ea&&k.trim().length>0,el=!g||es,ec=$?.sessionId===g?$:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==en,"data-state":g&&n?en?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[a||g?.slice(0,8)||"세션 없음",ei?` \xb7 ${ei}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===o.read(g)&&(s.clear(g),v([]),I(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:el,style:fF(el),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...fF(),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:J,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,i=`${g}:${n}`,a=W[i],s=P===i;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(fz,{children:e.q}),(0,r.jsx)(fD,{identity:ec,status:"settled",utteranceKey:n,children:(0,r.jsx)(fW,{children:e.a})}),"sent"===a?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!s&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>A(i),style:{...fF(),alignSelf:"flex-start"},children:"메인에 보내기"}),s&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value: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 X(e,n,F[i]??""),disabled:"sending"===a,style:fF("sending"===a),children:"sending"===a?"보내는 중…":"메인으로 전송"}),"sending"!==a&&(0,r.jsx)("button",{type:"button",onClick:()=>A(null),style:fF(),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)}),ee.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(fz,{children:e.question}),(0,r.jsxs)(fD,{identity:ec,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(fW,{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}`)),en&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(fz,{children:en.question}),(0,r.jsx)(fD,{identity:ec,status:"streaming",utteranceKey:`stream:${en.question}`,children:(0,r.jsx)(fW,{streaming:!0,children:en.text})})]}),!er&&(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",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),et&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:et})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),Q()},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,G.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-G.current<100;if(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}es||(e.preventDefault(),Q())},disabled:es||ea,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:ea?"세션 파일이 준비되면 질문할 수 있습니다.":es?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!es&&!eo,style:fF(!es&&!eo),children:es?"중단":"전송"})]})]})]})}let fH="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 fU(...e){return e.filter(Boolean).join(" ")}function f_(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),i=Math.floor(n%1440/60),a=n%60;return r>0?`${r}d ${i}h 후 리셋`:i>0?`${i}h ${a}m 후 리셋`:`${a}m 후 리셋`}function fB(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let i=Math.floor(r/1440),a=Math.floor(r%1440/60),s=r%60;return i>0?`${i}d ${a}h 후 만료`:a>0?`${a}h ${s}m 후 만료`:`${s}m 후 만료`}function fq(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 fV(e,t){return!1!==t?fq(e):"number"==typeof e&&Number.isFinite(e)&&0!==e?`≥${fq(e)}`:"가격 미상"}function fK(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function fG(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 fJ(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function fZ(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function fY(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function fX({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 fQ({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 f0(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 f1({limit:e,now:t,detailed:n}){let i="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,a=Math.max(0,Math.min(100,100*i)),s=Math.round(100*i),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),a=100*r,s=Math.max(0,100-a);if(!n.durationMs){let e=i/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?s/e:s}}let 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?s/u:s,pacePct:p,deltaPct:a-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=s>=90,h=o?.deltaPct!=null&&o.deltaPct>=.5?o.deltaPct:null,f=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:fU("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[s,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":s,children:[(0,r.jsx)("div",{className:fU("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${a}%`}}),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]}),f||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:f??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:f_(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)(fX,{label:"페이스",value:`${o.pacePct.toFixed(1)}%`}):null,o?(0,r.jsx)(fX,{label:o.partial?"남은 한도":`앞으로 ${o.unit}`,value:`${o.burn.toFixed(1)}%`}):null,o?.nominal!=null?(0,r.jsx)(fX,{label:"균등 배분 기준",value:`${o.nominal.toFixed(1)}%/${"하루"===o.unit?"일":"시간"} \xb7 계산값`}):null,l?(0,r.jsx)(fX,{label:"구간",value:`${f0(l.slotStart)} ~ ${f0(l.slotEnd)} \xb7 ${l.slotIndex+1}/${l.slotCount}`}):null,l?(0,r.jsx)(fX,{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 f2={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function f8({confirmId:e,pending:t,primaryRef:n,summary:i,onConfirm:a,onCancel:s}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),s())},children:[(0,r.jsxs)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:["저장된 리셋 ",i]}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:fU(fH,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:a,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:fH,disabled:t,onClick:s,children:"취소"})]})]})}function f4({report:e,brokerOk:t,now:n,active:a,identity:s,recommendation:o,pendingAction:l,feedback:c,onToggle:d,onReset:u}){let p=e.metadata??{},h=s??rw([e])[0],f=e.credentialId,m=Number.isSafeInteger(f)&&f>0,g=e.accountRole,x="usage-only"===g?"사용량":"control-only"===g?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,y=a?"active":e.disabled?"off":v?"auto-blocked":"idle",b="toggle"===l?"전환 중…":"reset"===l?"리셋 사용 중…":m?a?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${f_(e.autoBlockedUntilMs,n)}`:"control-only"===g?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===g?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,i.useId)(),k=(0,i.useId)(),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),M=(0,i.useRef)(null),R=(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,P=function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e),A=P?.id??null,F=fB(P?.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=>f2[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?f_(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=fB(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),H=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&L?.state==="available"&&0!==z&&null!=A;(0,i.useLayoutEffect)(()=>{if(I)return void R.current?.focus();if(E.current){var e;E.current=!1,e=M.current,e?.focus()}},[I]),(0,i.useEffect)(()=>{"reset"!==l&&(e.disabled||!t||L?.state!=="available")&&(E.current=!1,T(null))},[t,l,e.disabled,L?.state]);let U=async()=>{if(I&&!$.current){$.current=!0;try{await u(e,I.creditId)}finally{$.current=!1,E.current=!0,T(null)}}},_=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),B=l?"pending":a?"active":e.disabled?"off":v?"blocked":"idle";return(0,r.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":y,"aria-current":a?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(r0,{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:`${rb(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":B,role:l?"status":void 0,children:b}),null!=_&&_-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${f_(_,n).replace(/ 후 리셋$/,"")}`}):null]})]}),m?(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:fU(fH,"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,T(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(n2)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):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:()=>N(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(f1,{limit:e,now:n,detailed:j},e.id))]}),(e.limits??[]).length>0||h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":j,"aria-controls":k,onClick:()=>{let e=!j;S(e),e||N(!1)},children:j?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?I?(0,r.jsx)(f8,{confirmId:w,pending:"reset"===l,primaryRef:R,summary:I.summary,onConfirm:()=>{U()},onCancel:()=>{E.current=!0,T(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3 border-t border-border pt-2.5","data-reset-state":t?L&&"unavailable"!==L.state?"empty"===L.state||0===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:fU("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,H?(0,r.jsx)("button",{ref:M,type:"button",className:fU(fH,"ml-auto flex-none"),disabled:null!=l,onClick:()=>{A&&T({creditId:A,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 f5({state:e,loading:t,accountState:n,pendingActions:i,feedbackByCredential:a,onToggle:s,onReset:o}){let l=nd(1e4);rY();let c=e.data,d=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,u=rw(c?.reports??[]),p=null==d?-1:c?.reports.findIndex(e=>e.credentialId===d)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(fQ,{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)(f4,{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:a.get(d),onToggle:s,onReset:o},`${e.provider}:${d??e.metadata?.accountId??e.metadata?.email??t}`)})]})}function f6({model:e}){var t,n;let i=Math.max(1,Math.min(100,100*e.costShare)),a="unpriced"!==e.pricing&&"partial"!==e.pricing,s="unpriced"===e.pricing?fV(0,!1):`${fV(e.cost,a)} \xb7 ${fJ(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.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:s})]}),(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:`${i}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(fX,{label:"요청",value:fK(e.requests)}),(0,r.jsx)(fX,{label:"요청당",value:fV(e.costPerRequest,a)}),(0,r.jsx)(fX,{label:"토큰/요청",value:fG(e.tokensPerRequest)}),(0,r.jsx)(fX,{label:"출력/요청",value:fG(e.outputPerRequest)}),(0,r.jsx)(fX,{label:"캐시율",value:(t=e.cacheRate,"not-reported"===(n=e.cacheStatus)?"미보고":"unknown"===n?"알 수 없음":fJ(t,1))}),(0,r.jsx)(fX,{label:"TTFT",value:fZ(e.avgTtft)})]})]})}function f3({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:[fV(e.cost,e.costComplete)," \xb7 ",fJ(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)(fX,{label:"요청",value:fK(e.requests)}),(0,r.jsx)(fX,{label:"요청당",value:fV(e.costPerRequest,e.costComplete)}),(0,r.jsx)(fX,{label:"토큰/요청",value:fG(e.tokensPerRequest)})]})]})}function f7({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:fY(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:fV(e.cost,e.costComplete)})]})}function f9({state:e,loading:t}){let n=e.data,i=n?.overall.unpricedModels??0,a=n?.overall.cacheExcludedModels??0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(fQ,{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)(fX,{label:"요청",value:fK(n.overall.requests)}),(0,r.jsx)(fX,{label:"추정 비용",value:fV(n.overall.cost,n.overall.costComplete)}),(0,r.jsx)(fX,{label:"토큰",value:fG(n.overall.tokens)}),(0,r.jsx)(fX,{label:a>0?"캐시율(일부)":"캐시율",value:fJ(n.overall.cacheRate,1)}),(0,r.jsx)(fX,{label:i>0?"캐시 절감(일부)":"캐시 절감",value:fJ(n.overall.cacheSavings,1)}),(0,r.jsx)(fX,{label:"평균 TTFT",value:fZ(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)(f6,{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)(f3,{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)(f7,{day:e},e.timestamp))]}):null,(0,r.jsxs)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:["`omp stats` 기준 누적값입니다. 금액은 토큰 단가로 계산한 추정치이며 실제 청구액이나 구독 사용량이 아닙니다. 구독 한도 %는 계정 한도 탭에서 확인하세요.",i>0?` 가격을 다 매기지 못한 모델이 ${i}개 있어 추정 비용\xb7비중\xb7캐시 절감은 단가를 아는 사용량만 셉니다. ≥가 붙은 금액은 추정 비용의 최솟값입니다. 에이전트 종류별 집계는 모델을 나누지 않아 모든 행에 ≥를 붙입니다.`:null,a>0?` 캐시 사용량을 보고하지 않거나 보고 여부를 알 수 없는 모델 ${a}개는 캐시율 계산에서 뺐습니다.`:null]})]}):null]})}function me({reports:e,providerConnections:t}){return rY(),(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:re.map(n=>{let i=`character-roster-${n.seed}`,a=`character-roster-${n.seed}-status`,s=`${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:fU("character-roster-item",c&&"is-unavailable"),role:"listitem","aria-labelledby":i,"aria-describedby":c?a:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(r0,{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:a,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,r.jsx)("p",{children:n.voice})]})]}),(0,r.jsxs)("dl",{className:"character-roster-model",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"모델"}),(0,r.jsx)("dd",{title:s,children:s})]}),void 0!==n.oauthPosition?(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"계정"}),(0,r.jsxs)("dd",{children:["OAuth ",n.oauthPosition]})]}):null]}),(0,r.jsxs)("dl",{className:"character-roster-examples",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"호출"}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("code",{children:n.summonExample}),(0,r.jsx)("span",{children:n.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"Main 교체"}),(0,r.jsxs)("dd",{children:[n.switchExample?(0,r.jsx)("code",{children:n.switchExample}):(0,r.jsx)("strong",{children:"교체 불가"}),(0,r.jsx)("span",{children:n.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},n.alias)})})]})}function mt({open:e,sessionId:t,activeTab:n,onTabChange:a,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}),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(!1),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(()=>new Map),[k,j]=(0,i.useState)(()=>new Map),S=(0,i.useRef)(p),C=(0,i.useRef)(null),N=(0,i.useRef)(null),I=(0,i.useRef)(new Set),T=(0,i.useRef)(new Set);S.current=p,(0,i.useEffect)(()=>{if(!e||"characters"!==n)return;let t=new AbortController;return y(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);y(r)}).catch(()=>{t.signal.aborted||y(null)}),()=>t.abort()},[n,e,d.data]),(0,i.useEffect)(()=>{var r;let i,a,s,o,l,c,d,u,p,h;if(m(null),!e||"usage"!==n||!t)return;let f=(a=(r={onClear(){m(null)},onResult(e){m("fresh"===e.status?e.data:null)}}).intervalMs??2500,s=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 rE(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=s(()=>{l&&h(l)},a)))},stop(){u||(u=!0,d+=1,c?.abort(),c=null,p(),l=null)}});return C.current=f,f.setSessionId(t),()=>{f.stop(),C.current===f&&(C.current=null)}},[n,e,t]);let M=(0,i.useCallback)(async e=>{N.current?.abort();let t=new AbortController;N.current=t,x(!0);let n=await r$({refresh:e,previous:S.current.data,signal:t.signal});N.current!==t||t.signal.aborted||(h(n),x(!1))},[]);(0,i.useEffect)(()=>{e&&"models"===n&&("idle"===S.current.status||"error"===S.current.status)&&M(!1)},[n,e,M]),(0,i.useEffect)(()=>()=>{for(let e of(N.current?.abort(),I.current))e.abort()},[]);let R=(0,i.useCallback)(()=>{"models"===n?M(!0):o.refresh()},[n,M,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=rA(T.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 rL(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 rk&&("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(T.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=rA(T.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 rP(n,t,{signal:i.signal}),r=function(e){switch(e.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return e.code.startsWith("http_")?{tone:"error",message:`리셋 사용 실패: 서비스 응답 오류 (${e.code})`}:{tone:"error",message:`리셋 사용 실패: ${e.code}`}}}(e),a=await E();if(e.ok){let e="fresh"===a.status?a.data.reports.find(e=>e.credentialId===n):void 0,t=e?.savedReset?.availableCount;r.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}i.signal.aborted||j(e=>new Map(e).set(n,r))}catch(e){e instanceof rk&&(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 rk){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(T.current.size>0),w(e=>{let t=new Map(e);return t.delete(n),t})}},[E,o]);if(!e)return null;let P="models"===n?p.data?.generatedAt:d.data?.generatedAt,A="models"===n?p.data?.range:void 0,F=A?.from&&A.to?`${fY(A.from)}~${fY(A.to)}`:P?new Date(P).toLocaleTimeString():"",z="models"===n?g:"usage"===n&&u,W=z?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:fU("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)(fs.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>a(e),children:[(0,r.jsxs)(fs.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(fs.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(fs.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(fs.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(fs.J.Indicator,{})]}),(0,r.jsx)(fs.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(me,{reports:d.data?.reports,providerConnections:v})}),(0,r.jsxs)(fs.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)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:z,children:W})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(f5,{state:d,loading:u,accountState:f?.sessionId===t?f:null,pendingActions:b,feedbackByCredential:k,onToggle:e=>{$(e)},onReset:L})]}),(0,r.jsxs)(fs.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)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:z,children:W})]}),(0,r.jsx)(f9,{state:p,loading:g})]})]})]})}let mn="unknown",mr="/api/runs";class mi extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let ma=["completed","error","aborted","interrupted","running"],ms=["main","maker","checker","advisor","unattributed"],mo=["primary","rework","review"],ml=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],mc=["all","attributed"],md=["single","unknown"],mu=["config","harness"];function mp(e){return"object"==typeof e&&null!==e}function mh(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function mf(e){return!!mp(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&&ma.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&&(null===e.harnessRevision||"string"==typeof e.harnessRevision)}function mm(e){return!!mp(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&ms.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&mo.includes(e.purpose))&&mh(e.models)&&mh(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 mg(e){return!!mp(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 mx(e){return!!mp(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.failed&&Number.isFinite(e.failed)&&"number"==typeof e.noMatch&&Number.isFinite(e.noMatch)&&"number"==typeof e.cancelled&&Number.isFinite(e.cancelled)}function mv(e){return!!mp(e)&&"string"==typeof e.kind&&ms.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)&&mh(e.models)&&mh(e.efforts)&&md.includes(e.pairing)}function my(e){return!!mp(e)&&(null===e.revision||"string"==typeof e.revision)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)}function mb(e){return!!mp(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(mv)&&"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)&&Array.isArray(e.harnesses)&&e.harnesses.every(my)}function mw(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&ml.includes(e))}async function mk(e){try{return await e.json()}catch{throw new mi("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}let mj={groupBy:"config",harness:null};function mS(e,t){return e instanceof mi||e instanceof Error?e.message:t}function mC(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function mN(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 mI(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`}let mT={injection:"efficiency.sawKindInjection",developer:"efficiency.sawKindDeveloper",user:"efficiency.sawKindUser",compaction:"efficiency.sawKindCompaction",model:"efficiency.sawKindModel",effort:"efficiency.sawKindEffort",prompt:"efficiency.sawKindPrompt",rules:"efficiency.sawKindRules",memory:"efficiency.sawKindMemory"},mM={ok:"efficiency.sawToolOk",failed:"efficiency.sawToolFailed",noMatch:"efficiency.sawToolNoMatch",cancelled:"efficiency.sawToolCancelled",missing:"efficiency.sawToolMissing"},mR={failed:"critical",noMatch:"neutral",cancelled:"neutral",missing:"warning"};async function mE(e,t){let n,r=await fetch(e,{method:"GET",signal:t});try{n=await r.json()}catch{throw Error(`HTTP ${r.status}: invalid JSON`)}if(!r.ok)throw Error(n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error?n.error:`HTTP ${r.status}`);if(null===n)throw Error(`HTTP ${r.status}: empty body`);return n}function m$(e,t,n){return`${mr}/${encodeURIComponent(e)}/${t}?${new URLSearchParams(n).toString()}`}function mL(e){return e>0?new Date(e).toLocaleTimeString(void 0,{hour12:!1}):"—"}function mP({runId:e,role:t,entryId:n,call:a,label:s,t:o}){let[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)({status:"idle",value:null,error:null});return(0,r.jsxs)("div",{className:"run-saw-full-wrap",children:[(0,r.jsx)("button",{type:"button",className:"run-saw-link","aria-expanded":l,onClick:()=>{let r=!l;if(c(r),!r||"ready"===d.status||"loading"===d.status)return;u({status:"loading",value:null,error:null});let i={role:t,entry:n};a&&(i.call=a),mE(m$(e,"turns",i)).then(e=>u({status:"ready",value:e,error:null})).catch(e=>u({status:"error",value:null,error:e instanceof Error?e.message:String(e)}))},children:l?o("efficiency.sawHideFull"):s}),l?"ready"===d.status&&d.value?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("pre",{className:"run-saw-full",children:d.value.text}),d.value.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:o("efficiency.sawTruncated",{value:mC(d.value.text.length)})}):null]}):"error"===d.status?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:d.error}):(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:o("efficiency.sawLoading")}):null]})}function mA({event:e,runId:t,role:n,t:i}){let a=e.preview;if("compaction"===e.kind&&(null!=e.tokensBefore||null!=e.tokensAfter)){let t=i("efficiency.sawCompactionValue",{before:mN(e.tokensBefore??null),after:mN(e.tokensAfter??null)});a=a?`${t} \xb7 ${a}`:t}else void 0!==e.memoryIds&&(a=i("efficiency.sawMemoryIds",{value:e.memoryIds}));return(0,r.jsxs)("li",{className:"run-saw-event",children:[(0,r.jsxs)("div",{className:"run-saw-event-head",children:[(0,r.jsx)("span",{className:"run-saw-kind",children:i(mT[e.kind])}),(0,r.jsx)("span",{className:"run-saw-source",children:e.source}),(0,r.jsx)("span",{className:"run-saw-dim",children:mL(e.at)}),e.hiddenFromChat?(0,r.jsx)("span",{className:"run-saw-dim",children:i("efficiency.sawHiddenFromChat")}):null,e.sentToModel?null:(0,r.jsx)("span",{className:"run-saw-dim",children:i("efficiency.sawNotSent")})]}),a?(0,r.jsx)("p",{className:"run-saw-preview",children:a}):null,e.chars>e.preview.length?(0,r.jsx)(mP,{runId:t,role:n,entryId:e.entryId,call:null,label:i("efficiency.sawShowFull"),t:i}):null]})}function mF({call:e,runId:t,role:n,turnEntryId:i,t:a}){return(0,r.jsxs)("li",{className:"run-saw-tool",children:[(0,r.jsxs)("div",{className:"run-saw-tool-head",children:[(0,r.jsx)("span",{className:"run-saw-tool-name",children:e.name}),(0,r.jsx)("span",{className:"run-saw-num",children:mI(e.durationMs)}),null!==e.resultChars?(0,r.jsx)("span",{className:"run-saw-dim",children:a("efficiency.sawResultChars",{value:mC(e.resultChars)})}):null,"ok"!==e.status?(0,r.jsx)(nu.E,{tone:mR[e.status],variant:"weak",size:"medium",children:a(mM[e.status])}):null]}),(0,r.jsx)("code",{className:"run-saw-args",children:e.argsPreview}),(0,r.jsxs)("div",{className:"run-saw-tool-actions",children:[e.argsChars>e.argsPreview.length?(0,r.jsx)(mP,{runId:t,role:n,entryId:i,call:e.toolCallId,label:a("efficiency.sawShowArgs"),t:a}):null,e.resultEntryId?(0,r.jsx)(mP,{runId:t,role:n,entryId:e.resultEntryId,call:null,label:a("efficiency.sawShowResult"),t:a}):null]})]})}function mz({turn:e,runId:t,role:n,t:i}){let a=[e.model,mI(e.durationMs),e.usage?i("efficiency.sawUsage",{input:mN(e.usage.input),output:mN(e.usage.output),cacheRead:mN(e.usage.cacheRead)}):null,e.stopReason?i("efficiency.sawStop",{value:e.stopReason}):null].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"run-saw-turn",children:[(0,r.jsxs)("div",{className:"run-saw-turn-head",children:[(0,r.jsx)("span",{className:"run-saw-turn-label",children:i("efficiency.sawTurnLabel",{index:e.index})}),(0,r.jsx)("span",{className:"run-saw-dim",children:mL(e.at)})]}),(0,r.jsx)("p",{className:"run-saw-turn-meta",children:a}),e.toolsAdded.length>0||e.toolsRemoved.length>0?(0,r.jsx)("p",{className:"run-saw-dim",title:[...e.toolsAdded.map(e=>`+${e}`),...e.toolsRemoved.map(e=>`−${e}`)].join(" "),children:i("efficiency.sawToolsChanged",{added:e.toolsAdded.join(", ")||"0",removed:e.toolsRemoved.join(", ")||"0"})}):null,e.before.length>0?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:i("efficiency.sawBefore")}),(0,r.jsx)("ul",{className:"run-saw-events",children:e.before.map(e=>(0,r.jsx)(mA,{event:e,runId:t,role:n,t:i},e.entryId))})]}):null,e.toolCalls.length>0?(0,r.jsx)("ul",{className:"run-saw-tools",children:e.toolCalls.map(a=>(0,r.jsx)(mF,{call:a,runId:t,role:n,turnEntryId:e.entryId,t:i},a.toolCallId))}):null]})}function mW({runId:e,role:t,t:n}){let[a,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let n=new AbortController;return o(null),c(null),mE(m$(e,"prelude",{role:t}),n.signal).then(o).catch(e=>{n.signal.aborted||c(e instanceof Error?e.message:String(e))}),()=>n.abort()},[e,t]);let p=a?.recorded.digests.at(-1)??null,h=a?.rebuilt;return(0,r.jsxs)("section",{className:"run-saw-prelude","aria-label":n("efficiency.sawPreludeTitle"),children:[(0,r.jsx)("h4",{className:"run-saw-subtitle",children:n("efficiency.sawPreludeTitle")}),l?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:l}):null,a||l?null:(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:n("efficiency.sawLoading")}),a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:n("efficiency.sawPreludeRecorded")}),(0,r.jsx)("p",{className:"run-saw-line",children:p?n("efficiency.sawPreludeDigest",{value:p.digest}):n("efficiency.sawPreludeDigestNone")}),a.recorded.activeTools?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeTools",{value:a.recorded.activeTools.length})}),(0,r.jsx)("p",{className:"run-saw-names",children:a.recorded.activeTools.join(" \xb7 ")})]}):null,a.recorded.memoryRecall?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeMemory")}),(0,r.jsx)("p",{className:"run-saw-preview",children:a.recorded.memoryRecall.preview}),a.recorded.memoryRecall.chars>a.recorded.memoryRecall.preview.length?(0,r.jsx)(mP,{runId:e,role:t,entryId:a.recorded.memoryRecall.entryId,call:null,label:n("efficiency.sawShowFull"),t:n}):null]}):null,h?.status==="not-loaded"?(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeNotLoaded")}):h?.status==="available"?(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{u(!0),mE(m$(e,"prelude",{role:t,rebuild:"1"})).then(o).catch(e=>c(e instanceof Error?e.message:String(e))).finally(()=>u(!1))},disabled:d,children:n(d?"efficiency.sawPreludeLoading":"efficiency.sawPreludeReconstruct")})}):h?.status==="rebuilt"?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeApprox")}),null!==h.matchesRecorded?(0,r.jsx)("p",{className:"run-saw-line",children:n(h.matchesRecorded?"efficiency.sawPreludeMatch":"efficiency.sawPreludeMismatch")}):null,(0,r.jsx)("pre",{className:"run-saw-full",children:h.text}),h.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:n("efficiency.sawTruncated",{value:mC(h.text.length)})}):null]}):null]}):null]})}let mD={status:"idle",page:null,turns:[],loadingMore:!1,error:null};function mO({runId:e,t}){let[n,a]=(0,i.useState)(!1),[o,c]=(0,i.useState)("main"),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(mD),f=(0,i.useRef)(null),m=(0,i.useCallback)(t=>{f.current?.abort();let n=new AbortController;f.current=n,h(e=>0===t?{...mD,status:"loading"}:{...e,loadingMore:!0});let r={role:o,offset:String(t),limit:String(30)};d&&(r.injectedOnly="1"),mE(m$(e,"turns",r),n.signal).then(e=>h(n=>({status:"ready",page:e,turns:0===t?e.turns:[...n.turns,...e.turns],loadingMore:!1,error:null}))).catch(e=>{n.signal.aborted||h(n=>({...n,status:0===t?"error":n.status,loadingMore:!1,error:e instanceof Error?e.message:String(e)}))})},[e,o,d]);(0,i.useEffect)(()=>{n&&m(0)},[n,m]),(0,i.useEffect)(()=>()=>f.current?.abort(),[]);let g=p.page,x=g?g.total-p.turns.length:0,v=g?Object.entries(g.counts.bySource).sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])):[];return(0,r.jsxs)("section",{className:"run-saw","aria-label":t("efficiency.sawSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.sawSection")}),(0,r.jsx)("p",{className:"run-saw-approx",children:t("efficiency.sawApproxNote")}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"run-saw-controls",children:[g&&g.roles.length>1?(0,r.jsxs)("label",{className:"run-saw-role",children:[(0,r.jsx)("span",{children:t("efficiency.sawRole")}),(0,r.jsx)("select",{className:"efficiency-folder-select",value:o,onChange:e=>c(e.target.value),children:g.roles.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]}):null,(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:d,onPressedChange:u,children:t("efficiency.sawOnlyInjected")})]}),"loading"===p.status||"idle"===p.status?(0,r.jsx)("p",{className:"efficiency-empty",role:"status",children:t("efficiency.sawLoading")}):"error"===p.status?(0,r.jsxs)("div",{className:"efficiency-empty",role:"alert",children:[(0,r.jsx)("div",{children:t("efficiency.sawError")}),(0,r.jsx)("div",{className:"run-saw-dim",children:p.error})]}):g?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-summary",children:t("efficiency.sawSummary",{turns:g.counts.turns,injections:g.counts.injections,tools:g.counts.toolCalls,failed:g.counts.toolFailures})}),v.length>0?(0,r.jsx)("p",{className:"run-saw-names",children:v.map(([e,t])=>`${e} ${t}`).join(" \xb7 ")}):null,(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",children:t("efficiency.sawSecretsMasked")}),0===p.turns.length?(0,r.jsx)("p",{className:"efficiency-empty",children:t(d?"efficiency.sawFilterEmpty":"efficiency.sawEmpty")}):(0,r.jsx)("ol",{className:"run-saw-turns",children:p.turns.map(n=>(0,r.jsx)(mz,{turn:n,runId:e,role:g.role,t:t},n.entryId))}),g.trailing.length>0&&x<=0?(0,r.jsxs)("div",{className:"run-saw-group run-saw-trailing",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:t("efficiency.sawTrailing")}),(0,r.jsx)("ul",{className:"run-saw-events",children:g.trailing.map(n=>(0,r.jsx)(mA,{event:n,runId:e,role:g.role,t:t},n.entryId))})]}):null,(0,r.jsxs)("div",{className:"run-saw-actions",children:[(0,r.jsx)("span",{className:"run-saw-dim",children:t("efficiency.sawShown",{shown:p.turns.length,total:g.total})}),x>0?(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>m(p.turns.length),disabled:p.loadingMore,children:p.loadingMore?t("efficiency.sawLoading"):t("efficiency.sawMore",{value:Math.min(x,30)})}):null]}),p.error?(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",role:"alert",children:p.error}):null,(0,r.jsx)(mW,{runId:e,role:g.role,t:t})]}):null]}):(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>a(!0),children:t("efficiency.sawOpen")})})]})}let mH={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},mU={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function m_(...e){return e.filter(Boolean).join(" ")}function mB(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 mq(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function mV(e,t){return null===e?t("efficiency.harnessUnknown"):e.slice(0,7)}function mK({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 text-xs text-text-muted [overflow-wrap:anywhere]",children:e}),(0,r.jsx)("dd",{className:"m-0 flex-none text-right font-mono text-xs tabular-nums text-text",children:t})]})}function mG({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 mJ({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",mB(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function mZ({outcome:e,t}){return(0,r.jsx)(nu.E,{tone:mH[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function mY({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(nu.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 mX({run:e,selected:t,onSelect:n,t:i}){let a=e.title&&e.title.trim().length>0?e.title:i("efficiency.noTitle");return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",onClick:n,"aria-current":t?"true":void 0,className:m_("efficiency-run-item",t&&"is-selected"),children:[(0,r.jsxs)("span",{className:"efficiency-run-top",children:[(0,r.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,r.jsx)("span",{className:"efficiency-run-title",title:a,children:a}),(0,r.jsx)(mZ,{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}",mI(e.wallClockMs))}),(0,r.jsx)(mJ,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:i}),(0,r.jsx)("span",{className:"font-mono tabular-nums",title:e.harnessRevision??i("efficiency.harnessUnknown"),children:i("efficiency.harnessValue").replace("{value}",mV(e.harnessRevision,i))})]})]})})}function mQ({role:e,t}){let n=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),i=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort"),a=e.outputTokens-e.helpers.reduce((e,t)=>e+t.outputTokens,0),s=t(`efficiency.role${"main"===e.kind?"Main":"maker"===e.kind?"Maker":"checker"===e.kind?"Checker":"advisor"===e.kind?"Advisor":"Unattributed"}`);return(0,r.jsxs)("details",{className:"efficiency-role",children:[(0,r.jsxs)("summary",{className:"efficiency-role-summary",children:[(0,r.jsxs)("span",{className:"efficiency-role-head",children:[(0,r.jsx)("span",{className:"efficiency-role-id",children:e.id}),(0,r.jsx)(nu.E,{tone:mU[e.kind]??"neutral",variant:"weak",size:"medium",children:s}),(0,r.jsx)(mY,{purpose:e.purpose,t:t})]}),(0,r.jsx)("span",{className:"efficiency-model-line",title:n,children:n}),(0,r.jsxs)("span",{className:"efficiency-role-stats",children:[(0,r.jsxs)("span",{children:[t("efficiency.busyTime")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:mI(e.busyMs)})]}),(0,r.jsxs)("span",{children:[t("efficiency.estimatedCost")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:mB(e.estimatedCostUsd)})]}),(0,r.jsxs)("span",{children:[t("efficiency.tokens")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:mN(e.totalTokens)})]})]})]}),(0,r.jsxs)("div",{className:"efficiency-role-body",children:[(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:"efficiency-metrics",children:[(0,r.jsx)(mK,{label:t("efficiency.unpricedRequests"),value:mC(e.unpricedRequests)}),(0,r.jsx)(mK,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?mI(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,r.jsx)(mK,{label:t("efficiency.outputTokens"),value:mN(a)})]}),e.ttftRequests>0&&e.ttftRequests<e.requestCount?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.firstTokenPartial",{recorded:e.ttftRequests,total:e.requestCount})}):null,e.untimedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.untimedLowerBound").replace("{value}",mC(e.untimedRequests))}):null,e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.unpricedLowerBound")}):null,e.helpers.length>0?(0,r.jsxs)("section",{className:"efficiency-helpers","aria-label":t("efficiency.helpersTitle"),children:[(0,r.jsx)("h4",{className:"efficiency-helpers-title",children:t("efficiency.helpersTitle")}),(0,r.jsx)("ul",{className:"efficiency-helper-list",children:e.helpers.map(e=>(0,r.jsxs)("li",{className:"efficiency-helper",children:[(0,r.jsx)("span",{className:"efficiency-helper-name",children:`${e.purpose} \xb7 ${e.model}`}),(0,r.jsx)("span",{className:"efficiency-helper-value",children:t("efficiency.helperCallsValue",{count:e.requestCount,output:mN(e.outputTokens),tokens:mN(e.totalTokens),cost:mB(e.estimatedCostUsd)})})]},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.helpersIncludedNote")})]}):null]})]})}function m0({item:e,t}){let n="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,r.jsxs)("li",{className:"efficiency-bottleneck","data-kind":e.kind,children:[(0,r.jsx)("span",{className:"efficiency-bottleneck-label",children:n}),(0,r.jsx)("span",{className:"efficiency-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"efficiency-meter-fill",style:{inlineSize:`${Number.isFinite(e.relative)?Math.max(1,Math.min(100,100*e.relative)):1}%`}})}),(0,r.jsx)("span",{className:"efficiency-bottleneck-value",children:mI(e.ms)})]})}function m1({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:mI(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:mI(e.busyMs)})]})]}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,r.jsxs)("dl",{className:"efficiency-metrics",children:[(0,r.jsx)(mK,{label:t("efficiency.estimatedCost"),value:mB(e.estimatedCostUsd)}),(0,r.jsx)(mK,{label:t("efficiency.tokens"),value:mN(e.totalTokens)}),(0,r.jsx)(mK,{label:t("efficiency.harness"),value:mV(e.harnessRevision,t)})]}),e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(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)("ol",{className:"efficiency-bottlenecks",children:e.bottlenecks.map(e=>(0,r.jsx)(m0,{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}",mI(e.unmeasuredMs))}):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-roles",children:e.roles.map(e=>(0,r.jsx)(mQ,{role:e,t:t},e.id))},e.runId):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),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:"efficiency-metrics",children:e.toolTotals.map(e=>(0,r.jsx)(mK,{label:[e.toolName,t("efficiency.toolFailedValue").replace("{value}",String(e.failed)),...e.noMatch>0?[t("efficiency.toolNoMatchValue").replace("{value}",String(e.noMatch))]:[],...e.cancelled>0?[t("efficiency.toolCancelledValue").replace("{value}",String(e.cancelled))]:[]].join(" \xb7 "),value:mC(e.calls)},e.toolName))})]}):null,(0,r.jsx)(mO,{runId:e.runId,t:t},e.runId)]})}function m2(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 m8({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)(mK,{label:t("efficiency.scopeSessions"),value:mC(e.sessionCount)}),(0,r.jsx)(mK,{label:t("efficiency.scopeRuns"),value:mC(e.runCount)}),(0,r.jsx)(mK,{label:t("efficiency.scopeExcludedRuns"),value:mC(e.excludedRunCount)})]})})}function m4({config:e,baselineRuns:t,t:n}){let i=t>0?e.runCount/t:0,a=e.runCount>0?e.reworkRuns/e.runCount:0,s=e.runCount>0?e.errorRuns/e.runCount:0,o=function(e,t){if(1===e.length)return{text:mV(e[0].revision,t),full:e[0].revision??t("efficiency.harnessUnknown")};let n=e.map(e=>`${mV(e.revision,t)} \xd7${e.runCount}`),r=n.slice(0,4).join(" \xb7 ");return{text:n.length>4?`${r} \xb7 +${n.length-4}`:r,full:e.map(e=>`${e.revision??t("efficiency.harnessUnknown")} \xd7${e.runCount}`).join("\n")}}(e.harnesses,n);return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsx)("p",{className:"efficiency-model-line",title:m2(e.roles),children:m2(e.roles)}),(0,r.jsx)("p",{className:"efficiency-dim font-mono tabular-nums",title:o.full,children:n("efficiency.harnessValue").replace("{value}",o.text)}),e.roles.some(e=>"unknown"===e.pairing)?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.mixedPairingNote")}):null,(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:mq(i)})]}),(0,r.jsx)(mG,{share:i,label:mq(i)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(mK,{label:n("efficiency.medianElapsed"),value:mI(e.medianWallClockMs)}),(0,r.jsx)(mK,{label:n("efficiency.medianBusy"),value:mI(e.medianBusyMs)}),(0,r.jsx)(mK,{label:n("efficiency.medianTokens"),value:mN(e.medianTotalTokens)}),(0,r.jsx)(mK,{label:n("efficiency.medianEstimatedCost"),value:mB(e.medianEstimatedCostUsd)}),(0,r.jsx)(mK,{label:n("efficiency.totalEstimatedCost"),value:mB(e.totalEstimatedCostUsd)}),(0,r.jsx)(mK,{label:n("efficiency.reworkRate"),value:mq(a,1)}),(0,r.jsx)(mK,{label:n("efficiency.errorRate"),value:mq(s,1)}),(0,r.jsx)(mK,{label:n("efficiency.unpricedRuns"),value:mC(e.unpricedRuns)}),(0,r.jsx)(mK,{label:n("efficiency.untimedRuns"),value:mC(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",mC(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function m5({open:e,sessionId:t,activeTab:n,onTabChange:a,client:o,className:c}){let d=(0,i.useId)(),u=(0,i.useId)(),{t:p}=(0,F.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[a]=(0,i.useState)(()=>r??function(e=(e,t)=>fetch(e,t)){let t=async(t,n)=>{let r;try{r=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new mi("unreachable","효율 기록에 연결할 수 없습니다.")}let i=await mk(r);if(!r.ok){var a;throw new mi("http",(a=`HTTP ${r.status}`,null!==i&&"object"==typeof i&&"error"in i&&"string"==typeof i.error&&i.error?i.error:a),r.status)}return{response:r,body:i}};return{async listRuns(e,n,r){let{response:i,body:a}=await t(`${mr}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!mp(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(mf)&&mw(e.unmeasured)))throw new mi("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new mi("invalid-response",t,n)}}(a,"실행 목록 응답이 올바르지 않습니다.",i.status)},async getRun(e,n){let{response:r,body:i}=await t(`${mr}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!mf(e)||!(Array.isArray(e.roles)&&e.roles.every(mm)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(mg)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(mx)&&mw(e.unmeasured)))throw new mi("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new mi("invalid-response",t,n)}}(i,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,i,a){let s=new URLSearchParams;null!==e&&""!==e&&s.set("folder",e),s.set("sessions",String(n)),s.set("scope",r),a?.groupBy==="harness"&&s.set("groupBy","harness"),a?.harness&&s.set("harness",a.harness);let{response:o,body:l}=await t(`/api/experiments?${s.toString()}`,{method:"GET",signal:i});return function(e,t,n=null){try{if(!mp(e)||!((null===e.folder||"string"==typeof e.folder)&&mh(e.folders)&&"string"==typeof e.scope&&mc.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(mb)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&"string"==typeof e.groupBy&&mu.includes(e.groupBy)&&(null===e.harness||"string"==typeof e.harness)&&Array.isArray(e.harnesses)&&e.harnesses.every(my)&&mw(e.unmeasured)))throw new mi("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new mi("invalid-response",t,n)}}(l,"구성 비교 응답이 올바르지 않습니다.",o.status)}}}()),[s,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),[f,m]=(0,i.useState)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),y=(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 b=(0,i.useCallback)(()=>{if(!t||"governor"!==n||!e)return;g.current?.abort();let r=new AbortController;g.current=r,o(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),a.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&g.current===r){if(0===e.runs.length)return void o({status:"empty",runs:[],error:null});o({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||g.current!==r||o({status:"error",runs:[],error:mS(e,"실행 목록을 불러오지 못했습니다.")})})},[n,a,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}),a.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:mS(t,"실행 상세를 불러오지 못했습니다.")})})},[a,t]),k=(0,i.useCallback)((e,r="all",i=mj)=>{if(!t||"lab"!==n)return;v.current?.abort();let s=new AbortController;v.current=s,u(e=>({status:"loading",response:"ready"===e.status||"empty"===e.status?e.response:null,error:null})),a.listExperiments(e,30,r,s.signal,i).then(e=>{if(!s.signal.aborted&&v.current===s){if(0===e.configs.length)return void u({status:"empty",response:e,error:null});u({status:"ready",response:e,error:null})}}).catch(e=>{s.signal.aborted||v.current!==s||u({status:"error",response:null,error:mS(e,"구성 비교를 불러오지 못했습니다.")})})},[n,a,t]);(0,i.useEffect)(()=>{if(t&&"governor"===n)return b(),()=>{g.current?.abort(),g.current=null}},[n,b,e,t]),(0,i.useEffect)(()=>{if(t&&"lab"===n)return k(y.current),()=>{v.current?.abort(),v.current=null}},[n,k,t]),(0,i.useEffect)(()=>{if(t&&"governor"===n&&null!==p)return w(p),()=>{x.current?.abort(),x.current=null}},[n,w,p,t]),(0,i.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,i.useCallback)(e=>{x.current?.abort(),x.current=null,h(e),null===e&&c({status:"idle",runId:null,detail:null,error:null})},[]);return{list:s,detail:l,experiments:d,selectedRunId:p,selectRun:j,refreshRuns:(0,i.useCallback)(()=>{b()},[b]),refreshExperiments:(0,i.useCallback)((e,t="all",n=mj)=>{let r=void 0===e?y.current:e;void 0!==e&&(y.current=e,m(e)),k(r,t,n)},[k]),experimentFolder:f}}({sessionId:t,visible:e,activeTab:n,client:o}),[f,m]=(0,i.useState)(""),g=(0,i.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),x=(0,i.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),v=h.experimentFolder,y=h.experiments.response?.scope??"all",b={groupBy:h.experiments.response?.groupBy??"config",harness:h.experiments.response?.harness??null},w=h.experiments.response?.harnesses??[];if(!e)return null;let k="governor"===n&&"loading"===h.list.status||"lab"===n&&"loading"===h.experiments.status,j=k?p("efficiency.refreshing"):p("efficiency.refresh"),S="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:m_("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",c),"aria-labelledby":d,"aria-busy":k,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:S}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===n?h.refreshRuns():h.refreshExperiments(void 0,y,b)},disabled:k,children:j})]}),(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:m_("min-h-10 border-0 border-r border-border bg-bg px-4 text-sm text-text-muted last:border-r-0 hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent",n===e&&"bg-bg-selected font-semibold text-text"),onClick:()=>a(e),children:"governor"===e?p("efficiency.governor"):p("efficiency.lab")},e))}),"lab"===n?(0,r.jsxs)("div",{className:"efficiency-folderbar",children:[(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-folder`,children:p("efficiency.folder")}),(0,r.jsxs)("select",{id:`${u}-folder`,className:"efficiency-folder-select",value:v??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;m(t??""),h.refreshExperiments(t,y,b)},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.folderAll")}),g.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),v&&!g.includes(v)?(0,r.jsx)("option",{value:v,children:v}):null]}),(0,r.jsx)("input",{className:"efficiency-folder-input",value:f,placeholder:p("efficiency.folderPlaceholder"),"aria-label":p("efficiency.folder"),onChange:e=>m(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===f.trim()?null:f.trim();h.refreshExperiments(e,y,b)}}}),(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-harness`,children:p("efficiency.harness")}),(0,r.jsxs)("select",{id:`${u}-harness`,className:"efficiency-folder-select font-mono",value:b.harness??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;h.refreshExperiments(void 0,y,{groupBy:b.groupBy,harness:t})},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.harnessAll")}),w.map(e=>(0,r.jsx)("option",{value:e.revision??mn,children:`${mV(e.revision,p)} (${e.runCount})`},e.revision??mn)),b.harness&&!w.some(e=>(e.revision??mn)===b.harness)?(0,r.jsx)("option",{value:b.harness,children:b.harness===mn?p("efficiency.harnessUnknown"):b.harness.slice(0,7)}):null]}),(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"===y,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all",b),children:p("efficiency.scopeAttributed")}),(0,r.jsx)(nu.E,{tone:"attributed"===y?"informative":"neutral",variant:"weak",size:"medium",children:p("attributed"===y?"efficiency.scopeAttributed":"efficiency.scopeAll")}),(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"harness"===b.groupBy,onPressedChange:e=>h.refreshExperiments(void 0,y,{groupBy:e?"harness":"config",harness:b.harness}),children:p("efficiency.groupByHarness")})]})]}):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)(mX,{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)(m1,{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.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")}),(0,r.jsxs)("div",{className:"efficiency-stack",children:[(0,r.jsx)(m8,{response:e,t:p}),e.configs.map(t=>(0,r.jsx)(m4,{config:t,baselineRuns:x,t:p},JSON.stringify([t.roles.map(e=>[e.kind,e.models,e.efforts,e.count]),"harness"===e.groupBy?t.harnesses[0]?.revision??null:null])))]})]}):(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)(m8,{response:e,t:p})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")})]})})()})]})}function m6({cwd:e,onOpenFile:t}){let n,{t:a}=(0,F.s)(),[s,o]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e)return;let t=new AbortController;return fetch(`/api/project-docs?cwd=${encodeURIComponent(e)}`,{signal:t.signal}).then(async n=>{let r=await n.json();t.signal.aborted||(403===n.status?o({kind:"denied",cwd:e}):n.ok?o({kind:"ready",cwd:e,docs:r}):o({kind:"error",cwd:e,message:r.error??`HTTP ${n.status}`}))}).catch(n=>{t.signal.aborted||o({kind:"error",cwd:e,message:n instanceof Error?n.message:String(n)})}),()=>t.abort()},[e]);let l=e&&s?.cwd===e?s:null,c=(e,n,i)=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:"found"===i.state&&i.path?(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:i.path,"aria-label":`${e} — ${i.path}`,onClick:()=>t(i.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:n})]}):(0,r.jsxs)("div",{className:"file-doc-shortcuts-unavailable",title:i.path??void 0,children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:"denied"===i.state?a("files.docs.denied",{file:n}):a("files.docs.missing",{file:n})})]})});if(e)if(l)if("denied"===l.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.projectDenied")});else if("error"===l.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"alert",children:a("files.docs.loadFailed",{error:l.message})});else{let{docs:e}=l,i="missing"===e.handoff.state&&"missing"===e.docMap.state&&"missing"===e.history.state;n=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"file-doc-shortcuts-project",title:e.projectDir,children:a("files.docs.projectDir",{path:e.projectDir})}),i?(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.noneFound")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("ul",{className:"file-doc-shortcuts-list",children:[c(a("files.docs.current"),"HANDOFF.md",e.handoff),c(a("files.docs.map"),"doc/README.md",e.docMap)]}),(0,r.jsx)("h3",{className:"file-doc-shortcuts-heading",id:"file-doc-shortcuts-records",children:a("files.docs.records")}),e.history.records.length>0?(0,r.jsx)("ul",{className:"file-doc-shortcuts-list","aria-labelledby":"file-doc-shortcuts-records",children:e.history.records.map(e=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:e.path,"aria-label":`${a("files.docs.records")} ${e.date} ${e.topic} — ${e.fileName}`,onClick:()=>t(e.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-date",children:e.date}),(0,r.jsxs)("span",{className:"file-doc-shortcuts-file",children:[e.topic,"main.md"===e.fileName?"":` \xb7 ${e.fileName}`]})]})},e.path))}):(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:"denied"===e.history.state?a("files.docs.denied",{file:"doc/history"}):a("files.docs.missing",{file:"doc/history"})})]})]})}else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"status",children:a("files.docs.loading")});else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.noProject")});return(0,r.jsxs)("section",{className:"file-doc-shortcuts","aria-labelledby":"file-doc-shortcuts-title",children:[(0,r.jsx)("h2",{className:"file-doc-shortcuts-title",id:"file-doc-shortcuts-title",children:a("files.noneOpen")}),n]})}function m3(e){return"message"===e.type&&"message"in e}function m7(e){let t=e,n=t.branchPreview,r=m3(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&m3(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function m9({node:e,activePathIds:t,depth:n,isLast:i,parentLines:a,onSelect:s}){let{node:o,skipped:l,branchPreview:c,labelEntry:d}=m7(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),f=c?c.role??null:m3(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:()=>s(o.entry.id),children:[a.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),f&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===f?"var(--accent)":"var(--text-dim)",background:"user"===f?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===f?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===f?"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)(m9,{node:e,activePathIds:t,depth:n+1,isLast:l===o.children.length-1,parentLines:[...a,!i],onSelect:s},e.entry.id))]})}function ge({tree:e,activeLeafId:t,onLeafChange:n,hasSession:a}){let{t:s}=(0,F.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 a=e(i.children,n);if(a)return a}return null}(e,[])??[]):new Set,[e,t]),l=(0,i.useCallback)(e=>{n(e)},[n]),c=a?!function e(t){if(t.length>1)return!0;for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)?s("i18n.noBranches"):null:s("i18n.noActiveSession"),d=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=m7(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)(m9,{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??s("i18n.noBranches")})}function gt(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function gn(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function gr(e){let t=e.currentTime;[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n;let s=t+.18*r;a.gain.setValueAtTime(0,s),a.gain.linearRampToValueAtTime(.18,s+.02),a.gain.exponentialRampToValueAtTime(.001,s+.45),i.start(s),i.stop(s+.45)})}async function gi(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function ga(e){let t=e.window?.durationMs;if("number"==typeof t&&Number.isFinite(t)&&t>0)return t>=5184e5?"weekly":t<=432e5?"short":"other";let n=e.scope?.windowId,r=`${"string"==typeof n?n:""} ${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"}let gs="omp-sidebar-usage-collapsed",go="omp-sidebar-usage-order";function gl(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function gc(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function gd({direction:e}){return(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"up"===e?"2.5 7.5 6 4 9.5 7.5":"2.5 4.5 6 8 9.5 4.5"})})}function gu({usage:e,onOpen:t,onRelogin:n}){var a,s;let o,l,c,d,{t:u}=(0,F.s)(),p=U(),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),j=(0,i.useRef)(null),[S,C]=(0,i.useState)(!0);(0,i.useEffect)(()=>{try{C("0"!==window.localStorage.getItem(gs))}catch{}v(function(){try{let e=JSON.parse(window.localStorage.getItem(go)??"[]");return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}catch{return[]}}())},[]);let N=e.bai,I=e.state.data?.reports??[],T=nd(1e4),M=(o=rw(I),l=[],c=[],I.forEach((e,t)=>{let n=e.authError;if(!0===e.disabled&&!n)return;let r=o[t],i="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>T,a=!0===e.disabled?[]:e.limits??[],s=a.some(e=>e.scope?.shared===!0&&n2(e)),d=a.some(e=>null!==gl(e)&&"short"!==ga(e)),u=[];for(let e of a){let t=gl(e);null!==t&&(!d||"short"!==ga(e)||function(e){let t=e.amount?.usedFraction,n="number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null;return n2(e)||"warning"===e.status||null!==n&&n>=90}(e))&&u.push({key:e.id,label:e.label||e.id,percent:Math.round(100*t),state:i?"blocked":s?"account-spent":n2(e)?"spent":"usable"})}if(0===u.length&&!n)return;let p=n?"auth":i?"blocked":s?"account-spent":"ok",h={orderKey:"string"==typeof e.accountKey&&e.accountKey.length>0?`${e.provider}:${e.accountKey}`:void 0!==e.credentialId?`${e.provider}:#${e.credentialId}`:`${e.provider}:@${t}`,provider:e.provider,alias:r.alias,seed:r.seed,masked:r.masked,..."string"==typeof e.accountKey?{accountKey:e.accountKey}:{},rows:u,state:p,...n?{authError:n}:{},usable:"ok"===p&&u.some(e=>"usable"===e.state)};(h.usable?l:c).push(h)}),a=[...l,...c],d=new Map(x.map((e,t)=>[e,t])),[...a.filter(e=>d.has(e.orderKey)).sort((e,t)=>d.get(e.orderKey)-d.get(t.orderKey)),...a.filter(e=>!d.has(e.orderKey))]);(0,i.useEffect)(()=>{if(null===w)return;let e=[...j.current?.querySelectorAll("[data-order-key]")??[]].find(e=>e.dataset.orderKey===w.orderKey),t=e?.querySelector(`[data-direction="${w.direction}"]`),n=e?.querySelector(`[data-direction="${"up"===w.direction?"down":"up"}"]`);(t&&!t.disabled?t:n)?.focus(),k(null)},[w]);let R=(e,t)=>{let n,r,i,a="up"===t?e-1:e+1;if(a<0||a>=M.length)return;let s=M.map(e=>e.orderKey);[s[e],s[a]]=[s[a],s[e]];let o=(n=new Set(s),r=[...x,...s.filter(e=>!x.includes(e))],i=0,r.map(e=>n.has(e)?s[i++]:e));v(o);try{window.localStorage.setItem(go,JSON.stringify(o))}catch{}b(u("usage.moved",{account:M[e].alias,position:a+1})),k({orderKey:M[e].orderKey,direction:t})},E=e=>Math.max(1,e.rows.length),$=0,L=h||m?M:M.filter(e=>!($>=2)&&($+=E(e),!0)),P=M.slice(L.length).reduce((e,t)=>e+E(t),0),A=M.filter(e=>"auth"===e.state).length,z="measured"===N.status?(s=N.tokens)>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(Math.round(s)):u("empty"===N.status?"usage.baiEmpty":"usage.baiUnmeasured"),W="measured"===N.status&&null!==N.from&&null!==N.to?u("usage.baiRange",{from:gc(N.from),to:gc(N.to)}):null,D=e=>"auth"===e.state?u(e.authError?.reloginRequired?"usage.authExpired":"usage.authUnavailable"):"blocked"===e.state?u("usage.accountBlocked"):"account-spent"===e.state?u("usage.accountSpent"):null,O=e=>"spent"===e.state?u("usage.limitSpent"):null,H=u("usage.open",{rows:[...L.flatMap(e=>{let t=D(e);return 0===e.rows.length?[`${e.alias} (${t??""}${e.authError?`: ${e.authError.message}`:""})`]:e.rows.map(n=>{let r=O(n)??t;return`${e.alias} ${n.label} ${n.percent}%${null===r?"":` (${r})`}`})}),`${u("usage.bai")} ${z}${null===W?"":` \xb7 ${W}`}`].join(", ")})+(P>0?u("usage.openMore",{count:P}):""),_=M[0],B=void 0===_?{label:u("usage.bai"),value:z,danger:!1}:0===_.rows.length?{label:_.alias,value:D(_)??"",danger:!0}:{label:_.rows[0].label,value:`${_.rows[0].percent}%`,danger:_.rows[0].percent>=90},q=A>0?u("usage.authIssues",{count:A}):null,V=(0,r.jsxs)("div",{className:"navigator-usage",role:"group","aria-label":u("usage.title"),"data-editing":m?"":void 0,onClick:e=>{m||e.target instanceof Element&&e.target.closest("button, a")||t()},children:[(0,r.jsxs)("span",{className:"navigator-usage-header",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-open","aria-label":H,onClick:t,children:u("usage.title")}),null===q?null:(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),M.length>1&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-edit","data-active":m?"":void 0,onClick:()=>g(e=>!e),children:m?u("usage.reorderDone"):u("usage.reorder")})]}),(0,r.jsx)("div",{ref:j,role:m?"list":void 0,"aria-label":m?u("usage.reorderGroup"):void 0,className:"navigator-usage-groups",children:0===M.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:u("usage.none")}):L.map((e,t)=>{let i=D(e);return(0,r.jsxs)("div",{className:"navigator-usage-group","data-order-key":e.orderKey,role:m?"listitem":void 0,children:[(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(r0,{seed:e.seed,size:24,provider:e.provider}),(0,r.jsx)("span",{className:"navigator-usage-alias",children:e.alias}),null===i?null:(0,r.jsx)("span",{className:"navigator-usage-state","data-tone":"auth"===e.state?"danger":void 0,children:i}),m&&(0,r.jsxs)("span",{className:"navigator-usage-moves",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"up","aria-label":u("usage.moveUp",{account:e.alias}),disabled:0===t,onClick:()=>R(t,"up"),children:(0,r.jsx)(gd,{direction:"up"})}),(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"down","aria-label":u("usage.moveDown",{account:e.alias}),disabled:t===M.length-1,onClick:()=>R(t,"down"),children:(0,r.jsx)(gd,{direction:"down"})})]})]}),e.authError&&(0,r.jsxs)("span",{className:"navigator-usage-auth",children:[(0,r.jsx)("span",{className:"navigator-usage-reason",children:e.authError.message}),e.authError.reloginRequired&&n&&!m&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-relogin","aria-label":u("usage.reloginFor",{account:e.alias}),onClick:()=>n({provider:e.provider,alias:e.alias,seed:e.seed,masked:e.masked,...e.accountKey?{accountKey:e.accountKey}:{},reason:e.authError?.message??""}),children:u("usage.relogin")})]}),e.rows.map(e=>{let t=O(e);return(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:e.label}),null===t?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:t}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,r.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)})]},e.orderKey)})}),!m&&(P>0||h)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":h,onClick:()=>f(e=>!e),children:h?u("usage.showLess"):u("usage.showMore",{count:P})}),(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:u("usage.bai")}),(0,r.jsx)("span",{className:"navigator-usage-value",style:"measured"===N.status?void 0:{color:"var(--text-muted)"},children:z})]}),null===W?null:(0,r.jsx)("span",{className:"navigator-usage-account",children:W})]}),(0,r.jsx)("span",{className:"navigator-usage-live","aria-live":"polite",children:y})]});return p?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!S,"aria-label":S?`${H}${null===q?"":`, ${q}`}`:u("usage.showLess"),onClick:()=>{let e=!S;C(e);try{window.localStorage.setItem(gs,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:S?B.label:u("usage.showLess")}),S&&(0,r.jsx)("span",{className:"navigator-usage-value",style:B.danger?{color:"var(--danger)"}:void 0,children:B.value}),S&&null!==q&&(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:S?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),S?null:V]}):V}let gp=[{code:"ko",tag:"ko-KR",englishName:"Korean",nativeName:"한국어"},{code:"en",tag:"en-US",englishName:"English",nativeName:"English"},{code:"vi",tag:"vi-VN",englishName:"Vietnamese",nativeName:"Tiếng Việt"},{code:"ja",tag:"ja-JP",englishName:"Japanese",nativeName:"日本語"},{code:"th",tag:"th-TH",englishName:"Thai",nativeName:"ไทย"}];function gh(e){return"string"==typeof e?gp.find(t=>t.code===e):void 0}let gf=/[ăâđêôơưàáạảãằắặẳẵầấậẩẫèéẹẻẽềếệểễìíịỉĩòóọỏõồốộổỗờớợởỡùúụủũừứựửữỳýỵỷỹ]/giu,gm={ko:/[\uac00-\ud7a3\u1100-\u11ff\u3130-\u318f]/gu,ja:/[\u3040-\u30ff\u4e00-\u9fff]/gu,th:/[\u0e00-\u0e7f]/gu,vi:gf,en:/[a-z]/giu};function gg(e,t){let n=gm[t];return!n||"en"===t&&e.match(gf)?0:e.match(n)?.length??0}function gx(e,t,n){let r=gg(e,t.code),i=gg(e,n.code);if(r!==i)return r>i?t:n}function gv(){return{entries:[],open:{user:null,assistant:null},nextId:0,call:0,carry:null,cutOff:null}}let gy=/[.!?。!?…]["'”’)\]」』]*/u,gb=RegExp(`${gy.source}$`,"u");function gw(e){return e.replace(/([.!?])(?=[\p{Lu}\p{Lo}])/gu,"$1 ")}function gk(e,t,n){let{entries:r,nextId:i}=e,a=r.filter(t=>t.call===e.call),s=e.open[t.role];if(null===s){if("user"===t.role){let e=a.at(-1);e&&""===e.original&&(s=e.id)}else{let e=a.filter(e=>""===e.translation);s=(e.findLast(e=>e.heard)??e.at(-1))?.id??null}null===s&&(r=[...r,{id:s=i++,original:"",heard:!1,translation:"",...n,call:e.call}])}let o=gw(t.text),l="user"===t.role?{original:o,heard:t.final}:{translation:o};return r=r.map(e=>e.id===s?{...e,...l}:e),{...e,entries:r,nextId:i,open:{...e.open,[t.role]:t.final?null:s}}}let gj=e=>{fetch(`/api/live/call/${encodeURIComponent(e)}`,{method:"DELETE"}).catch(()=>{})},gS=(e,t)=>`${e.code}>${t.code}`,gC="cuelo-translator";function gN(){let e={mine:gp[0],theirs:gp[1]};try{let t=JSON.parse(window.localStorage.getItem(gC)??"null");if(!t||"object"!=typeof t)return e;let n=gh(t.mine)??e.mine,r=gh(t.theirs)??e.theirs;return n.code===r.code?e:{mine:n,theirs:r}}catch{return e}}function gI(){return(0,r.jsxs)("svg",{width:"22",height:"22",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:"3",width:"6",height:"11",rx:"3"}),(0,r.jsx)("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v3"})]})}function gT({visible:e=!0,onBack:t}){let{tt:n}=et(),[a,o]=(0,i.useState)(gN),{mine:l,theirs:c}=a,[d,u]=(0,i.useState)([]),p=(0,i.useRef)(gv()),[h,f]=(0,i.useState)(0),m=(0,i.useRef)(a),g=(0,i.useRef)(null);(0,i.useEffect)(()=>{window.localStorage.setItem(gC,JSON.stringify({mine:l.code,theirs:c.code}))},[l,c]);let x=function(e){let[t,n]=(0,i.useState)("idle"),[r,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),d=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(!1),y=(0,i.useRef)(!1),b=(0,i.useRef)(!1),w=(0,i.useRef)(void 0),k=(0,i.useRef)(0),j=(0,i.useRef)(e);(0,i.useEffect)(()=>{j.current=e},[e]),(0,i.useEffect)(()=>{c("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let S=(0,i.useCallback)(()=>{k.current+=1;let e=g.current;for(let e of(g.current=null,x.current=null,v.current=!1,y.current=!1,b.current=!1,window.clearTimeout(w.current),w.current=void 0,m.current?.close(),m.current=null,d.current?.close(),d.current=null,u.current=null,p.current=null,h.current?.getTracks()??[]))e.stop();h.current=null;let t=f.current;f.current=null,t&&(t.srcObject=null,t.remove()),e&&gj(e)},[]),C=(0,i.useCallback)(e=>{S(),n(e)},[S]),N=(0,i.useCallback)((e,t)=>{v.current?(a(e),o(t??null),C("error")):S()},[S,C]),I=(0,i.useCallback)(()=>v.current&&y.current&&b.current,[]),T=(0,i.useCallback)(e=>{k.current===e&&I()&&n("live")},[I]),M=(0,i.useCallback)(()=>{let e=p.current,t=f.current;e&&t&&t.srcObject!==e&&(t.srcObject=e)},[]),R=(0,i.useCallback)(async(e,t,r)=>{try{let i,a,s=new RTCPeerConnection;if(d.current=s,u.current=s.addTransceiver("audio",{direction:"sendrecv"}).sender,s.ontrack=t=>{k.current===e&&d.current===s&&(p.current=t.streams[0]??new MediaStream([t.track]),M())},await s.setLocalDescription(await s.createOffer()),await cr(s),k.current!==e)return;let o=s.localDescription?.sdp;if(!o)throw Error("The browser produced no offer SDP.");let l=await fetch("/api/live/interpret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:o,mine:t.code,theirs:r.code})}),c=await l.json().catch(()=>({})),h="",f="";if(c&&"object"==typeof c&&("error"in c&&(i=c.error),"message"in c&&"string"==typeof c.message&&(a=c.message),"callId"in c&&"string"==typeof c.callId&&(h=c.callId),"sdp"in c&&"string"==typeof c.sdp&&(f=c.sdp)),!l.ok||!h||!f){k.current===e&&N(ci(l.status,i),a);return}if(k.current!==e)return void gj(h);if(await s.setRemoteDescription({type:"answer",sdp:f}),k.current!==e){s.close(),gj(h);return}g.current=h;let x=new EventSource(`/api/live/events?callId=${encodeURIComponent(h)}`);m.current=x,x.onmessage=t=>{let r;if(k.current===e){try{r=JSON.parse(t.data)}catch{return}if(r&&"object"==typeof r&&"type"in r){if("state"===r.type&&"state"in r){var i;if("string"!=typeof r.state||(i=r.state,!0!==cn[i]))return;"connecting"===r.state||"live"===r.state||"working"===r.state?I()&&n(r.state):"error"===r.state?N("upstream",r.state):v.current?C(r.state):S();return}if("transcript"===r.type&&"role"in r&&"text"in r&&"final"in r){v.current&&("user"===r.role||"assistant"===r.role)&&"string"==typeof r.text&&j.current({role:r.role,text:r.text,final:!0===r.final});return}"error"===r.type&&"message"in r&&"string"==typeof r.message&&N("upstream",r.message)}}},x.onerror=()=>{k.current===e&&g.current&&N("failed")},y.current=!0,T(e)}catch(t){k.current===e&&N("failed",t instanceof Error?t.message:String(t))}},[M,N,I,S,T,C]),E=(0,i.useCallback)(async e=>{let t;try{t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(n){let t=n instanceof DOMException?n.name:"";k.current===e&&N("NotAllowedError"===t||"SecurityError"===t?"mic-denied":"mic-unavailable");return}let n=u.current;if(k.current!==e||!n){for(let e of t.getTracks())e.stop();return}h.current=t;try{await n.replaceTrack(t.getAudioTracks()[0]??null)}catch(t){k.current===e&&N("failed",t instanceof Error?t.message:String(t));return}k.current===e&&(b.current=!0,M(),T(e))},[M,N,T]),$=(0,i.useCallback)((e,t)=>{let n=gS(e,t);if(x.current===n||v.current)return;S(),x.current=n;let r=k.current;w.current=window.setTimeout(()=>{k.current!==r||v.current||S()},25e3),R(r,e,t)},[R,S]),L=(0,i.useCallback)((e,t)=>{let r=gS(e,t),i=x.current===r&&!v.current&&null!==d.current;i||(S(),x.current=r),window.clearTimeout(w.current),w.current=void 0,v.current=!0;let s=k.current;a(null),o(null),n("connecting");let l=document.createElement("audio");l.autoplay=!0,f.current=l,M(),i||R(s,e,t),E(s)},[E,M,R,S]),P=(0,i.useCallback)(()=>C("idle"),[C]);return(0,i.useEffect)(()=>()=>S(),[S]),{state:t,failure:r,detail:s,supported:l,prepare:$,start:L,stop:P}}((0,i.useCallback)(e=>{p.current=function(e,t,n){var r,i;let a,s;if("assistant"!==t.role)return gk(e,t,n);let o=e.carry;if(null===o&&null===e.open.assistant&&e.cutOff&&(o={...e.cutOff,rest:null}),null===o){if(!t.final)return gk(e,t,n);let r=gk(e,{...t,final:!1},n),i=r.open.assistant,a=r.entries.find(e=>e.id===i),s=void 0!==a&&!gb.test(a.translation.trimEnd())&&r.entries.some(t=>t.call===e.call&&t.id>a.id&&""!==t.original);return{...r,open:{...r.open,assistant:null},cutOff:s?{id:a.id,base:a.translation}:null}}let{id:l,base:c}=o,{rest:d}=o,u=(r=t.text,(s=(a=gy.exec(r))?r.slice(0,a.index+a[0].length):r).length>24?null:{head:s,rest:r.slice(s.length).trim()}),p=u?u.rest:t.text,h=u?(i=u.head,gw(/[\p{Script=Latin}\d]$/u.test(c)&&/^[\p{Script=Latin}\d]/u.test(i)?`${c} ${i}`:c+i)):c,f={...e,entries:e.entries.map(e=>e.id===l?{...e,translation:h}:e)};return p?d=(f=gk({...f,open:{...f.open,assistant:d}},{...t,text:p,final:!1},n)).open.assistant:null!==d&&(f={...f,entries:f.entries.map(e=>e.id===d?{...e,translation:""}:e)}),{...f,open:{...f.open,assistant:t.final?null:d},carry:t.final?null:{id:l,base:c,rest:d},cutOff:null}}(p.current,e,m.current),u(p.current.entries)},[])),v="connecting"===x.state||"live"===x.state||"working"===x.state,y=e=>{var t;m.current=e,p.current={...t=p.current,open:{user:null,assistant:null},call:t.call+1,carry:null,cutOff:null},f(p.current.call),x.start(e.mine,e.theirs)},b=e=>{e.mine.code!==e.theirs.code&&(o(e),v&&y(e))},{prepare:w,stop:k,supported:j}=x;(0,i.useEffect)(()=>{e||k()},[k,e]),(0,i.useEffect)(()=>{e&&!v&&!0===j&&window.isSecureContext&&w(l,c)},[v,l,w,j,c,e]),(0,i.useEffect)(()=>{let e=g.current;e&&(e.scrollTop=e.scrollHeight)},[d]);let S=!1===x.supported,C=!window.isSecureContext,N="error"===x.state&&x.failure?function(e,t,n){switch(t){case"mic-denied":return e("translator.micDenied");case"mic-unavailable":return e("translator.micUnavailable");case"auth":return e("translator.auth");case"upstream":return e("translator.upstream",{error:n??""});default:return e("translator.failed",{error:n??""})}}(n,x.failure,x.detail):C?n("translator.insecure"):S?n("translator.unsupported"):null,I="connecting"===x.state?n("translator.connecting"):"live"===x.state||"working"===x.state?n("translator.live"):"",T=e=>gp.map(t=>(0,r.jsx)("option",{value:t.code,disabled:t.code===e.code,children:t.nativeName},t.code));return(0,r.jsxs)("section",{className:"translator-view","aria-label":n("translator.title"),hidden:!e,children:[(0,r.jsxs)("header",{className:"translator-header",children:[t?(0,r.jsx)(s.r,{variant:"ghost",size:"small",onClick:t,children:n("translator.back")}):null,(0,r.jsx)("h2",{className:"translator-title",children:n("translator.title")}),(0,r.jsxs)("div",{className:"translator-languages",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.me")}),(0,r.jsx)("select",{"aria-label":n("translator.myLanguage"),value:l.code,onChange:e=>{let t=gh(e.target.value);t&&b({mine:t,theirs:c})},children:T(c)})]}),(0,r.jsx)("button",{type:"button",className:"translator-swap","aria-label":n("translator.swap"),title:n("translator.swap"),onClick:()=>b({mine:c,theirs:l}),children:"⇄"}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.them")}),(0,r.jsx)("select",{"aria-label":n("translator.theirLanguage"),value:c.code,onChange:e=>{let t=gh(e.target.value);t&&b({mine:l,theirs:t})},children:T(l)})]})]}),(0,r.jsx)("div",{className:"translator-actions",children:(0,r.jsx)(s.r,{variant:"ghost",size:"small",disabled:0===d.length,onClick:()=>{var e;e=p.current,p.current={...gv(),call:e.call},u([])},children:n("translator.clear")})})]}),N?(0,r.jsx)("p",{className:"translator-banner","data-tone":"error"===x.state?"danger":void 0,role:"error"===x.state?"alert":"status",children:N}):null,(0,r.jsxs)("div",{ref:g,className:"translator-log",role:"log","aria-label":n("translator.conversation"),children:[0===d.length?(0,r.jsx)("p",{className:"translator-empty",children:n("translator.empty")}):null,d.map(e=>{let t=function(e){let t=gx(e.original,e.mine,e.theirs);if(t)return t;let n=gx(e.translation,e.mine,e.theirs);if(n)return n===e.mine?e.theirs:e.mine}(e),i=t?t===e.mine?e.theirs:e.mine:void 0;return(0,r.jsx)("div",{className:"translator-entry","data-side":t===e.mine?"me":"them",children:(0,r.jsxs)("div",{className:"translator-bubble",children:[e.translation?(0,r.jsx)("p",{className:"translator-translation",lang:i?.tag,children:e.translation}):v&&e.call===h?(0,r.jsx)("p",{className:"translator-pending",children:n("translator.translationPending")}):null,e.original?(0,r.jsxs)("p",{className:"translator-original",lang:t?.tag,children:[(0,r.jsxs)("span",{className:"sr-only",children:[n("translator.original"),": "]}),e.original]}):null]})},e.id)})]}),(0,r.jsxs)("div",{className:"translator-dock",children:[(0,r.jsx)("p",{className:"translator-status",role:"status","aria-live":"polite",children:I}),(0,r.jsxs)("button",{type:"button",className:"translator-call-button","aria-pressed":v,disabled:!v&&(S||C||null===x.supported),onClick:()=>v?x.stop():y(a),children:[(0,r.jsx)(gI,{}),v?n("translator.stop"):n("translator.start")]})]})]})}function gM({onOpen:e}){let{tt:t}=et();return(0,r.jsxs)("div",{id:"navigator-translator-panel",className:"translator-panel",children:[(0,r.jsx)("p",{className:"translator-panel-hint",children:t("translator.panelHint")}),e?(0,r.jsx)("button",{type:"button",className:"translator-panel-open",onClick:e,children:t("translator.open")}):null]})}let gR="git pull && bun install && bun run build && node Tools/CUELO_Setup/files/native-runtime-patch.js --target .";function gE(e){return"unknown"===e?e:`v${e}`}function g$(){let{locale:e,t}=(0,F.s)(),n=U(),[a,s]=(0,i.useState)(null),[o,l]=(0,i.useState)("idle"),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),[y,b]=(0,i.useState)(null),w=(0,i.useCallback)(()=>{let e=g.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=c5(e.top,e.bottom,t,c6(t,.72,620),{margin:12,minHeight:0}),i=Math.min(430,window.innerWidth-24),a=Math.max(12,window.innerWidth-i-12);b({left:Math.min(e.right+8,a),width:i,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,i.useEffect)(()=>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 b(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();s(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(m.current??void 0),m.current=null},[]),(0,i.useEffect)(()=>{if(!c)return;let e=e=>{g.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||!a?.updateAvailable||!a.latestRelease)return null;let j=a.latestRelease,S=j.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(j.publishedAt)):null,C=j.body.trim()||j.name,N=async e=>{try{await ni(e),clearTimeout(m.current??void 0),f(e),m.current=setTimeout(()=>f(null),1600)}catch{p(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:g,"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:gE(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:gE(j.version)})]}),c&&y&&(0,_.createPortal)((0,r.jsxs)("div",{ref:x,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:y.left,top:y.top,bottom:y.bottom,zIndex:700,width:y.width,maxHeight:y.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:gE(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:gE(a.currentAppVersion)})}),S&&(0,r.jsx)("span",{children:S})]})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.changelog")}),(0,r.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,r.jsx)(nc,{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:gR}),(0,r.jsx)("button",{type:"button",onClick:()=>void N(gR),title:h===gR?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":h===gR?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===gR?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:h===gR?(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 gL="pi-web:last-open-by-workspace";function gP(){try{return window.localStorage}catch{return null}}function gA(e){let t=e.getItem(gL);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function gF(e,t=gP()){if(t)try{let n=gA(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(gL):t.setItem(gL,JSON.stringify(n))}catch{}}let gz="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",gW="omp-web:wide-chat";function gD(){try{return fR(window.localStorage)}catch{return fR(null)}}function gO(e){let t=document.querySelector(`[data-dispatch-key="${CSS.escape(e)}"]`);return t&&0!==t.getClientRects().length?t.querySelector(".answer-dispatch-open")??t.closest(".answer-dispatch")?.querySelector(".answer-dispatch-toggle")??null:null}function gH({auxiliaryDeck:e,resourcePanel:t}={}){var n,p,f,m,k;let j,S,C,N,I,T,M,R,E,$,L,P,A,z,W,D,_,B,q,V,K=(0,a.useRouter)(),G=(0,a.useSearchParams)(),[J]=(0,i.useState)(()=>{let e;return{requestedCwd:e=G.get("cwd")?.trim()||null,sessionId:e?null:G.get("session")}}),{preference:Z,toggleTheme:Y}=nr(),{locale:X,setLocale:Q,t:ee,supportedLocales:et}=(0,F.s)(),en=function(){let[e,t]=(0,i.useState)(null),[n,r]=(0,i.useState)(!1),a=(0,i.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,i.useEffect)(()=>{try{r("1"===window.localStorage.getItem(fr))}catch{}return a(),window.addEventListener("focus",a),()=>window.removeEventListener("focus",a)},[a]),{permission:e,dismissed:n,request:(0,i.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,a)},[a]),dismiss:(0,i.useCallback)(()=>{r(!0);try{window.localStorage.setItem(fr,"1")}catch{}},[])}}(),er=(0,i.useSyncExternalStore)(O.subscribe,O.getSnapshot,H);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,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:uf(),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.setProperty("--app-viewport-height",`${e.height}px`):t.style.removeProperty("--app-viewport-height");let r=0!==window.scrollX||0!==window.scrollY,i=.01>Math.abs(e.scale-1);r&&i&&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 ei=uw(),ea=U(),{soundEnabled:es,onSoundToggle:eo,playCueSound:el,preloadCueSound:ec,unlockAudio:ed,soundEnabledRef:eu}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),a=(0,i.useRef)(null),s=(0,i.useRef)(0),o=(0,i.useRef)(new Map),l=(0,i.useRef)(new Map),c=(0,i.useRef)(new Map),d=(0,i.useRef)(null);rY();let u=(0,i.useRef)(new Map),p=(0,i.useRef)(new Map),h=(0,i.useRef)(new Map),f=(0,i.useCallback)(e=>{let t=p.current.get(e);return t||(t=gi(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),m=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),g=(0,i.useCallback)(()=>(d.current??=nZ(),d.current),[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async e=>{if(!e)return;let t=await g(),r=ru(e);for(let i of nD){let a=r?nJ(rd(r),r.id,i):nG(t,e,i);if(a){for(let e of a.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 a.voices)f(e).catch(()=>{})}}},[g,f]),v=(0,i.useCallback)(()=>{s.current+=1;let e=a.current;if(a.current=null,e)try{e.stop()}catch{}},[]),y=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=m();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[m]);(0,i.useEffect)(()=>{let e=()=>y(),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)}},[y]);let b=(0,i.useCallback)(()=>{let e=!n.current;e?y(!0):v(),n.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,y]),w=(0,i.useCallback)(e=>{if(!n.current)return;let t=m();if(!t)return;v();let r=s.current,i=()=>{if(r===s.current&&n.current&&(!e||e()))try{gr(t)}catch{}};"suspended"===t.state?t.resume().then(i).catch(()=>{}):i()},[m,v]);return{soundEnabled:e,onSoundToggle:b,playCueSound:(0,i.useCallback)(async(e,t="done",r)=>{let i=await g(),d=ru(e),p=null===t?null:d?nJ(rd(d),d.id,t):nG(i,e,t),h=`${d?.alias??e??""}\u0000${t??""}`,x=p?nY(p.stickers,l.current.get(h)??null):null;null!==x&&l.current.set(h,x);let y=p?nY(p.voices,o.current.get(h)??null):null,b=y?p?.lines.get(y)??null:null;!y&&p&&null!==(b=nY(p.captions,c.current.get(h)??null))&&c.current.set(h,b);let k={sticker:x,text:b};if(!n.current||r&&!r())return k;let j=m();if(!j)return k;if(!y)return null!==t&&nH[t]||w(r),k;v();let S=s.current,C=()=>S!==s.current||!n.current||void 0!==r&&!r();return(async()=>{if(!("suspended"===j.state&&(await j.resume().catch(()=>{}),C())))try{let e=u.current.get(y);e||(e=f(y).then(e=>j.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(y),e}),u.current.set(y,e));let t=await e;if(C())return;let n=j.createBufferSource(),r=j.createGain();n.buffer=t,n.connect(r),r.connect(j.destination),r.gain.setValueAtTime(.82,j.currentTime),n.onended=()=>{a.current===n&&(a.current=null)},a.current=n,n.start(),o.current.set(h,y)}catch{if(C()||null!==t&&nH[t])return;try{gr(j)}catch{}}})(),k},[m,w,v,g,f]),preloadCueSound:x,unlockAudio:y,soundEnabledRef:n}}(),eh=function(){let[e,t]=(0,i.useState)({status:"idle",data:null,error:null}),[n,r]=(0,i.useState)(!0),[a,s]=(0,i.useState)(null),o=(0,i.useRef)(null),l=(0,i.useRef)(null),c=(0,i.useCallback)(()=>{l.current?.abort();let e=new AbortController;l.current=e,r$({signal:e.signal}).then(t=>{e.signal.aborted||s(t)})},[]);(0,i.useEffect)(()=>{var e;let n,i,a,s,d,u,p,h,f,m,g=(i=(e={onResult(e){t(e),r(!1)}}).intervalMs??6e4,a=e.setIntervalImpl??setInterval,s=e.clearIntervalImpl??clearInterval,d=e.initialData??null,u=null,p=0,h=!1,f=!1,m=async t=>{u?.abort(),u=new AbortController;let n=++p,r=await rR({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,m(!1),n=a(()=>{f||m(!1)},i))},refresh:()=>h?m(!0):Promise.resolve(rC(d,new rk("사용량 폴링이 중지되었습니다.","aborted"))),setPaused(e){f=e},stop(){h=!1,p+=1,u?.abort(),u=null,s(n),n=void 0}});return o.current=g,g.start(),c(),()=>{g.stop(),l.current?.abort(),o.current===g&&(o.current=null)}},[c]);let d=(0,i.useCallback)(async()=>{let e=o.current;if(!e)return{status:"error",data:null,error:new rk("사용량 폴링이 시작되지 않았습니다.","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}})(a),[a])}}();n=eh.state.data?.reports,(0,i.useEffect)(()=>{rK(n)},[n]);let[ef,em]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),ev=(0,i.useRef)(new Set),ey=(0,i.useCallback)(()=>{eu.current&&el(null,"done")},[el,eu]),[eb,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(null),eN=(0,i.useRef)(0),eI=(0,i.useRef)(null),[eT,eM]=(0,i.useState)(null),eR=(0,i.useRef)(0),eE=(0,i.useCallback)(e=>{eM(t=>t?.id===e?null:t)},[]),[e$,eL]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{eL("1"===window.localStorage.getItem(gW))}catch{}},[]);let eP=(0,i.useCallback)(()=>{eL(e=>{let t=!e;try{window.localStorage.setItem(gW,t?"1":"0")}catch{}return t})},[]),[eA,eF]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(()=>J.requestedCwd?"validating":"idle"),[eD,eO]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(0),[e_,eB]=(0,i.useState)(0),[eq,eV]=(0,i.useState)(0),[eK,eG]=(0,i.useState)(0),[eJ,eZ]=(0,i.useState)(!1),[eY,eX]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(null),[e1]=(0,i.useState)(()=>{let e;return e=0,{reset(){e+=1,e0(null)},check(t,n){let r=++e;e0("checking"),t().then(t=>{r===e&&e0("fresh"===t.status?function(e,t){if(!t.accountKey)return"unknown";let n=e.filter(e=>e.provider===t.provider&&e.accountKey===t.accountKey);return n.some(e=>!0!==e.disabled&&!e.authError)?"recovered":n.length>0?"still-failing":"unknown"}(t.data.reports,n):"unknown")},()=>{r===e&&e0("unknown")})}}}),[e2,e8]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(0),e6=(0,i.useRef)(null),e3=(0,i.useRef)(null),[e7,e9]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(null),[ti,ta]=(0,i.useReducer)(g,h),[ts,to]=(0,i.useState)("characters"),[tl,tc]=(0,i.useState)("governor"),[td,tu]=(0,i.useState)(()=>x(0)),[tp]=(0,i.useState)(gD),[th]=(0,i.useState)(fE),[tf,tm]=(0,i.useState)([]),[tg,tx]=(0,i.useState)({sessions:[],complete:!1}),[tv,ty]=(0,i.useState)(!1),[tb,tw]=(0,i.useState)(!1),[tk,tj]=(0,i.useState)(0),tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tI=(0,i.useRef)(null),tT=(0,i.useCallback)(()=>{tj(e=>e+1)},[]),tM=(0,i.useCallback)(e=>{e&&ex(!0),em(e),e||tT()},[tT]),tR=(0,i.useCallback)(e=>{tC.current=e},[]),tE=(0,i.useRef)(!1),[t$,tL]=(0,i.useState)(!1),tP=(0,i.useRef)(!1),tA=(0,i.useRef)(!1),tF=(0,i.useRef)(0),[tz,tW]=(0,i.useState)(!1),[tD,tO]=(0,i.useState)(!1),tH=(0,i.useRef)(null),[tU,t_]=(0,i.useState)(null),[tB,tq]=(0,i.useState)(null),tV=(0,i.useRef)(null),tK=(0,i.useRef)(!1);tV.current=tU,(0,i.useEffect)(()=>{t_(d0())},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||tE.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=cT();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:dX(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(dV,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:eb?.id??null,resumeUrl:r});if(i.entered){tE.current=!0;return}t=i.error},r=async()=>{if(!e&&!tE.current)try{let i=tK.current?null:tV.current,a=await d2({sessionId:eb?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:i?{requestId:i.requestId,stageHash:i.stageHash}:null});tF.current=0;let s=!!(a.serverBootId&&tH.current&&a.serverBootId!==tH.current);if(tP.current||s){var r=eb?.id??null;cT();try{sessionStorage.setItem(dG,JSON.stringify({schemaVersion:1,sessionId:r,at:Date.now()}))}catch{}window.location.reload();return}a.serverBootId&&(tH.current=a.serverBootId),tA.current=!0,!e&&a.update&&(tq(a.update),a.update.cleanup&&"running"!==a.update.cleanup.status&&(tK.current=!0)),n(a)}catch{tF.current+=1,!e&&tA.current&&tF.current>=2&&(tP.current=!0,tL(!0))}},i=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",i),r();let a=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(a),window.removeEventListener("ompweb:update-maintenance",i)}},[eb?.id]),(0,i.useEffect)(()=>{if(!t$)return;let e=window.setTimeout(()=>tW(!0),12e4);return()=>window.clearTimeout(e)},[t$]),(0,i.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(dG);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(dG),!1):n.sessionId===e&&(sessionStorage.removeItem(dG),!0)})(eb?.id??null)&&tO(!0)},[eb?.id]),(0,i.useEffect)(()=>{if(!tD)return;let e=window.setTimeout(()=>tO(!1),8e3);return()=>window.clearTimeout(e)},[tD]);let tG=tU?.requestId??null,tJ=tU?.dismissed??!0,tZ=tB?.requestId??null,tY=tB?.deploymentCompleted??!1,tX=tB?.cleanup?.status??null;(0,i.useEffect)(()=>{if(!tG||tJ||tZ!==tG||!tY)return;let e=dY(tX);if(null===e)return;let t=window.setTimeout(()=>{t_(d1(tG))},e);return()=>window.clearTimeout(t)},[tG,tJ,tZ,tY,tX]),(0,i.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(dV);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&&eb?.id!==e.sessionId)return;let t=!1;return d4(e).then(e=>{t||"resumed"!==e||(tK.current=!1,t_(d0()),eU(e=>e+1),eV(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[eb?.id]);let tQ=(0,i.useCallback)(e=>{if("Tab"!==e.key)return;let t=tI.current;if(!t)return;let n=Array.from(t.querySelectorAll(gz));if(0===n.length)return;let r=e.shiftKey?n[0]:n[n.length-1],i=document.activeElement;i!==r&&t.contains(i)||(e.preventDefault(),(e.shiftKey?n[n.length-1]:n[0]).focus())},[]),[t0,t1]=(0,i.useState)(!0),[t2,t8]=(0,i.useState)(!1),[t4,t5]=(0,i.useState)(!1),t6=(0,i.useRef)(t0),t3=(0,i.useRef)(!1),t7=(0,i.useRef)(!0),t9=(0,i.useRef)(null);t6.current=t0;let ne=(j=(p={clientPainted:t2,compactWorkspace:er,requestedOpen:t0}).requestedOpen&&p.clientPainted,{laidOut:p.requestedOpen&&(!p.compactWorkspace||p.clientPainted),presented:j,drawer:j&&p.compactWorkspace}),nt=(0,i.useCallback)(e=>{t3.current=e,t1(e),ta(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),nn=(0,i.useRef)(null),na=(0,i.useRef)(!1),ns=(0,i.useRef)(260),no=(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}),[]),nl=function(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:a,getMaxWidth:s,growthDirection:o,maxWidth:l,minWidth:c,storageKey:d,widthRef:u}=e,p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(!1),[m,g]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),y=(0,i.useCallback)(()=>Math.min(l,Math.max(c,s())),[s,l,c]),b=(0,i.useCallback)(e=>{var t;let n,r;return t=y(),n=Number.isFinite(e)?e:c,r=Math.max(c,t),Math.round(Math.max(c,Math.min(r,n)))},[y,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=b(e),a=i!==u.current;return w(i),g(i),r&&(a||n)&&gn(d,i),i},[w,b,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]),N=(0,i.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let n="right"===o?1:-1,r=b(t.startWidth+(e.clientX-t.startX)*n);w(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[w,b,S,o]),I=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),T=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),R=(0,i.useCallback)(()=>{k(a?.()??r,{forcePersist:!0})},[k,r,a]),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(y(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),R())},[k,y,o,c,R,u]);return(0,i.useEffect)(()=>{if(f.current)return;f.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??a?.()??r,{persist:!1});null!==e&&e!==t&&gn(d,t)},[k,r,a,d]),(0,i.useEffect)(()=>{if(!f.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:R,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":y(),"aria-valuemin":c,"aria-valuenow":m,"aria-valuetext":`${m} px`,onDoubleClick:R,onKeyDown:$,onLostPointerCapture:M,onPointerCancel:T,onPointerDown:C,onPointerMove:N,onPointerUp:I,role:"separator",tabIndex:0},width:m}}({ariaLabel:ee("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:no,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:ns}),nc=nl.reclampWidth;(0,i.useEffect)(()=>{let e=t9.current;if(e===er)return;t5(!0),null!==e&&(e?t3.current=t6.current:t7.current=t6.current),t9.current=er;let t=er?t3.current:t7.current;er?nt(t):t1(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>t5(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[er,nt]),(0,i.useEffect)(()=>{t8(!0)},[]),(0,i.useEffect)(()=>{let e=na.current;if(na.current=ne.drawer,ne.drawer){let e=nl.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(gz)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||nn.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[ne.drawer,nl.panelRef]),(0,i.useEffect)(()=>{nc()},[nc,ti.activeView]),(0,i.useEffect)(()=>{let e=tS.current;if(!e)return;let t=e=>{tu(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(!tk)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>tC.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[tk]),(0,i.useEffect)(()=>{if("command-palette"!==ti.transientLayer)return;let e=tI.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(gz)?.focus()});return()=>cancelAnimationFrame(t)},[ti.transientLayer]),(0,i.useEffect)(()=>{er||"navigator-drawer"!==ti.transientLayer||ta({type:"close-layer"})},[er,ti.transientLayer]),(0,i.useEffect)(()=>{let e=new AbortController;return tx(e=>({...e,complete:!1})),fetch("/api/sessions",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t.sessions))throw Error("Invalid session census");tm(t.sessions),tx({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()},[eH,eb?.id]);let nd=(0,i.useRef)(null),nu=(0,i.useRef)(null),[nh,nf]=(0,i.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),nm=(0,i.useRef)(null),ng=(0,i.useCallback)((e,t,n)=>{nm.current=n,nf(n=>{let r=n$.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),nx=(0,i.useCallback)(e=>{nf(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),nm.current?.(e)},[]),[nv,ny]=(0,i.useState)(null),nb=(0,i.useCallback)(e=>{ny(e)},[]),[nw,nk]=(0,i.useState)(null),[nj,nS]=(0,i.useState)([]),[nC,nN]=(0,i.useState)(null),[nI,nT]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let n=await t.json(),r=n.fields?.find(e=>"task.maxConcurrency"===e.path),i=r?.value??r?.defaultValue,a="number"==typeof i?i:"string"==typeof i?Number.parseInt(i,10):NaN;!e.signal.aborted&&Number.isFinite(a)&&a>0&&nN(a)}).catch(()=>{}),()=>e.abort()},[]);let[nM,nR]=(0,i.useState)({kind:"idle"}),nE=(0,i.useRef)(null),n$=(0,i.useRef)(eb?.id??null);n$.current=eb?.id??null;let nL=(0,i.useCallback)(e=>{nk(e)},[]),[nP,nA]=(0,i.useState)(null),nF=(0,i.useRef)(null),nz=(0,i.useCallback)((e,t)=>{ni(t).then(()=>{nF.current&&clearTimeout(nF.current),nA(e),nF.current=setTimeout(()=>nA(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nF.current&&clearTimeout(nF.current),nE.current&&clearTimeout(nE.current)},[]),(0,i.useEffect)(()=>()=>eI.current?.abort(),[]);let[nW,nO]=(0,i.useState)(null),nU=(0,i.useCallback)(e=>{nO(e)},[]),[n_,nB]=(0,i.useState)(null),[nq,nV]=(0,i.useState)(null),[nK,nX]=(0,i.useState)(null),[nQ,n0]=(0,i.useState)(!1),[n1,n2]=(0,i.useState)("subagents"),n8=(0,i.useCallback)((e,t=!1)=>{ta({type:"select-view",view:e}),nV(null),er&&nt(!1),(t||"chat"===e)&&tT()},[er,tT,nt]),n4=(0,i.useRef)(!1),n5=(0,i.useCallback)(()=>{n4.current=!0,ta({type:"set-deck-expanded",expanded:!ti.deckExpanded})},[ti.deckExpanded]);(0,i.useEffect)(()=>{if(!n4.current)return;n4.current=!1;let e=requestAnimationFrame(()=>{[...document.querySelectorAll("#workspace-auxiliary-panel [data-panel-expand]")].find(e=>e.getClientRects().length>0)?.focus()});return()=>cancelAnimationFrame(e)},[ti.deckExpanded]);let[n6,n3]=(0,i.useState)(null),n7=(0,i.useCallback)((e,t=!0)=>{n3(e),t&&n8("subagents")},[n8]),n9=eb?.id??null;(0,i.useEffect)(()=>{n3(null)},[n9]);let[re,rt]=(0,i.useState)(null),rn=(0,i.useCallback)(e=>{gO(e)||(ti.deckExpanded&&"pinned"===td.deck?ta({type:"set-deck-expanded",expanded:!1}):ta({type:"select-view",view:"chat"})),rt(e)},[td.deck,ti.deckExpanded]);(0,i.useEffect)(()=>{if(!re)return;let e=requestAnimationFrame(()=>{gO(re)?.focus(),rt(null)});return()=>cancelAnimationFrame(e)},[re]);let rr=(0,i.useCallback)(e=>{let t=ti.transientLayer===e;nV(null),er&&"navigator-drawer"===ti.transientLayer&&nt(!1),ta({type:"toggle-layer",layer:e}),t&&tT()},[er,tT,nt,ti.transientLayer]),ri=(0,i.useCallback)(()=>{if("chat"!==ti.activeView){n2(ti.activeView),n8("chat",!0);return}n8(n1,!0)},[n1,n8,ti.activeView]),ra=(0,i.useCallback)(e=>{nV(null),ta({type:"close-layer"}),er&&nt(!1),e1.reset(),eX(e)},[er,e1,nt]),rs=(0,i.useCallback)(()=>{e1.reset(),eX(null),tT()},[e1,tT]),ro=eh.refresh,rl=(0,i.useCallback)(()=>{null!==eY&&e1.check(ro,eY)},[ro,e1,eY]),rc=(0,i.useCallback)(()=>e7?(te||(e9(!1),tT()),!0):null!==eY?(rs(),!0):eJ?(eZ(!1),tT(),!0):nQ?(n0(!1),tT(),!0):nq?(nV(null),tT(),!0):ti.transientLayer?("navigator-drawer"===ti.transientLayer&&nt(!1),ta({type:"close-layer"}),tT(),!0):ti.deckExpanded&&"pinned"===td.deck&&document.activeElement?.closest("#workspace-auxiliary-panel")?(n4.current=!0,ta({type:"set-deck-expanded",expanded:!1}),!0):"chat"!==ti.activeView&&(ta({type:"select-view",view:"chat"}),tT(),!0),[rs,nQ,eY,nq,te,e7,tT,nt,eJ,ti.activeView,ti.transientLayer,ti.deckExpanded,td.deck]),rp=(0,i.useCallback)(e=>{ta({type:"close-layer"}),er&&nt(!1),nV(t=>t===e?null:e)},[er,nt]),rh=(0,i.useCallback)(()=>{ta({type:"close-layer"}),er&&nt(!1),nV("session")},[er,nt]),rf=(0,i.useCallback)(()=>{if(nV(null),er){let e="navigator-drawer"!==ti.transientLayer;nt(e),e||tT();return}ta({type:"close-layer"}),t1(e=>{let t=!e;return t7.current=t,t})},[er,tT,nt,ti.transientLayer]);(0,i.useEffect)(()=>{if(!nq||!nu.current)return;let e=()=>{let e=nu.current.getBoundingClientRect();nX({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(nu.current),()=>t.disconnect()},[nq]);let[rm,rg]=(0,i.useState)([]),[rx,rv]=(0,i.useState)(null),ry=(0,i.useRef)(new Map),rb=(0,i.useCallback)(()=>{"view-stack"===td.deck&&ta({type:"select-view",view:"chat"}),er&&nt(!1),tT()},[er,td.deck,tT,nt]),rw=(0,i.useCallback)((e,t)=>{nd.current?.insertText(c1(e,t)),rb()},[rb]),rj=(0,i.useCallback)((e,t,n)=>{nd.current?.insertText(c2(e,t,n)),rb()},[rb]),rS=(0,i.useCallback)((e,t)=>{let n=nd.current;return!!n&&(n.addAttachments(e),t&&n.insertText(t),rb(),!0)},[rb]),rN=(0,i.useCallback)(e=>{nd.current?.insertText(e),rb()},[rb]),rI=J.sessionId,[rT,rM]=(0,i.useState)(null);nr({cwd:eb?.cwd??eA??rT,syncWithOmp:!0});let rE=(0,i.useRef)(null),[rL,rP]=(0,i.useState)(()=>!rI),rA=(0,i.useRef)(!1),rF=(0,i.useRef)(0),rz=(0,i.useCallback)(()=>{rF.current+=1},[]);(0,i.useEffect)(()=>{eb&&function(e,t,n=gP()){if(n)try{let r=gA(n);r[e]=t,n.setItem(gL,JSON.stringify(r))}catch{}}(eb.projectRoot??rE.current??eb.cwd,eb.id)},[eb]),(0,i.useEffect)(()=>{let e=J.requestedCwd;if(!e)return;let t=new AbortController;return eW("validating"),eO(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}`);rA.current=!0,eF(t.cwd),eW("ready")}).catch(e=>{t.signal.aborted||(eO(e instanceof Error?e.message:String(e)),eW("error"))}),()=>t.abort()},[J]);let rW=(0,i.useCallback)(e=>{let t=++rF.current,n=function(e,t=gP()){if(!t)return null;try{let n=gA(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!==rF.current)return;let i=r?.sessions.find(e=>e.id===n);if(!i){r&&gF(e);return}(i.projectRoot??i.cwd)!==e?gF(e):(ew(i),eB(e=>e+1),new URLSearchParams(window.location.search).get("session")!==i.id&&K.replace(`?session=${encodeURIComponent(i.id)}`,{scroll:!1}))}).catch(()=>{})},[K]),rD=(0,i.useCallback)((e,t)=>{if(rz(),rM(e),!e)return;let n=t??e,r=rE.current??(eb?eb.projectRoot??eb.cwd:null);if(rE.current=n,rA.current){rA.current=!1;return}r!==n&&(eN.current+=1,eI.current?.abort(),eI.current=null,ej(null),eC(null),ew(null),eF(t=>t&&t!==e?null:t),eB(e=>e+1),nf({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nV(null),rg([]),rv(null),ta({type:"select-view",view:"chat"}),rW(n),K.replace("/",{scroll:!1}))},["/",K,eb,rz,rW]),rO=(0,i.useCallback)((e,t,n)=>{eF(null),eC(n),ew(e),nf({sessionId:e.id,tree:[],leafId:null,navigation:0}),eB(e=>e+1),ny(null),rP(!0),er&&!t&&(nt(!1),ta({type:"select-view",view:"chat"})),t&&(rA.current=!0),t||K.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[er,K,nt]),rH=(0,i.useCallback)((e,t=!1)=>{if(rE.current=e.projectRoot??e.cwd,rz(),!t&&eb){let t=(eb.projectRoot??eb.cwd)===(e.projectRoot??e.cwd);if(eb.id===e.id&&t){eN.current+=1,eI.current?.abort(),eI.current=null,ej(null),er&&nt(!1);return}}if(!t&&ek?.id===e.id)return;eN.current+=1;let n=eN.current;if(eI.current?.abort(),t||!eb){eI.current=null,ej(null),rO(e,t,null);return}let r=new AbortController;eI.current=r,ej(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");eN.current===n&&rO(e,!1,r)}).catch(t=>{r.signal.aborted||eN.current!==n||(console.error("Failed to preload session before switching:",t),rO(e,!1,null))}).finally(()=>{eN.current===n&&(eI.current=null,ej(null))})},[rO,rz,er,ek?.id,eb,nt]),rU=(0,i.useCallback)((e,t)=>{eN.current+=1,eI.current?.abort(),eI.current=null,ej(null),eC(null),rz(),ew(null),eF(t),eB(e=>e+1),nf({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nV(null),ta({type:"select-view",view:"chat"}),er&&nt(!1),K.replace("/",{scroll:!1})},["/",rz,er,K,nt]),r_=(0,i.useCallback)(e=>{let t=eb?.projectRoot??rE.current??eb?.cwd??rT;if(!t||!eb)return;let n=tf.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===eb.id);if(r<0)return;let i=n[r+e];i&&(nV(null),ta({type:"close-layer"}),rH(i),tT())},[rT,tf,rH,tT,eb]);f={onNewSession:e=>rU(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>rr("command-palette"),onToggleNavigator:rf,onToggleResources:()=>n8("resource"===ti.activeView?"chat":"resource",!0),onSelectView:e=>n8(e,!0),onCycleView:(0,i.useCallback)(e=>{let t=(d.indexOf(ti.activeView)+e+d.length)%d.length;n8(d[t],!0)},[n8,ti.activeView]),onNavigateSession:r_,onEscape:rc,enabled:!eJ&&!e7&&null===eY,activeCwd:rT},(S=(0,i.useRef)(f)).current=f,(0,i.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let n=t.now?.()??Date.now();if(y||e.isComposing||229===e.keyCode||n-b<100)return;let r=e.target,i="u">typeof Element&&r instanceof Element?r:null,a=!!i?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!i?.closest("[data-dismissible-layer], [data-capture-keys], [role='listbox'], [role='menu'], [role='combobox'][aria-expanded='true'], [aria-haspopup][aria-expanded='true']")&&(t.onEscape?.()?(e.preventDefault(),e.stopPropagation()):!(a||i?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(i?.closest("[data-capture-keys]")||!1===t.enabled)return;let s=e.key.toLowerCase(),o=(e.ctrlKey||e.metaKey)&&!e.altKey;if(o&&!e.shiftKey&&"k"===s)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(o&&!e.shiftKey&&"b"===s)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(o&&!e.shiftKey&&"u"===s)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(o&&!e.shiftKey&&/^[1-7]$/.test(s)){if(!t.onSelectView)return;let n=d[Number(s)-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"===s&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,S.current)},t=()=>w(!0),n=()=>w(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",n,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",n,{capture:!0})}},[]);let rB=(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&&ew(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),rq=(0,i.useCallback)(e=>{rz(),eF(null),ew(e),eU(e=>e+1),rB(e.id),K.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[rz,K,rB]),rV=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&dU({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&rH(e)}})},[rH]),rG=(0,i.useCallback)(e=>{eU(e=>e+1),e6.current?.pending&&e5(e=>e+1),eV(e=>e+1),eb&&rB(eb.id),"completed"===e.outcome&&dO()&&rV({targetSession:eb,title:eb?.name??ee("i18n.sessionComplete"),body:ee("i18n.taskFinished")})},[rV,rB,eb,ee]),rJ=(0,i.useCallback)(e=>{var t;dO()&&(t=ev.current,!(!dH(e)||t.has(e.id))&&(t.add(e.id),1)&&rV({targetSession:eb,title:ee("i18n.attentionNeeded"),body:"custom"===e.method?ee("i18n.extensionInputNeeded"):"ask"===e.method?e.questions[0]?.question||ee("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rV,eb,ee]),rZ=(0,i.useCallback)(async()=>{let e=eb?.id;if(e&&"naming"!==nM.kind){nE.current&&clearTimeout(nE.current),nV(null),nR({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(eU(e=>e+1),n$.current!==e)return;ew(t=>t?.id===e?{...t,name:r}:t),nk(t=>t?.sessionId===e?{...t,sessionName:r}:t),nR({kind:"success"}),nE.current=setTimeout(()=>nR({kind:"idle"}),1800)}catch(t){if(n$.current!==e)return;nR({kind:"error",message:t instanceof Error?t.message:String(t)}),nE.current=setTimeout(()=>nR({kind:"idle"}),5e3)}}},[nM.kind,eb?.id]);(0,i.useEffect)(()=>{nE.current&&clearTimeout(nE.current),nR({kind:"idle"})},[eb?.id]);let rX=(0,i.useCallback)(e=>{rz(),eU(e=>e+1),eB(e=>e+1),eF(null),ew(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),rB(e),K.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[rz,K,rB]),rQ=(0,i.useCallback)(()=>{rP(!0)},[]),r0=(0,i.useCallback)(e=>{if(rz(),eU(e=>e+1),eb?.id===e){let e=eb.cwd;ew(null),eF(e??null),eB(e=>e+1),nf({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nV(null),ta({type:"select-view",view:"chat"}),tT(),K.replace("/",{scroll:!1})}},["/",rz,tT,eb,K]),r1=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,a=`file:${e}`;i&&ry.current.delete(a),rg(n=>{let s=n.find(e=>e.id===a);if(!s)return[...n,{id:a,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:i}];let o=!r||s.sourceSessionId===r,l=!i||s.initialDisplayMode===i;return o&&l?n:n.map(e=>{if(e.id!==a)return e;let t={...e};return r&&(t.sourceSessionId=r),i&&(t.initialDisplayMode=i),t})}),rv(a),ta({type:"select-view",view:"files"}),nV(null),er&&nt(!1)},[er,nt]),r2=(0,i.useCallback)(e=>{r1(e,tN(e),{sourceSessionId:eb?.id??null})},[r1,eb?.id]),r8=(0,i.useCallback)(e=>{ry.current.delete(e);let t=rm.filter(t=>t.id!==e);rg(t),rv(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===ti.activeView&&n8("chat",!0)},[rm,n8,ti.activeView]),r4=(0,i.useCallback)(()=>{eb&&window.open(`/api/sessions/${encodeURIComponent(eb.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[eb]),r5=eA??(null===eb&&rT?rT:null),r6=null!==eb||null!==r5,r3="chat"!==ti.activeView,r7=eb?.cwd??r5,r9=rL&&!r6,ie=(0,i.useCallback)((e,t)=>{e6.current=e,e8(e),tr(e.error?ee("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&e9(!1),eG(e=>e+1),eB(e=>e+1))},[ee]);(0,i.useEffect)(()=>{let e=e3.current!==r7;if(e3.current=r7,e&&(e6.current=null,e8(null),e9(!1),tr(null)),!r7)return;let t=e6.current,n=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(r7)}`,{signal:n.signal}).then(async e=>{let n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);ie(n,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>n.abort()},[ie,r7,e4]);let it=(0,i.useCallback)(async e=>{if(r7&&!te){tt(!0),tr(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r7,action:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let r=e6.current;ie(n,r),(n.trusted||"cancel"===e)&&(e9(!1),tT())}catch(e){tr(e instanceof Error?e.message:String(e))}finally{tt(!1)}}},[ie,te,r7,tT]),ir=rm.find(e=>e.id===rx)??null,ii=rT?tN(rT)||rT:null,ia=eb?.cwd??r5,is=ia?tN(ia)||ia:null,io=(eb?.name?.trim()||eb?.firstMessage?.trim()||(r5?ee("i18n.newSession"):ii)||"CUELO").replace(/\s+/g," ").trim(),il=io.length>96?`${io.slice(0,93)}…`:io,ic=ii?`${il} — ${ii} — CUELO`:`${il} — CUELO`,id=ii?`${io} — ${ii}`:io,iu=eb?.transient?`${id} \xb7 ${ee("session.inMemory")}`:id,ip=nj.filter(e=>"pending"===e.status||"running"===e.status).length,ih=nI?ee("workspace.mainAttention"):tb?ee("workspace.mainWaiting"):tv?ee("workspace.mainWorking"):ee("workspace.mainIdle"),im=`${nI?"⚠":tb?"○":tv?"●":"○"} Main ${ih} \xb7 Sub ${ip}${nC?`/${nC}`:""}`,ig=(0,i.useCallback)(e=>n8(e,!0),[n8]),ix=(N=(C=(m={deckVisible:r3,pinDecision:td,deckExpanded:ti.deckExpanded}).deckVisible&&"pinned"===m.pinDecision.deck)&&m.deckExpanded,{replacesTranscript:m.deckVisible&&("view-stack"===m.pinDecision.deck||N),expandable:C,expanded:N,staleExpansion:m.deckExpanded&&!C}),iv=ix.replacesTranscript,iy=ix.expandable?{expanded:ix.expanded,onToggle:n5}:null,ib=ix.staleExpansion;(0,i.useEffect)(()=>{ib&&ta({type:"set-deck-expanded",expanded:!1})},[ib]),(0,i.useEffect)(()=>{let e=()=>{document.title!==ic&&(document.title=ic)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[ic]);let iw="ko"===X?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat"},ik="chat"!==ti.activeView,ij=ik?iw[ti.activeView]:iw[n1],iS=(I=nW&&Number.isFinite(nW.contextWindow)&&nW.contextWindow>0?nW.contextWindow:null,T=nW&&"number"==typeof nW.tokens&&Number.isFinite(nW.tokens)?Math.max(0,nW.tokens):null,R=null===(M=nW&&"number"==typeof nW.percent&&Number.isFinite(nW.percent)?nW.percent:null!==T&&null!==I?T/I*100:null)?"normal":M>90?"critical":M>70?"warning":"normal",E=null===T?"?":gt(T),$=null===I?"?":gt(I),L=null===M?"?":`${M.toFixed(0)}%`,{level:R,percent:M,fillPercent:null===M?0:Math.min(100,Math.max(0,M)),readout:null===I?null:`${L} \xb7 ${E}/${$}`,usedLabel:E,limitLabel:$,percentLabel:L}),iC=iS.readout,iN=iC?ee("chat.contextUsageTitle",{used:iS.usedLabel,limit:iS.limitLabel,percent:iS.percentLabel}):null,iI="critical"===iS.level?ee("chat.contextUsageCritical"):"warning"===iS.level?ee("chat.contextUsageWarning"):null,iT=(k=nw?.userMessages,!eb||eb.transient?"unsaved":("number"==typeof k?k:0)>0||eb.messageCount>0?null:"no-messages"),iM="unsaved"===iT?ee("title.unsaved"):"no-messages"===iT?ee("title.noMessages"):null,iR=iM??("error"===nM.kind?nM.message:null),iE="naming"===nM.kind?ee("title.generating"):"success"===nM.kind?ee("title.updated"):"error"===nM.kind?ee("title.failed"):ee("title.generate"),i$=(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)(pg,{tabs:rm,activeTabId:rx??"",onSelectTab:rv,onCloseTab:r8})}),(0,r.jsx)("div",{className:"workspace-file-content",children:ir?.filePath?(0,r.jsx)(pf,{filePath:ir.filePath,cwd:rT??void 0,sourceSessionId:ir.sourceSessionId,gitRefreshKey:eq,initialDisplayMode:ir.initialDisplayMode,viewStateStore:ry.current,viewStateKey:ir.id,onMentionLines:rj,onAtMention:rw,onInsertText:rN,onOpenFile:e=>r1(e,tN(e),{sourceSessionId:ir.sourceSessionId})},ir.id):(0,r.jsx)("div",{className:"workspace-file-empty",children:(0,r.jsx)(m6,{cwd:eb?.cwd??rT,onOpenFile:r2})})})]}),iL=(0,r.jsx)(mt,{open:"resource"===ti.activeView,sessionId:eb?.id??null,activeTab:ts,onTabChange:to,usage:eh}),iP=(0,r.jsx)(m5,{open:"efficiency"===ti.activeView,sessionId:eb?.id??null,activeTab:tl,onTabChange:tc}),iA=(0,r.jsx)(fk,{title:iw.process,data:n_,onOpenFile:r2}),iF=eb?eb.path?eb.path:nw?.sessionId===eb.id&&nw.sessionFile?nw.sessionFile:null:null,iz=(0,r.jsx)(fO,{title:iw.sidechat,sessionId:eb?.id??null,sessionPath:iF,sessionName:eb?.name,historyStore:tp,flights:th,sessionCensus:tg,visible:"sidechat"===ti.activeView}),iW=r3?(0,r.jsx)(fw,{activeView:ti.activeView,onViewChange:e=>n8(e),viewLabels:iw,sessionId:eb?.id??null,sessionPath:iF,sessionName:eb?.name,sessionCwd:eb?.cwd??r5??void 0,liveSubagents:nj,processSlot:iA,fileSlot:i$,sideChatSlot:iz,resourceSlot:t??iL,efficiencySlot:iP,visible:!0,onClose:()=>ta({type:"select-view",view:"chat"}),onReturnFocus:tT,expand:iy,selectedMaker:n6,onSelectMaker:n3,onReturnToDispatch:rn,onOpenFile:r2,fileOpen:!!ir?.filePath}):null,iD=e??iW,iO=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ep,{selectedSessionId:ek?.id??eb?.id??null,optimisticSession:ek??eb,onSelectSession:rH,onNewSession:rU,initialSessionId:rI,skipInitialProjectSelection:null!==J.requestedCwd,onInitialRestoreDone:rQ,refreshKey:eH,onSessionDeleted:r0,selectedCwd:eb?.cwd??eA??null,onCwdChange:rD,onBackgroundTaskDone:ey,translatorPanel:(0,r.jsx)(gM,{onOpen:er?()=>nt(!1):void 0}),translatorActive:ef,onTranslatorActiveChange:tM}),(0,r.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[(0,r.jsx)(gu,{usage:eh,onOpen:()=>{to("usage"),n8("resource",!1)},onRelogin:ra}),(0,r.jsx)(g$,{}),(0,r.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{nV(null),ta({type:"close-layer"}),er&&nt(!1),eZ(!0)},title:ee("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"})]}),ee("common.settings")]})]})]}),iH=tU&&tB&&tB.requestId===tU.requestId&&tB.deploymentCompleted?tB:null,iU=iH?.cleanup??null,i_=iH&&!tU?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:dY(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:dY(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:dY(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:dY(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:dY(e.status)}}(iU):null;return(0,r.jsxs)(np.Provider,{value:rS,children:[t$?(0,r.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,r.jsxs)("div",{className:"server-restart-card",children:[(0,r.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,r.jsx)("strong",{children:ee("restart.title")}),(0,r.jsx)("span",{children:ee(tz?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:tS,className:"workspace-shell","data-active-view":ti.activeView,"data-deck-mode":td.deck,"data-deck-visible":r3,"data-chat-wide":e$?"true":void 0,children:[(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${ne.drawer?" is-open":""}${t2?"":" sidebar-mobile-pending"}${t4?" sidebar-mode-shift":""}`,onClick:()=>{nt(!1),tT()}}),(0,r.jsx)("div",{ref:nl.panelRef,id:"session-sidebar",className:`sidebar-container${ne.laidOut?" sidebar-open":" sidebar-closed"}${t2?"":" sidebar-mobile-pending"}${t4?" sidebar-mode-shift":""}${nl.isResizing?" sidebar-resizing":""}`,"aria-hidden":er&&!ne.presented,inert:er&&!ne.presented,style:{"--sidebar-width":`${nl.width}px`},children:iO}),ne.laidOut&&(0,r.jsx)("div",{...nl.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${nl.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${ee("layout.resizeSidebar")}: ${ee("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":ti.activeView,"aria-hidden":ne.drawer,inert:ne.drawer,children:[(0,r.jsxs)("div",{ref:nu,className:"workspace-header-stack","data-soft-keyboard":ei&&ea?"open":void 0,children:[i_&&tU&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":i_.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:i_.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:i_.detail}),i_.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>t_(d1(tU.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tD&&!(i_&&tU)&&(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:ee("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:ee("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tO(!1),"aria-label":ee("restart.returnedDismiss"),children:ee("i18n.close")})]}),(0,r.jsx)(fi,{variant:"banner",locale:X,...en}),(0,r.jsxs)("header",{className:"workspace-header-seam",children:[(0,r.jsx)(s.r,{ref:nn,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:rf,"aria-controls":"session-sidebar","aria-expanded":ne.presented,title:ne.presented?ee("sidebar.hide"):ee("sidebar.show"),"aria-label":ne.presented?ee("sidebar.hide"):ee("sidebar.show"),children:ne.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:iu,children:[(0,r.jsxs)("div",{className:"workspace-session-identity-line",children:[is&&(0,r.jsx)("em",{className:"workspace-session-project",children:is}),(0,r.jsx)("strong",{children:il})]}),(0,r.jsx)("span",{className:"workspace-session-status","aria-live":"polite",children:im})]}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===nM.kind?nM.message:""}),r6&&e2?.requiresTrust&&!e2.trusted&&(0,r.jsxs)(s.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{tr(e2.error?ee("trust.applyFailed",{error:e2.error}):null),nV(null),ta({type:"close-layer"}),e9(!0),e2.pending&&e5(e=>e+1)},title:ee("grant"===e2.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":ee("grant"===e2.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"})]}),!er&&(0,r.jsx)("span",{children:ee("trust.resourcesNotLoaded")})]}),r6&&iC&&(0,r.jsxs)(s.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:rh,"aria-expanded":"session"===nq,title:iN??ee("session.title"),"aria-label":iI?`${iN}. ${iI}`:iN??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":iS.level,style:{inlineSize:`${iS.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":iS.level,children:iC})]}),r6&&(0,r.jsx)(l.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:ik,onPressedChange:ri,"aria-controls":"workspace-auxiliary-panel",title:"ko"===X?"보조 패널":"Auxiliary panel",children:(0,r.jsx)("span",{className:"workspace-panel-toggle-label",children:ij})}),(0,r.jsxs)(c.k.Root,{open:nQ,onOpenChange:e=>n0(e),placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===X?"더 보기":"More","aria-label":"ko"===X?"더 보기":"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"===X?"세션 및 환경 메뉴":"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"===X?"세션":"Session"}),(0,r.jsx)(c.k.Item,{onClick:rh,children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("session.title")})})}),(0,r.jsx)(c.k.Item,{onClick:r4,disabled:!eb,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:ee("history.label")}),!eb&&(0,r.jsx)(c.k.ItemDescription,{children:ee("history.unsaved")})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>void rZ(),disabled:null!==iM||"naming"===nM.kind,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:iE}),iR&&(0,r.jsx)(c.k.ItemDescription,{children:iR})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>rp("branches"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("i18n.branches")})})}),(0,r.jsx)(c.k.Item,{onClick:()=>rp("system"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("system.label")})})})]}),(0,r.jsxs)(c.k.Group,{children:[(0,r.jsx)(c.k.GroupLabel,{children:"ko"===X?"환경":"Environment"}),(0,r.jsx)(fi,{variant:"menu",locale:X,...en}),(0,r.jsx)(c.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();Y({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("light"===Z?"theme.light":"dark"===Z?"theme.dark":"theme.auto")})})}),et.map(e=>(0,r.jsx)(c.k.Item,{role:"menuitemradio","aria-checked":X===e.id,onClick:()=>Q(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:()=>{nV(null),ta({type:"close-layer"}),er&&nt(!1),eZ(!0)},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("common.settings")})})})]})]})})})]})]}),nq&&nK&&(0,r.jsxs)("div",{style:{position:"fixed",top:nK.top,left:nK.left,width:nK.width,maxHeight:`calc(100dvh - ${nK.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===nq&&(0,r.jsx)("div",{className:"workspace-top-panel","aria-label":ee("i18n.branches"),children:(0,r.jsx)(ge,{tree:nh.sessionId===(eb?.id??null)?nh.tree:[],activeLeafId:nh.sessionId===(eb?.id??null)?nh.leafId:null,onLeafChange:nx,hasSession:!!eb})}),"system"===nq&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:nv?(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:nv}):""===nv?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:ee("system.empty")}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:ee("system.load")})}),"session"===nq&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:nw?(P=nw.totalActiveMs??0,A=[...nw.sessionName?[{label:ee("session.name"),value:nw.sessionName,copyField:null}]:[],{label:ee("session.file"),value:nw.sessionFile??ee("session.inMemory"),copyField:"file"},{label:ee("session.id"),value:nw.sessionId,copyField:"id"},...P>0?[{label:ee("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`})(P),copyField:null}]:[]],z=[[ee("session.user"),nw.userMessages.toLocaleString(X)],[ee("session.assistant"),nw.assistantMessages.toLocaleString(X)],[ee("session.toolCalls"),nw.toolCalls.toLocaleString(X)],[ee("session.toolResults"),nw.toolResults.toLocaleString(X)],[ee("session.total"),nw.totalMessages.toLocaleString(X)]],W=[[ee("session.input"),nw.tokens.input.toLocaleString(X)],[ee("session.output"),nw.tokens.output.toLocaleString(X)],...nw.tokens.cacheRead>0?[[ee("session.cacheRead"),nw.tokens.cacheRead.toLocaleString(X)]]:[],...nw.tokens.cacheWrite>0?[[ee("session.cacheWrite"),nw.tokens.cacheWrite.toLocaleString(X)]]:[],[ee("session.total"),nw.tokens.total.toLocaleString(X)]],D=nW??nw.contextUsage,_=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),B=[...nw.cost>0?[[ee("session.cost"),`$${nw.cost.toFixed(4)}`]]:[],...D?.contextWindow?[[ee("session.context"),`${null!==D.tokens?_(D.tokens):"?"} / ${_(D.contextWindow)}${null!==D.percent?` \xb7 ${D.percent.toFixed(1)}%`:""}`]]:[],...nw.tokens.cacheRead+nw.tokens.cacheWrite>0&&nw.tokens.cacheRead+nw.tokens.cacheWrite+nw.tokens.input>0?[[ee("session.cacheHitRate"),`${(nw.tokens.cacheRead/(nw.tokens.cacheRead+nw.tokens.cacheWrite+nw.tokens.input)*100).toFixed(1)}%`]]:[]],q=(e,t,n="left",i=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:i?"max-content max-content":"auto minmax(0, 1fr)",columnGap:i?14:12,rowGap:4,justifyContent:i?"start":void 0},children:t.map(([t,a])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:a})]},`${e}:${t}`))})]}),V=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:ee("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:A.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=nP===t,(0,r.jsx)("button",{type:"button",title:i?ee("session.copied"):ee("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:er?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:er?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[V,q(ee("session.messages"),z),q(ee("session.tokens"),[...W,...B],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:ee("session.load")})})]})]}),(0,r.jsxs)("div",{className:"chat-content-layout",children:[(0,r.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-translator-open":ef?"true":void 0,children:[r6?(0,r.jsx)(u$,{session:eb,newSessionCwd:r5,initialSessionData:eS,transitioning:null!==ek,onAgentEnd:rG,onAttentionNeeded:rJ,onSessionCreated:rq,onSessionForked:rX,modelsRefreshKey:eK,chatInputRef:nd,onBranchDataChange:ng,onSystemPromptChange:nb,onSessionStatsChange:nL,onSessionStatsPanelOpen:rh,onContextUsageChange:nU,onSubagentsChange:nS,onOpenWorkspaceView:ig,onOpenSessionList:ne.presented?void 0:rf,onOpenMaker:n7,selectedMaker:n6,onProcessLogChange:nB,onOpenFile:r2,transcriptReplacement:iv?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iD}):null,onComposerFocusChange:tR,onSessionBusyChange:ty,onWaitingChange:tw,onAttentionChange:nT,soundEnabled:es,onSoundToggle:eo,playCueSound:el,preloadCueSound:ec,unlockAudio:ed,jumpRequest:eT,onJumpHandled:eE},e_):iv?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iD}):"validating"===ez?(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:ee("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd})]}):"error"===ez?(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:ee("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eD})]}):r9?rT?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:ee("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:ee("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."}),ee("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),ee("workspace.addModels")]})]})]}):null,eg?(0,r.jsx)(gT,{visible:ef,onBack:()=>tM(!1)}):null]}),"pinned"===td.deck&&r3&&!ix.expanded&&(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:iD})]})]}),"command-palette"===ti.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(ta({type:"close-layer"}),tT())},children:(0,r.jsxs)("div",{ref:tI,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:tQ,"aria-label":"ko"===X?"명령 팔레트":"Command palette",children:[(0,r.jsxs)("header",{children:[(0,r.jsx)("strong",{children:"ko"===X?"명령 팔레트":"Command palette"}),(0,r.jsx)("kbd",{children:"Ctrl K"})]}),(0,r.jsx)(uD,{t:ee,onPick:(e,t)=>{ta({type:"close-layer"}),n8("chat",!1),eR.current+=1,eM({id:eR.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:()=>n8(e,!0),children:[(0,r.jsx)("span",{children:iw[e]}),(0,r.jsx)("small",{children:ti.activeView===e?"ko"===X?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{to(e),n8("resource",!1)},children:[(0,r.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,r.jsx)("small",{children:iw.resource})]},e)),(0,r.jsxs)("button",{type:"button",onClick:rf,children:[(0,r.jsx)("span",{children:ne.presented?ee("sidebar.hide"):ee("sidebar.show")}),(0,r.jsx)("small",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:eP,children:(0,r.jsx)("span",{children:ee(e$?"palette.wideChatOff":"palette.wideChatOn")})}),(0,r.jsx)("button",{type:"button",onClick:()=>{ta({type:"close-layer"}),eZ(!0)},children:(0,r.jsx)("span",{children:ee("common.settings")})})]})]})})]}),eJ&&(0,r.jsx)(ft,{cwd:r7,sessionId:eb?.id??null,onClose:()=>{eZ(!1),e5(e=>e+1),tT()},onModelsChanged:()=>eG(e=>e+1),onReloaded:()=>eB(e=>e+1)}),null!==eY&&(0,r.jsx)(hk,{cwd:r7,onClose:rs,onModelsChanged:()=>eG(e=>e+1),relogin:{target:eY,outcome:eQ,onLoginSucceeded:rl}}),e7&&r7&&(0,r.jsx)(fa,{cwd:r7,busy:te,scheduled:e2?.pending==="grant",error:tn,onCancel:()=>{te||(e9(!1),tT())},onConfirm:()=>void it("grant"),onCancelSchedule:()=>void it("cancel")})]})}},80455:(e,t,n)=>{Promise.resolve().then(n.bind(n,42661)),Promise.resolve().then(n.bind(n,92176))},92176:(e,t,n)=>{"use strict";n.d(t,{I18nProvider:()=>h,s:()=>f});var r=n(95155),i=n(12115);let a=JSON.parse('{"cloudProjects.launch":"GitHub 저장소 열기","cloudProjects.title":"클라우드 프로젝트","cloudProjects.description":"GitHub 저장소를 가져와 이 서버에서 작업을 이어가세요.","cloudProjects.github":"GitHub 저장소","cloudProjects.serverFolder":"서버 폴더 열기","cloudProjects.account":"GitHub 연결","cloudProjects.connectTitle":"내 GitHub 저장소 연결","cloudProjects.connectHelp":"연결하면 비공개 저장소도 목록에서 선택할 수 있습니다.","cloudProjects.connected":"GitHub 연결됨","cloudProjects.refresh":"다시 확인","cloudProjects.waiting":"로그인 대기 중","cloudProjects.connect":"GitHub 연결","cloudProjects.deviceHelp":"아래 코드를 GitHub 로그인 화면에 입력하세요.","cloudProjects.copyCode":"코드 복사","cloudProjects.copied":"복사됨","cloudProjects.copyFailure":"코드를 복사하지 못했습니다. 코드를 선택해 직접 복사하세요.","cloudProjects.openLogin":"GitHub에서 로그인","cloudProjects.permissionHelp":"GitHub에서 계정과 요청 권한을 확인하고 승인하세요. 인증 토큰은 서버에만 저장됩니다.","cloudProjects.preparingCode":"로그인 코드를 준비하고 있습니다.","cloudProjects.repositories":"내 저장소","cloudProjects.search":"저장소 검색","cloudProjects.searchPlaceholder":"이름 또는 설명으로 찾기","cloudProjects.loading":"저장소를 불러오고 있습니다.","cloudProjects.private":"비공개","cloudProjects.public":"공개","cloudProjects.empty":"일치하는 저장소가 없습니다. 다른 이름으로 검색하거나 URL을 입력하세요.","cloudProjects.more":"더 보기","cloudProjects.urlLabel":"선택한 저장소 또는 GitHub URL","cloudProjects.publicHelp":"공개 저장소는 로그인 없이도 가져올 수 있습니다. 이미 가져온 저장소는 변경 없이 다시 엽니다.","cloudProjects.error":"작업을 완료하지 못했습니다.","cloudProjects.openingHelp":"저장소를 서버에 가져오고 있습니다. 크기에 따라 시간이 걸릴 수 있습니다.","cloudProjects.opening":"프로젝트 여는 중","cloudProjects.open":"프로젝트 열기","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":"열린 파일 없음","files.docs.noProject":"프로젝트를 선택하면 문서 바로가기가 보입니다.","files.docs.loading":"프로젝트 문서를 찾는 중…","files.docs.projectDenied":"이 프로젝트 폴더는 CUELO가 읽을 수 있는 폴더 밖에 있습니다.","files.docs.loadFailed":"프로젝트 문서를 불러오지 못했습니다: {error}","files.docs.projectDir":"프로젝트 폴더: {path}","files.docs.noneFound":"저장소 루트까지 HANDOFF.md가 없고, 이 폴더에 doc/README.md나 doc/history도 없습니다.","files.docs.current":"현재 상태","files.docs.map":"문서 지도","files.docs.records":"최근 기록","files.docs.missing":"{file} 없음","files.docs.denied":"{file}은(는) 읽기 허용 폴더 밖에 있습니다","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":"목록 비우기","navigator.resultsToCheck":"확인할 결과","navigator.resultsToCheckCount":"확인할 결과 {count}","navigator.resultsToCheckHint":"이 브라우저에서 마지막으로 연 뒤 새로 끝난 대화","navigator.resultsToCheckEmpty":"확인할 결과가 없습니다.","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.emptyProjectLabel":"작업 폴더","chat.emptyProjectHint":"첫 메시지를 보내면 이 폴더에서 새 세션이 시작됩니다.","chat.openSessionList":"세션 목록 열기","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.attachStoredTooLarge":"{name} 파일이 파일당 {limit} 제한을 초과합니다.","chat.attachUploadFailed":"{name} 파일을 저장하지 못했습니다: {error}","chat.attachTranscribePending":"선택 필요","chat.transcribeGroup":"음성 받아쓰기","chat.transcribeChecking":"길이 확인 중","chat.transcribeConfirmTitle":"{name} 받아쓰기를 시작할까요?","chat.transcribePlanSummary":"{duration} \xb7 받아쓰기 호출 약 {calls}회","chat.transcribeDurationUnknown":"길이 알 수 없음","chat.transcribeUsageNotice":"받아쓰기는 연결된 계정의 사용량에 포함됩니다. 시작을 누르기 전에는 아무것도 보내지 않습니다.","chat.transcribeStart":"받아쓰기 시작","chat.transcribeSkip":"받아쓰지 않기","chat.transcribeCancel":"받아쓰기 취소","chat.transcribeRunning":"{name} 받아쓰는 중","chat.transcribeRetry":"다시 시도","chat.transcribeAction":"받아쓰기","chat.transcribeSkipped":"{name}은(는) 받아쓰지 않고 저장된 파일 경로만 보냅니다.","chat.transcribeFailedRow":"{name} 받아쓰기 실패: {error}","chat.transcribeToolMissing":"음성 도구(ffmpeg)를 쓸 수 없어 이 음성을 받아쓰기용으로 준비하지 못했습니다.","chat.transcribePartialFailed":"{total}조각 중 {done}조각까지 처리하고 멈췄습니다. 일부 결과는 붙이지 않았습니다.","chat.transcribeTooLong":"받아쓴 내용이 다른 첨부와 합친 글자 수 제한을 넘습니다.","chat.attachmentSettingsNav":"첨부 파일","chat.attachmentSettingsTitle":"첨부 파일","chat.attachmentSettingsDescription":"대화에 첨부한 파일은 에이전트가 열 수 있도록 이 컴퓨터에 저장됩니다.","chat.attachmentSettingsLoadFailed":"첨부 설정을 불러오지 못했습니다","chat.attachmentUploadLimit":"파일당 업로드 한도(MB)","chat.attachmentUploadLimitHelp":"이보다 큰 파일은 보내기 전에 거절합니다. 메시지에 바로 읽어 넣는 텍스트는 따로 문서당 8MB, 합계 240,000자 한도를 지킵니다.","chat.attachmentUploadLimitInvalid":"1 이상의 정수(MB)를 입력하세요.","chat.attachmentAutoCleanup":"쓰이지 않는 첨부 자동 삭제","chat.attachmentAutoCleanupHelp":"대화\xb7분기\xb7보내지 않은 초안에서 쓰이는 첨부는 지우지 않습니다. 어디에서도 쓰이지 않는다고 확인된 때부터 {days}일이 지나면 삭제하고, 쓰임을 확인할 수 없는 파일은 남겨 둡니다.","chat.attachmentSettingsSaved":"저장했습니다","characterMode.nav":"캐릭터","characterMode.title":"캐릭터","characterMode.description":"화면에 보이는 캐릭터의 얼굴\xb7이름\xb7스티커\xb7완료 음성을 고릅니다.","characterMode.label":"캐릭터 세트","characterMode.default":"기본","characterMode.office":"사무실 모드","characterMode.help":"이 PC의 서버 전체에 적용됩니다. 사무실 모드에서는 이 PC 프로필의 캐릭터 세트가 openai-codex 자리를 대신합니다. 나머지 자리는 그대로입니다.","characterMode.noRoster":"이 PC에는 사무실 캐릭터 세트가 없어 기본 캐릭터가 그대로 쓰입니다.","characterMode.saved":"저장했습니다","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 수준 사용","roles.harnessNote":"CUELO Maker 자리는 지정하기 전에도 목록에 표시됩니다. 쓸 자리만 직접 모델을 고르세요. 저장해도 로그인하거나 모델을 시험 호출하지 않습니다.","roles.harnessUnset":"미설정","roles.harness.implSonnet":"Maker \xb7 NORMAL 비-UI 우선","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL 대안","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD 코드","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD 코드 대안","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.currentReasoning":"현재 추론 강도: {level}","chat.fastModeActive":"Fast 켜짐 \xb7 이 모델에 적용 중. 우선 처리라 요금\xb7사용량이 더 들 수 있습니다. 누르면 끕니다","chat.fastModeInactive":"Fast 요청됨 \xb7 이 모델\xb7계정에는 적용되지 않음. 누르면 끕니다","chat.fastModeOff":"Fast 꺼짐 \xb7 누르면 우선 처리를 요청합니다(provider에 따라 요금\xb7사용량이 더 듭니다)","chat.fastModeUnknown":"Fast 상태 확인 전 \xb7 누르면 이 세션의 실제 상태를 읽고 바꿉니다","chat.fastModeBusy":"Fast 바꾸는 중","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.liveVoiceSettingsNav":"통화 음성","chat.liveVoiceSettingsTitle":"통화 음성","chat.liveVoiceSettingsDescription":"라이브 통화와 통역 통화에서 말할 Codex 목소리를 고릅니다. 선택은 다음 통화부터 적용됩니다.","chat.liveVoiceSpeakerGroup":"목소리","chat.liveVoiceCodexLabel":"Codex 목소리","chat.liveVoiceCodexHelp":"라이브 통화와 통역 통화에서 이 목소리로 말합니다.","chat.liveVoiceLoadFailed":"음성 설정을 불러오지 못했습니다","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.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":"확대","toolImage.dialogLabel":"확대한 이미지","toolImage.requestEdit":"이 화면 수정 요청","toolImage.requestEditHint":"이 이미지를 입력창에 붙입니다. 고칠 내용을 적어 보내세요.","toolImage.noComposer":"붙일 입력창이 없습니다. 대화를 열고 「이 화면 수정 요청」을 누르세요.","toolImage.loadFailed":"이미지를 가져오지 못했습니다. 「이 화면 수정 요청」을 다시 누르세요.","toolImage.markHint":"고칠 곳을 드래그해 표시하세요","toolImage.markLimit":"구역은 {count}개까지 표시할 수 있습니다","toolImage.clearMarks":"표시 지우기","toolImage.regionLabel":"구역 {n}","toolImage.locatorIntro":"첨부한 화면에 고칠 곳을 빨간 상자로 표시했습니다(구역 {range}). 구역별 확대 그림이 뒤에 이어집니다.","toolImage.locatorRegion":"구역 {n}: x={x}, y={y}, 폭 {w}, 높이 {h} (원본 {width}\xd7{height} 픽셀 기준)","files.pickElement":"요소 지정","files.pickElementHint":"미리보기에서 고칠 요소를 누르세요","files.pickedElement":"지정한 요소","files.requestElementEdit":"이 요소 수정 요청","files.clearPick":"지정 해제","files.pickLocatorElement":"요소: {selector}","files.pickLocatorText":"텍스트: \\"{text}\\"","files.pickLocatorPosition":"화면 위치: x={x}, y={y}, 폭 {w}, 높이 {h} (미리보기 {vw}\xd7{vh} 기준)","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":"실행 취소","models.navGroupRoles":"역할 배정","models.navGroupAccounts":"연결된 계정","models.navGroupCustom":"직접 추가한 제공자","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.reloadSessionHint":"열린 세션의 설정과 스킬을 다시 불러옵니다. Plugin은 해제되지 않으니, 해제하려면 CUELO를 재시작하세요.","i18n.reloading":"다시 불러오는 중...","i18n.packageRemoved":"패키지가 제거되었습니다.","i18n.packageInstalled":"패키지가 설치되었습니다.","i18n.packageUpdated":"패키지가 업데이트되었습니다.","i18n.packageDisabled":"패키지가 비활성화되었습니다.","i18n.packageDisabledRestartRequired":"비활성화 설정을 저장했습니다. 이미 불러온 Plugin은 CUELO를 재시작해야 멈춥니다. 세션 다시 불러오기로는 해제되지 않습니다.","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.showOriginalReply":"영어 원문 보기","i18n.hideOriginalReply":"영어 원문 접기","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":"미측정","usage.title":"사용량","usage.reorder":"순서 편집","usage.reorderDone":"완료","usage.reorderGroup":"계정 표시 순서","usage.moveUp":"{account} 위로","usage.moveDown":"{account} 아래로","usage.moved":"{account}: {position}번째로 이동","usage.authExpired":"인증 만료","usage.authUnavailable":"사용 불가","usage.relogin":"재로그인","usage.reloginFor":"{account} 계정 재로그인","usage.authIssues":"계정 오류 {count}","relogin.title":"재로그인 대상","relogin.guide":"「{action}」을 누른 뒤 브라우저에서 이 계정으로 로그인하세요. 다른 계정으로 로그인하면 이 계정의 오류는 그대로 남습니다.","relogin.done":"로그인을 마쳤습니다.","relogin.checking":"{account} 상태를 확인하려고 사용량을 다시 읽는 중…","relogin.recovered":"{account} 계정 인증이 복구됐습니다.","relogin.stillFailing":"로그인은 끝났지만 {account} 계정은 아직 인증 오류입니다. 다른 계정으로 로그인했을 수 있습니다.","relogin.unknown":"사용량에서 {account} 계정을 찾지 못해 복구 여부를 확인하지 못했습니다.","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.mixedPairingNote":"혼합 구성: 요청별 모델\xb7추론 강도 조합과 순서는 확인되지 않았습니다. 같은 조건의 실행으로 단정할 수 없습니다.","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.toolFailedValue":"실패 {value}","efficiency.toolNoMatchValue":"무일치 {value}","efficiency.toolCancelledValue":"중단 {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","efficiency.harness":"하네스","efficiency.harnessValue":"하네스 {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"모든 하네스","efficiency.groupByHarness":"하네스별로 나누기","efficiency.harnessNote":"하네스는 run 시작 시점에 설치돼 있던 CUELO 버전입니다. 이 PC의 업데이트 기록으로만 정하며, 기록이 없거나 기록 밖에서 바뀐 구간은 unknown입니다.","efficiency.sawSection":"모델이 본 것","efficiency.sawApproxNote":"세션 기록으로 다시 맞춘 근사치입니다. 요청마다 보낸 시스템 프롬프트와 컨텍스트 훅이 바꾼 내용은 기록에 남지 않습니다.","efficiency.sawOpen":"요청별로 보기","efficiency.sawLoading":"요청 기록을 읽는 중…","efficiency.sawError":"요청 기록을 읽지 못했습니다.","efficiency.sawEmpty":"이 run에는 모델 요청 기록이 없습니다.","efficiency.sawFilterEmpty":"주입이 있는 요청이 없습니다.","efficiency.sawRole":"대화 기록","efficiency.sawSummary":"요청 {turns}회 \xb7 주입 {injections}건 \xb7 도구 {tools}회 \xb7 실패 {failed}건","efficiency.sawOnlyInjected":"주입 있는 요청만","efficiency.sawTurnLabel":"요청 {index}","efficiency.sawBefore":"이 요청 전에 들어온 것","efficiency.sawTrailing":"마지막 요청 뒤에 들어온 것 (이 run의 모델 요청에는 들어가지 않음)","efficiency.sawShowFull":"전체 보기","efficiency.sawShowArgs":"인자 보기","efficiency.sawShowResult":"결과 보기","efficiency.sawHideFull":"접기","efficiency.sawTruncated":"앞 {value}자만 보입니다.","efficiency.sawMore":"{value}개 더 보기","efficiency.sawShown":"{total}개 중 {shown}개 표시","efficiency.sawHiddenFromChat":"채팅에는 안 보임","efficiency.sawNotSent":"모델에 안 보냄","efficiency.sawSecretsMasked":"비밀값처럼 보이는 문자열은 [REDACTED]로 가렸습니다.","efficiency.sawKindInjection":"주입","efficiency.sawKindDeveloper":"개발자 메시지","efficiency.sawKindUser":"사용자 메시지","efficiency.sawKindCompaction":"압축","efficiency.sawKindModel":"모델 변경","efficiency.sawKindEffort":"effort 변경","efficiency.sawKindPrompt":"시스템 프롬프트 바뀜","efficiency.sawKindRules":"규칙 주입","efficiency.sawKindMemory":"기억 회상","efficiency.sawCompactionValue":"{before} → {after} 토큰","efficiency.sawMemoryIds":"기억 {value}건 회상 (본문은 기록되지 않음)","efficiency.sawToolOk":"성공","efficiency.sawToolFailed":"실패","efficiency.sawToolNoMatch":"일치 없음","efficiency.sawToolCancelled":"중단","efficiency.sawToolMissing":"결과 없음","efficiency.sawResultChars":"결과 {value}자","efficiency.sawUsage":"입력 {input} \xb7 출력 {output} \xb7 캐시 읽기 {cacheRead}","efficiency.sawStop":"종료: {value}","efficiency.sawToolsChanged":"도구 목록 변경: +{added} −{removed}","efficiency.sawPreludeTitle":"시스템 프롬프트와 도구","efficiency.sawPreludeRecorded":"기록된 것","efficiency.sawPreludeTools":"마지막 요청에 켜진 도구 {value}개 (기록됨)","efficiency.sawPreludeDigest":"시스템 프롬프트 지문: {value}","efficiency.sawPreludeDigestNone":"이 run 시점의 시스템 프롬프트 지문이 기록에 없습니다.","efficiency.sawPreludeMemory":"기억 회상 블록 (시스템 프롬프트의 일부, 기록됨)","efficiency.sawPreludeReconstruct":"지금 설정으로 다시 만들기","efficiency.sawPreludeLoading":"다시 만드는 중…","efficiency.sawPreludeApprox":"지금 설정으로 다시 만든 것이며 보낸 그대로가 아닙니다.","efficiency.sawPreludeNotLoaded":"이 세션이 지금 열려 있지 않아 다시 만들 수 없습니다. 시스템 프롬프트 본문은 기록되지 않습니다.","efficiency.sawPreludeMatch":"지금 프롬프트의 지문이 이 run의 기록과 같습니다.","efficiency.sawPreludeMismatch":"지금 프롬프트의 지문이 이 run의 기록과 다릅니다. 그사이 바뀌었을 수 있습니다.","toolRun.running":"실행 중","toolRun.failed":"실패","toolRun.exitCode":"exit {code}","toolRun.diffStats":"{added}줄 추가, {removed}줄 삭제","panel.expand":"패널 넓게 보기","panel.restore":"원래 크기로","panel.more":"더 보기","panel.liveSync":"실시간 반영","panel.subagentsCount":"기록 {count}건","panel.refresh":"기록 새로고침","panel.close":"패널 닫기","makerDetail.region":"{title} 기록","makerDetail.noFiles":"이 Maker는 파일을 바꾸지 않았습니다","makerDetail.noChecks":"검사 실행 없음","makerDetail.archiveUnobserved":"기록에 도구 결과가 없어 확인할 수 없습니다","makerDetail.unavailable":"이 시도와 정확히 맞는 실행 기록이 없어 상세를 열 수 없습니다","makerDetail.checkPassed":"통과","makerDetail.checkUnverified":"판정 미확인","makerDetail.checkFailed":"실패","makerDetail.checkUnobserved":"결과 미관측","dispatchLane.label":"Maker 시도","dispatchLane.runPhase":"{run}({phase})","dispatchLane.checks":"검사 {passed}/{total}","dispatchLane.checksUnobserved":"검사 미관측","dispatchLane.checksLoading":"검사 읽는 중","dispatchLane.attempt":"시도 {attempt}","dispatchLane.attemptUnknown":"시도","dispatchLane.verdict.accepted":"수용","dispatchLane.verdict.rework":"재작업","dispatchLane.verdict.held":"보류","dispatchLane.open":"자세히","dispatchLane.openLabel":"{title} 자세히 보기","dispatchLane.unavailable":"상세 없음"}'),s=["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:{"cloudProjects.launch":"Open GitHub repository","cloudProjects.title":"Cloud project","cloudProjects.description":"Bring a GitHub repository to this server and keep working.","cloudProjects.github":"GitHub repositories","cloudProjects.serverFolder":"Open server folder","cloudProjects.account":"GitHub connection","cloudProjects.connectTitle":"Connect your GitHub repositories","cloudProjects.connectHelp":"Sign in to select private repositories from your list.","cloudProjects.connected":"Connected to GitHub","cloudProjects.refresh":"Check again","cloudProjects.waiting":"Waiting for sign-in","cloudProjects.connect":"Connect GitHub","cloudProjects.deviceHelp":"Enter this code on the GitHub sign-in page.","cloudProjects.copyCode":"Copy code","cloudProjects.copied":"Copied","cloudProjects.copyFailure":"Could not copy the code. Select and copy it manually.","cloudProjects.openLogin":"Sign in on GitHub","cloudProjects.permissionHelp":"Check the account and requested permissions on GitHub before approving. Tokens stay on the server.","cloudProjects.preparingCode":"Preparing your sign-in code.","cloudProjects.repositories":"Your repositories","cloudProjects.search":"Find a repository","cloudProjects.searchPlaceholder":"Search by name or description","cloudProjects.loading":"Loading repositories.","cloudProjects.private":"Private","cloudProjects.public":"Public","cloudProjects.empty":"No matching repositories. Try another name or enter a URL.","cloudProjects.more":"Show more","cloudProjects.urlLabel":"Selected repository or GitHub URL","cloudProjects.publicHelp":"Public repositories do not require sign-in. Existing workspaces are reopened without changing your files.","cloudProjects.error":"Could not complete the operation.","cloudProjects.openingHelp":"Importing the repository to this server. Large repositories may take a while.","cloudProjects.opening":"Opening project","cloudProjects.open":"Open project","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","files.docs.noProject":"Select a project to see its documents.","files.docs.loading":"Looking for project documents…","files.docs.projectDenied":"This project folder is outside the folders CUELO may read.","files.docs.loadFailed":"Could not load project documents: {error}","files.docs.projectDir":"Project folder: {path}","files.docs.noneFound":"No HANDOFF.md up to the repository root, and no doc/README.md or doc/history in this folder.","files.docs.current":"Current state","files.docs.map":"Document map","files.docs.records":"Recent records","files.docs.missing":"{file} not found","files.docs.denied":"{file} is outside the readable folders","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","navigator.resultsToCheck":"To review","navigator.resultsToCheckCount":"To review {count}","navigator.resultsToCheckHint":"Finished conversations with new activity since you last opened them in this browser","navigator.resultsToCheckEmpty":"Nothing to review.","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.emptyProjectLabel":"Project folder","chat.emptyProjectHint":"Your first message starts a new session in this folder.","chat.openSessionList":"Open session list","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.attachStoredTooLarge":"{name} exceeds the {limit} per-file limit.","chat.attachUploadFailed":"Could not save {name}: {error}","chat.attachTranscribePending":"Needs your choice","chat.transcribeGroup":"Audio transcription","chat.transcribeChecking":"Checking length","chat.transcribeConfirmTitle":"Transcribe {name}?","chat.transcribePlanSummary":"{duration} \xb7 transcription calls: about {calls}","chat.transcribeDurationUnknown":"Length unknown","chat.transcribeUsageNotice":"Transcription counts toward the connected account's usage. Nothing is sent until you start.","chat.transcribeStart":"Start transcription","chat.transcribeSkip":"Don't transcribe","chat.transcribeCancel":"Cancel transcription","chat.transcribeRunning":"Transcribing {name}","chat.transcribeRetry":"Try again","chat.transcribeAction":"Transcribe","chat.transcribeSkipped":"{name} has no transcript; only the saved file path is sent.","chat.transcribeFailedRow":"{name}: transcription failed. {error}","chat.transcribeToolMissing":"The audio tool (ffmpeg) is not available, so this audio cannot be prepared for transcription.","chat.transcribePartialFailed":"Stopped after {done} of {total} parts; no partial transcript is attached.","chat.transcribeTooLong":"The transcript does not fit beside the other attachments.","chat.attachmentSettingsNav":"Attachments","chat.attachmentSettingsTitle":"Attachments","chat.attachmentSettingsDescription":"Files you attach in chat are saved on this computer so the agent can open them.","chat.attachmentSettingsLoadFailed":"Could not load attachment settings","chat.attachmentUploadLimit":"Upload limit per file (MB)","chat.attachmentUploadLimitHelp":"Larger files are refused before they are sent. Text read straight into the message keeps its own limits: 8 MB per document and 240,000 characters in total.","chat.attachmentUploadLimitInvalid":"Enter a whole number of MB, 1 or more.","chat.attachmentAutoCleanup":"Delete unused attachments automatically","chat.attachmentAutoCleanupHelp":"Attachments used by a conversation, a branch, or an unsent draft are kept. A file is deleted {days} days after it is confirmed unused everywhere; a file whose use cannot be confirmed is kept.","chat.attachmentSettingsSaved":"Saved","characterMode.nav":"Characters","characterMode.title":"Characters","characterMode.description":"Choose the faces, names, stickers and completion voices you see on screen.","characterMode.label":"Character set","characterMode.default":"Default","characterMode.office":"Office mode","characterMode.help":"Applies to this whole PC server. In office mode, the character set in this PC's profile takes the openai-codex seat. The other seats stay as they are.","characterMode.noRoster":"This PC has no office character set, so the default characters stay in use.","characterMode.saved":"Saved","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","roles.harnessNote":"CUELO Maker slots are listed even before you assign them. Pick your own model only for the slots you use; saving does not sign in or test the model.","roles.harnessUnset":"not set","roles.harness.implSonnet":"Maker \xb7 NORMAL non-UI (first choice)","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL fallback","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD code","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD code fallback","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.currentReasoning":"Current reasoning level: {level}","chat.fastModeActive":"Fast on \xb7 applied to this model. Priority service may cost more or use more quota. Click to turn off","chat.fastModeInactive":"Fast requested \xb7 not applied for this model or account. Click to turn off","chat.fastModeOff":"Fast off \xb7 click to request priority service (may cost more or use more quota, depending on the provider)","chat.fastModeUnknown":"Fast state not checked yet \xb7 click to read this session's actual state and change it","chat.fastModeBusy":"Changing Fast","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.liveVoiceSettingsNav":"Call voice","chat.liveVoiceSettingsTitle":"Call voice","chat.liveVoiceSettingsDescription":"Choose the Codex voice that speaks in live and interpreter calls. The choice applies from the next call.","chat.liveVoiceSpeakerGroup":"Voice","chat.liveVoiceCodexLabel":"Codex voice","chat.liveVoiceCodexHelp":"Speaks in live calls and interpreter calls.","chat.liveVoiceLoadFailed":"Could not load voice settings","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.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":"The run stopped before it finished, for example when the server or PC went down. If it does not resume automatically, send a message to continue.","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","toolImage.dialogLabel":"Enlarged image","toolImage.requestEdit":"Request changes to this screen","toolImage.requestEditHint":"Attach this image to the message box. Describe the change, then send.","toolImage.noComposer":"There is no message box to attach to. Open a conversation, then press Request changes to this screen.","toolImage.loadFailed":"Couldn't load the image. Press Request changes to this screen again.","toolImage.markHint":"Drag over the part to change","toolImage.markLimit":"You can mark up to {count} areas","toolImage.clearMarks":"Clear marks","toolImage.regionLabel":"Area {n}","toolImage.locatorIntro":"The parts to change are marked with red boxes on the attached screen (areas {range}). A close-up of each area follows.","toolImage.locatorRegion":"Area {n}: x={x}, y={y}, width {w}, height {h} (original {width}\xd7{height} pixels)","files.pickElement":"Pick element","files.pickElementHint":"Click the element to change in the preview","files.pickedElement":"Picked element","files.requestElementEdit":"Request changes to this element","files.clearPick":"Clear selection","files.pickLocatorElement":"Element: {selector}","files.pickLocatorText":'Text: "{text}"',"files.pickLocatorPosition":"Position: x={x}, y={y}, width {w}, height {h} ({vw}\xd7{vh} preview)","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","models.navGroupRoles":"Role assignments","models.navGroupAccounts":"Connected accounts","models.navGroupCustom":"Custom providers","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.reloadSessionHint":"Reloads settings and skills for the open session. It does not unload plugins; restart CUELO for that.","i18n.reloading":"Reloading...","i18n.packageRemoved":"Package removed.","i18n.packageInstalled":"Package installed.","i18n.packageUpdated":"Package updated.","i18n.packageDisabled":"Package disabled.","i18n.packageDisabledRestartRequired":"Disabled setting saved. The plugin already loaded keeps running until CUELO restarts; reloading the session does not unload it.","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.showOriginalReply":"Show English original","i18n.hideOriginalReply":"Hide English original","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","usage.title":"Usage","usage.reorder":"Reorder","usage.reorderDone":"Done","usage.reorderGroup":"Account display order","usage.moveUp":"Move {account} up","usage.moveDown":"Move {account} down","usage.moved":"{account} moved to position {position}","usage.authExpired":"sign-in expired","usage.authUnavailable":"unavailable","usage.relogin":"Sign in again","usage.reloginFor":"Sign in again as {account}","usage.authIssues":"Account issues: {count}","relogin.title":"Account to sign in again","relogin.guide":"Press {action} and finish in the browser with this account. Signing in with a different account leaves this one failing.","relogin.done":"Sign-in finished.","relogin.checking":"Re-reading usage to check {account}…","relogin.recovered":"{account} is signed in again.","relogin.stillFailing":"Sign-in finished, but {account} still reports an auth error. You may have signed in with a different account.","relogin.unknown":"Could not find {account} in usage, so recovery is not confirmed.","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.mixedPairingNote":"Mixed configuration: which model and reasoning effort each request used, and in what order, could not be determined. These runs cannot be assumed to share the same conditions.","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.toolFailedValue":"failed {value}","efficiency.toolNoMatchValue":"no match {value}","efficiency.toolCancelledValue":"cancelled {value}","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","efficiency.harness":"Harness","efficiency.harnessValue":"Harness {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"All harnesses","efficiency.groupByHarness":"Split by harness","efficiency.harnessNote":"Harness is the CUELO version installed when the run started. It comes only from this PC's update records; runs without a record, or in a span changed outside the records, are unknown.","efficiency.sawSection":"What the model saw","efficiency.sawApproxNote":"Approximate, rebuilt from the session log. The system prompt sent with each request and context-hook rewrites are not recorded.","efficiency.sawOpen":"Show requests","efficiency.sawLoading":"Loading requests…","efficiency.sawError":"Could not load requests.","efficiency.sawEmpty":"No model requests are recorded for this run.","efficiency.sawFilterEmpty":"No requests with injections.","efficiency.sawRole":"Transcript","efficiency.sawSummary":"{turns} requests \xb7 {injections} injected \xb7 {tools} tool calls \xb7 {failed} failed","efficiency.sawOnlyInjected":"Only requests with injections","efficiency.sawTurnLabel":"Request {index}","efficiency.sawBefore":"Arrived before this request","efficiency.sawTrailing":"Arrived after the last request (not part of any model request in this run)","efficiency.sawShowFull":"Show full text","efficiency.sawShowArgs":"Show arguments","efficiency.sawShowResult":"Show result","efficiency.sawHideFull":"Collapse","efficiency.sawTruncated":"Showing the first {value} characters.","efficiency.sawMore":"Load {value} more","efficiency.sawShown":"Showing {shown} of {total}","efficiency.sawHiddenFromChat":"Hidden in chat","efficiency.sawNotSent":"Not sent to the model","efficiency.sawSecretsMasked":"Strings that look like secrets are replaced with [REDACTED].","efficiency.sawKindInjection":"Injected","efficiency.sawKindDeveloper":"Developer message","efficiency.sawKindUser":"User message","efficiency.sawKindCompaction":"Compaction","efficiency.sawKindModel":"Model change","efficiency.sawKindEffort":"Effort change","efficiency.sawKindPrompt":"System prompt changed","efficiency.sawKindRules":"Rules injected","efficiency.sawKindMemory":"Memory recall","efficiency.sawCompactionValue":"{before} → {after} tokens","efficiency.sawMemoryIds":"{value} memories recalled (text not recorded)","efficiency.sawToolOk":"OK","efficiency.sawToolFailed":"Failed","efficiency.sawToolNoMatch":"No match","efficiency.sawToolCancelled":"Cancelled","efficiency.sawToolMissing":"No result","efficiency.sawResultChars":"result {value} chars","efficiency.sawUsage":"in {input} \xb7 out {output} \xb7 cache read {cacheRead}","efficiency.sawStop":"stop: {value}","efficiency.sawToolsChanged":"Tool list changed: +{added} −{removed}","efficiency.sawPreludeTitle":"System prompt and tools","efficiency.sawPreludeRecorded":"Recorded","efficiency.sawPreludeTools":"{value} tools active in the last request (recorded)","efficiency.sawPreludeDigest":"System prompt fingerprint: {value}","efficiency.sawPreludeDigestNone":"No system prompt fingerprint is recorded for this run.","efficiency.sawPreludeMemory":"Memory recall block (part of the system prompt, recorded)","efficiency.sawPreludeReconstruct":"Rebuild from current settings","efficiency.sawPreludeLoading":"Rebuilding…","efficiency.sawPreludeApprox":"Rebuilt now from the current configuration, not as sent.","efficiency.sawPreludeNotLoaded":"This session is not loaded right now, so it cannot be rebuilt. The system prompt text is not recorded.","efficiency.sawPreludeMatch":"The current prompt's fingerprint matches this run's record.","efficiency.sawPreludeMismatch":"The current prompt's fingerprint differs from this run's record; it may have changed since.","toolRun.running":"Running","toolRun.failed":"Failed","toolRun.exitCode":"exit {code}","toolRun.diffStats":"{added} lines added, {removed} lines removed","panel.expand":"Widen panel","panel.restore":"Restore size","panel.more":"More","panel.liveSync":"Live updates","panel.subagentsCount":"{count} records","panel.refresh":"Refresh records","panel.close":"Close panel","makerDetail.region":"{title} record","makerDetail.noFiles":"This Maker changed no files","makerDetail.noChecks":"No checks were run","makerDetail.archiveUnobserved":"The record holds no tool results, so this cannot be confirmed","makerDetail.unavailable":"No run record matches this attempt exactly, so its detail cannot be opened","makerDetail.checkPassed":"passed","makerDetail.checkUnverified":"verdict not confirmed","makerDetail.checkFailed":"failed","makerDetail.checkUnobserved":"result not observed","dispatchLane.label":"Maker attempts","dispatchLane.runPhase":"{run} ({phase})","dispatchLane.checks":"checks {passed}/{total}","dispatchLane.checksUnobserved":"checks not observed","dispatchLane.checksLoading":"reading checks","dispatchLane.attempt":"attempt {attempt}","dispatchLane.attemptUnknown":"attempt","dispatchLane.verdict.accepted":"accepted","dispatchLane.verdict.rework":"rework","dispatchLane.verdict.held":"held","dispatchLane.open":"Details","dispatchLane.openLabel":"Open details for {title}","dispatchLane.unavailable":"No detail"}}),l({id:"zh-CN",label:"简体中文",messages:{"cloudProjects.launch":"打开 GitHub 仓库","cloudProjects.title":"云端项目","cloudProjects.description":"将 GitHub 仓库导入此服务器并继续工作。","cloudProjects.github":"GitHub 仓库","cloudProjects.serverFolder":"打开服务器文件夹","cloudProjects.account":"GitHub 连接","cloudProjects.connectTitle":"连接你的 GitHub 仓库","cloudProjects.connectHelp":"登录后也可以从列表中选择私有仓库。","cloudProjects.connected":"已连接 GitHub","cloudProjects.refresh":"重新检查","cloudProjects.waiting":"等待登录","cloudProjects.connect":"连接 GitHub","cloudProjects.deviceHelp":"在 GitHub 登录页面输入以下代码。","cloudProjects.copyCode":"复制代码","cloudProjects.copied":"已复制","cloudProjects.copyFailure":"无法复制代码。请选择并手动复制。","cloudProjects.openLogin":"在 GitHub 上登录","cloudProjects.permissionHelp":"请在 GitHub 上确认账号和请求的权限后再授权。令牌仅保存在服务器上。","cloudProjects.preparingCode":"正在准备登录代码。","cloudProjects.repositories":"你的仓库","cloudProjects.search":"搜索仓库","cloudProjects.searchPlaceholder":"按名称或描述搜索","cloudProjects.loading":"正在加载仓库。","cloudProjects.private":"私有","cloudProjects.public":"公开","cloudProjects.empty":"没有匹配的仓库。请尝试其他名称或输入 URL。","cloudProjects.more":"显示更多","cloudProjects.urlLabel":"选中的仓库或 GitHub URL","cloudProjects.publicHelp":"公开仓库无需登录即可导入。已存在的工作区会直接打开,不修改文件。","cloudProjects.error":"操作未能完成。","cloudProjects.openingHelp":"正在将仓库导入服务器。大型仓库可能需要一些时间。","cloudProjects.opening":"正在打开项目","cloudProjects.open":"打开项目","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":"没有打开的文件","files.docs.noProject":"选择项目后可查看其文档。","files.docs.loading":"正在查找项目文档…","files.docs.projectDenied":"此项目文件夹不在 CUELO 可读取的文件夹范围内。","files.docs.loadFailed":"无法加载项目文档:{error}","files.docs.projectDir":"项目文件夹:{path}","files.docs.noneFound":"直到仓库根目录都没有 HANDOFF.md,此文件夹中也没有 doc/README.md 或 doc/history。","files.docs.current":"当前状态","files.docs.map":"文档地图","files.docs.records":"最近记录","files.docs.missing":"未找到 {file}","files.docs.denied":"{file} 不在可读取的文件夹范围内","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":"清空列表","navigator.resultsToCheck":"待查看","navigator.resultsToCheckCount":"待查看 {count}","navigator.resultsToCheckHint":"自你在此浏览器上次打开后又有新进展且已结束的对话","navigator.resultsToCheckEmpty":"没有待查看的结果。","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.emptyProjectLabel":"工作文件夹","chat.emptyProjectHint":"发送第一条消息后,将在此文件夹中开始新会话。","chat.openSessionList":"打开会话列表","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.attachStoredTooLarge":"{name} 超出每个文件 {limit} 的限制。","chat.attachUploadFailed":"无法保存 {name}:{error}","chat.attachTranscribePending":"需要选择","chat.transcribeGroup":"音频转写","chat.transcribeChecking":"正在检查时长","chat.transcribeConfirmTitle":"要转写 {name} 吗?","chat.transcribePlanSummary":"{duration} \xb7 约 {calls} 次转写调用","chat.transcribeDurationUnknown":"时长未知","chat.transcribeUsageNotice":"转写会计入已连接账户的用量。点击开始之前不会发送任何内容。","chat.transcribeStart":"开始转写","chat.transcribeSkip":"不转写","chat.transcribeCancel":"取消转写","chat.transcribeRunning":"正在转写 {name}","chat.transcribeRetry":"重试","chat.transcribeAction":"转写","chat.transcribeSkipped":"{name} 没有转写,只发送已保存的文件路径。","chat.transcribeFailedRow":"{name} 转写失败:{error}","chat.transcribeToolMissing":"音频工具(ffmpeg)不可用,无法为转写准备此音频。","chat.transcribePartialFailed":"在 {total} 段中的第 {done} 段后停止;未附加部分转写。","chat.transcribeTooLong":"转写内容与其他附件合计超出字数限制。","chat.attachmentSettingsNav":"附件","chat.attachmentSettingsTitle":"附件","chat.attachmentSettingsDescription":"在聊天中附加的文件会保存在这台电脑上,供代理打开。","chat.attachmentSettingsLoadFailed":"无法加载附件设置","chat.attachmentUploadLimit":"每个文件的上传上限(MB)","chat.attachmentUploadLimitHelp":"超过上限的文件会在发送前被拒绝。直接读入消息的文本仍有单独限制:每个文档 8 MB,总计 240,000 个字符。","chat.attachmentUploadLimitInvalid":"请输入不小于 1 的整数(MB)。","chat.attachmentAutoCleanup":"自动删除未使用的附件","chat.attachmentAutoCleanupHelp":"对话、分支或未发送草稿中使用的附件会保留。确认在任何地方都不再使用后,{days} 天后删除;无法确认是否使用的文件会保留。","chat.attachmentSettingsSaved":"已保存","characterMode.nav":"角色","characterMode.title":"角色","characterMode.description":"选择屏幕上显示的头像、名称、贴纸和完成语音。","characterMode.label":"角色集","characterMode.default":"默认","characterMode.office":"办公室模式","characterMode.help":"适用于这台电脑的整个服务器。办公室模式下,这台电脑配置中的角色集会替换 openai-codex 席位,其余席位保持不变。","characterMode.noRoster":"这台电脑没有办公室角色集,因此继续使用默认角色。","characterMode.saved":"已保存","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":"使用配置的默认推理级别","roles.harnessNote":"CUELO Maker 角色在分配之前也会列出。只为要用的角色自行选择模型;保存不会登录或试调用模型。","roles.harnessUnset":"未设置","roles.harness.implSonnet":"Maker \xb7 NORMAL 非 UI(优先)","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL 备选","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD 代码","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD 代码备选","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.currentReasoning":"当前推理级别:{level}","chat.fastModeActive":"Fast 已开启 \xb7 正在应用于此模型。优先处理可能产生更多费用或用量。点击关闭","chat.fastModeInactive":"已请求 Fast \xb7 此模型或账户未应用。点击关闭","chat.fastModeOff":"Fast 已关闭 \xb7 点击请求优先处理(视提供商可能产生更多费用或用量)","chat.fastModeUnknown":"尚未确认 Fast 状态 \xb7 点击读取此会话的实际状态并切换","chat.fastModeBusy":"正在切换 Fast","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.liveVoiceSettingsNav":"通话语音","chat.liveVoiceSettingsTitle":"通话语音","chat.liveVoiceSettingsDescription":"选择实时通话和口译通话中使用的 Codex 语音。该选择从下一次通话开始生效。","chat.liveVoiceSpeakerGroup":"语音","chat.liveVoiceCodexLabel":"Codex 语音","chat.liveVoiceCodexHelp":"实时通话和口译通话都使用这个语音。","chat.liveVoiceLoadFailed":"无法加载语音设置","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.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":"放大","toolImage.dialogLabel":"放大的图片","toolImage.requestEdit":"请求修改此画面","toolImage.requestEditHint":"把这张图片附加到输入框。写下要改的地方后再发送。","toolImage.noComposer":"没有可附加的输入框。请先打开对话,再点击“请求修改此画面”。","toolImage.loadFailed":"无法获取图片。请再次点击“请求修改此画面”。","toolImage.markHint":"拖动框出要修改的地方","toolImage.markLimit":"最多可标记 {count} 个区域","toolImage.clearMarks":"清除标记","toolImage.regionLabel":"区域 {n}","toolImage.locatorIntro":"已在附加的画面上用红框标出要修改的地方(区域 {range})。后面依次附上各区域的放大图。","toolImage.locatorRegion":"区域 {n}:x={x}, y={y}, 宽 {w}, 高 {h}(以原图 {width}\xd7{height} 像素为准)","files.pickElement":"指定元素","files.pickElementHint":"在预览中点击要修改的元素","files.pickedElement":"已指定的元素","files.requestElementEdit":"请求修改此元素","files.clearPick":"取消指定","files.pickLocatorElement":"元素:{selector}","files.pickLocatorText":"文本:“{text}”","files.pickLocatorPosition":"画面位置:x={x}, y={y}, 宽 {w}, 高 {h}(以预览 {vw}\xd7{vh} 为准)","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":"撤销","models.navGroupRoles":"角色分配","models.navGroupAccounts":"已连接账户","models.navGroupCustom":"自定义提供商","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.reloadSessionHint":"重新加载当前会话的设置和技能。不会卸载插件;如需卸载,请重启 CUELO。","i18n.reloading":"重新加载中...","i18n.packageRemoved":"包已移除。","i18n.packageInstalled":"包已安装。","i18n.packageUpdated":"包已更新。","i18n.packageDisabled":"包已禁用。","i18n.packageDisabledRestartRequired":"已保存禁用设置。已加载的插件会继续运行,直到 CUELO 重启;重新加载会话无法卸载它。","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.showOriginalReply":"查看英文原文","i18n.hideOriginalReply":"收起英文原文","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":"未测量","usage.title":"用量","usage.reorder":"调整顺序","usage.reorderDone":"完成","usage.reorderGroup":"账户显示顺序","usage.moveUp":"上移 {account}","usage.moveDown":"下移 {account}","usage.moved":"{account} 已移到第 {position} 位","usage.authExpired":"登录已过期","usage.authUnavailable":"不可用","usage.relogin":"重新登录","usage.reloginFor":"重新登录 {account}","usage.authIssues":"账户异常 {count}","relogin.title":"需要重新登录的账户","relogin.guide":"点击「{action}」后,请在浏览器中用此账户完成登录。用其他账户登录时,此账户仍保持错误。","relogin.done":"登录已完成。","relogin.checking":"正在重新读取用量以确认 {account}…","relogin.recovered":"{account} 已重新登录。","relogin.stillFailing":"登录已完成,但 {account} 仍报告认证错误。可能登录了其他账户。","relogin.unknown":"用量中找不到 {account},无法确认是否恢复。","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.mixedPairingNote":"混合配置:无法确认每个请求使用的模型与推理强度组合及其顺序。不能断定这些 run 处于相同条件。","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.toolFailedValue":"失败 {value}","efficiency.toolNoMatchValue":"无匹配 {value}","efficiency.toolCancelledValue":"中断 {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","efficiency.harness":"Harness","efficiency.harnessValue":"Harness {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"全部 harness","efficiency.groupByHarness":"按 harness 拆分","efficiency.harnessNote":"Harness 指 run 开始时已安装的 CUELO 版本,只根据本机的更新记录确定;没有记录或在记录之外变更的区间显示为 unknown。","efficiency.sawSection":"模型看到的内容","efficiency.sawApproxNote":"根据会话记录重建的近似视图。每次请求发送的系统提示词和上下文钩子的改写都没有记录。","efficiency.sawOpen":"按请求查看","efficiency.sawLoading":"正在读取请求…","efficiency.sawError":"无法读取请求记录。","efficiency.sawEmpty":"此运行没有模型请求记录。","efficiency.sawFilterEmpty":"没有包含注入的请求。","efficiency.sawRole":"记录","efficiency.sawSummary":"请求 {turns} 次 \xb7 注入 {injections} 条 \xb7 工具 {tools} 次 \xb7 失败 {failed} 次","efficiency.sawOnlyInjected":"仅含注入的请求","efficiency.sawTurnLabel":"请求 {index}","efficiency.sawBefore":"此请求之前到达","efficiency.sawTrailing":"最后一次请求之后到达(未进入本次运行的任何模型请求)","efficiency.sawShowFull":"查看全文","efficiency.sawShowArgs":"查看参数","efficiency.sawShowResult":"查看结果","efficiency.sawHideFull":"收起","efficiency.sawTruncated":"仅显示前 {value} 个字符。","efficiency.sawMore":"再加载 {value} 个","efficiency.sawShown":"已显示 {shown}/{total}","efficiency.sawHiddenFromChat":"聊天中不显示","efficiency.sawNotSent":"未发送给模型","efficiency.sawSecretsMasked":"疑似密钥的字符串已替换为 [REDACTED]。","efficiency.sawKindInjection":"注入","efficiency.sawKindDeveloper":"开发者消息","efficiency.sawKindUser":"用户消息","efficiency.sawKindCompaction":"压缩","efficiency.sawKindModel":"模型切换","efficiency.sawKindEffort":"推理强度变更","efficiency.sawKindPrompt":"系统提示词已变更","efficiency.sawKindRules":"注入规则","efficiency.sawKindMemory":"记忆召回","efficiency.sawCompactionValue":"{before} → {after} tokens","efficiency.sawMemoryIds":"召回 {value} 条记忆(正文未记录)","efficiency.sawToolOk":"成功","efficiency.sawToolFailed":"失败","efficiency.sawToolNoMatch":"无匹配","efficiency.sawToolCancelled":"中断","efficiency.sawToolMissing":"无结果","efficiency.sawResultChars":"结果 {value} 字符","efficiency.sawUsage":"输入 {input} \xb7 输出 {output} \xb7 缓存读取 {cacheRead}","efficiency.sawStop":"结束:{value}","efficiency.sawToolsChanged":"工具列表变化:+{added} −{removed}","efficiency.sawPreludeTitle":"系统提示词与工具","efficiency.sawPreludeRecorded":"已记录","efficiency.sawPreludeTools":"最后一次请求启用的工具 {value} 个(已记录)","efficiency.sawPreludeDigest":"系统提示词指纹:{value}","efficiency.sawPreludeDigestNone":"没有此运行时的系统提示词指纹记录。","efficiency.sawPreludeMemory":"记忆召回块(系统提示词的一部分,已记录)","efficiency.sawPreludeReconstruct":"按当前设置重建","efficiency.sawPreludeLoading":"正在重建…","efficiency.sawPreludeApprox":"依据当前配置重建,并非实际发送的内容。","efficiency.sawPreludeNotLoaded":"此会话当前未加载,无法重建。系统提示词正文没有记录。","efficiency.sawPreludeMatch":"当前提示词指纹与此运行的记录一致。","efficiency.sawPreludeMismatch":"当前提示词指纹与此运行的记录不同,之后可能已变更。","toolRun.running":"运行中","toolRun.failed":"失败","toolRun.exitCode":"exit {code}","toolRun.diffStats":"新增 {added} 行,删除 {removed} 行","panel.expand":"加宽面板","panel.restore":"恢复原大小","panel.more":"更多","panel.liveSync":"实时同步","panel.subagentsCount":"{count} 条记录","panel.refresh":"刷新记录","panel.close":"关闭面板","makerDetail.region":"{title} 记录","makerDetail.noFiles":"此 Maker 未修改任何文件","makerDetail.noChecks":"未运行检查","makerDetail.archiveUnobserved":"记录中没有工具结果,无法确认","makerDetail.unavailable":"没有与此次尝试完全对应的运行记录,无法打开详情","makerDetail.checkPassed":"通过","makerDetail.checkUnverified":"判定未确认","makerDetail.checkFailed":"失败","makerDetail.checkUnobserved":"结果未观测","dispatchLane.label":"Maker 尝试","dispatchLane.runPhase":"{run}({phase})","dispatchLane.checks":"检查 {passed}/{total}","dispatchLane.checksUnobserved":"检查未观测","dispatchLane.checksLoading":"正在读取检查","dispatchLane.attempt":"尝试 {attempt}","dispatchLane.attemptUnknown":"尝试","dispatchLane.verdict.accepted":"已接受","dispatchLane.verdict.rework":"返工","dispatchLane.verdict.held":"搁置","dispatchLane.open":"详情","dispatchLane.openLabel":"查看 {title} 详情","dispatchLane.unavailable":"无详情"}}),l({id:"ko",label:"한국어",messages:a});var d=n(2730);let u="pi-locale",p=(0,i.createContext)(null);function h({children:e}){let[t,n]=(0,i.useState)("en"),[a,l]=(0,i.useState)(!1),f=(0,i.useMemo)(()=>c().map(e=>o.get(e)).filter(e=>!!e),[]),m=(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)&&s.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 g=(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,m,n),[t,m]),v=(0,i.useMemo)(()=>({locale:a?t:"en",setLocale:g,t:x,supportedLocales:f}),[a,t,g,x,f]);return(0,r.jsx)(p.Provider,{value:v,children:e})}function f(){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,[4697,7935,6072,7330,2545,3459,8441,3794,7358],()=>e(e.s=80455)),_N_E=e.O()}]);
74
+ ${x}`:""}`,"aria-label":`${S} ${v}, 업무 ${p.title}${f?`, 현재 단계 ${f}`:""}${g?`, ${g}`:""}${x?`, ${x}`:""}, ${d?d.status:u?.status??"미확인"}, 모델 ${w.model??"미확인"}, 추론 ${j}`,"aria-describedby":m&&d?c:void 0,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"===b.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":b.agent,title:`${b.agent} \xb7 ${fd[b.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),b.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:p.title})]}),d?(0,r.jsx)("span",{style:{color:fl(d),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:d.status}):u?(0,r.jsx)("span",{style:{color:"failed"===u.status?"var(--danger)":"aborted"===u.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:u.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),f&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${f}`,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 ",f]}),m?.phase&&(0,r.jsxs)("span",{className:"subagent-phase-line",style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[(0,r.jsx)(sG,{phase:m.phase}),x&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle)"},title:x,children:` \xb7 ${x}`})]}),m&&d&&(0,r.jsx)("span",{className:"subagent-eta-line",style:{gridColumn:"1 / -1",minWidth:0,color:"var(--seed-color-fg-neutral)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)(sQ,{snapshot:d,view:m,id:c})}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":w.model?w.effort?"both":"model":w.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[k,w.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",j]})]}),(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:v}),(0,r.jsx)("span",{children:y})]}),(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:[d?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",d.progress.toolCount]}),(0,r.jsxs)("span",{children:[d.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}분`}(d.progress.durationMs)})]}),u&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===u.messages?"메시지 수 미확인":`메시지 ${u.messages}`}),(0,r.jsxs)("span",{children:[(u.bytes/1024).toFixed(+(u.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)}일 전`}(u.modified)})]})]})]})})}function fv({title:e,sessionId:t,sessionPath:n,sessionCwd:a,liveSubagents:s,client:o,visible:l=!0,onClose:c,onReturnFocus:d,selection:u,onSelectionChange:p,onReturnToOrigin:h,onOpenFile:f}){let{t:m}=(0,F.s)(),g=(0,i.useMemo)(()=>o??ih(),[o]),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)({kind:"loading"}),[w,k]=(0,i.useState)({kind:"loading"}),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(null),I=p?u??null:C,T=p??N,[M,R]=(0,i.useState)(0),E=(0,i.useRef)(null),$=(0,i.useRef)(null);(0,i.useEffect)(()=>{v([]),b({kind:"loading"}),k({kind:"loading"}),S(!1),N(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,a]=await Promise.allSettled([g.getLiveSnapshots(t,r.signal),g.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===i.status)v(i.value.subagents),b(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=sj(i.reason);b("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===a.status)S(!0===a.value.listTruncated),k(a.value.subagents.length>0?{kind:"ready",data:a.value.subagents}:{kind:"empty",data:[]});else{let e=sj(a.reason);k("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};i();let a=setInterval(()=>void i(),3e3),s=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",s),()=>{e=!0,r?.abort(),clearInterval(a),document.removeEventListener("visibilitychange",s)}},[M,g,t,l]);let L=(0,i.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let i of[...e,...t]){let e=n.get(i.id);if(!e){r.push(i.id),n.set(i.id,i);continue}let[t,a]=fu(i)>=fu(e)?[i,e]:[e,i];n.set(i.id,{...t,assignment:t.assignment??a.assignment,description:t.description??a.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(s,x),[s,x]),P="ready"===w.kind||"empty"===w.kind?w.data:[],A=(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})(L,P),[P,L]),z=I?A.find(e=>e.key===I.key)??null:null,W=z&&I?.toolCallId&&z.live?.parentToolCallId!==I.toolCallId?null:z,D=sq({sessionId:t,snapshots:L,client:g,enabled:l&&!I,cwd:a??void 0});if((0,i.useEffect)(()=>{let e=$.current;if(I||!e)return;$.current=null;let t=[...E.current?.querySelectorAll("[data-subagent-key]")??[]].find(t=>t.dataset.subagentKey===e);t?.focus({preventScroll:!1})}),I&&t)return(0,r.jsx)(fg,{sessionId:t,sessionCwd:a,record:W,selection:I,client:g,visible:l,onOpenFile:f,onBack:()=>{T(null),I.origin&&h?h(I.origin):$.current=I.key}});let O=0===A.length&&"loading"===y.kind&&"loading"===w.kind,H=0===A.length&&("empty"===y.kind||0===s.length)&&"empty"===w.kind;return(0,r.jsxs)("section",{ref:E,"aria-label":"Subagent 기록","data-state":O?"loading":H?"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.jsx)(uQ,{title:e,titleTooltip:n??void 0,subtitle:O||!t?void 0:m("panel.subagentsCount",{count:A.length}),actions:[{id:"refresh",label:m("panel.refresh"),icon:fp,onClick:()=>R(e=>e+1)}],close:c?{label:m("panel.close"),onClick:()=>{c?.(),d?.()}}:void 0}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?O?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):H?(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:A.map(e=>(0,r.jsx)(fx,{record:e,view:e.live?D.get(e.live.id):void 0,onSelect:()=>T({key:e.key})},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!O&&"loading"===y.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!O&&"loading"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===y.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:y.message}),"error"===y.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:y.message}),"unreachable"===w.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:w.message}),"error"===w.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:w.message}),j&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let fy=new Set(["efficiency","sidechat","resource"]),fb=["process","efficiency","subagents","files","resource","sidechat"];function fw({activeView:e,onViewChange:t,viewLabels:n,sessionId:i,sessionPath:a,sessionName:l,sessionCwd:c,liveSubagents:d,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:f,resourceSlot:m,efficiencySlot:g,visible:x=!0,onClose:v,onReturnFocus:y,expand:b=null,selectedMaker:w,onSelectMaker:k,onReturnToDispatch:j,onOpenFile:S,fileOpen:C=!1}){return(0,r.jsx)(uK.Provider,{value:b,children:(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":e,"data-expanded":b?.expanded?"true":void 0,children:(0,r.jsxs)(fs.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)(fs.J.List,{"aria-label":"보조 패널 보기",children:[fb.map(e=>{let t="subagents"===e?d.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(fs.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)(nu.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,r.jsx)(fs.J.Indicator,{})]}),(fy.has(e)||"files"===e&&!C)&&(0,r.jsx)(u0,{className:"auxiliary-deck-expand"}),v&&(0,r.jsx)(s.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{v?.(),y?.()},"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)(fs.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(fs.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(fs.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(fv,{title:n.subagents,sessionId:i,sessionPath:a,sessionCwd:c,liveSubagents:d,client:u,visible:x&&"subagents"===e,selection:w,onSelectionChange:k,onReturnToOrigin:j,onOpenFile:S})}),(0,r.jsx)(fs.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,r.jsx)(fs.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:f}),(0,r.jsx)(fs.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:m})]})})})}function fk({title:e,data:t,onOpenFile:n}){let{t:a}=(0,F.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.jsx)(uQ,{title:`${o.length} ${a(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:a("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} ${a(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${a(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(s.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!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?a("chat.expandProcess"):a("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:d??a("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,a)=>{let s=t?.messages[i.idx];return s?(0,r.jsx)(o5,{message:i.blocks?eH(s,i.blocks,{omitUsage:!0}):s,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[i.idx],sessionId:t?.sessionId,showTimestamp:!1},`process-${e.anchorIdx}-${a}`):null})})]},`turn-${e.anchorIdx}-${i}`)})]})]})}let fj=6,fS="omp-btw-log:",fC="omp-btw-log-index";function fN(e){return e.trim().toLowerCase()}function fI(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function fT(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 fM(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function fR(e,t={}){let n=t.now??Date.now,r=new Map,i=new Set,a=!1,s=[],o=t=>{if(e)try{e.removeItem(t)}catch{}},l=e=>{r.delete(e),i.delete(e),o(fS+e)},c=()=>{let e=new Set,t=[];for(let n of(s.sort((e,t)=>t.updatedAt-e.updatedAt),s))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):l(n.id));s=t},d=()=>{if(!a){if(a=!0,e)try{let t=e.getItem(fC),n=t?JSON.parse(t):[];Array.isArray(n)&&(s=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:fN(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{s=[]}c()}},u=e=>{d();for(let t=s.length-1;t>=0;t-=1){if(s[t].id===e)continue;let[n]=s.splice(t,1);return l(n.id),!0}return!1},p=t=>{if(e){try{e.setItem(fC,JSON.stringify(s));return}catch(e){if(!fM(e)||!u(t))return}try{e.setItem(fC,JSON.stringify(s))}catch{}}},h=t=>{let n=fN(t);if(!n)return[];if(i.has(n))return fI(r.get(n)??[]);if(e)try{let t=e.getItem(fS+n);if(t){let e=JSON.parse(t),i=fT(e?.entries);return r.set(n,i),fI(i)}}catch{}return fI(r.get(n)??[])},f=e=>{let t=fN(e);t&&(d(),s=s.filter(e=>e.id!==t),l(t),p(null))};return{read:h,append:(t,a)=>((t,a)=>{let o=fN(t);if(!o)return[];let l=fT(a),h=n();if(r.set(o,fI(l)),d(),(s=s.filter(e=>e.id!==o)).unshift({id:o,updatedAt:h}),c(),p(o),!e)return fI(l);let f=JSON.stringify({updatedAt:h,entries:l});try{return e.setItem(fS+o,f),i.delete(o),fI(l)}catch(e){if(!fM(e)||!u(o))return i.add(o),fI(l)}p(o);try{e.setItem(fS+o,f),i.delete(o)}catch{i.add(o)}return fI(l)})(t,[...h(t),a]),history:(e,t=fj)=>h(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:f,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=fN(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);i.set(t,Number.isFinite(n)?n:0)}let a=r?fN(r):null,l=n();for(let e of[...s])if(e.id!==a){if(!i.has(e.id)){f(e.id);continue}l-Math.max(i.get(e.id)??0,e.updatedAt)>6048e5&&f(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(fS))continue;let r=fN(n.slice(fS.length));i.has(r)||r===a||c.push(n)}}catch{return}for(let e of c)o(e)}}}function fE(){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 f$ extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function fL(e){let t;try{t=JSON.parse(e)}catch{throw new f$("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new f$("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new f$("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class fP{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()?[fL(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[fL(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function fA(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 fF(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 fz({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 fW({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)(nc,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function fD({identity:e,status:t,utteranceKey:n,children:i}){let a=rZ(e?.sessionId,e?.provider,e?.credentialId),s=lH(a?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[a&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(r0,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:a.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[i,s&&(0,r.jsx)("img",{src:s.src,alt:s.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function fO({title:e,sessionId:t,sessionPath:n,sessionName:a,historyStore:s,flights:o,sessionCensus:l,client:c,visible:d=!0,onClose:u,onReturnFocus:p}){let h,f,m=(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(-fj)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new f$("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new f$("http",await fA(r),r.status);if(!r.body)throw new f$("stream","사이드채팅 스트림을 열 수 없습니다.");let i=r.body.getReader(),a=new fP,s="",o=null,l=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)s+=t.v;else if("done"===t.t)s=t.v||s;else if("m"===t.t)o=t.v;else throw new f$("server",t.v)};try{for(;;){let e=await i.read();if(e.done)break;l(a.push(e.value))}l(a.finish())}catch(e){if(n.signal?.aborted||e instanceof f$)throw e;throw new f$("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{i.releaseLock()}if(!s)throw new f$("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:s,model:o}}}}(),[c]),g=t?.toLowerCase()??null,[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)({}),w=g??"",k=y[w]??"",j=(e,t)=>{b(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,i.useState)(0),[N,I]=(0,i.useState)({}),[T,M]=(0,i.useState)({}),[R,E]=(0,i.useState)({}),[$,L]=(0,i.useState)(null),[P,A]=(0,i.useState)(null),[F,z]=(0,i.useState)({}),[W,D]=(0,i.useState)({}),[O,H]=(0,i.useState)({}),U=(0,i.useRef)((h=new Set,f=new Set,{claim:e=>!(!e||h.has(e)||f.has(e))&&(h.add(e),!0),markSent(e){h.delete(e),f.add(e)},release(e){h.delete(e)}})),_=(0,i.useRef)(!0),B=(0,i.useRef)(g),q=(0,i.useRef)(d),V=(0,i.useRef)(null),K=(0,i.useRef)(!1),G=(0,i.useRef)(0),J=(0,i.useRef)(null);B.current=g,q.current=d,(0,i.useEffect)(()=>(_.current=!0,()=>{_.current=!1}),[]),(0,i.useEffect)(()=>{v(g?s.read(g):[])},[s,g]);let Z=(0,i.useRef)(null);(0,i.useEffect)(()=>{L(null),Z.current=null},[g]),(0,i.useEffect)(()=>{if(!d||!g||Z.current===g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0;return{provider:t.provider,..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&(Z.current=g,L(t?{...t,sessionId:g}:null))}).catch(()=>{e&&(Z.current=g,L(null))}),()=>{e=!1}},[g,d]),(0,i.useEffect)(()=>{if(!g)return;let e=()=>{if(!_.current||B.current!==g)return;let e=o.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)I(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),b(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;E(e=>({...e,[g]:t}))}v(s.read(g))}else null===o.read(g)&&v(s.read(g));C(e=>e+1)},t=o.subscribe(g,e);return e(),t},[o,s,g]),(0,i.useEffect)(()=>{l&&s.cleanup(l,g)},[s,g,l]),(0,i.useEffect)(()=>{d&&V.current?.focus()},[d,g]),(0,i.useEffect)(()=>{if(!d)return;let e=requestAnimationFrame(()=>{let e=J.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,d]);let Y=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=o.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await m.ask({sessionPath:n,question:e,history:s.history(g),signal:r,onEvent:e=>o.ingest(g,e)});s.append(g,{q:e,a:t.text,at:Date.now()}),o.finish(g,{kind:"done",model:t.model})}catch(n){let t=o.read(g)?.text??"";if(r.aborted){let n=!1;t&&(s.append(g,{q:e,a:t,at:Date.now()}),n=!0),o.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof f$?n.kind:"unknown",i=n instanceof Error?n.message:String(n);o.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:i})}}finally{_.current&&q.current&&V.current?.focus()}},X=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(U.current.claim(r)){D(e=>({...e,[r]:"sending"})),H(e=>{let t={...e};return delete t[r],t});try{var i,a;let t,s=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),o=null;try{o=await s.json()}catch{}if(!s.ok){if(o&&"object"==typeof o&&"error"in o&&"string"==typeof o.error)throw Error(o.error);throw Error(`HTTP ${s.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,a=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",i,"","[사이드채팅 답변]",a,...t?["","[추가 지시]",t]:[]].join("\n"));await dB(g,{type:l?"steer":"prompt",message:c}),U.current.markSent(r),D(e=>({...e,[r]:"sent"}))}catch(e){U.current.release(r),D(e=>{let t={...e};return delete t[r],t}),H(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},Q=()=>{if(g&&null!==o.read(g))return void o.abort(g);let e=k.trim();e&&(j(w,""),Y(e))},ee=N[g??""]??[],et=T[g??""],en=g?o.read(g):null,er=x.length>0||ee.length>0||null!==en,ei=en?.model??R[g??""],ea=!g||!n,es=null!==en,eo=!es&&!ea&&k.trim().length>0,el=!g||es,ec=$?.sessionId===g?$:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==en,"data-state":g&&n?en?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[a||g?.slice(0,8)||"세션 없음",ei?` \xb7 ${ei}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===o.read(g)&&(s.clear(g),v([]),I(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:el,style:fF(el),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...fF(),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:J,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,i=`${g}:${n}`,a=W[i],s=P===i;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(fz,{children:e.q}),(0,r.jsx)(fD,{identity:ec,status:"settled",utteranceKey:n,children:(0,r.jsx)(fW,{children:e.a})}),"sent"===a?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!s&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>A(i),style:{...fF(),alignSelf:"flex-start"},children:"메인에 보내기"}),s&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value: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 X(e,n,F[i]??""),disabled:"sending"===a,style:fF("sending"===a),children:"sending"===a?"보내는 중…":"메인으로 전송"}),"sending"!==a&&(0,r.jsx)("button",{type:"button",onClick:()=>A(null),style:fF(),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)}),ee.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(fz,{children:e.question}),(0,r.jsxs)(fD,{identity:ec,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(fW,{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}`)),en&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(fz,{children:en.question}),(0,r.jsx)(fD,{identity:ec,status:"streaming",utteranceKey:`stream:${en.question}`,children:(0,r.jsx)(fW,{streaming:!0,children:en.text})})]}),!er&&(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",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),et&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:et})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),Q()},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,G.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-G.current<100;if(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}es||(e.preventDefault(),Q())},disabled:es||ea,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:ea?"세션 파일이 준비되면 질문할 수 있습니다.":es?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!es&&!eo,style:fF(!es&&!eo),children:es?"중단":"전송"})]})]})]})}let fH="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 fU(...e){return e.filter(Boolean).join(" ")}function f_(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),i=Math.floor(n%1440/60),a=n%60;return r>0?`${r}d ${i}h 후 리셋`:i>0?`${i}h ${a}m 후 리셋`:`${a}m 후 리셋`}function fB(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let i=Math.floor(r/1440),a=Math.floor(r%1440/60),s=r%60;return i>0?`${i}d ${a}h 후 만료`:a>0?`${a}h ${s}m 후 만료`:`${s}m 후 만료`}function fq(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 fV(e,t){return!1!==t?fq(e):"number"==typeof e&&Number.isFinite(e)&&0!==e?`≥${fq(e)}`:"가격 미상"}function fK(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function fG(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 fJ(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function fZ(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function fY(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function fX({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 fQ({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 f0(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 f1({limit:e,now:t,detailed:n}){let i="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,a=Math.max(0,Math.min(100,100*i)),s=Math.round(100*i),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),a=100*r,s=Math.max(0,100-a);if(!n.durationMs){let e=i/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?s/e:s}}let 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?s/u:s,pacePct:p,deltaPct:a-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=s>=90,h=o?.deltaPct!=null&&o.deltaPct>=.5?o.deltaPct:null,f=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:fU("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[s,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":s,children:[(0,r.jsx)("div",{className:fU("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${a}%`}}),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]}),f||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:f??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:f_(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)(fX,{label:"페이스",value:`${o.pacePct.toFixed(1)}%`}):null,o?(0,r.jsx)(fX,{label:o.partial?"남은 한도":`앞으로 ${o.unit}`,value:`${o.burn.toFixed(1)}%`}):null,o?.nominal!=null?(0,r.jsx)(fX,{label:"균등 배분 기준",value:`${o.nominal.toFixed(1)}%/${"하루"===o.unit?"일":"시간"} \xb7 계산값`}):null,l?(0,r.jsx)(fX,{label:"구간",value:`${f0(l.slotStart)} ~ ${f0(l.slotEnd)} \xb7 ${l.slotIndex+1}/${l.slotCount}`}):null,l?(0,r.jsx)(fX,{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 f2={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function f8({confirmId:e,pending:t,primaryRef:n,summary:i,onConfirm:a,onCancel:s}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),s())},children:[(0,r.jsxs)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:["저장된 리셋 ",i]}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:fU(fH,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:a,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:fH,disabled:t,onClick:s,children:"취소"})]})]})}function f4({report:e,brokerOk:t,now:n,active:a,identity:s,recommendation:o,pendingAction:l,feedback:c,onToggle:d,onReset:u}){let p=e.metadata??{},h=s??rw([e])[0],f=e.credentialId,m=Number.isSafeInteger(f)&&f>0,g=e.accountRole,x="usage-only"===g?"사용량":"control-only"===g?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,y=a?"active":e.disabled?"off":v?"auto-blocked":"idle",b="toggle"===l?"전환 중…":"reset"===l?"리셋 사용 중…":m?a?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${f_(e.autoBlockedUntilMs,n)}`:"control-only"===g?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===g?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,i.useId)(),k=(0,i.useId)(),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),M=(0,i.useRef)(null),R=(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,P=function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e),A=P?.id??null,F=fB(P?.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=>f2[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?f_(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=fB(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),H=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&L?.state==="available"&&0!==z&&null!=A;(0,i.useLayoutEffect)(()=>{if(I)return void R.current?.focus();if(E.current){var e;E.current=!1,e=M.current,e?.focus()}},[I]),(0,i.useEffect)(()=>{"reset"!==l&&(e.disabled||!t||L?.state!=="available")&&(E.current=!1,T(null))},[t,l,e.disabled,L?.state]);let U=async()=>{if(I&&!$.current){$.current=!0;try{await u(e,I.creditId)}finally{$.current=!1,E.current=!0,T(null)}}},_=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),B=l?"pending":a?"active":e.disabled?"off":v?"blocked":"idle";return(0,r.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":y,"aria-current":a?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(r0,{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:`${rb(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":B,role:l?"status":void 0,children:b}),null!=_&&_-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${f_(_,n).replace(/ 후 리셋$/,"")}`}):null]})]}),m?(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:fU(fH,"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,T(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(n2)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):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:()=>N(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(f1,{limit:e,now:n,detailed:j},e.id))]}),(e.limits??[]).length>0||h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":j,"aria-controls":k,onClick:()=>{let e=!j;S(e),e||N(!1)},children:j?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?I?(0,r.jsx)(f8,{confirmId:w,pending:"reset"===l,primaryRef:R,summary:I.summary,onConfirm:()=>{U()},onCancel:()=>{E.current=!0,T(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3 border-t border-border pt-2.5","data-reset-state":t?L&&"unavailable"!==L.state?"empty"===L.state||0===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:fU("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,H?(0,r.jsx)("button",{ref:M,type:"button",className:fU(fH,"ml-auto flex-none"),disabled:null!=l,onClick:()=>{A&&T({creditId:A,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 f5({state:e,loading:t,accountState:n,pendingActions:i,feedbackByCredential:a,onToggle:s,onReset:o}){let l=nd(1e4);rY();let c=e.data,d=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,u=rw(c?.reports??[]),p=null==d?-1:c?.reports.findIndex(e=>e.credentialId===d)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(fQ,{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)(f4,{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:a.get(d),onToggle:s,onReset:o},`${e.provider}:${d??e.metadata?.accountId??e.metadata?.email??t}`)})]})}function f6({model:e}){var t,n;let i=Math.max(1,Math.min(100,100*e.costShare)),a="unpriced"!==e.pricing&&"partial"!==e.pricing,s="unpriced"===e.pricing?fV(0,!1):`${fV(e.cost,a)} \xb7 ${fJ(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.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:s})]}),(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:`${i}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(fX,{label:"요청",value:fK(e.requests)}),(0,r.jsx)(fX,{label:"요청당",value:fV(e.costPerRequest,a)}),(0,r.jsx)(fX,{label:"토큰/요청",value:fG(e.tokensPerRequest)}),(0,r.jsx)(fX,{label:"출력/요청",value:fG(e.outputPerRequest)}),(0,r.jsx)(fX,{label:"캐시율",value:(t=e.cacheRate,"not-reported"===(n=e.cacheStatus)?"미보고":"unknown"===n?"알 수 없음":fJ(t,1))}),(0,r.jsx)(fX,{label:"TTFT",value:fZ(e.avgTtft)})]})]})}function f3({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:[fV(e.cost,e.costComplete)," \xb7 ",fJ(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)(fX,{label:"요청",value:fK(e.requests)}),(0,r.jsx)(fX,{label:"요청당",value:fV(e.costPerRequest,e.costComplete)}),(0,r.jsx)(fX,{label:"토큰/요청",value:fG(e.tokensPerRequest)})]})]})}function f7({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:fY(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:fV(e.cost,e.costComplete)})]})}function f9({state:e,loading:t}){let n=e.data,i=n?.overall.unpricedModels??0,a=n?.overall.cacheExcludedModels??0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(fQ,{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)(fX,{label:"요청",value:fK(n.overall.requests)}),(0,r.jsx)(fX,{label:"추정 비용",value:fV(n.overall.cost,n.overall.costComplete)}),(0,r.jsx)(fX,{label:"토큰",value:fG(n.overall.tokens)}),(0,r.jsx)(fX,{label:a>0?"캐시율(일부)":"캐시율",value:fJ(n.overall.cacheRate,1)}),(0,r.jsx)(fX,{label:i>0?"캐시 절감(일부)":"캐시 절감",value:fJ(n.overall.cacheSavings,1)}),(0,r.jsx)(fX,{label:"평균 TTFT",value:fZ(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)(f6,{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)(f3,{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)(f7,{day:e},e.timestamp))]}):null,(0,r.jsxs)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:["`omp stats` 기준 누적값입니다. 금액은 토큰 단가로 계산한 추정치이며 실제 청구액이나 구독 사용량이 아닙니다. 구독 한도 %는 계정 한도 탭에서 확인하세요.",i>0?` 가격을 다 매기지 못한 모델이 ${i}개 있어 추정 비용\xb7비중\xb7캐시 절감은 단가를 아는 사용량만 셉니다. ≥가 붙은 금액은 추정 비용의 최솟값입니다. 에이전트 종류별 집계는 모델을 나누지 않아 모든 행에 ≥를 붙입니다.`:null,a>0?` 캐시 사용량을 보고하지 않거나 보고 여부를 알 수 없는 모델 ${a}개는 캐시율 계산에서 뺐습니다.`:null]})]}):null]})}function me({reports:e,providerConnections:t}){return rY(),(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:re.map(n=>{let i=`character-roster-${n.seed}`,a=`character-roster-${n.seed}-status`,s=`${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:fU("character-roster-item",c&&"is-unavailable"),role:"listitem","aria-labelledby":i,"aria-describedby":c?a:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(r0,{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:a,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,r.jsx)("p",{children:n.voice})]})]}),(0,r.jsxs)("dl",{className:"character-roster-model",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"모델"}),(0,r.jsx)("dd",{title:s,children:s})]}),void 0!==n.oauthPosition?(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"계정"}),(0,r.jsxs)("dd",{children:["OAuth ",n.oauthPosition]})]}):null]}),(0,r.jsxs)("dl",{className:"character-roster-examples",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"호출"}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("code",{children:n.summonExample}),(0,r.jsx)("span",{children:n.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"Main 교체"}),(0,r.jsxs)("dd",{children:[n.switchExample?(0,r.jsx)("code",{children:n.switchExample}):(0,r.jsx)("strong",{children:"교체 불가"}),(0,r.jsx)("span",{children:n.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},n.alias)})})]})}function mt({open:e,sessionId:t,activeTab:n,onTabChange:a,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}),[f,m]=(0,i.useState)(null),[g,x]=(0,i.useState)(!1),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(()=>new Map),[k,j]=(0,i.useState)(()=>new Map),S=(0,i.useRef)(p),C=(0,i.useRef)(null),N=(0,i.useRef)(null),I=(0,i.useRef)(new Set),T=(0,i.useRef)(new Set);S.current=p,(0,i.useEffect)(()=>{if(!e||"characters"!==n)return;let t=new AbortController;return y(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);y(r)}).catch(()=>{t.signal.aborted||y(null)}),()=>t.abort()},[n,e,d.data]),(0,i.useEffect)(()=>{var r;let i,a,s,o,l,c,d,u,p,h;if(m(null),!e||"usage"!==n||!t)return;let f=(a=(r={onClear(){m(null)},onResult(e){m("fresh"===e.status?e.data:null)}}).intervalMs??2500,s=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 rE(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=s(()=>{l&&h(l)},a)))},stop(){u||(u=!0,d+=1,c?.abort(),c=null,p(),l=null)}});return C.current=f,f.setSessionId(t),()=>{f.stop(),C.current===f&&(C.current=null)}},[n,e,t]);let M=(0,i.useCallback)(async e=>{N.current?.abort();let t=new AbortController;N.current=t,x(!0);let n=await r$({refresh:e,previous:S.current.data,signal:t.signal});N.current!==t||t.signal.aborted||(h(n),x(!1))},[]);(0,i.useEffect)(()=>{e&&"models"===n&&("idle"===S.current.status||"error"===S.current.status)&&M(!1)},[n,e,M]),(0,i.useEffect)(()=>()=>{for(let e of(N.current?.abort(),I.current))e.abort()},[]);let R=(0,i.useCallback)(()=>{"models"===n?M(!0):o.refresh()},[n,M,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=rA(T.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 rL(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 rk&&("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(T.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=rA(T.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 rP(n,t,{signal:i.signal}),r=function(e){switch(e.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return e.code.startsWith("http_")?{tone:"error",message:`리셋 사용 실패: 서비스 응답 오류 (${e.code})`}:{tone:"error",message:`리셋 사용 실패: ${e.code}`}}}(e),a=await E();if(e.ok){let e="fresh"===a.status?a.data.reports.find(e=>e.credentialId===n):void 0,t=e?.savedReset?.availableCount;r.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}i.signal.aborted||j(e=>new Map(e).set(n,r))}catch(e){e instanceof rk&&(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 rk){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(T.current.size>0),w(e=>{let t=new Map(e);return t.delete(n),t})}},[E,o]);if(!e)return null;let P="models"===n?p.data?.generatedAt:d.data?.generatedAt,A="models"===n?p.data?.range:void 0,F=A?.from&&A.to?`${fY(A.from)}~${fY(A.to)}`:P?new Date(P).toLocaleTimeString():"",z="models"===n?g:"usage"===n&&u,W=z?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:fU("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)(fs.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>a(e),children:[(0,r.jsxs)(fs.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(fs.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(fs.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(fs.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(fs.J.Indicator,{})]}),(0,r.jsx)(fs.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(me,{reports:d.data?.reports,providerConnections:v})}),(0,r.jsxs)(fs.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)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:z,children:W})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(f5,{state:d,loading:u,accountState:f?.sessionId===t?f:null,pendingActions:b,feedbackByCredential:k,onToggle:e=>{$(e)},onReset:L})]}),(0,r.jsxs)(fs.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)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:z,children:W})]}),(0,r.jsx)(f9,{state:p,loading:g})]})]})]})}let mn="unknown",mr="/api/runs";class mi extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let ma=["completed","error","aborted","interrupted","running"],ms=["main","maker","checker","advisor","unattributed"],mo=["primary","rework","review"],ml=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],mc=["all","attributed"],md=["single","unknown"],mu=["config","harness"];function mp(e){return"object"==typeof e&&null!==e}function mh(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function mf(e){return!!mp(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&&ma.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&&(null===e.harnessRevision||"string"==typeof e.harnessRevision)}function mm(e){return!!mp(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&ms.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&mo.includes(e.purpose))&&mh(e.models)&&mh(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 mg(e){return!!mp(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 mx(e){return!!mp(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.failed&&Number.isFinite(e.failed)&&"number"==typeof e.noMatch&&Number.isFinite(e.noMatch)&&"number"==typeof e.cancelled&&Number.isFinite(e.cancelled)}function mv(e){return!!mp(e)&&"string"==typeof e.kind&&ms.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)&&mh(e.models)&&mh(e.efforts)&&md.includes(e.pairing)}function my(e){return!!mp(e)&&(null===e.revision||"string"==typeof e.revision)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)}function mb(e){return!!mp(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(mv)&&"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)&&Array.isArray(e.harnesses)&&e.harnesses.every(my)}function mw(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&ml.includes(e))}async function mk(e){try{return await e.json()}catch{throw new mi("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}let mj={groupBy:"config",harness:null};function mS(e,t){return e instanceof mi||e instanceof Error?e.message:t}function mC(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function mN(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 mI(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`}let mT={injection:"efficiency.sawKindInjection",developer:"efficiency.sawKindDeveloper",user:"efficiency.sawKindUser",compaction:"efficiency.sawKindCompaction",model:"efficiency.sawKindModel",effort:"efficiency.sawKindEffort",prompt:"efficiency.sawKindPrompt",rules:"efficiency.sawKindRules",memory:"efficiency.sawKindMemory"},mM={ok:"efficiency.sawToolOk",failed:"efficiency.sawToolFailed",noMatch:"efficiency.sawToolNoMatch",cancelled:"efficiency.sawToolCancelled",missing:"efficiency.sawToolMissing"},mR={failed:"critical",noMatch:"neutral",cancelled:"neutral",missing:"warning"};async function mE(e,t){let n,r=await fetch(e,{method:"GET",signal:t});try{n=await r.json()}catch{throw Error(`HTTP ${r.status}: invalid JSON`)}if(!r.ok)throw Error(n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error?n.error:`HTTP ${r.status}`);if(null===n)throw Error(`HTTP ${r.status}: empty body`);return n}function m$(e,t,n){return`${mr}/${encodeURIComponent(e)}/${t}?${new URLSearchParams(n).toString()}`}function mL(e){return e>0?new Date(e).toLocaleTimeString(void 0,{hour12:!1}):"—"}function mP({runId:e,role:t,entryId:n,call:a,label:s,t:o}){let[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)({status:"idle",value:null,error:null});return(0,r.jsxs)("div",{className:"run-saw-full-wrap",children:[(0,r.jsx)("button",{type:"button",className:"run-saw-link","aria-expanded":l,onClick:()=>{let r=!l;if(c(r),!r||"ready"===d.status||"loading"===d.status)return;u({status:"loading",value:null,error:null});let i={role:t,entry:n};a&&(i.call=a),mE(m$(e,"turns",i)).then(e=>u({status:"ready",value:e,error:null})).catch(e=>u({status:"error",value:null,error:e instanceof Error?e.message:String(e)}))},children:l?o("efficiency.sawHideFull"):s}),l?"ready"===d.status&&d.value?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("pre",{className:"run-saw-full",children:d.value.text}),d.value.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:o("efficiency.sawTruncated",{value:mC(d.value.text.length)})}):null]}):"error"===d.status?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:d.error}):(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:o("efficiency.sawLoading")}):null]})}function mA({event:e,runId:t,role:n,t:i}){let a=e.preview;if("compaction"===e.kind&&(null!=e.tokensBefore||null!=e.tokensAfter)){let t=i("efficiency.sawCompactionValue",{before:mN(e.tokensBefore??null),after:mN(e.tokensAfter??null)});a=a?`${t} \xb7 ${a}`:t}else void 0!==e.memoryIds&&(a=i("efficiency.sawMemoryIds",{value:e.memoryIds}));return(0,r.jsxs)("li",{className:"run-saw-event",children:[(0,r.jsxs)("div",{className:"run-saw-event-head",children:[(0,r.jsx)("span",{className:"run-saw-kind",children:i(mT[e.kind])}),(0,r.jsx)("span",{className:"run-saw-source",children:e.source}),(0,r.jsx)("span",{className:"run-saw-dim",children:mL(e.at)}),e.hiddenFromChat?(0,r.jsx)("span",{className:"run-saw-dim",children:i("efficiency.sawHiddenFromChat")}):null,e.sentToModel?null:(0,r.jsx)("span",{className:"run-saw-dim",children:i("efficiency.sawNotSent")})]}),a?(0,r.jsx)("p",{className:"run-saw-preview",children:a}):null,e.chars>e.preview.length?(0,r.jsx)(mP,{runId:t,role:n,entryId:e.entryId,call:null,label:i("efficiency.sawShowFull"),t:i}):null]})}function mF({call:e,runId:t,role:n,turnEntryId:i,t:a}){return(0,r.jsxs)("li",{className:"run-saw-tool",children:[(0,r.jsxs)("div",{className:"run-saw-tool-head",children:[(0,r.jsx)("span",{className:"run-saw-tool-name",children:e.name}),(0,r.jsx)("span",{className:"run-saw-num",children:mI(e.durationMs)}),null!==e.resultChars?(0,r.jsx)("span",{className:"run-saw-dim",children:a("efficiency.sawResultChars",{value:mC(e.resultChars)})}):null,"ok"!==e.status?(0,r.jsx)(nu.E,{tone:mR[e.status],variant:"weak",size:"medium",children:a(mM[e.status])}):null]}),(0,r.jsx)("code",{className:"run-saw-args",children:e.argsPreview}),(0,r.jsxs)("div",{className:"run-saw-tool-actions",children:[e.argsChars>e.argsPreview.length?(0,r.jsx)(mP,{runId:t,role:n,entryId:i,call:e.toolCallId,label:a("efficiency.sawShowArgs"),t:a}):null,e.resultEntryId?(0,r.jsx)(mP,{runId:t,role:n,entryId:e.resultEntryId,call:null,label:a("efficiency.sawShowResult"),t:a}):null]})]})}function mz({turn:e,runId:t,role:n,t:i}){let a=[e.model,mI(e.durationMs),e.usage?i("efficiency.sawUsage",{input:mN(e.usage.input),output:mN(e.usage.output),cacheRead:mN(e.usage.cacheRead)}):null,e.stopReason?i("efficiency.sawStop",{value:e.stopReason}):null].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"run-saw-turn",children:[(0,r.jsxs)("div",{className:"run-saw-turn-head",children:[(0,r.jsx)("span",{className:"run-saw-turn-label",children:i("efficiency.sawTurnLabel",{index:e.index})}),(0,r.jsx)("span",{className:"run-saw-dim",children:mL(e.at)})]}),(0,r.jsx)("p",{className:"run-saw-turn-meta",children:a}),e.toolsAdded.length>0||e.toolsRemoved.length>0?(0,r.jsx)("p",{className:"run-saw-dim",title:[...e.toolsAdded.map(e=>`+${e}`),...e.toolsRemoved.map(e=>`−${e}`)].join(" "),children:i("efficiency.sawToolsChanged",{added:e.toolsAdded.join(", ")||"0",removed:e.toolsRemoved.join(", ")||"0"})}):null,e.before.length>0?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:i("efficiency.sawBefore")}),(0,r.jsx)("ul",{className:"run-saw-events",children:e.before.map(e=>(0,r.jsx)(mA,{event:e,runId:t,role:n,t:i},e.entryId))})]}):null,e.toolCalls.length>0?(0,r.jsx)("ul",{className:"run-saw-tools",children:e.toolCalls.map(a=>(0,r.jsx)(mF,{call:a,runId:t,role:n,turnEntryId:e.entryId,t:i},a.toolCallId))}):null]})}function mW({runId:e,role:t,t:n}){let[a,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let n=new AbortController;return o(null),c(null),mE(m$(e,"prelude",{role:t}),n.signal).then(o).catch(e=>{n.signal.aborted||c(e instanceof Error?e.message:String(e))}),()=>n.abort()},[e,t]);let p=a?.recorded.digests.at(-1)??null,h=a?.rebuilt;return(0,r.jsxs)("section",{className:"run-saw-prelude","aria-label":n("efficiency.sawPreludeTitle"),children:[(0,r.jsx)("h4",{className:"run-saw-subtitle",children:n("efficiency.sawPreludeTitle")}),l?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:l}):null,a||l?null:(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:n("efficiency.sawLoading")}),a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:n("efficiency.sawPreludeRecorded")}),(0,r.jsx)("p",{className:"run-saw-line",children:p?n("efficiency.sawPreludeDigest",{value:p.digest}):n("efficiency.sawPreludeDigestNone")}),a.recorded.activeTools?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeTools",{value:a.recorded.activeTools.length})}),(0,r.jsx)("p",{className:"run-saw-names",children:a.recorded.activeTools.join(" \xb7 ")})]}):null,a.recorded.memoryRecall?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeMemory")}),(0,r.jsx)("p",{className:"run-saw-preview",children:a.recorded.memoryRecall.preview}),a.recorded.memoryRecall.chars>a.recorded.memoryRecall.preview.length?(0,r.jsx)(mP,{runId:e,role:t,entryId:a.recorded.memoryRecall.entryId,call:null,label:n("efficiency.sawShowFull"),t:n}):null]}):null,h?.status==="not-loaded"?(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeNotLoaded")}):h?.status==="available"?(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{u(!0),mE(m$(e,"prelude",{role:t,rebuild:"1"})).then(o).catch(e=>c(e instanceof Error?e.message:String(e))).finally(()=>u(!1))},disabled:d,children:n(d?"efficiency.sawPreludeLoading":"efficiency.sawPreludeReconstruct")})}):h?.status==="rebuilt"?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeApprox")}),null!==h.matchesRecorded?(0,r.jsx)("p",{className:"run-saw-line",children:n(h.matchesRecorded?"efficiency.sawPreludeMatch":"efficiency.sawPreludeMismatch")}):null,(0,r.jsx)("pre",{className:"run-saw-full",children:h.text}),h.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:n("efficiency.sawTruncated",{value:mC(h.text.length)})}):null]}):null]}):null]})}let mD={status:"idle",page:null,turns:[],loadingMore:!1,error:null};function mO({runId:e,t}){let[n,a]=(0,i.useState)(!1),[o,c]=(0,i.useState)("main"),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(mD),f=(0,i.useRef)(null),m=(0,i.useCallback)(t=>{f.current?.abort();let n=new AbortController;f.current=n,h(e=>0===t?{...mD,status:"loading"}:{...e,loadingMore:!0});let r={role:o,offset:String(t),limit:String(30)};d&&(r.injectedOnly="1"),mE(m$(e,"turns",r),n.signal).then(e=>h(n=>({status:"ready",page:e,turns:0===t?e.turns:[...n.turns,...e.turns],loadingMore:!1,error:null}))).catch(e=>{n.signal.aborted||h(n=>({...n,status:0===t?"error":n.status,loadingMore:!1,error:e instanceof Error?e.message:String(e)}))})},[e,o,d]);(0,i.useEffect)(()=>{n&&m(0)},[n,m]),(0,i.useEffect)(()=>()=>f.current?.abort(),[]);let g=p.page,x=g?g.total-p.turns.length:0,v=g?Object.entries(g.counts.bySource).sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])):[];return(0,r.jsxs)("section",{className:"run-saw","aria-label":t("efficiency.sawSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.sawSection")}),(0,r.jsx)("p",{className:"run-saw-approx",children:t("efficiency.sawApproxNote")}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"run-saw-controls",children:[g&&g.roles.length>1?(0,r.jsxs)("label",{className:"run-saw-role",children:[(0,r.jsx)("span",{children:t("efficiency.sawRole")}),(0,r.jsx)("select",{className:"efficiency-folder-select",value:o,onChange:e=>c(e.target.value),children:g.roles.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]}):null,(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:d,onPressedChange:u,children:t("efficiency.sawOnlyInjected")})]}),"loading"===p.status||"idle"===p.status?(0,r.jsx)("p",{className:"efficiency-empty",role:"status",children:t("efficiency.sawLoading")}):"error"===p.status?(0,r.jsxs)("div",{className:"efficiency-empty",role:"alert",children:[(0,r.jsx)("div",{children:t("efficiency.sawError")}),(0,r.jsx)("div",{className:"run-saw-dim",children:p.error})]}):g?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-summary",children:t("efficiency.sawSummary",{turns:g.counts.turns,injections:g.counts.injections,tools:g.counts.toolCalls,failed:g.counts.toolFailures})}),v.length>0?(0,r.jsx)("p",{className:"run-saw-names",children:v.map(([e,t])=>`${e} ${t}`).join(" \xb7 ")}):null,(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",children:t("efficiency.sawSecretsMasked")}),0===p.turns.length?(0,r.jsx)("p",{className:"efficiency-empty",children:t(d?"efficiency.sawFilterEmpty":"efficiency.sawEmpty")}):(0,r.jsx)("ol",{className:"run-saw-turns",children:p.turns.map(n=>(0,r.jsx)(mz,{turn:n,runId:e,role:g.role,t:t},n.entryId))}),g.trailing.length>0&&x<=0?(0,r.jsxs)("div",{className:"run-saw-group run-saw-trailing",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:t("efficiency.sawTrailing")}),(0,r.jsx)("ul",{className:"run-saw-events",children:g.trailing.map(n=>(0,r.jsx)(mA,{event:n,runId:e,role:g.role,t:t},n.entryId))})]}):null,(0,r.jsxs)("div",{className:"run-saw-actions",children:[(0,r.jsx)("span",{className:"run-saw-dim",children:t("efficiency.sawShown",{shown:p.turns.length,total:g.total})}),x>0?(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>m(p.turns.length),disabled:p.loadingMore,children:p.loadingMore?t("efficiency.sawLoading"):t("efficiency.sawMore",{value:Math.min(x,30)})}):null]}),p.error?(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",role:"alert",children:p.error}):null,(0,r.jsx)(mW,{runId:e,role:g.role,t:t})]}):null]}):(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>a(!0),children:t("efficiency.sawOpen")})})]})}let mH={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},mU={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function m_(...e){return e.filter(Boolean).join(" ")}function mB(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 mq(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function mV(e,t){return null===e?t("efficiency.harnessUnknown"):e.slice(0,7)}function mK({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 text-xs text-text-muted [overflow-wrap:anywhere]",children:e}),(0,r.jsx)("dd",{className:"m-0 flex-none text-right font-mono text-xs tabular-nums text-text",children:t})]})}function mG({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 mJ({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",mB(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function mZ({outcome:e,t}){return(0,r.jsx)(nu.E,{tone:mH[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function mY({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(nu.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 mX({run:e,selected:t,onSelect:n,t:i}){let a=e.title&&e.title.trim().length>0?e.title:i("efficiency.noTitle");return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",onClick:n,"aria-current":t?"true":void 0,className:m_("efficiency-run-item",t&&"is-selected"),children:[(0,r.jsxs)("span",{className:"efficiency-run-top",children:[(0,r.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,r.jsx)("span",{className:"efficiency-run-title",title:a,children:a}),(0,r.jsx)(mZ,{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}",mI(e.wallClockMs))}),(0,r.jsx)(mJ,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:i}),(0,r.jsx)("span",{className:"font-mono tabular-nums",title:e.harnessRevision??i("efficiency.harnessUnknown"),children:i("efficiency.harnessValue").replace("{value}",mV(e.harnessRevision,i))})]})]})})}function mQ({role:e,t}){let n=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),i=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort"),a=e.outputTokens-e.helpers.reduce((e,t)=>e+t.outputTokens,0),s=t(`efficiency.role${"main"===e.kind?"Main":"maker"===e.kind?"Maker":"checker"===e.kind?"Checker":"advisor"===e.kind?"Advisor":"Unattributed"}`);return(0,r.jsxs)("details",{className:"efficiency-role",children:[(0,r.jsxs)("summary",{className:"efficiency-role-summary",children:[(0,r.jsxs)("span",{className:"efficiency-role-head",children:[(0,r.jsx)("span",{className:"efficiency-role-id",children:e.id}),(0,r.jsx)(nu.E,{tone:mU[e.kind]??"neutral",variant:"weak",size:"medium",children:s}),(0,r.jsx)(mY,{purpose:e.purpose,t:t})]}),(0,r.jsx)("span",{className:"efficiency-model-line",title:n,children:n}),(0,r.jsxs)("span",{className:"efficiency-role-stats",children:[(0,r.jsxs)("span",{children:[t("efficiency.busyTime")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:mI(e.busyMs)})]}),(0,r.jsxs)("span",{children:[t("efficiency.estimatedCost")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:mB(e.estimatedCostUsd)})]}),(0,r.jsxs)("span",{children:[t("efficiency.tokens")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:mN(e.totalTokens)})]})]})]}),(0,r.jsxs)("div",{className:"efficiency-role-body",children:[(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:"efficiency-metrics",children:[(0,r.jsx)(mK,{label:t("efficiency.unpricedRequests"),value:mC(e.unpricedRequests)}),(0,r.jsx)(mK,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?mI(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,r.jsx)(mK,{label:t("efficiency.outputTokens"),value:mN(a)})]}),e.ttftRequests>0&&e.ttftRequests<e.requestCount?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.firstTokenPartial",{recorded:e.ttftRequests,total:e.requestCount})}):null,e.untimedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.untimedLowerBound").replace("{value}",mC(e.untimedRequests))}):null,e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.unpricedLowerBound")}):null,e.helpers.length>0?(0,r.jsxs)("section",{className:"efficiency-helpers","aria-label":t("efficiency.helpersTitle"),children:[(0,r.jsx)("h4",{className:"efficiency-helpers-title",children:t("efficiency.helpersTitle")}),(0,r.jsx)("ul",{className:"efficiency-helper-list",children:e.helpers.map(e=>(0,r.jsxs)("li",{className:"efficiency-helper",children:[(0,r.jsx)("span",{className:"efficiency-helper-name",children:`${e.purpose} \xb7 ${e.model}`}),(0,r.jsx)("span",{className:"efficiency-helper-value",children:t("efficiency.helperCallsValue",{count:e.requestCount,output:mN(e.outputTokens),tokens:mN(e.totalTokens),cost:mB(e.estimatedCostUsd)})})]},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.helpersIncludedNote")})]}):null]})]})}function m0({item:e,t}){let n="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,r.jsxs)("li",{className:"efficiency-bottleneck","data-kind":e.kind,children:[(0,r.jsx)("span",{className:"efficiency-bottleneck-label",children:n}),(0,r.jsx)("span",{className:"efficiency-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"efficiency-meter-fill",style:{inlineSize:`${Number.isFinite(e.relative)?Math.max(1,Math.min(100,100*e.relative)):1}%`}})}),(0,r.jsx)("span",{className:"efficiency-bottleneck-value",children:mI(e.ms)})]})}function m1({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:mI(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:mI(e.busyMs)})]})]}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,r.jsxs)("dl",{className:"efficiency-metrics",children:[(0,r.jsx)(mK,{label:t("efficiency.estimatedCost"),value:mB(e.estimatedCostUsd)}),(0,r.jsx)(mK,{label:t("efficiency.tokens"),value:mN(e.totalTokens)}),(0,r.jsx)(mK,{label:t("efficiency.harness"),value:mV(e.harnessRevision,t)})]}),e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(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)("ol",{className:"efficiency-bottlenecks",children:e.bottlenecks.map(e=>(0,r.jsx)(m0,{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}",mI(e.unmeasuredMs))}):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-roles",children:e.roles.map(e=>(0,r.jsx)(mQ,{role:e,t:t},e.id))},e.runId):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),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:"efficiency-metrics",children:e.toolTotals.map(e=>(0,r.jsx)(mK,{label:[e.toolName,t("efficiency.toolFailedValue").replace("{value}",String(e.failed)),...e.noMatch>0?[t("efficiency.toolNoMatchValue").replace("{value}",String(e.noMatch))]:[],...e.cancelled>0?[t("efficiency.toolCancelledValue").replace("{value}",String(e.cancelled))]:[]].join(" \xb7 "),value:mC(e.calls)},e.toolName))})]}):null,(0,r.jsx)(mO,{runId:e.runId,t:t},e.runId)]})}function m2(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 m8({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)(mK,{label:t("efficiency.scopeSessions"),value:mC(e.sessionCount)}),(0,r.jsx)(mK,{label:t("efficiency.scopeRuns"),value:mC(e.runCount)}),(0,r.jsx)(mK,{label:t("efficiency.scopeExcludedRuns"),value:mC(e.excludedRunCount)})]})})}function m4({config:e,baselineRuns:t,t:n}){let i=t>0?e.runCount/t:0,a=e.runCount>0?e.reworkRuns/e.runCount:0,s=e.runCount>0?e.errorRuns/e.runCount:0,o=function(e,t){if(1===e.length)return{text:mV(e[0].revision,t),full:e[0].revision??t("efficiency.harnessUnknown")};let n=e.map(e=>`${mV(e.revision,t)} \xd7${e.runCount}`),r=n.slice(0,4).join(" \xb7 ");return{text:n.length>4?`${r} \xb7 +${n.length-4}`:r,full:e.map(e=>`${e.revision??t("efficiency.harnessUnknown")} \xd7${e.runCount}`).join("\n")}}(e.harnesses,n);return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsx)("p",{className:"efficiency-model-line",title:m2(e.roles),children:m2(e.roles)}),(0,r.jsx)("p",{className:"efficiency-dim font-mono tabular-nums",title:o.full,children:n("efficiency.harnessValue").replace("{value}",o.text)}),e.roles.some(e=>"unknown"===e.pairing)?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.mixedPairingNote")}):null,(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:mq(i)})]}),(0,r.jsx)(mG,{share:i,label:mq(i)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(mK,{label:n("efficiency.medianElapsed"),value:mI(e.medianWallClockMs)}),(0,r.jsx)(mK,{label:n("efficiency.medianBusy"),value:mI(e.medianBusyMs)}),(0,r.jsx)(mK,{label:n("efficiency.medianTokens"),value:mN(e.medianTotalTokens)}),(0,r.jsx)(mK,{label:n("efficiency.medianEstimatedCost"),value:mB(e.medianEstimatedCostUsd)}),(0,r.jsx)(mK,{label:n("efficiency.totalEstimatedCost"),value:mB(e.totalEstimatedCostUsd)}),(0,r.jsx)(mK,{label:n("efficiency.reworkRate"),value:mq(a,1)}),(0,r.jsx)(mK,{label:n("efficiency.errorRate"),value:mq(s,1)}),(0,r.jsx)(mK,{label:n("efficiency.unpricedRuns"),value:mC(e.unpricedRuns)}),(0,r.jsx)(mK,{label:n("efficiency.untimedRuns"),value:mC(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",mC(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function m5({open:e,sessionId:t,activeTab:n,onTabChange:a,client:o,className:c}){let d=(0,i.useId)(),u=(0,i.useId)(),{t:p}=(0,F.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[a]=(0,i.useState)(()=>r??function(e=(e,t)=>fetch(e,t)){let t=async(t,n)=>{let r;try{r=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new mi("unreachable","효율 기록에 연결할 수 없습니다.")}let i=await mk(r);if(!r.ok){var a;throw new mi("http",(a=`HTTP ${r.status}`,null!==i&&"object"==typeof i&&"error"in i&&"string"==typeof i.error&&i.error?i.error:a),r.status)}return{response:r,body:i}};return{async listRuns(e,n,r){let{response:i,body:a}=await t(`${mr}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!mp(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(mf)&&mw(e.unmeasured)))throw new mi("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new mi("invalid-response",t,n)}}(a,"실행 목록 응답이 올바르지 않습니다.",i.status)},async getRun(e,n){let{response:r,body:i}=await t(`${mr}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!mf(e)||!(Array.isArray(e.roles)&&e.roles.every(mm)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(mg)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(mx)&&mw(e.unmeasured)))throw new mi("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new mi("invalid-response",t,n)}}(i,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,i,a){let s=new URLSearchParams;null!==e&&""!==e&&s.set("folder",e),s.set("sessions",String(n)),s.set("scope",r),a?.groupBy==="harness"&&s.set("groupBy","harness"),a?.harness&&s.set("harness",a.harness);let{response:o,body:l}=await t(`/api/experiments?${s.toString()}`,{method:"GET",signal:i});return function(e,t,n=null){try{if(!mp(e)||!((null===e.folder||"string"==typeof e.folder)&&mh(e.folders)&&"string"==typeof e.scope&&mc.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(mb)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&"string"==typeof e.groupBy&&mu.includes(e.groupBy)&&(null===e.harness||"string"==typeof e.harness)&&Array.isArray(e.harnesses)&&e.harnesses.every(my)&&mw(e.unmeasured)))throw new mi("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new mi("invalid-response",t,n)}}(l,"구성 비교 응답이 올바르지 않습니다.",o.status)}}}()),[s,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),[f,m]=(0,i.useState)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),y=(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 b=(0,i.useCallback)(()=>{if(!t||"governor"!==n||!e)return;g.current?.abort();let r=new AbortController;g.current=r,o(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),a.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&g.current===r){if(0===e.runs.length)return void o({status:"empty",runs:[],error:null});o({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||g.current!==r||o({status:"error",runs:[],error:mS(e,"실행 목록을 불러오지 못했습니다.")})})},[n,a,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}),a.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:mS(t,"실행 상세를 불러오지 못했습니다.")})})},[a,t]),k=(0,i.useCallback)((e,r="all",i=mj)=>{if(!t||"lab"!==n)return;v.current?.abort();let s=new AbortController;v.current=s,u(e=>({status:"loading",response:"ready"===e.status||"empty"===e.status?e.response:null,error:null})),a.listExperiments(e,30,r,s.signal,i).then(e=>{if(!s.signal.aborted&&v.current===s){if(0===e.configs.length)return void u({status:"empty",response:e,error:null});u({status:"ready",response:e,error:null})}}).catch(e=>{s.signal.aborted||v.current!==s||u({status:"error",response:null,error:mS(e,"구성 비교를 불러오지 못했습니다.")})})},[n,a,t]);(0,i.useEffect)(()=>{if(t&&"governor"===n)return b(),()=>{g.current?.abort(),g.current=null}},[n,b,e,t]),(0,i.useEffect)(()=>{if(t&&"lab"===n)return k(y.current),()=>{v.current?.abort(),v.current=null}},[n,k,t]),(0,i.useEffect)(()=>{if(t&&"governor"===n&&null!==p)return w(p),()=>{x.current?.abort(),x.current=null}},[n,w,p,t]),(0,i.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,i.useCallback)(e=>{x.current?.abort(),x.current=null,h(e),null===e&&c({status:"idle",runId:null,detail:null,error:null})},[]);return{list:s,detail:l,experiments:d,selectedRunId:p,selectRun:j,refreshRuns:(0,i.useCallback)(()=>{b()},[b]),refreshExperiments:(0,i.useCallback)((e,t="all",n=mj)=>{let r=void 0===e?y.current:e;void 0!==e&&(y.current=e,m(e)),k(r,t,n)},[k]),experimentFolder:f}}({sessionId:t,visible:e,activeTab:n,client:o}),[f,m]=(0,i.useState)(""),g=(0,i.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),x=(0,i.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),v=h.experimentFolder,y=h.experiments.response?.scope??"all",b={groupBy:h.experiments.response?.groupBy??"config",harness:h.experiments.response?.harness??null},w=h.experiments.response?.harnesses??[];if(!e)return null;let k="governor"===n&&"loading"===h.list.status||"lab"===n&&"loading"===h.experiments.status,j=k?p("efficiency.refreshing"):p("efficiency.refresh"),S="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:m_("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",c),"aria-labelledby":d,"aria-busy":k,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:S}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===n?h.refreshRuns():h.refreshExperiments(void 0,y,b)},disabled:k,children:j})]}),(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:m_("min-h-10 border-0 border-r border-border bg-bg px-4 text-sm text-text-muted last:border-r-0 hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent",n===e&&"bg-bg-selected font-semibold text-text"),onClick:()=>a(e),children:"governor"===e?p("efficiency.governor"):p("efficiency.lab")},e))}),"lab"===n?(0,r.jsxs)("div",{className:"efficiency-folderbar",children:[(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-folder`,children:p("efficiency.folder")}),(0,r.jsxs)("select",{id:`${u}-folder`,className:"efficiency-folder-select",value:v??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;m(t??""),h.refreshExperiments(t,y,b)},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.folderAll")}),g.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),v&&!g.includes(v)?(0,r.jsx)("option",{value:v,children:v}):null]}),(0,r.jsx)("input",{className:"efficiency-folder-input",value:f,placeholder:p("efficiency.folderPlaceholder"),"aria-label":p("efficiency.folder"),onChange:e=>m(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===f.trim()?null:f.trim();h.refreshExperiments(e,y,b)}}}),(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-harness`,children:p("efficiency.harness")}),(0,r.jsxs)("select",{id:`${u}-harness`,className:"efficiency-folder-select font-mono",value:b.harness??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;h.refreshExperiments(void 0,y,{groupBy:b.groupBy,harness:t})},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.harnessAll")}),w.map(e=>(0,r.jsx)("option",{value:e.revision??mn,children:`${mV(e.revision,p)} (${e.runCount})`},e.revision??mn)),b.harness&&!w.some(e=>(e.revision??mn)===b.harness)?(0,r.jsx)("option",{value:b.harness,children:b.harness===mn?p("efficiency.harnessUnknown"):b.harness.slice(0,7)}):null]}),(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"===y,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all",b),children:p("efficiency.scopeAttributed")}),(0,r.jsx)(nu.E,{tone:"attributed"===y?"informative":"neutral",variant:"weak",size:"medium",children:p("attributed"===y?"efficiency.scopeAttributed":"efficiency.scopeAll")}),(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"harness"===b.groupBy,onPressedChange:e=>h.refreshExperiments(void 0,y,{groupBy:e?"harness":"config",harness:b.harness}),children:p("efficiency.groupByHarness")})]})]}):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)(mX,{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)(m1,{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.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")}),(0,r.jsxs)("div",{className:"efficiency-stack",children:[(0,r.jsx)(m8,{response:e,t:p}),e.configs.map(t=>(0,r.jsx)(m4,{config:t,baselineRuns:x,t:p},JSON.stringify([t.roles.map(e=>[e.kind,e.models,e.efforts,e.count]),"harness"===e.groupBy?t.harnesses[0]?.revision??null:null])))]})]}):(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)(m8,{response:e,t:p})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")})]})})()})]})}function m6({cwd:e,onOpenFile:t}){let n,{t:a}=(0,F.s)(),[s,o]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e)return;let t=new AbortController;return fetch(`/api/project-docs?cwd=${encodeURIComponent(e)}`,{signal:t.signal}).then(async n=>{let r=await n.json();t.signal.aborted||(403===n.status?o({kind:"denied",cwd:e}):n.ok?o({kind:"ready",cwd:e,docs:r}):o({kind:"error",cwd:e,message:r.error??`HTTP ${n.status}`}))}).catch(n=>{t.signal.aborted||o({kind:"error",cwd:e,message:n instanceof Error?n.message:String(n)})}),()=>t.abort()},[e]);let l=e&&s?.cwd===e?s:null,c=(e,n,i)=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:"found"===i.state&&i.path?(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:i.path,"aria-label":`${e} — ${i.path}`,onClick:()=>t(i.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:n})]}):(0,r.jsxs)("div",{className:"file-doc-shortcuts-unavailable",title:i.path??void 0,children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:"denied"===i.state?a("files.docs.denied",{file:n}):a("files.docs.missing",{file:n})})]})});if(e)if(l)if("denied"===l.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.projectDenied")});else if("error"===l.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"alert",children:a("files.docs.loadFailed",{error:l.message})});else{let{docs:e}=l,i="missing"===e.handoff.state&&"missing"===e.docMap.state&&"missing"===e.history.state;n=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"file-doc-shortcuts-project",title:e.projectDir,children:a("files.docs.projectDir",{path:e.projectDir})}),i?(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.noneFound")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("ul",{className:"file-doc-shortcuts-list",children:[c(a("files.docs.current"),"HANDOFF.md",e.handoff),c(a("files.docs.map"),"doc/README.md",e.docMap)]}),(0,r.jsx)("h3",{className:"file-doc-shortcuts-heading",id:"file-doc-shortcuts-records",children:a("files.docs.records")}),e.history.records.length>0?(0,r.jsx)("ul",{className:"file-doc-shortcuts-list","aria-labelledby":"file-doc-shortcuts-records",children:e.history.records.map(e=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:e.path,"aria-label":`${a("files.docs.records")} ${e.date} ${e.topic} — ${e.fileName}`,onClick:()=>t(e.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-date",children:e.date}),(0,r.jsxs)("span",{className:"file-doc-shortcuts-file",children:[e.topic,"main.md"===e.fileName?"":` \xb7 ${e.fileName}`]})]})},e.path))}):(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:"denied"===e.history.state?a("files.docs.denied",{file:"doc/history"}):a("files.docs.missing",{file:"doc/history"})})]})]})}else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"status",children:a("files.docs.loading")});else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.noProject")});return(0,r.jsxs)("section",{className:"file-doc-shortcuts","aria-labelledby":"file-doc-shortcuts-title",children:[(0,r.jsx)("h2",{className:"file-doc-shortcuts-title",id:"file-doc-shortcuts-title",children:a("files.noneOpen")}),n]})}function m3(e){return"message"===e.type&&"message"in e}function m7(e){let t=e,n=t.branchPreview,r=m3(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&m3(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function m9({node:e,activePathIds:t,depth:n,isLast:i,parentLines:a,onSelect:s}){let{node:o,skipped:l,branchPreview:c,labelEntry:d}=m7(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),f=c?c.role??null:m3(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:()=>s(o.entry.id),children:[a.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),f&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===f?"var(--accent)":"var(--text-dim)",background:"user"===f?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===f?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===f?"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)(m9,{node:e,activePathIds:t,depth:n+1,isLast:l===o.children.length-1,parentLines:[...a,!i],onSelect:s},e.entry.id))]})}function ge({tree:e,activeLeafId:t,onLeafChange:n,hasSession:a}){let{t:s}=(0,F.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 a=e(i.children,n);if(a)return a}return null}(e,[])??[]):new Set,[e,t]),l=(0,i.useCallback)(e=>{n(e)},[n]),c=a?!function e(t){if(t.length>1)return!0;for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)?s("i18n.noBranches"):null:s("i18n.noActiveSession"),d=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=m7(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)(m9,{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??s("i18n.noBranches")})}function gt(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function gn(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function gr(e){let t=e.currentTime;[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),a=e.createGain();i.connect(a),a.connect(e.destination),i.type="sine",i.frequency.value=n;let s=t+.18*r;a.gain.setValueAtTime(0,s),a.gain.linearRampToValueAtTime(.18,s+.02),a.gain.exponentialRampToValueAtTime(.001,s+.45),i.start(s),i.stop(s+.45)})}async function gi(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function ga(e){let t=e.window?.durationMs;if("number"==typeof t&&Number.isFinite(t)&&t>0)return t>=5184e5?"weekly":t<=432e5?"short":"other";let n=e.scope?.windowId,r=`${"string"==typeof n?n:""} ${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"}let gs="omp-sidebar-usage-collapsed",go="omp-sidebar-usage-order";function gl(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function gc(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function gd({direction:e}){return(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"up"===e?"2.5 7.5 6 4 9.5 7.5":"2.5 4.5 6 8 9.5 4.5"})})}function gu({usage:e,onOpen:t,onRelogin:n}){var a,s;let o,l,c,d,{t:u}=(0,F.s)(),p=U(),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(!1),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),j=(0,i.useRef)(null),[S,C]=(0,i.useState)(!0);(0,i.useEffect)(()=>{try{C("0"!==window.localStorage.getItem(gs))}catch{}v(function(){try{let e=JSON.parse(window.localStorage.getItem(go)??"[]");return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}catch{return[]}}())},[]);let N=e.bai,I=e.state.data?.reports??[],T=nd(1e4),M=(o=rw(I),l=[],c=[],I.forEach((e,t)=>{let n=e.authError;if(!0===e.disabled&&!n)return;let r=o[t],i="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>T,a=!0===e.disabled?[]:e.limits??[],s=a.some(e=>e.scope?.shared===!0&&n2(e)),d=a.some(e=>null!==gl(e)&&"short"!==ga(e)),u=[];for(let e of a){let t=gl(e);null!==t&&(!d||"short"!==ga(e)||function(e){let t=e.amount?.usedFraction,n="number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null;return n2(e)||"warning"===e.status||null!==n&&n>=90}(e))&&u.push({key:e.id,label:e.label||e.id,percent:Math.round(100*t),state:i?"blocked":s?"account-spent":n2(e)?"spent":"usable"})}if(0===u.length&&!n)return;let p=n?"auth":i?"blocked":s?"account-spent":"ok",h={orderKey:"string"==typeof e.accountKey&&e.accountKey.length>0?`${e.provider}:${e.accountKey}`:void 0!==e.credentialId?`${e.provider}:#${e.credentialId}`:`${e.provider}:@${t}`,provider:e.provider,alias:r.alias,seed:r.seed,masked:r.masked,..."string"==typeof e.accountKey?{accountKey:e.accountKey}:{},rows:u,state:p,...n?{authError:n}:{},usable:"ok"===p&&u.some(e=>"usable"===e.state)};(h.usable?l:c).push(h)}),a=[...l,...c],d=new Map(x.map((e,t)=>[e,t])),[...a.filter(e=>d.has(e.orderKey)).sort((e,t)=>d.get(e.orderKey)-d.get(t.orderKey)),...a.filter(e=>!d.has(e.orderKey))]);(0,i.useEffect)(()=>{if(null===w)return;let e=[...j.current?.querySelectorAll("[data-order-key]")??[]].find(e=>e.dataset.orderKey===w.orderKey),t=e?.querySelector(`[data-direction="${w.direction}"]`),n=e?.querySelector(`[data-direction="${"up"===w.direction?"down":"up"}"]`);(t&&!t.disabled?t:n)?.focus(),k(null)},[w]);let R=(e,t)=>{let n,r,i,a="up"===t?e-1:e+1;if(a<0||a>=M.length)return;let s=M.map(e=>e.orderKey);[s[e],s[a]]=[s[a],s[e]];let o=(n=new Set(s),r=[...x,...s.filter(e=>!x.includes(e))],i=0,r.map(e=>n.has(e)?s[i++]:e));v(o);try{window.localStorage.setItem(go,JSON.stringify(o))}catch{}b(u("usage.moved",{account:M[e].alias,position:a+1})),k({orderKey:M[e].orderKey,direction:t})},E=e=>Math.max(1,e.rows.length),$=0,L=h||m?M:M.filter(e=>!($>=2)&&($+=E(e),!0)),P=M.slice(L.length).reduce((e,t)=>e+E(t),0),A=M.filter(e=>"auth"===e.state).length,z="measured"===N.status?(s=N.tokens)>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(Math.round(s)):u("empty"===N.status?"usage.baiEmpty":"usage.baiUnmeasured"),W="measured"===N.status&&null!==N.from&&null!==N.to?u("usage.baiRange",{from:gc(N.from),to:gc(N.to)}):null,D=e=>"auth"===e.state?u(e.authError?.reloginRequired?"usage.authExpired":"usage.authUnavailable"):"blocked"===e.state?u("usage.accountBlocked"):"account-spent"===e.state?u("usage.accountSpent"):null,O=e=>"spent"===e.state?u("usage.limitSpent"):null,H=u("usage.open",{rows:[...L.flatMap(e=>{let t=D(e);return 0===e.rows.length?[`${e.alias} (${t??""}${e.authError?`: ${e.authError.message}`:""})`]:e.rows.map(n=>{let r=O(n)??t;return`${e.alias} ${n.label} ${n.percent}%${null===r?"":` (${r})`}`})}),`${u("usage.bai")} ${z}${null===W?"":` \xb7 ${W}`}`].join(", ")})+(P>0?u("usage.openMore",{count:P}):""),_=M[0],B=void 0===_?{label:u("usage.bai"),value:z,danger:!1}:0===_.rows.length?{label:_.alias,value:D(_)??"",danger:!0}:{label:_.rows[0].label,value:`${_.rows[0].percent}%`,danger:_.rows[0].percent>=90},q=A>0?u("usage.authIssues",{count:A}):null,V=(0,r.jsxs)("div",{className:"navigator-usage",role:"group","aria-label":u("usage.title"),"data-editing":m?"":void 0,onClick:e=>{m||e.target instanceof Element&&e.target.closest("button, a")||t()},children:[(0,r.jsxs)("span",{className:"navigator-usage-header",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-open","aria-label":H,onClick:t,children:u("usage.title")}),null===q?null:(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),M.length>1&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-edit","data-active":m?"":void 0,onClick:()=>g(e=>!e),children:m?u("usage.reorderDone"):u("usage.reorder")})]}),(0,r.jsx)("div",{ref:j,role:m?"list":void 0,"aria-label":m?u("usage.reorderGroup"):void 0,className:"navigator-usage-groups",children:0===M.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:u("usage.none")}):L.map((e,t)=>{let i=D(e);return(0,r.jsxs)("div",{className:"navigator-usage-group","data-order-key":e.orderKey,role:m?"listitem":void 0,children:[(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(r0,{seed:e.seed,size:24,provider:e.provider}),(0,r.jsx)("span",{className:"navigator-usage-alias",children:e.alias}),null===i?null:(0,r.jsx)("span",{className:"navigator-usage-state","data-tone":"auth"===e.state?"danger":void 0,children:i}),m&&(0,r.jsxs)("span",{className:"navigator-usage-moves",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"up","aria-label":u("usage.moveUp",{account:e.alias}),disabled:0===t,onClick:()=>R(t,"up"),children:(0,r.jsx)(gd,{direction:"up"})}),(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"down","aria-label":u("usage.moveDown",{account:e.alias}),disabled:t===M.length-1,onClick:()=>R(t,"down"),children:(0,r.jsx)(gd,{direction:"down"})})]})]}),e.authError&&(0,r.jsxs)("span",{className:"navigator-usage-auth",children:[(0,r.jsx)("span",{className:"navigator-usage-reason",children:e.authError.message}),e.authError.reloginRequired&&n&&!m&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-relogin","aria-label":u("usage.reloginFor",{account:e.alias}),onClick:()=>n({provider:e.provider,alias:e.alias,seed:e.seed,masked:e.masked,...e.accountKey?{accountKey:e.accountKey}:{},reason:e.authError?.message??""}),children:u("usage.relogin")})]}),e.rows.map(e=>{let t=O(e);return(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:e.label}),null===t?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:t}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,r.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)})]},e.orderKey)})}),!m&&(P>0||h)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":h,onClick:()=>f(e=>!e),children:h?u("usage.showLess"):u("usage.showMore",{count:P})}),(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:u("usage.bai")}),(0,r.jsx)("span",{className:"navigator-usage-value",style:"measured"===N.status?void 0:{color:"var(--text-muted)"},children:z})]}),null===W?null:(0,r.jsx)("span",{className:"navigator-usage-account",children:W})]}),(0,r.jsx)("span",{className:"navigator-usage-live","aria-live":"polite",children:y})]});return p?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!S,"aria-label":S?`${H}${null===q?"":`, ${q}`}`:u("usage.showLess"),onClick:()=>{let e=!S;C(e);try{window.localStorage.setItem(gs,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:S?B.label:u("usage.showLess")}),S&&(0,r.jsx)("span",{className:"navigator-usage-value",style:B.danger?{color:"var(--danger)"}:void 0,children:B.value}),S&&null!==q&&(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:S?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),S?null:V]}):V}let gp=[{code:"ko",tag:"ko-KR",englishName:"Korean",nativeName:"한국어"},{code:"en",tag:"en-US",englishName:"English",nativeName:"English"},{code:"vi",tag:"vi-VN",englishName:"Vietnamese",nativeName:"Tiếng Việt"},{code:"ja",tag:"ja-JP",englishName:"Japanese",nativeName:"日本語"},{code:"th",tag:"th-TH",englishName:"Thai",nativeName:"ไทย"}];function gh(e){return"string"==typeof e?gp.find(t=>t.code===e):void 0}let gf=/[ăâđêôơưàáạảãằắặẳẵầấậẩẫèéẹẻẽềếệểễìíịỉĩòóọỏõồốộổỗờớợởỡùúụủũừứựửữỳýỵỷỹ]/giu,gm={ko:/[\uac00-\ud7a3\u1100-\u11ff\u3130-\u318f]/gu,ja:/[\u3040-\u30ff\u4e00-\u9fff]/gu,th:/[\u0e00-\u0e7f]/gu,vi:gf,en:/[a-z]/giu};function gg(e,t){let n=gm[t];return!n||"en"===t&&e.match(gf)?0:e.match(n)?.length??0}function gx(e,t,n){let r=gg(e,t.code),i=gg(e,n.code);if(r!==i)return r>i?t:n}function gv(){return{entries:[],open:{user:null,assistant:null},nextId:0,call:0,carry:null,cutOff:null}}let gy=/[.!?。!?…]["'”’)\]」』]*/u,gb=RegExp(`${gy.source}$`,"u");function gw(e){return e.replace(/([.!?])(?=[\p{Lu}\p{Lo}])/gu,"$1 ")}function gk(e,t,n){let{entries:r,nextId:i}=e,a=r.filter(t=>t.call===e.call),s=e.open[t.role];if(null===s){if("user"===t.role){let e=a.at(-1);e&&""===e.original&&(s=e.id)}else{let e=a.filter(e=>""===e.translation);s=(e.findLast(e=>e.heard)??e.at(-1))?.id??null}null===s&&(r=[...r,{id:s=i++,original:"",heard:!1,translation:"",...n,call:e.call}])}let o=gw(t.text),l="user"===t.role?{original:o,heard:t.final}:{translation:o};return r=r.map(e=>e.id===s?{...e,...l}:e),{...e,entries:r,nextId:i,open:{...e.open,[t.role]:t.final?null:s}}}let gj=e=>{fetch(`/api/live/call/${encodeURIComponent(e)}`,{method:"DELETE"}).catch(()=>{})},gS=(e,t)=>`${e.code}>${t.code}`,gC="cuelo-translator";function gN(){let e={mine:gp[0],theirs:gp[1]};try{let t=JSON.parse(window.localStorage.getItem(gC)??"null");if(!t||"object"!=typeof t)return e;let n=gh(t.mine)??e.mine,r=gh(t.theirs)??e.theirs;return n.code===r.code?e:{mine:n,theirs:r}}catch{return e}}function gI(){return(0,r.jsxs)("svg",{width:"22",height:"22",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:"3",width:"6",height:"11",rx:"3"}),(0,r.jsx)("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v3"})]})}function gT({visible:e=!0,onBack:t}){let{tt:n}=et(),[a,o]=(0,i.useState)(gN),{mine:l,theirs:c}=a,[d,u]=(0,i.useState)([]),p=(0,i.useRef)(gv()),[h,f]=(0,i.useState)(0),m=(0,i.useRef)(a),g=(0,i.useRef)(null);(0,i.useEffect)(()=>{window.localStorage.setItem(gC,JSON.stringify({mine:l.code,theirs:c.code}))},[l,c]);let x=function(e){let[t,n]=(0,i.useState)("idle"),[r,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),d=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(!1),y=(0,i.useRef)(!1),b=(0,i.useRef)(!1),w=(0,i.useRef)(void 0),k=(0,i.useRef)(0),j=(0,i.useRef)(e);(0,i.useEffect)(()=>{j.current=e},[e]),(0,i.useEffect)(()=>{c("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let S=(0,i.useCallback)(()=>{k.current+=1;let e=g.current;for(let e of(g.current=null,x.current=null,v.current=!1,y.current=!1,b.current=!1,window.clearTimeout(w.current),w.current=void 0,m.current?.close(),m.current=null,d.current?.close(),d.current=null,u.current=null,p.current=null,h.current?.getTracks()??[]))e.stop();h.current=null;let t=f.current;f.current=null,t&&(t.srcObject=null,t.remove()),e&&gj(e)},[]),C=(0,i.useCallback)(e=>{S(),n(e)},[S]),N=(0,i.useCallback)((e,t)=>{v.current?(a(e),o(t??null),C("error")):S()},[S,C]),I=(0,i.useCallback)(()=>v.current&&y.current&&b.current,[]),T=(0,i.useCallback)(e=>{k.current===e&&I()&&n("live")},[I]),M=(0,i.useCallback)(()=>{let e=p.current,t=f.current;e&&t&&t.srcObject!==e&&(t.srcObject=e)},[]),R=(0,i.useCallback)(async(e,t,r)=>{try{let i,a,s=new RTCPeerConnection;if(d.current=s,u.current=s.addTransceiver("audio",{direction:"sendrecv"}).sender,s.ontrack=t=>{k.current===e&&d.current===s&&(p.current=t.streams[0]??new MediaStream([t.track]),M())},await s.setLocalDescription(await s.createOffer()),await cr(s),k.current!==e)return;let o=s.localDescription?.sdp;if(!o)throw Error("The browser produced no offer SDP.");let l=await fetch("/api/live/interpret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:o,mine:t.code,theirs:r.code})}),c=await l.json().catch(()=>({})),h="",f="";if(c&&"object"==typeof c&&("error"in c&&(i=c.error),"message"in c&&"string"==typeof c.message&&(a=c.message),"callId"in c&&"string"==typeof c.callId&&(h=c.callId),"sdp"in c&&"string"==typeof c.sdp&&(f=c.sdp)),!l.ok||!h||!f){k.current===e&&N(ci(l.status,i),a);return}if(k.current!==e)return void gj(h);if(await s.setRemoteDescription({type:"answer",sdp:f}),k.current!==e){s.close(),gj(h);return}g.current=h;let x=new EventSource(`/api/live/events?callId=${encodeURIComponent(h)}`);m.current=x,x.onmessage=t=>{let r;if(k.current===e){try{r=JSON.parse(t.data)}catch{return}if(r&&"object"==typeof r&&"type"in r){if("state"===r.type&&"state"in r){var i;if("string"!=typeof r.state||(i=r.state,!0!==cn[i]))return;"connecting"===r.state||"live"===r.state||"working"===r.state?I()&&n(r.state):"error"===r.state?N("upstream",r.state):v.current?C(r.state):S();return}if("transcript"===r.type&&"role"in r&&"text"in r&&"final"in r){v.current&&("user"===r.role||"assistant"===r.role)&&"string"==typeof r.text&&j.current({role:r.role,text:r.text,final:!0===r.final});return}"error"===r.type&&"message"in r&&"string"==typeof r.message&&N("upstream",r.message)}}},x.onerror=()=>{k.current===e&&g.current&&N("failed")},y.current=!0,T(e)}catch(t){k.current===e&&N("failed",t instanceof Error?t.message:String(t))}},[M,N,I,S,T,C]),E=(0,i.useCallback)(async e=>{let t;try{t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(n){let t=n instanceof DOMException?n.name:"";k.current===e&&N("NotAllowedError"===t||"SecurityError"===t?"mic-denied":"mic-unavailable");return}let n=u.current;if(k.current!==e||!n){for(let e of t.getTracks())e.stop();return}h.current=t;try{await n.replaceTrack(t.getAudioTracks()[0]??null)}catch(t){k.current===e&&N("failed",t instanceof Error?t.message:String(t));return}k.current===e&&(b.current=!0,M(),T(e))},[M,N,T]),$=(0,i.useCallback)((e,t)=>{let n=gS(e,t);if(x.current===n||v.current)return;S(),x.current=n;let r=k.current;w.current=window.setTimeout(()=>{k.current!==r||v.current||S()},25e3),R(r,e,t)},[R,S]),L=(0,i.useCallback)((e,t)=>{let r=gS(e,t),i=x.current===r&&!v.current&&null!==d.current;i||(S(),x.current=r),window.clearTimeout(w.current),w.current=void 0,v.current=!0;let s=k.current;a(null),o(null),n("connecting");let l=document.createElement("audio");l.autoplay=!0,f.current=l,M(),i||R(s,e,t),E(s)},[E,M,R,S]),P=(0,i.useCallback)(()=>C("idle"),[C]);return(0,i.useEffect)(()=>()=>S(),[S]),{state:t,failure:r,detail:s,supported:l,prepare:$,start:L,stop:P}}((0,i.useCallback)(e=>{p.current=function(e,t,n){var r,i;let a,s;if("assistant"!==t.role)return gk(e,t,n);let o=e.carry;if(null===o&&null===e.open.assistant&&e.cutOff&&(o={...e.cutOff,rest:null}),null===o){if(!t.final)return gk(e,t,n);let r=gk(e,{...t,final:!1},n),i=r.open.assistant,a=r.entries.find(e=>e.id===i),s=void 0!==a&&!gb.test(a.translation.trimEnd())&&r.entries.some(t=>t.call===e.call&&t.id>a.id&&""!==t.original);return{...r,open:{...r.open,assistant:null},cutOff:s?{id:a.id,base:a.translation}:null}}let{id:l,base:c}=o,{rest:d}=o,u=(r=t.text,(s=(a=gy.exec(r))?r.slice(0,a.index+a[0].length):r).length>24?null:{head:s,rest:r.slice(s.length).trim()}),p=u?u.rest:t.text,h=u?(i=u.head,gw(/[\p{Script=Latin}\d]$/u.test(c)&&/^[\p{Script=Latin}\d]/u.test(i)?`${c} ${i}`:c+i)):c,f={...e,entries:e.entries.map(e=>e.id===l?{...e,translation:h}:e)};return p?d=(f=gk({...f,open:{...f.open,assistant:d}},{...t,text:p,final:!1},n)).open.assistant:null!==d&&(f={...f,entries:f.entries.map(e=>e.id===d?{...e,translation:""}:e)}),{...f,open:{...f.open,assistant:t.final?null:d},carry:t.final?null:{id:l,base:c,rest:d},cutOff:null}}(p.current,e,m.current),u(p.current.entries)},[])),v="connecting"===x.state||"live"===x.state||"working"===x.state,y=e=>{var t;m.current=e,p.current={...t=p.current,open:{user:null,assistant:null},call:t.call+1,carry:null,cutOff:null},f(p.current.call),x.start(e.mine,e.theirs)},b=e=>{e.mine.code!==e.theirs.code&&(o(e),v&&y(e))},{prepare:w,stop:k,supported:j}=x;(0,i.useEffect)(()=>{e||k()},[k,e]),(0,i.useEffect)(()=>{e&&!v&&!0===j&&window.isSecureContext&&w(l,c)},[v,l,w,j,c,e]),(0,i.useEffect)(()=>{let e=g.current;e&&(e.scrollTop=e.scrollHeight)},[d]);let S=!1===x.supported,C=!window.isSecureContext,N="error"===x.state&&x.failure?function(e,t,n){switch(t){case"mic-denied":return e("translator.micDenied");case"mic-unavailable":return e("translator.micUnavailable");case"auth":return e("translator.auth");case"upstream":return e("translator.upstream",{error:n??""});default:return e("translator.failed",{error:n??""})}}(n,x.failure,x.detail):C?n("translator.insecure"):S?n("translator.unsupported"):null,I="connecting"===x.state?n("translator.connecting"):"live"===x.state||"working"===x.state?n("translator.live"):"",T=e=>gp.map(t=>(0,r.jsx)("option",{value:t.code,disabled:t.code===e.code,children:t.nativeName},t.code));return(0,r.jsxs)("section",{className:"translator-view","aria-label":n("translator.title"),hidden:!e,children:[(0,r.jsxs)("header",{className:"translator-header",children:[t?(0,r.jsx)(s.r,{variant:"ghost",size:"small",onClick:t,children:n("translator.back")}):null,(0,r.jsx)("h2",{className:"translator-title",children:n("translator.title")}),(0,r.jsxs)("div",{className:"translator-languages",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.me")}),(0,r.jsx)("select",{"aria-label":n("translator.myLanguage"),value:l.code,onChange:e=>{let t=gh(e.target.value);t&&b({mine:t,theirs:c})},children:T(c)})]}),(0,r.jsx)("button",{type:"button",className:"translator-swap","aria-label":n("translator.swap"),title:n("translator.swap"),onClick:()=>b({mine:c,theirs:l}),children:"⇄"}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.them")}),(0,r.jsx)("select",{"aria-label":n("translator.theirLanguage"),value:c.code,onChange:e=>{let t=gh(e.target.value);t&&b({mine:l,theirs:t})},children:T(l)})]})]}),(0,r.jsx)("div",{className:"translator-actions",children:(0,r.jsx)(s.r,{variant:"ghost",size:"small",disabled:0===d.length,onClick:()=>{var e;e=p.current,p.current={...gv(),call:e.call},u([])},children:n("translator.clear")})})]}),N?(0,r.jsx)("p",{className:"translator-banner","data-tone":"error"===x.state?"danger":void 0,role:"error"===x.state?"alert":"status",children:N}):null,(0,r.jsxs)("div",{ref:g,className:"translator-log",role:"log","aria-label":n("translator.conversation"),children:[0===d.length?(0,r.jsx)("p",{className:"translator-empty",children:n("translator.empty")}):null,d.map(e=>{let t=function(e){let t=gx(e.original,e.mine,e.theirs);if(t)return t;let n=gx(e.translation,e.mine,e.theirs);if(n)return n===e.mine?e.theirs:e.mine}(e),i=t?t===e.mine?e.theirs:e.mine:void 0;return(0,r.jsx)("div",{className:"translator-entry","data-side":t===e.mine?"me":"them",children:(0,r.jsxs)("div",{className:"translator-bubble",children:[e.translation?(0,r.jsx)("p",{className:"translator-translation",lang:i?.tag,children:e.translation}):v&&e.call===h?(0,r.jsx)("p",{className:"translator-pending",children:n("translator.translationPending")}):null,e.original?(0,r.jsxs)("p",{className:"translator-original",lang:t?.tag,children:[(0,r.jsxs)("span",{className:"sr-only",children:[n("translator.original"),": "]}),e.original]}):null]})},e.id)})]}),(0,r.jsxs)("div",{className:"translator-dock",children:[(0,r.jsx)("p",{className:"translator-status",role:"status","aria-live":"polite",children:I}),(0,r.jsxs)("button",{type:"button",className:"translator-call-button","aria-pressed":v,disabled:!v&&(S||C||null===x.supported),onClick:()=>v?x.stop():y(a),children:[(0,r.jsx)(gI,{}),v?n("translator.stop"):n("translator.start")]})]})]})}function gM({onOpen:e}){let{tt:t}=et();return(0,r.jsxs)("div",{id:"navigator-translator-panel",className:"translator-panel",children:[(0,r.jsx)("p",{className:"translator-panel-hint",children:t("translator.panelHint")}),e?(0,r.jsx)("button",{type:"button",className:"translator-panel-open",onClick:e,children:t("translator.open")}):null]})}let gR="git pull && bun install && bun run build && node Tools/CUELO_Setup/files/native-runtime-patch.js --target .";function gE(e){return"unknown"===e?e:`v${e}`}function g$(){let{locale:e,t}=(0,F.s)(),n=U(),[a,s]=(0,i.useState)(null),[o,l]=(0,i.useState)("idle"),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),m=(0,i.useRef)(null),g=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),[y,b]=(0,i.useState)(null),w=(0,i.useCallback)(()=>{let e=g.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=c5(e.top,e.bottom,t,c6(t,.72,620),{margin:12,minHeight:0}),i=Math.min(430,window.innerWidth-24),a=Math.max(12,window.innerWidth-i-12);b({left:Math.min(e.right+8,a),width:i,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,i.useEffect)(()=>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 b(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();s(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(m.current??void 0),m.current=null},[]),(0,i.useEffect)(()=>{if(!c)return;let e=e=>{g.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||!a?.updateAvailable||!a.latestRelease)return null;let j=a.latestRelease,S=j.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(j.publishedAt)):null,C=j.body.trim()||j.name,N=async e=>{try{await ni(e),clearTimeout(m.current??void 0),f(e),m.current=setTimeout(()=>f(null),1600)}catch{p(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:g,"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:gE(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:gE(j.version)})]}),c&&y&&(0,_.createPortal)((0,r.jsxs)("div",{ref:x,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:y.left,top:y.top,bottom:y.bottom,zIndex:700,width:y.width,maxHeight:y.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:gE(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:gE(a.currentAppVersion)})}),S&&(0,r.jsx)("span",{children:S})]})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.changelog")}),(0,r.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,r.jsx)(nc,{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:gR}),(0,r.jsx)("button",{type:"button",onClick:()=>void N(gR),title:h===gR?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":h===gR?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===gR?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:h===gR?(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 gL="pi-web:last-open-by-workspace";function gP(){try{return window.localStorage}catch{return null}}function gA(e){let t=e.getItem(gL);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function gF(e,t=gP()){if(t)try{let n=gA(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(gL):t.setItem(gL,JSON.stringify(n))}catch{}}let gz="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",gW="omp-web:wide-chat";function gD(){try{return fR(window.localStorage)}catch{return fR(null)}}function gO(e){let t=document.querySelector(`[data-dispatch-key="${CSS.escape(e)}"]`);return t&&0!==t.getClientRects().length?t.querySelector(".answer-dispatch-open")??t.closest(".answer-dispatch")?.querySelector(".answer-dispatch-toggle")??null:null}function gH({auxiliaryDeck:e,resourcePanel:t}={}){var n,p,f,m,k;let j,S,C,N,I,T,M,R,E,$,L,P,A,z,W,D,_,B,q,V,K=(0,a.useRouter)(),G=(0,a.useSearchParams)(),[J]=(0,i.useState)(()=>{let e;return{requestedCwd:e=G.get("cwd")?.trim()||null,sessionId:e?null:G.get("session")}}),{preference:Z,toggleTheme:Y}=nr(),{locale:X,setLocale:Q,t:ee,supportedLocales:et}=(0,F.s)(),en=function(){let[e,t]=(0,i.useState)(null),[n,r]=(0,i.useState)(!1),a=(0,i.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,i.useEffect)(()=>{try{r("1"===window.localStorage.getItem(fr))}catch{}return a(),window.addEventListener("focus",a),()=>window.removeEventListener("focus",a)},[a]),{permission:e,dismissed:n,request:(0,i.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,a)},[a]),dismiss:(0,i.useCallback)(()=>{r(!0);try{window.localStorage.setItem(fr,"1")}catch{}},[])}}(),er=(0,i.useSyncExternalStore)(O.subscribe,O.getSnapshot,H);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,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:uf(),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.setProperty("--app-viewport-height",`${e.height}px`):t.style.removeProperty("--app-viewport-height");let r=0!==window.scrollX||0!==window.scrollY,i=.01>Math.abs(e.scale-1);r&&i&&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 ei=uw(),ea=U(),{soundEnabled:es,onSoundToggle:eo,playCueSound:el,preloadCueSound:ec,unlockAudio:ed,soundEnabledRef:eu}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),a=(0,i.useRef)(null),s=(0,i.useRef)(0),o=(0,i.useRef)(new Map),l=(0,i.useRef)(new Map),c=(0,i.useRef)(new Map),d=(0,i.useRef)(null);rY();let u=(0,i.useRef)(new Map),p=(0,i.useRef)(new Map),h=(0,i.useRef)(new Map),f=(0,i.useCallback)(e=>{let t=p.current.get(e);return t||(t=gi(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),m=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),g=(0,i.useCallback)(()=>(d.current??=nZ(),d.current),[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async e=>{if(!e)return;let t=await g(),r=ru(e);for(let i of nD){let a=r?nJ(rd(r),r.id,i):nG(t,e,i);if(a){for(let e of a.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 a.voices)f(e).catch(()=>{})}}},[g,f]),v=(0,i.useCallback)(()=>{s.current+=1;let e=a.current;if(a.current=null,e)try{e.stop()}catch{}},[]),y=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=m();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[m]);(0,i.useEffect)(()=>{let e=()=>y(),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)}},[y]);let b=(0,i.useCallback)(()=>{let e=!n.current;e?y(!0):v(),n.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,y]),w=(0,i.useCallback)(e=>{if(!n.current)return;let t=m();if(!t)return;v();let r=s.current,i=()=>{if(r===s.current&&n.current&&(!e||e()))try{gr(t)}catch{}};"suspended"===t.state?t.resume().then(i).catch(()=>{}):i()},[m,v]);return{soundEnabled:e,onSoundToggle:b,playCueSound:(0,i.useCallback)(async(e,t="done",r)=>{let i=await g(),d=ru(e),p=null===t?null:d?nJ(rd(d),d.id,t):nG(i,e,t),h=`${d?.alias??e??""}\u0000${t??""}`,x=p?nY(p.stickers,l.current.get(h)??null):null;null!==x&&l.current.set(h,x);let y=p?nY(p.voices,o.current.get(h)??null):null,b=y?p?.lines.get(y)??null:null;!y&&p&&null!==(b=nY(p.captions,c.current.get(h)??null))&&c.current.set(h,b);let k={sticker:x,text:b};if(!n.current||r&&!r())return k;let j=m();if(!j)return k;if(!y)return null!==t&&nH[t]||w(r),k;v();let S=s.current,C=()=>S!==s.current||!n.current||void 0!==r&&!r();return(async()=>{if(!("suspended"===j.state&&(await j.resume().catch(()=>{}),C())))try{let e=u.current.get(y);e||(e=f(y).then(e=>j.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(y),e}),u.current.set(y,e));let t=await e;if(C())return;let n=j.createBufferSource(),r=j.createGain();n.buffer=t,n.connect(r),r.connect(j.destination),r.gain.setValueAtTime(.82,j.currentTime),n.onended=()=>{a.current===n&&(a.current=null)},a.current=n,n.start(),o.current.set(h,y)}catch{if(C()||null!==t&&nH[t])return;try{gr(j)}catch{}}})(),k},[m,w,v,g,f]),preloadCueSound:x,unlockAudio:y,soundEnabledRef:n}}(),eh=function(){let[e,t]=(0,i.useState)({status:"idle",data:null,error:null}),[n,r]=(0,i.useState)(!0),[a,s]=(0,i.useState)(null),o=(0,i.useRef)(null),l=(0,i.useRef)(null),c=(0,i.useCallback)(()=>{l.current?.abort();let e=new AbortController;l.current=e,r$({signal:e.signal}).then(t=>{e.signal.aborted||s(t)})},[]);(0,i.useEffect)(()=>{var e;let n,i,a,s,d,u,p,h,f,m,g=(i=(e={onResult(e){t(e),r(!1)}}).intervalMs??6e4,a=e.setIntervalImpl??setInterval,s=e.clearIntervalImpl??clearInterval,d=e.initialData??null,u=null,p=0,h=!1,f=!1,m=async t=>{u?.abort(),u=new AbortController;let n=++p,r=await rR({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,m(!1),n=a(()=>{f||m(!1)},i))},refresh:()=>h?m(!0):Promise.resolve(rC(d,new rk("사용량 폴링이 중지되었습니다.","aborted"))),setPaused(e){f=e},stop(){h=!1,p+=1,u?.abort(),u=null,s(n),n=void 0}});return o.current=g,g.start(),c(),()=>{g.stop(),l.current?.abort(),o.current===g&&(o.current=null)}},[c]);let d=(0,i.useCallback)(async()=>{let e=o.current;if(!e)return{status:"error",data:null,error:new rk("사용량 폴링이 시작되지 않았습니다.","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}})(a),[a])}}();n=eh.state.data?.reports,(0,i.useEffect)(()=>{rK(n)},[n]);let[ef,em]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),ev=(0,i.useRef)(new Set),ey=(0,i.useCallback)(()=>{eu.current&&el(null,"done")},[el,eu]),[eb,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(null),eN=(0,i.useRef)(0),eI=(0,i.useRef)(null),[eT,eM]=(0,i.useState)(null),eR=(0,i.useRef)(0),eE=(0,i.useCallback)(e=>{eM(t=>t?.id===e?null:t)},[]),[e$,eL]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{eL("1"===window.localStorage.getItem(gW))}catch{}},[]);let eP=(0,i.useCallback)(()=>{eL(e=>{let t=!e;try{window.localStorage.setItem(gW,t?"1":"0")}catch{}return t})},[]),[eA,eF]=(0,i.useState)(null),[ez,eW]=(0,i.useState)(()=>J.requestedCwd?"validating":"idle"),[eD,eO]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(0),[e_,eB]=(0,i.useState)(0),[eq,eV]=(0,i.useState)(0),[eK,eG]=(0,i.useState)(0),[eJ,eZ]=(0,i.useState)(!1),[eY,eX]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(null),[e1]=(0,i.useState)(()=>{let e;return e=0,{reset(){e+=1,e0(null)},check(t,n){let r=++e;e0("checking"),t().then(t=>{r===e&&e0("fresh"===t.status?function(e,t){if(!t.accountKey)return"unknown";let n=e.filter(e=>e.provider===t.provider&&e.accountKey===t.accountKey);return n.some(e=>!0!==e.disabled&&!e.authError)?"recovered":n.length>0?"still-failing":"unknown"}(t.data.reports,n):"unknown")},()=>{r===e&&e0("unknown")})}}}),[e2,e8]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(0),e6=(0,i.useRef)(null),e3=(0,i.useRef)(null),[e7,e9]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(null),[ti,ta]=(0,i.useReducer)(g,h),[ts,to]=(0,i.useState)("characters"),[tl,tc]=(0,i.useState)("governor"),[td,tu]=(0,i.useState)(()=>x(0)),[tp]=(0,i.useState)(gD),[th]=(0,i.useState)(fE),[tf,tm]=(0,i.useState)([]),[tg,tx]=(0,i.useState)({sessions:[],complete:!1}),[tv,ty]=(0,i.useState)(!1),[tb,tw]=(0,i.useState)(!1),[tk,tj]=(0,i.useState)(0),tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tI=(0,i.useRef)(null),tT=(0,i.useCallback)(()=>{tj(e=>e+1)},[]),tM=(0,i.useCallback)(e=>{e&&ex(!0),em(e),e||tT()},[tT]),tR=(0,i.useCallback)(e=>{tC.current=e},[]),tE=(0,i.useRef)(!1),[t$,tL]=(0,i.useState)(!1),tP=(0,i.useRef)(!1),tA=(0,i.useRef)(!1),tF=(0,i.useRef)(0),[tz,tW]=(0,i.useState)(!1),[tD,tO]=(0,i.useState)(!1),tH=(0,i.useRef)(null),[tU,t_]=(0,i.useState)(null),[tB,tq]=(0,i.useState)(null),tV=(0,i.useRef)(null),tK=(0,i.useRef)(!1);tV.current=tU,(0,i.useEffect)(()=>{t_(d0())},[]),(0,i.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||tE.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=cT();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:dX(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(dV,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:eb?.id??null,resumeUrl:r});if(i.entered){tE.current=!0;return}t=i.error},r=async()=>{if(!e&&!tE.current)try{let i=tK.current?null:tV.current,a=await d2({sessionId:eb?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:i?{requestId:i.requestId,stageHash:i.stageHash}:null});tF.current=0;let s=!!(a.serverBootId&&tH.current&&a.serverBootId!==tH.current);if(tP.current||s){var r=eb?.id??null;cT();try{sessionStorage.setItem(dG,JSON.stringify({schemaVersion:1,sessionId:r,at:Date.now()}))}catch{}window.location.reload();return}a.serverBootId&&(tH.current=a.serverBootId),tA.current=!0,!e&&a.update&&(tq(a.update),a.update.cleanup&&"running"!==a.update.cleanup.status&&(tK.current=!0)),n(a)}catch{tF.current+=1,!e&&tA.current&&tF.current>=2&&(tP.current=!0,tL(!0))}},i=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",i),r();let a=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(a),window.removeEventListener("ompweb:update-maintenance",i)}},[eb?.id]),(0,i.useEffect)(()=>{if(!t$)return;let e=window.setTimeout(()=>tW(!0),12e4);return()=>window.clearTimeout(e)},[t$]),(0,i.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(dG);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(dG),!1):n.sessionId===e&&(sessionStorage.removeItem(dG),!0)})(eb?.id??null)&&tO(!0)},[eb?.id]),(0,i.useEffect)(()=>{if(!tD)return;let e=window.setTimeout(()=>tO(!1),8e3);return()=>window.clearTimeout(e)},[tD]);let tG=tU?.requestId??null,tJ=tU?.dismissed??!0,tZ=tB?.requestId??null,tY=tB?.deploymentCompleted??!1,tX=tB?.cleanup?.status??null;(0,i.useEffect)(()=>{if(!tG||tJ||tZ!==tG||!tY)return;let e=dY(tX);if(null===e)return;let t=window.setTimeout(()=>{t_(d1(tG))},e);return()=>window.clearTimeout(t)},[tG,tJ,tZ,tY,tX]),(0,i.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(dV);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&&eb?.id!==e.sessionId)return;let t=!1;return d4(e).then(e=>{t||"resumed"!==e||(tK.current=!1,t_(d0()),eU(e=>e+1),eV(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[eb?.id]);let tQ=(0,i.useCallback)(e=>{if("Tab"!==e.key)return;let t=tI.current;if(!t)return;let n=Array.from(t.querySelectorAll(gz));if(0===n.length)return;let r=e.shiftKey?n[0]:n[n.length-1],i=document.activeElement;i!==r&&t.contains(i)||(e.preventDefault(),(e.shiftKey?n[n.length-1]:n[0]).focus())},[]),[t0,t1]=(0,i.useState)(!0),[t2,t8]=(0,i.useState)(!1),[t4,t5]=(0,i.useState)(!1),t6=(0,i.useRef)(t0),t3=(0,i.useRef)(!1),t7=(0,i.useRef)(!0),t9=(0,i.useRef)(null);t6.current=t0;let ne=(j=(p={clientPainted:t2,compactWorkspace:er,requestedOpen:t0}).requestedOpen&&p.clientPainted,{laidOut:p.requestedOpen&&(!p.compactWorkspace||p.clientPainted),presented:j,drawer:j&&p.compactWorkspace}),nt=(0,i.useCallback)(e=>{t3.current=e,t1(e),ta(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),nn=(0,i.useRef)(null),na=(0,i.useRef)(!1),ns=(0,i.useRef)(260),no=(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}),[]),nl=function(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:a,getMaxWidth:s,growthDirection:o,maxWidth:l,minWidth:c,storageKey:d,widthRef:u}=e,p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(!1),[m,g]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),y=(0,i.useCallback)(()=>Math.min(l,Math.max(c,s())),[s,l,c]),b=(0,i.useCallback)(e=>{var t;let n,r;return t=y(),n=Number.isFinite(e)?e:c,r=Math.max(c,t),Math.round(Math.max(c,Math.min(r,n)))},[y,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=b(e),a=i!==u.current;return w(i),g(i),r&&(a||n)&&gn(d,i),i},[w,b,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]),N=(0,i.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let n="right"===o?1:-1,r=b(t.startWidth+(e.clientX-t.startX)*n);w(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[w,b,S,o]),I=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),T=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,i.useCallback)(e=>{S(e.pointerId)},[S]),R=(0,i.useCallback)(()=>{k(a?.()??r,{forcePersist:!0})},[k,r,a]),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(y(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),R())},[k,y,o,c,R,u]);return(0,i.useEffect)(()=>{if(f.current)return;f.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??a?.()??r,{persist:!1});null!==e&&e!==t&&gn(d,t)},[k,r,a,d]),(0,i.useEffect)(()=>{if(!f.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:R,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":y(),"aria-valuemin":c,"aria-valuenow":m,"aria-valuetext":`${m} px`,onDoubleClick:R,onKeyDown:$,onLostPointerCapture:M,onPointerCancel:T,onPointerDown:C,onPointerMove:N,onPointerUp:I,role:"separator",tabIndex:0},width:m}}({ariaLabel:ee("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:no,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:ns}),nc=nl.reclampWidth;(0,i.useEffect)(()=>{let e=t9.current;if(e===er)return;t5(!0),null!==e&&(e?t3.current=t6.current:t7.current=t6.current),t9.current=er;let t=er?t3.current:t7.current;er?nt(t):t1(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>t5(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[er,nt]),(0,i.useEffect)(()=>{t8(!0)},[]),(0,i.useEffect)(()=>{let e=na.current;if(na.current=ne.drawer,ne.drawer){let e=nl.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(gz)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||nn.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[ne.drawer,nl.panelRef]),(0,i.useEffect)(()=>{nc()},[nc,ti.activeView]),(0,i.useEffect)(()=>{let e=tS.current;if(!e)return;let t=e=>{tu(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(!tk)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>tC.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[tk]),(0,i.useEffect)(()=>{if("command-palette"!==ti.transientLayer)return;let e=tI.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(gz)?.focus()});return()=>cancelAnimationFrame(t)},[ti.transientLayer]),(0,i.useEffect)(()=>{er||"navigator-drawer"!==ti.transientLayer||ta({type:"close-layer"})},[er,ti.transientLayer]),(0,i.useEffect)(()=>{let e=new AbortController;return tx(e=>({...e,complete:!1})),fetch("/api/sessions",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t.sessions))throw Error("Invalid session census");tm(t.sessions),tx({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()},[eH,eb?.id]);let nd=(0,i.useRef)(null),nu=(0,i.useRef)(null),[nh,nf]=(0,i.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),nm=(0,i.useRef)(null),ng=(0,i.useCallback)((e,t,n)=>{nm.current=n,nf(n=>{let r=n$.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),nx=(0,i.useCallback)(e=>{nf(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),nm.current?.(e)},[]),[nv,ny]=(0,i.useState)(null),nb=(0,i.useCallback)(e=>{ny(e)},[]),[nw,nk]=(0,i.useState)(null),[nj,nS]=(0,i.useState)([]),[nC,nN]=(0,i.useState)(null),[nI,nT]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let n=await t.json(),r=n.fields?.find(e=>"task.maxConcurrency"===e.path),i=r?.value??r?.defaultValue,a="number"==typeof i?i:"string"==typeof i?Number.parseInt(i,10):NaN;!e.signal.aborted&&Number.isFinite(a)&&a>0&&nN(a)}).catch(()=>{}),()=>e.abort()},[]);let[nM,nR]=(0,i.useState)({kind:"idle"}),nE=(0,i.useRef)(null),n$=(0,i.useRef)(eb?.id??null);n$.current=eb?.id??null;let nL=(0,i.useCallback)(e=>{nk(e)},[]),[nP,nA]=(0,i.useState)(null),nF=(0,i.useRef)(null),nz=(0,i.useCallback)((e,t)=>{ni(t).then(()=>{nF.current&&clearTimeout(nF.current),nA(e),nF.current=setTimeout(()=>nA(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nF.current&&clearTimeout(nF.current),nE.current&&clearTimeout(nE.current)},[]),(0,i.useEffect)(()=>()=>eI.current?.abort(),[]);let[nW,nO]=(0,i.useState)(null),nU=(0,i.useCallback)(e=>{nO(e)},[]),[n_,nB]=(0,i.useState)(null),[nq,nV]=(0,i.useState)(null),[nK,nX]=(0,i.useState)(null),[nQ,n0]=(0,i.useState)(!1),[n1,n2]=(0,i.useState)("subagents"),n8=(0,i.useCallback)((e,t=!1)=>{ta({type:"select-view",view:e}),nV(null),er&&nt(!1),(t||"chat"===e)&&tT()},[er,tT,nt]),n4=(0,i.useRef)(!1),n5=(0,i.useCallback)(()=>{n4.current=!0,ta({type:"set-deck-expanded",expanded:!ti.deckExpanded})},[ti.deckExpanded]);(0,i.useEffect)(()=>{if(!n4.current)return;n4.current=!1;let e=requestAnimationFrame(()=>{[...document.querySelectorAll("#workspace-auxiliary-panel [data-panel-expand]")].find(e=>e.getClientRects().length>0)?.focus()});return()=>cancelAnimationFrame(e)},[ti.deckExpanded]);let[n6,n3]=(0,i.useState)(null),n7=(0,i.useCallback)((e,t=!0)=>{n3(e),t&&n8("subagents")},[n8]),n9=eb?.id??null;(0,i.useEffect)(()=>{n3(null)},[n9]);let[re,rt]=(0,i.useState)(null),rn=(0,i.useCallback)(e=>{gO(e)||(ti.deckExpanded&&"pinned"===td.deck?ta({type:"set-deck-expanded",expanded:!1}):ta({type:"select-view",view:"chat"})),rt(e)},[td.deck,ti.deckExpanded]);(0,i.useEffect)(()=>{if(!re)return;let e=requestAnimationFrame(()=>{gO(re)?.focus(),rt(null)});return()=>cancelAnimationFrame(e)},[re]);let rr=(0,i.useCallback)(e=>{let t=ti.transientLayer===e;nV(null),er&&"navigator-drawer"===ti.transientLayer&&nt(!1),ta({type:"toggle-layer",layer:e}),t&&tT()},[er,tT,nt,ti.transientLayer]),ri=(0,i.useCallback)(()=>{if("chat"!==ti.activeView){n2(ti.activeView),n8("chat",!0);return}n8(n1,!0)},[n1,n8,ti.activeView]),ra=(0,i.useCallback)(e=>{nV(null),ta({type:"close-layer"}),er&&nt(!1),e1.reset(),eX(e)},[er,e1,nt]),rs=(0,i.useCallback)(()=>{e1.reset(),eX(null),tT()},[e1,tT]),ro=eh.refresh,rl=(0,i.useCallback)(()=>{null!==eY&&e1.check(ro,eY)},[ro,e1,eY]),rc=(0,i.useCallback)(()=>e7?(te||(e9(!1),tT()),!0):null!==eY?(rs(),!0):eJ?(eZ(!1),tT(),!0):nQ?(n0(!1),tT(),!0):nq?(nV(null),tT(),!0):ti.transientLayer?("navigator-drawer"===ti.transientLayer&&nt(!1),ta({type:"close-layer"}),tT(),!0):ti.deckExpanded&&"pinned"===td.deck&&document.activeElement?.closest("#workspace-auxiliary-panel")?(n4.current=!0,ta({type:"set-deck-expanded",expanded:!1}),!0):"chat"!==ti.activeView&&(ta({type:"select-view",view:"chat"}),tT(),!0),[rs,nQ,eY,nq,te,e7,tT,nt,eJ,ti.activeView,ti.transientLayer,ti.deckExpanded,td.deck]),rp=(0,i.useCallback)(e=>{ta({type:"close-layer"}),er&&nt(!1),nV(t=>t===e?null:e)},[er,nt]),rh=(0,i.useCallback)(()=>{ta({type:"close-layer"}),er&&nt(!1),nV("session")},[er,nt]),rf=(0,i.useCallback)(()=>{if(nV(null),er){let e="navigator-drawer"!==ti.transientLayer;nt(e),e||tT();return}ta({type:"close-layer"}),t1(e=>{let t=!e;return t7.current=t,t})},[er,tT,nt,ti.transientLayer]);(0,i.useEffect)(()=>{if(!nq||!nu.current)return;let e=()=>{let e=nu.current.getBoundingClientRect();nX({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(nu.current),()=>t.disconnect()},[nq]);let[rm,rg]=(0,i.useState)([]),[rx,rv]=(0,i.useState)(null),ry=(0,i.useRef)(new Map),rb=(0,i.useCallback)(()=>{"view-stack"===td.deck&&ta({type:"select-view",view:"chat"}),er&&nt(!1),tT()},[er,td.deck,tT,nt]),rw=(0,i.useCallback)((e,t)=>{nd.current?.insertText(c1(e,t)),rb()},[rb]),rj=(0,i.useCallback)((e,t,n)=>{nd.current?.insertText(c2(e,t,n)),rb()},[rb]),rS=(0,i.useCallback)((e,t)=>{let n=nd.current;return!!n&&(n.addAttachments(e),t&&n.insertText(t),rb(),!0)},[rb]),rN=(0,i.useCallback)(e=>{nd.current?.insertText(e),rb()},[rb]),rI=J.sessionId,[rT,rM]=(0,i.useState)(null);nr({cwd:eb?.cwd??eA??rT,syncWithOmp:!0});let rE=(0,i.useRef)(null),[rL,rP]=(0,i.useState)(()=>!rI),rA=(0,i.useRef)(!1),rF=(0,i.useRef)(0),rz=(0,i.useCallback)(()=>{rF.current+=1},[]);(0,i.useEffect)(()=>{eb&&function(e,t,n=gP()){if(n)try{let r=gA(n);r[e]=t,n.setItem(gL,JSON.stringify(r))}catch{}}(eb.projectRoot??rE.current??eb.cwd,eb.id)},[eb]),(0,i.useEffect)(()=>{let e=J.requestedCwd;if(!e)return;let t=new AbortController;return eW("validating"),eO(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}`);rA.current=!0,eF(t.cwd),eW("ready")}).catch(e=>{t.signal.aborted||(eO(e instanceof Error?e.message:String(e)),eW("error"))}),()=>t.abort()},[J]);let rW=(0,i.useCallback)(e=>{let t=++rF.current,n=function(e,t=gP()){if(!t)return null;try{let n=gA(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!==rF.current)return;let i=r?.sessions.find(e=>e.id===n);if(!i){r&&gF(e);return}(i.projectRoot??i.cwd)!==e?gF(e):(ew(i),eB(e=>e+1),new URLSearchParams(window.location.search).get("session")!==i.id&&K.replace(`?session=${encodeURIComponent(i.id)}`,{scroll:!1}))}).catch(()=>{})},[K]),rD=(0,i.useCallback)((e,t)=>{if(rz(),rM(e),!e)return;let n=t??e,r=rE.current??(eb?eb.projectRoot??eb.cwd:null);if(rE.current=n,rA.current){rA.current=!1;return}r!==n&&(eN.current+=1,eI.current?.abort(),eI.current=null,ej(null),eC(null),ew(null),eF(t=>t&&t!==e?null:t),eB(e=>e+1),nf({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nV(null),rg([]),rv(null),ta({type:"select-view",view:"chat"}),rW(n),K.replace("/",{scroll:!1}))},["/",K,eb,rz,rW]),rO=(0,i.useCallback)((e,t,n)=>{eF(null),eC(n),ew(e),nf({sessionId:e.id,tree:[],leafId:null,navigation:0}),eB(e=>e+1),ny(null),rP(!0),er&&!t&&(nt(!1),ta({type:"select-view",view:"chat"})),t&&(rA.current=!0),t||K.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[er,K,nt]),rH=(0,i.useCallback)((e,t=!1)=>{if(rE.current=e.projectRoot??e.cwd,rz(),!t&&eb){let t=(eb.projectRoot??eb.cwd)===(e.projectRoot??e.cwd);if(eb.id===e.id&&t){eN.current+=1,eI.current?.abort(),eI.current=null,ej(null),er&&nt(!1);return}}if(!t&&ek?.id===e.id)return;eN.current+=1;let n=eN.current;if(eI.current?.abort(),t||!eb){eI.current=null,ej(null),rO(e,t,null);return}let r=new AbortController;eI.current=r,ej(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");eN.current===n&&rO(e,!1,r)}).catch(t=>{r.signal.aborted||eN.current!==n||(console.error("Failed to preload session before switching:",t),rO(e,!1,null))}).finally(()=>{eN.current===n&&(eI.current=null,ej(null))})},[rO,rz,er,ek?.id,eb,nt]),rU=(0,i.useCallback)((e,t)=>{eN.current+=1,eI.current?.abort(),eI.current=null,ej(null),eC(null),rz(),ew(null),eF(t),eB(e=>e+1),nf({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nV(null),ta({type:"select-view",view:"chat"}),er&&nt(!1),K.replace("/",{scroll:!1})},["/",rz,er,K,nt]),r_=(0,i.useCallback)(e=>{let t=eb?.projectRoot??rE.current??eb?.cwd??rT;if(!t||!eb)return;let n=tf.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===eb.id);if(r<0)return;let i=n[r+e];i&&(nV(null),ta({type:"close-layer"}),rH(i),tT())},[rT,tf,rH,tT,eb]);f={onNewSession:e=>rU(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>rr("command-palette"),onToggleNavigator:rf,onToggleResources:()=>n8("resource"===ti.activeView?"chat":"resource",!0),onSelectView:e=>n8(e,!0),onCycleView:(0,i.useCallback)(e=>{let t=(d.indexOf(ti.activeView)+e+d.length)%d.length;n8(d[t],!0)},[n8,ti.activeView]),onNavigateSession:r_,onEscape:rc,enabled:!eJ&&!e7&&null===eY,activeCwd:rT},(S=(0,i.useRef)(f)).current=f,(0,i.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let n=t.now?.()??Date.now();if(y||e.isComposing||229===e.keyCode||n-b<100)return;let r=e.target,i="u">typeof Element&&r instanceof Element?r:null,a=!!i?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!i?.closest("[data-dismissible-layer], [data-capture-keys], [role='listbox'], [role='menu'], [role='combobox'][aria-expanded='true'], [aria-haspopup][aria-expanded='true']")&&(t.onEscape?.()?(e.preventDefault(),e.stopPropagation()):!(a||i?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(i?.closest("[data-capture-keys]")||!1===t.enabled)return;let s=e.key.toLowerCase(),o=(e.ctrlKey||e.metaKey)&&!e.altKey;if(o&&!e.shiftKey&&"k"===s)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(o&&!e.shiftKey&&"b"===s)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(o&&!e.shiftKey&&"u"===s)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(o&&!e.shiftKey&&/^[1-7]$/.test(s)){if(!t.onSelectView)return;let n=d[Number(s)-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"===s&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,S.current)},t=()=>w(!0),n=()=>w(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",n,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",n,{capture:!0})}},[]);let rB=(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&&ew(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),rq=(0,i.useCallback)(e=>{rz(),eF(null),ew(e),eU(e=>e+1),rB(e.id),K.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[rz,K,rB]),rV=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&dU({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&rH(e)}})},[rH]),rG=(0,i.useCallback)(e=>{eU(e=>e+1),e6.current?.pending&&e5(e=>e+1),eV(e=>e+1),eb&&rB(eb.id),"completed"===e.outcome&&dO()&&rV({targetSession:eb,title:eb?.name??ee("i18n.sessionComplete"),body:ee("i18n.taskFinished")})},[rV,rB,eb,ee]),rJ=(0,i.useCallback)(e=>{var t;dO()&&(t=ev.current,!(!dH(e)||t.has(e.id))&&(t.add(e.id),1)&&rV({targetSession:eb,title:ee("i18n.attentionNeeded"),body:"custom"===e.method?ee("i18n.extensionInputNeeded"):"ask"===e.method?e.questions[0]?.question||ee("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[rV,eb,ee]),rZ=(0,i.useCallback)(async()=>{let e=eb?.id;if(e&&"naming"!==nM.kind){nE.current&&clearTimeout(nE.current),nV(null),nR({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(eU(e=>e+1),n$.current!==e)return;ew(t=>t?.id===e?{...t,name:r}:t),nk(t=>t?.sessionId===e?{...t,sessionName:r}:t),nR({kind:"success"}),nE.current=setTimeout(()=>nR({kind:"idle"}),1800)}catch(t){if(n$.current!==e)return;nR({kind:"error",message:t instanceof Error?t.message:String(t)}),nE.current=setTimeout(()=>nR({kind:"idle"}),5e3)}}},[nM.kind,eb?.id]);(0,i.useEffect)(()=>{nE.current&&clearTimeout(nE.current),nR({kind:"idle"})},[eb?.id]);let rX=(0,i.useCallback)(e=>{rz(),eU(e=>e+1),eB(e=>e+1),eF(null),ew(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),rB(e),K.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[rz,K,rB]),rQ=(0,i.useCallback)(()=>{rP(!0)},[]),r0=(0,i.useCallback)(e=>{if(rz(),eU(e=>e+1),eb?.id===e){let e=eb.cwd;ew(null),eF(e??null),eB(e=>e+1),nf({sessionId:null,tree:[],leafId:null,navigation:0}),ny(null),nV(null),ta({type:"select-view",view:"chat"}),tT(),K.replace("/",{scroll:!1})}},["/",rz,tT,eb,K]),r1=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,a=`file:${e}`;i&&ry.current.delete(a),rg(n=>{let s=n.find(e=>e.id===a);if(!s)return[...n,{id:a,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:i}];let o=!r||s.sourceSessionId===r,l=!i||s.initialDisplayMode===i;return o&&l?n:n.map(e=>{if(e.id!==a)return e;let t={...e};return r&&(t.sourceSessionId=r),i&&(t.initialDisplayMode=i),t})}),rv(a),ta({type:"select-view",view:"files"}),nV(null),er&&nt(!1)},[er,nt]),r2=(0,i.useCallback)(e=>{r1(e,tN(e),{sourceSessionId:eb?.id??null})},[r1,eb?.id]),r8=(0,i.useCallback)(e=>{ry.current.delete(e);let t=rm.filter(t=>t.id!==e);rg(t),rv(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===ti.activeView&&n8("chat",!0)},[rm,n8,ti.activeView]),r4=(0,i.useCallback)(()=>{eb&&window.open(`/api/sessions/${encodeURIComponent(eb.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[eb]),r5=eA??(null===eb&&rT?rT:null),r6=null!==eb||null!==r5,r3="chat"!==ti.activeView,r7=eb?.cwd??r5,r9=rL&&!r6,ie=(0,i.useCallback)((e,t)=>{e6.current=e,e8(e),tr(e.error?ee("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&e9(!1),eG(e=>e+1),eB(e=>e+1))},[ee]);(0,i.useEffect)(()=>{let e=e3.current!==r7;if(e3.current=r7,e&&(e6.current=null,e8(null),e9(!1),tr(null)),!r7)return;let t=e6.current,n=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(r7)}`,{signal:n.signal}).then(async e=>{let n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);ie(n,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>n.abort()},[ie,r7,e4]);let it=(0,i.useCallback)(async e=>{if(r7&&!te){tt(!0),tr(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r7,action:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let r=e6.current;ie(n,r),(n.trusted||"cancel"===e)&&(e9(!1),tT())}catch(e){tr(e instanceof Error?e.message:String(e))}finally{tt(!1)}}},[ie,te,r7,tT]),ir=rm.find(e=>e.id===rx)??null,ii=rT?tN(rT)||rT:null,ia=eb?.cwd??r5,is=ia?tN(ia)||ia:null,io=(eb?.name?.trim()||eb?.firstMessage?.trim()||(r5?ee("i18n.newSession"):ii)||"CUELO").replace(/\s+/g," ").trim(),il=io.length>96?`${io.slice(0,93)}…`:io,ic=ii?`${il} — ${ii} — CUELO`:`${il} — CUELO`,id=ii?`${io} — ${ii}`:io,iu=eb?.transient?`${id} \xb7 ${ee("session.inMemory")}`:id,ip=nj.filter(e=>"pending"===e.status||"running"===e.status).length,ih=nI?ee("workspace.mainAttention"):tb?ee("workspace.mainWaiting"):tv?ee("workspace.mainWorking"):ee("workspace.mainIdle"),im=`${nI?"⚠":tb?"○":tv?"●":"○"} Main ${ih} \xb7 Sub ${ip}${nC?`/${nC}`:""}`,ig=(0,i.useCallback)(e=>n8(e,!0),[n8]),ix=(N=(C=(m={deckVisible:r3,pinDecision:td,deckExpanded:ti.deckExpanded}).deckVisible&&"pinned"===m.pinDecision.deck)&&m.deckExpanded,{replacesTranscript:m.deckVisible&&("view-stack"===m.pinDecision.deck||N),expandable:C,expanded:N,staleExpansion:m.deckExpanded&&!C}),iv=ix.replacesTranscript,iy=ix.expandable?{expanded:ix.expanded,onToggle:n5}:null,ib=ix.staleExpansion;(0,i.useEffect)(()=>{ib&&ta({type:"set-deck-expanded",expanded:!1})},[ib]),(0,i.useEffect)(()=>{let e=()=>{document.title!==ic&&(document.title=ic)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[ic]);let iw="ko"===X?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat"},ik="chat"!==ti.activeView,ij=ik?iw[ti.activeView]:iw[n1],iS=(I=nW&&Number.isFinite(nW.contextWindow)&&nW.contextWindow>0?nW.contextWindow:null,T=nW&&"number"==typeof nW.tokens&&Number.isFinite(nW.tokens)?Math.max(0,nW.tokens):null,R=null===(M=nW&&"number"==typeof nW.percent&&Number.isFinite(nW.percent)?nW.percent:null!==T&&null!==I?T/I*100:null)?"normal":M>90?"critical":M>70?"warning":"normal",E=null===T?"?":gt(T),$=null===I?"?":gt(I),L=null===M?"?":`${M.toFixed(0)}%`,{level:R,percent:M,fillPercent:null===M?0:Math.min(100,Math.max(0,M)),readout:null===I?null:`${L} \xb7 ${E}/${$}`,usedLabel:E,limitLabel:$,percentLabel:L}),iC=iS.readout,iN=iC?ee("chat.contextUsageTitle",{used:iS.usedLabel,limit:iS.limitLabel,percent:iS.percentLabel}):null,iI="critical"===iS.level?ee("chat.contextUsageCritical"):"warning"===iS.level?ee("chat.contextUsageWarning"):null,iT=(k=nw?.userMessages,!eb||eb.transient?"unsaved":("number"==typeof k?k:0)>0||eb.messageCount>0?null:"no-messages"),iM="unsaved"===iT?ee("title.unsaved"):"no-messages"===iT?ee("title.noMessages"):null,iR=iM??("error"===nM.kind?nM.message:null),iE="naming"===nM.kind?ee("title.generating"):"success"===nM.kind?ee("title.updated"):"error"===nM.kind?ee("title.failed"):ee("title.generate"),i$=(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)(pg,{tabs:rm,activeTabId:rx??"",onSelectTab:rv,onCloseTab:r8})}),(0,r.jsx)("div",{className:"workspace-file-content",children:ir?.filePath?(0,r.jsx)(pf,{filePath:ir.filePath,cwd:rT??void 0,sourceSessionId:ir.sourceSessionId,gitRefreshKey:eq,initialDisplayMode:ir.initialDisplayMode,viewStateStore:ry.current,viewStateKey:ir.id,onMentionLines:rj,onAtMention:rw,onInsertText:rN,onOpenFile:e=>r1(e,tN(e),{sourceSessionId:ir.sourceSessionId})},ir.id):(0,r.jsx)("div",{className:"workspace-file-empty",children:(0,r.jsx)(m6,{cwd:eb?.cwd??rT,onOpenFile:r2})})})]}),iL=(0,r.jsx)(mt,{open:"resource"===ti.activeView,sessionId:eb?.id??null,activeTab:ts,onTabChange:to,usage:eh}),iP=(0,r.jsx)(m5,{open:"efficiency"===ti.activeView,sessionId:eb?.id??null,activeTab:tl,onTabChange:tc}),iA=(0,r.jsx)(fk,{title:iw.process,data:n_,onOpenFile:r2}),iF=eb?eb.path?eb.path:nw?.sessionId===eb.id&&nw.sessionFile?nw.sessionFile:null:null,iz=(0,r.jsx)(fO,{title:iw.sidechat,sessionId:eb?.id??null,sessionPath:iF,sessionName:eb?.name,historyStore:tp,flights:th,sessionCensus:tg,visible:"sidechat"===ti.activeView}),iW=r3?(0,r.jsx)(fw,{activeView:ti.activeView,onViewChange:e=>n8(e),viewLabels:iw,sessionId:eb?.id??null,sessionPath:iF,sessionName:eb?.name,sessionCwd:eb?.cwd??r5??void 0,liveSubagents:nj,processSlot:iA,fileSlot:i$,sideChatSlot:iz,resourceSlot:t??iL,efficiencySlot:iP,visible:!0,onClose:()=>ta({type:"select-view",view:"chat"}),onReturnFocus:tT,expand:iy,selectedMaker:n6,onSelectMaker:n3,onReturnToDispatch:rn,onOpenFile:r2,fileOpen:!!ir?.filePath}):null,iD=e??iW,iO=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ep,{selectedSessionId:ek?.id??eb?.id??null,optimisticSession:ek??eb,onSelectSession:rH,onNewSession:rU,initialSessionId:rI,skipInitialProjectSelection:null!==J.requestedCwd,onInitialRestoreDone:rQ,refreshKey:eH,onSessionDeleted:r0,selectedCwd:eb?.cwd??eA??null,onCwdChange:rD,onBackgroundTaskDone:ey,translatorPanel:(0,r.jsx)(gM,{onOpen:er?()=>nt(!1):void 0}),translatorActive:ef,onTranslatorActiveChange:tM}),(0,r.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[(0,r.jsx)(gu,{usage:eh,onOpen:()=>{to("usage"),n8("resource",!1)},onRelogin:ra}),(0,r.jsx)(g$,{}),(0,r.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{nV(null),ta({type:"close-layer"}),er&&nt(!1),eZ(!0)},title:ee("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"})]}),ee("common.settings")]})]})]}),iH=tU&&tB&&tB.requestId===tU.requestId&&tB.deploymentCompleted?tB:null,iU=iH?.cleanup??null,i_=iH&&!tU?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:dY(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:dY(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:dY(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:dY(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:dY(e.status)}}(iU):null;return(0,r.jsxs)(np.Provider,{value:rS,children:[t$?(0,r.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,r.jsxs)("div",{className:"server-restart-card",children:[(0,r.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,r.jsx)("strong",{children:ee("restart.title")}),(0,r.jsx)("span",{children:ee(tz?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:tS,className:"workspace-shell","data-active-view":ti.activeView,"data-deck-mode":td.deck,"data-deck-visible":r3,"data-chat-wide":e$?"true":void 0,children:[(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${ne.drawer?" is-open":""}${t2?"":" sidebar-mobile-pending"}${t4?" sidebar-mode-shift":""}`,onClick:()=>{nt(!1),tT()}}),(0,r.jsx)("div",{ref:nl.panelRef,id:"session-sidebar",className:`sidebar-container${ne.laidOut?" sidebar-open":" sidebar-closed"}${t2?"":" sidebar-mobile-pending"}${t4?" sidebar-mode-shift":""}${nl.isResizing?" sidebar-resizing":""}`,"aria-hidden":er&&!ne.presented,inert:er&&!ne.presented,style:{"--sidebar-width":`${nl.width}px`},children:iO}),ne.laidOut&&(0,r.jsx)("div",{...nl.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${nl.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${ee("layout.resizeSidebar")}: ${ee("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":ti.activeView,"aria-hidden":ne.drawer,inert:ne.drawer,children:[(0,r.jsxs)("div",{ref:nu,className:"workspace-header-stack","data-soft-keyboard":ei&&ea?"open":void 0,children:[i_&&tU&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":i_.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:i_.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:i_.detail}),i_.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>t_(d1(tU.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tD&&!(i_&&tU)&&(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:ee("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:ee("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tO(!1),"aria-label":ee("restart.returnedDismiss"),children:ee("i18n.close")})]}),(0,r.jsx)(fi,{variant:"banner",locale:X,...en}),(0,r.jsxs)("header",{className:"workspace-header-seam",children:[(0,r.jsx)(s.r,{ref:nn,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:rf,"aria-controls":"session-sidebar","aria-expanded":ne.presented,title:ne.presented?ee("sidebar.hide"):ee("sidebar.show"),"aria-label":ne.presented?ee("sidebar.hide"):ee("sidebar.show"),children:ne.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:iu,children:[(0,r.jsxs)("div",{className:"workspace-session-identity-line",children:[is&&(0,r.jsx)("em",{className:"workspace-session-project",children:is}),(0,r.jsx)("strong",{children:il})]}),(0,r.jsx)("span",{className:"workspace-session-status","aria-live":"polite",children:im})]}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===nM.kind?nM.message:""}),r6&&e2?.requiresTrust&&!e2.trusted&&(0,r.jsxs)(s.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{tr(e2.error?ee("trust.applyFailed",{error:e2.error}):null),nV(null),ta({type:"close-layer"}),e9(!0),e2.pending&&e5(e=>e+1)},title:ee("grant"===e2.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":ee("grant"===e2.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"})]}),!er&&(0,r.jsx)("span",{children:ee("trust.resourcesNotLoaded")})]}),r6&&iC&&(0,r.jsxs)(s.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:rh,"aria-expanded":"session"===nq,title:iN??ee("session.title"),"aria-label":iI?`${iN}. ${iI}`:iN??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":iS.level,style:{inlineSize:`${iS.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":iS.level,children:iC})]}),r6&&(0,r.jsx)(l.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:ik,onPressedChange:ri,"aria-controls":"workspace-auxiliary-panel",title:"ko"===X?"보조 패널":"Auxiliary panel",children:(0,r.jsx)("span",{className:"workspace-panel-toggle-label",children:ij})}),(0,r.jsxs)(c.k.Root,{open:nQ,onOpenChange:e=>n0(e),placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===X?"더 보기":"More","aria-label":"ko"===X?"더 보기":"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"===X?"세션 및 환경 메뉴":"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"===X?"세션":"Session"}),(0,r.jsx)(c.k.Item,{onClick:rh,children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("session.title")})})}),(0,r.jsx)(c.k.Item,{onClick:r4,disabled:!eb,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:ee("history.label")}),!eb&&(0,r.jsx)(c.k.ItemDescription,{children:ee("history.unsaved")})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>void rZ(),disabled:null!==iM||"naming"===nM.kind,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:iE}),iR&&(0,r.jsx)(c.k.ItemDescription,{children:iR})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>rp("branches"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("i18n.branches")})})}),(0,r.jsx)(c.k.Item,{onClick:()=>rp("system"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("system.label")})})})]}),(0,r.jsxs)(c.k.Group,{children:[(0,r.jsx)(c.k.GroupLabel,{children:"ko"===X?"환경":"Environment"}),(0,r.jsx)(fi,{variant:"menu",locale:X,...en}),(0,r.jsx)(c.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();Y({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("light"===Z?"theme.light":"dark"===Z?"theme.dark":"theme.auto")})})}),et.map(e=>(0,r.jsx)(c.k.Item,{role:"menuitemradio","aria-checked":X===e.id,onClick:()=>Q(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:()=>{nV(null),ta({type:"close-layer"}),er&&nt(!1),eZ(!0)},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:ee("common.settings")})})})]})]})})})]})]}),nq&&nK&&(0,r.jsxs)("div",{style:{position:"fixed",top:nK.top,left:nK.left,width:nK.width,maxHeight:`calc(100dvh - ${nK.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===nq&&(0,r.jsx)("div",{className:"workspace-top-panel","aria-label":ee("i18n.branches"),children:(0,r.jsx)(ge,{tree:nh.sessionId===(eb?.id??null)?nh.tree:[],activeLeafId:nh.sessionId===(eb?.id??null)?nh.leafId:null,onLeafChange:nx,hasSession:!!eb})}),"system"===nq&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:nv?(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:nv}):""===nv?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:ee("system.empty")}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:ee("system.load")})}),"session"===nq&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:nw?(P=nw.totalActiveMs??0,A=[...nw.sessionName?[{label:ee("session.name"),value:nw.sessionName,copyField:null}]:[],{label:ee("session.file"),value:nw.sessionFile??ee("session.inMemory"),copyField:"file"},{label:ee("session.id"),value:nw.sessionId,copyField:"id"},...P>0?[{label:ee("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`})(P),copyField:null}]:[]],z=[[ee("session.user"),nw.userMessages.toLocaleString(X)],[ee("session.assistant"),nw.assistantMessages.toLocaleString(X)],[ee("session.toolCalls"),nw.toolCalls.toLocaleString(X)],[ee("session.toolResults"),nw.toolResults.toLocaleString(X)],[ee("session.total"),nw.totalMessages.toLocaleString(X)]],W=[[ee("session.input"),nw.tokens.input.toLocaleString(X)],[ee("session.output"),nw.tokens.output.toLocaleString(X)],...nw.tokens.cacheRead>0?[[ee("session.cacheRead"),nw.tokens.cacheRead.toLocaleString(X)]]:[],...nw.tokens.cacheWrite>0?[[ee("session.cacheWrite"),nw.tokens.cacheWrite.toLocaleString(X)]]:[],[ee("session.total"),nw.tokens.total.toLocaleString(X)]],D=nW??nw.contextUsage,_=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),B=[...nw.cost>0?[[ee("session.cost"),`$${nw.cost.toFixed(4)}`]]:[],...D?.contextWindow?[[ee("session.context"),`${null!==D.tokens?_(D.tokens):"?"} / ${_(D.contextWindow)}${null!==D.percent?` \xb7 ${D.percent.toFixed(1)}%`:""}`]]:[],...nw.tokens.cacheRead+nw.tokens.cacheWrite>0&&nw.tokens.cacheRead+nw.tokens.cacheWrite+nw.tokens.input>0?[[ee("session.cacheHitRate"),`${(nw.tokens.cacheRead/(nw.tokens.cacheRead+nw.tokens.cacheWrite+nw.tokens.input)*100).toFixed(1)}%`]]:[]],q=(e,t,n="left",i=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:i?"max-content max-content":"auto minmax(0, 1fr)",columnGap:i?14:12,rowGap:4,justifyContent:i?"start":void 0},children:t.map(([t,a])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:a})]},`${e}:${t}`))})]}),V=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:ee("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:A.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=nP===t,(0,r.jsx)("button",{type:"button",title:i?ee("session.copied"):ee("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:er?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:er?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[V,q(ee("session.messages"),z),q(ee("session.tokens"),[...W,...B],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:ee("session.load")})})]})]}),(0,r.jsxs)("div",{className:"chat-content-layout",children:[(0,r.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-translator-open":ef?"true":void 0,children:[r6?(0,r.jsx)(u$,{session:eb,newSessionCwd:r5,initialSessionData:eS,transitioning:null!==ek,onAgentEnd:rG,onAttentionNeeded:rJ,onSessionCreated:rq,onSessionForked:rX,modelsRefreshKey:eK,chatInputRef:nd,onBranchDataChange:ng,onSystemPromptChange:nb,onSessionStatsChange:nL,onSessionStatsPanelOpen:rh,onContextUsageChange:nU,onSubagentsChange:nS,onOpenWorkspaceView:ig,onOpenSessionList:ne.presented?void 0:rf,onOpenMaker:n7,selectedMaker:n6,onProcessLogChange:nB,onOpenFile:r2,transcriptReplacement:iv?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iD}):null,onComposerFocusChange:tR,onSessionBusyChange:ty,onWaitingChange:tw,onAttentionChange:nT,soundEnabled:es,onSoundToggle:eo,playCueSound:el,preloadCueSound:ec,unlockAudio:ed,jumpRequest:eT,onJumpHandled:eE},e_):iv?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iD}):"validating"===ez?(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:ee("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd})]}):"error"===ez?(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:ee("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:J.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eD})]}):r9?rT?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:ee("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:ee("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."}),ee("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),ee("workspace.addModels")]})]})]}):null,eg?(0,r.jsx)(gT,{visible:ef,onBack:()=>tM(!1)}):null]}),"pinned"===td.deck&&r3&&!ix.expanded&&(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:iD})]})]}),"command-palette"===ti.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(ta({type:"close-layer"}),tT())},children:(0,r.jsxs)("div",{ref:tI,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:tQ,"aria-label":"ko"===X?"명령 팔레트":"Command palette",children:[(0,r.jsxs)("header",{children:[(0,r.jsx)("strong",{children:"ko"===X?"명령 팔레트":"Command palette"}),(0,r.jsx)("kbd",{children:"Ctrl K"})]}),(0,r.jsx)(uD,{t:ee,onPick:(e,t)=>{ta({type:"close-layer"}),n8("chat",!1),eR.current+=1,eM({id:eR.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:()=>n8(e,!0),children:[(0,r.jsx)("span",{children:iw[e]}),(0,r.jsx)("small",{children:ti.activeView===e?"ko"===X?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{to(e),n8("resource",!1)},children:[(0,r.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,r.jsx)("small",{children:iw.resource})]},e)),(0,r.jsxs)("button",{type:"button",onClick:rf,children:[(0,r.jsx)("span",{children:ne.presented?ee("sidebar.hide"):ee("sidebar.show")}),(0,r.jsx)("small",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:eP,children:(0,r.jsx)("span",{children:ee(e$?"palette.wideChatOff":"palette.wideChatOn")})}),(0,r.jsx)("button",{type:"button",onClick:()=>{ta({type:"close-layer"}),eZ(!0)},children:(0,r.jsx)("span",{children:ee("common.settings")})})]})]})})]}),eJ&&(0,r.jsx)(ft,{cwd:r7,sessionId:eb?.id??null,onClose:()=>{eZ(!1),e5(e=>e+1),tT()},onModelsChanged:()=>eG(e=>e+1),onReloaded:()=>eB(e=>e+1)}),null!==eY&&(0,r.jsx)(hk,{cwd:r7,onClose:rs,onModelsChanged:()=>eG(e=>e+1),relogin:{target:eY,outcome:eQ,onLoginSucceeded:rl}}),e7&&r7&&(0,r.jsx)(fa,{cwd:r7,busy:te,scheduled:e2?.pending==="grant",error:tn,onCancel:()=>{te||(e9(!1),tT())},onConfirm:()=>void it("grant"),onCancelSchedule:()=>void it("cancel")})]})}},80455:(e,t,n)=>{Promise.resolve().then(n.bind(n,42661)),Promise.resolve().then(n.bind(n,92176))},92176:(e,t,n)=>{"use strict";n.d(t,{I18nProvider:()=>h,s:()=>f});var r=n(95155),i=n(12115);let a=JSON.parse('{"cloudProjects.launch":"GitHub 저장소 열기","cloudProjects.title":"클라우드 프로젝트","cloudProjects.description":"GitHub 저장소를 가져와 이 서버에서 작업을 이어가세요.","cloudProjects.github":"GitHub 저장소","cloudProjects.serverFolder":"서버 폴더 열기","cloudProjects.account":"GitHub 연결","cloudProjects.connectTitle":"내 GitHub 저장소 연결","cloudProjects.connectHelp":"연결하면 비공개 저장소도 목록에서 선택할 수 있습니다.","cloudProjects.connected":"GitHub 연결됨","cloudProjects.refresh":"다시 확인","cloudProjects.waiting":"로그인 대기 중","cloudProjects.connect":"GitHub 연결","cloudProjects.deviceHelp":"아래 코드를 GitHub 로그인 화면에 입력하세요.","cloudProjects.copyCode":"코드 복사","cloudProjects.copied":"복사됨","cloudProjects.copyFailure":"코드를 복사하지 못했습니다. 코드를 선택해 직접 복사하세요.","cloudProjects.openLogin":"GitHub에서 로그인","cloudProjects.permissionHelp":"GitHub에서 계정과 요청 권한을 확인하고 승인하세요. 인증 토큰은 서버에만 저장됩니다.","cloudProjects.preparingCode":"로그인 코드를 준비하고 있습니다.","cloudProjects.repositories":"내 저장소","cloudProjects.search":"저장소 검색","cloudProjects.searchPlaceholder":"이름 또는 설명으로 찾기","cloudProjects.loading":"저장소를 불러오고 있습니다.","cloudProjects.private":"비공개","cloudProjects.public":"공개","cloudProjects.empty":"일치하는 저장소가 없습니다. 다른 이름으로 검색하거나 URL을 입력하세요.","cloudProjects.more":"더 보기","cloudProjects.urlLabel":"선택한 저장소 또는 GitHub URL","cloudProjects.publicHelp":"공개 저장소는 로그인 없이도 가져올 수 있습니다. 이미 가져온 저장소는 변경 없이 다시 엽니다.","cloudProjects.error":"작업을 완료하지 못했습니다.","cloudProjects.openingHelp":"저장소를 서버에 가져오고 있습니다. 크기에 따라 시간이 걸릴 수 있습니다.","cloudProjects.opening":"프로젝트 여는 중","cloudProjects.open":"프로젝트 열기","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":"열린 파일 없음","files.docs.noProject":"프로젝트를 선택하면 문서 바로가기가 보입니다.","files.docs.loading":"프로젝트 문서를 찾는 중…","files.docs.projectDenied":"이 프로젝트 폴더는 CUELO가 읽을 수 있는 폴더 밖에 있습니다.","files.docs.loadFailed":"프로젝트 문서를 불러오지 못했습니다: {error}","files.docs.projectDir":"프로젝트 폴더: {path}","files.docs.noneFound":"저장소 루트까지 HANDOFF.md가 없고, 이 폴더에 doc/README.md나 doc/history도 없습니다.","files.docs.current":"현재 상태","files.docs.map":"문서 지도","files.docs.records":"최근 기록","files.docs.missing":"{file} 없음","files.docs.denied":"{file}은(는) 읽기 허용 폴더 밖에 있습니다","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":"목록 비우기","navigator.resultsToCheck":"확인할 결과","navigator.resultsToCheckCount":"확인할 결과 {count}","navigator.resultsToCheckHint":"이 브라우저에서 마지막으로 연 뒤 새로 끝난 대화","navigator.resultsToCheckEmpty":"확인할 결과가 없습니다.","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":"메시지 입력… / 명령어 \xb7 @ 파일","chat.steer":"지시","chat.followUp":"후속 메시지","chat.send":"보내기","chat.attachImageLimit":"메시지 하나에 이미지를 최대 {count}개까지 첨부할 수 있습니다.","chat.attachImageTooLarge":"{name} 파일이 이미지당 {limit} 제한을 초과합니다.","chat.attachFile":"파일 첨부","chat.emptyProjectLabel":"작업 폴더","chat.emptyProjectHint":"첫 메시지를 보내면 이 폴더에서 새 세션이 시작됩니다.","chat.openSessionList":"세션 목록 열기","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.attachStoredTooLarge":"{name} 파일이 파일당 {limit} 제한을 초과합니다.","chat.attachUploadFailed":"{name} 파일을 저장하지 못했습니다: {error}","chat.attachTranscribePending":"선택 필요","chat.transcribeGroup":"음성 받아쓰기","chat.transcribeChecking":"길이 확인 중","chat.transcribeConfirmTitle":"{name} 받아쓰기를 시작할까요?","chat.transcribePlanSummary":"{duration} \xb7 받아쓰기 호출 약 {calls}회","chat.transcribeDurationUnknown":"길이 알 수 없음","chat.transcribeUsageNotice":"받아쓰기는 연결된 계정의 사용량에 포함됩니다. 시작을 누르기 전에는 아무것도 보내지 않습니다.","chat.transcribeStart":"받아쓰기 시작","chat.transcribeSkip":"받아쓰지 않기","chat.transcribeCancel":"받아쓰기 취소","chat.transcribeRunning":"{name} 받아쓰는 중","chat.transcribeRetry":"다시 시도","chat.transcribeAction":"받아쓰기","chat.transcribeSkipped":"{name}은(는) 받아쓰지 않고 저장된 파일 경로만 보냅니다.","chat.transcribeFailedRow":"{name} 받아쓰기 실패: {error}","chat.transcribeToolMissing":"음성 도구(ffmpeg)를 쓸 수 없어 이 음성을 받아쓰기용으로 준비하지 못했습니다.","chat.transcribePartialFailed":"{total}조각 중 {done}조각까지 처리하고 멈췄습니다. 일부 결과는 붙이지 않았습니다.","chat.transcribeTooLong":"받아쓴 내용이 다른 첨부와 합친 글자 수 제한을 넘습니다.","chat.attachmentSettingsNav":"첨부 파일","chat.attachmentSettingsTitle":"첨부 파일","chat.attachmentSettingsDescription":"대화에 첨부한 파일은 에이전트가 열 수 있도록 이 컴퓨터에 저장됩니다.","chat.attachmentSettingsLoadFailed":"첨부 설정을 불러오지 못했습니다","chat.attachmentUploadLimit":"파일당 업로드 한도(MB)","chat.attachmentUploadLimitHelp":"이보다 큰 파일은 보내기 전에 거절합니다. 메시지에 바로 읽어 넣는 텍스트는 따로 문서당 8MB, 합계 240,000자 한도를 지킵니다.","chat.attachmentUploadLimitInvalid":"1 이상의 정수(MB)를 입력하세요.","chat.attachmentAutoCleanup":"쓰이지 않는 첨부 자동 삭제","chat.attachmentAutoCleanupHelp":"대화\xb7분기\xb7보내지 않은 초안에서 쓰이는 첨부는 지우지 않습니다. 어디에서도 쓰이지 않는다고 확인된 때부터 {days}일이 지나면 삭제하고, 쓰임을 확인할 수 없는 파일은 남겨 둡니다.","chat.attachmentSettingsSaved":"저장했습니다","characterMode.nav":"캐릭터","characterMode.title":"캐릭터","characterMode.description":"화면에 보이는 캐릭터의 얼굴\xb7이름\xb7스티커\xb7완료 음성을 고릅니다.","characterMode.label":"캐릭터 세트","characterMode.default":"기본","characterMode.office":"사무실 모드","characterMode.help":"이 PC의 서버 전체에 적용됩니다. 사무실 모드에서는 이 PC 프로필의 캐릭터 세트가 openai-codex 자리를 대신합니다. 나머지 자리는 그대로입니다.","characterMode.noRoster":"이 PC에는 사무실 캐릭터 세트가 없어 기본 캐릭터가 그대로 쓰입니다.","characterMode.saved":"저장했습니다","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 수준 사용","roles.harnessNote":"CUELO Maker 자리는 지정하기 전에도 목록에 표시됩니다. 쓸 자리만 직접 모델을 고르세요. 저장해도 로그인하거나 모델을 시험 호출하지 않습니다.","roles.harnessUnset":"미설정","roles.harness.implSonnet":"Maker \xb7 NORMAL 비-UI 우선","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL 대안","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD 코드","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD 코드 대안","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.currentReasoning":"현재 추론 강도: {level}","chat.fastModeActive":"Fast 켜짐 \xb7 이 모델에 적용 중. 우선 처리라 요금\xb7사용량이 더 들 수 있습니다. 누르면 끕니다","chat.fastModeInactive":"Fast 요청됨 \xb7 이 모델\xb7계정에는 적용되지 않음. 누르면 끕니다","chat.fastModeOff":"Fast 꺼짐 \xb7 누르면 우선 처리를 요청합니다(provider에 따라 요금\xb7사용량이 더 듭니다)","chat.fastModeUnknown":"Fast 상태 확인 전 \xb7 누르면 이 세션의 실제 상태를 읽고 바꿉니다","chat.fastModeBusy":"Fast 바꾸는 중","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.liveVoiceSettingsNav":"통화 음성","chat.liveVoiceSettingsTitle":"통화 음성","chat.liveVoiceSettingsDescription":"라이브 통화와 통역 통화에서 말할 Codex 목소리를 고릅니다. 선택은 다음 통화부터 적용됩니다.","chat.liveVoiceSpeakerGroup":"목소리","chat.liveVoiceCodexLabel":"Codex 목소리","chat.liveVoiceCodexHelp":"라이브 통화와 통역 통화에서 이 목소리로 말합니다.","chat.liveVoiceLoadFailed":"음성 설정을 불러오지 못했습니다","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.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":"확대","toolImage.dialogLabel":"확대한 이미지","toolImage.requestEdit":"이 화면 수정 요청","toolImage.requestEditHint":"이 이미지를 입력창에 붙입니다. 고칠 내용을 적어 보내세요.","toolImage.noComposer":"붙일 입력창이 없습니다. 대화를 열고 「이 화면 수정 요청」을 누르세요.","toolImage.loadFailed":"이미지를 가져오지 못했습니다. 「이 화면 수정 요청」을 다시 누르세요.","toolImage.markHint":"고칠 곳을 드래그해 표시하세요","toolImage.markLimit":"구역은 {count}개까지 표시할 수 있습니다","toolImage.clearMarks":"표시 지우기","toolImage.regionLabel":"구역 {n}","toolImage.locatorIntro":"첨부한 화면에 고칠 곳을 빨간 상자로 표시했습니다(구역 {range}). 구역별 확대 그림이 뒤에 이어집니다.","toolImage.locatorRegion":"구역 {n}: x={x}, y={y}, 폭 {w}, 높이 {h} (원본 {width}\xd7{height} 픽셀 기준)","files.pickElement":"요소 지정","files.pickElementHint":"미리보기에서 고칠 요소를 누르세요","files.pickedElement":"지정한 요소","files.requestElementEdit":"이 요소 수정 요청","files.clearPick":"지정 해제","files.pickLocatorElement":"요소: {selector}","files.pickLocatorText":"텍스트: \\"{text}\\"","files.pickLocatorPosition":"화면 위치: x={x}, y={y}, 폭 {w}, 높이 {h} (미리보기 {vw}\xd7{vh} 기준)","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":"실행 취소","models.navGroupRoles":"역할 배정","models.navGroupAccounts":"연결된 계정","models.navGroupCustom":"직접 추가한 제공자","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.reloadSessionHint":"열린 세션의 설정과 스킬을 다시 불러옵니다. Plugin은 해제되지 않으니, 해제하려면 CUELO를 재시작하세요.","i18n.reloading":"다시 불러오는 중...","i18n.packageRemoved":"패키지가 제거되었습니다.","i18n.packageInstalled":"패키지가 설치되었습니다.","i18n.packageUpdated":"패키지가 업데이트되었습니다.","i18n.packageDisabled":"패키지가 비활성화되었습니다.","i18n.packageDisabledRestartRequired":"비활성화 설정을 저장했습니다. 이미 불러온 Plugin은 CUELO를 재시작해야 멈춥니다. 세션 다시 불러오기로는 해제되지 않습니다.","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.showOriginalReply":"영어 원문 보기","i18n.hideOriginalReply":"영어 원문 접기","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":"미측정","usage.title":"사용량","usage.reorder":"순서 편집","usage.reorderDone":"완료","usage.reorderGroup":"계정 표시 순서","usage.moveUp":"{account} 위로","usage.moveDown":"{account} 아래로","usage.moved":"{account}: {position}번째로 이동","usage.authExpired":"인증 만료","usage.authUnavailable":"사용 불가","usage.relogin":"재로그인","usage.reloginFor":"{account} 계정 재로그인","usage.authIssues":"계정 오류 {count}","relogin.title":"재로그인 대상","relogin.guide":"「{action}」을 누른 뒤 브라우저에서 이 계정으로 로그인하세요. 다른 계정으로 로그인하면 이 계정의 오류는 그대로 남습니다.","relogin.done":"로그인을 마쳤습니다.","relogin.checking":"{account} 상태를 확인하려고 사용량을 다시 읽는 중…","relogin.recovered":"{account} 계정 인증이 복구됐습니다.","relogin.stillFailing":"로그인은 끝났지만 {account} 계정은 아직 인증 오류입니다. 다른 계정으로 로그인했을 수 있습니다.","relogin.unknown":"사용량에서 {account} 계정을 찾지 못해 복구 여부를 확인하지 못했습니다.","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.mixedPairingNote":"혼합 구성: 요청별 모델\xb7추론 강도 조합과 순서는 확인되지 않았습니다. 같은 조건의 실행으로 단정할 수 없습니다.","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.toolFailedValue":"실패 {value}","efficiency.toolNoMatchValue":"무일치 {value}","efficiency.toolCancelledValue":"중단 {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","efficiency.harness":"하네스","efficiency.harnessValue":"하네스 {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"모든 하네스","efficiency.groupByHarness":"하네스별로 나누기","efficiency.harnessNote":"하네스는 run 시작 시점에 설치돼 있던 CUELO 버전입니다. 이 PC의 업데이트 기록으로만 정하며, 기록이 없거나 기록 밖에서 바뀐 구간은 unknown입니다.","efficiency.sawSection":"모델이 본 것","efficiency.sawApproxNote":"세션 기록으로 다시 맞춘 근사치입니다. 요청마다 보낸 시스템 프롬프트와 컨텍스트 훅이 바꾼 내용은 기록에 남지 않습니다.","efficiency.sawOpen":"요청별로 보기","efficiency.sawLoading":"요청 기록을 읽는 중…","efficiency.sawError":"요청 기록을 읽지 못했습니다.","efficiency.sawEmpty":"이 run에는 모델 요청 기록이 없습니다.","efficiency.sawFilterEmpty":"주입이 있는 요청이 없습니다.","efficiency.sawRole":"대화 기록","efficiency.sawSummary":"요청 {turns}회 \xb7 주입 {injections}건 \xb7 도구 {tools}회 \xb7 실패 {failed}건","efficiency.sawOnlyInjected":"주입 있는 요청만","efficiency.sawTurnLabel":"요청 {index}","efficiency.sawBefore":"이 요청 전에 들어온 것","efficiency.sawTrailing":"마지막 요청 뒤에 들어온 것 (이 run의 모델 요청에는 들어가지 않음)","efficiency.sawShowFull":"전체 보기","efficiency.sawShowArgs":"인자 보기","efficiency.sawShowResult":"결과 보기","efficiency.sawHideFull":"접기","efficiency.sawTruncated":"앞 {value}자만 보입니다.","efficiency.sawMore":"{value}개 더 보기","efficiency.sawShown":"{total}개 중 {shown}개 표시","efficiency.sawHiddenFromChat":"채팅에는 안 보임","efficiency.sawNotSent":"모델에 안 보냄","efficiency.sawSecretsMasked":"비밀값처럼 보이는 문자열은 [REDACTED]로 가렸습니다.","efficiency.sawKindInjection":"주입","efficiency.sawKindDeveloper":"개발자 메시지","efficiency.sawKindUser":"사용자 메시지","efficiency.sawKindCompaction":"압축","efficiency.sawKindModel":"모델 변경","efficiency.sawKindEffort":"effort 변경","efficiency.sawKindPrompt":"시스템 프롬프트 바뀜","efficiency.sawKindRules":"규칙 주입","efficiency.sawKindMemory":"기억 회상","efficiency.sawCompactionValue":"{before} → {after} 토큰","efficiency.sawMemoryIds":"기억 {value}건 회상 (본문은 기록되지 않음)","efficiency.sawToolOk":"성공","efficiency.sawToolFailed":"실패","efficiency.sawToolNoMatch":"일치 없음","efficiency.sawToolCancelled":"중단","efficiency.sawToolMissing":"결과 없음","efficiency.sawResultChars":"결과 {value}자","efficiency.sawUsage":"입력 {input} \xb7 출력 {output} \xb7 캐시 읽기 {cacheRead}","efficiency.sawStop":"종료: {value}","efficiency.sawToolsChanged":"도구 목록 변경: +{added} −{removed}","efficiency.sawPreludeTitle":"시스템 프롬프트와 도구","efficiency.sawPreludeRecorded":"기록된 것","efficiency.sawPreludeTools":"마지막 요청에 켜진 도구 {value}개 (기록됨)","efficiency.sawPreludeDigest":"시스템 프롬프트 지문: {value}","efficiency.sawPreludeDigestNone":"이 run 시점의 시스템 프롬프트 지문이 기록에 없습니다.","efficiency.sawPreludeMemory":"기억 회상 블록 (시스템 프롬프트의 일부, 기록됨)","efficiency.sawPreludeReconstruct":"지금 설정으로 다시 만들기","efficiency.sawPreludeLoading":"다시 만드는 중…","efficiency.sawPreludeApprox":"지금 설정으로 다시 만든 것이며 보낸 그대로가 아닙니다.","efficiency.sawPreludeNotLoaded":"이 세션이 지금 열려 있지 않아 다시 만들 수 없습니다. 시스템 프롬프트 본문은 기록되지 않습니다.","efficiency.sawPreludeMatch":"지금 프롬프트의 지문이 이 run의 기록과 같습니다.","efficiency.sawPreludeMismatch":"지금 프롬프트의 지문이 이 run의 기록과 다릅니다. 그사이 바뀌었을 수 있습니다.","toolRun.running":"실행 중","toolRun.failed":"실패","toolRun.exitCode":"exit {code}","toolRun.diffStats":"{added}줄 추가, {removed}줄 삭제","panel.expand":"패널 넓게 보기","panel.restore":"원래 크기로","panel.more":"더 보기","panel.liveSync":"실시간 반영","panel.subagentsCount":"기록 {count}건","panel.refresh":"기록 새로고침","panel.close":"패널 닫기","makerDetail.region":"{title} 기록","makerDetail.noFiles":"이 Maker는 파일을 바꾸지 않았습니다","makerDetail.noChecks":"검사 실행 없음","makerDetail.archiveUnobserved":"기록에 도구 결과가 없어 확인할 수 없습니다","makerDetail.unavailable":"이 시도와 정확히 맞는 실행 기록이 없어 상세를 열 수 없습니다","makerDetail.checkPassed":"통과","makerDetail.checkUnverified":"판정 미확인","makerDetail.checkFailed":"실패","makerDetail.checkUnobserved":"결과 미관측","dispatchLane.label":"Maker 시도","dispatchLane.runPhase":"{run}({phase})","dispatchLane.checks":"검사 {passed}/{total}","dispatchLane.checksUnobserved":"검사 미관측","dispatchLane.checksLoading":"검사 읽는 중","dispatchLane.attempt":"시도 {attempt}","dispatchLane.attemptUnknown":"시도","dispatchLane.verdict.accepted":"수용","dispatchLane.verdict.rework":"재작업","dispatchLane.verdict.held":"보류","dispatchLane.open":"자세히","dispatchLane.openLabel":"{title} 자세히 보기","dispatchLane.unavailable":"상세 없음"}'),s=["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:{"cloudProjects.launch":"Open GitHub repository","cloudProjects.title":"Cloud project","cloudProjects.description":"Bring a GitHub repository to this server and keep working.","cloudProjects.github":"GitHub repositories","cloudProjects.serverFolder":"Open server folder","cloudProjects.account":"GitHub connection","cloudProjects.connectTitle":"Connect your GitHub repositories","cloudProjects.connectHelp":"Sign in to select private repositories from your list.","cloudProjects.connected":"Connected to GitHub","cloudProjects.refresh":"Check again","cloudProjects.waiting":"Waiting for sign-in","cloudProjects.connect":"Connect GitHub","cloudProjects.deviceHelp":"Enter this code on the GitHub sign-in page.","cloudProjects.copyCode":"Copy code","cloudProjects.copied":"Copied","cloudProjects.copyFailure":"Could not copy the code. Select and copy it manually.","cloudProjects.openLogin":"Sign in on GitHub","cloudProjects.permissionHelp":"Check the account and requested permissions on GitHub before approving. Tokens stay on the server.","cloudProjects.preparingCode":"Preparing your sign-in code.","cloudProjects.repositories":"Your repositories","cloudProjects.search":"Find a repository","cloudProjects.searchPlaceholder":"Search by name or description","cloudProjects.loading":"Loading repositories.","cloudProjects.private":"Private","cloudProjects.public":"Public","cloudProjects.empty":"No matching repositories. Try another name or enter a URL.","cloudProjects.more":"Show more","cloudProjects.urlLabel":"Selected repository or GitHub URL","cloudProjects.publicHelp":"Public repositories do not require sign-in. Existing workspaces are reopened without changing your files.","cloudProjects.error":"Could not complete the operation.","cloudProjects.openingHelp":"Importing the repository to this server. Large repositories may take a while.","cloudProjects.opening":"Opening project","cloudProjects.open":"Open project","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","files.docs.noProject":"Select a project to see its documents.","files.docs.loading":"Looking for project documents…","files.docs.projectDenied":"This project folder is outside the folders CUELO may read.","files.docs.loadFailed":"Could not load project documents: {error}","files.docs.projectDir":"Project folder: {path}","files.docs.noneFound":"No HANDOFF.md up to the repository root, and no doc/README.md or doc/history in this folder.","files.docs.current":"Current state","files.docs.map":"Document map","files.docs.records":"Recent records","files.docs.missing":"{file} not found","files.docs.denied":"{file} is outside the readable folders","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","navigator.resultsToCheck":"To review","navigator.resultsToCheckCount":"To review {count}","navigator.resultsToCheckHint":"Finished conversations with new activity since you last opened them in this browser","navigator.resultsToCheckEmpty":"Nothing to review.","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… / commands \xb7 @ 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.emptyProjectLabel":"Project folder","chat.emptyProjectHint":"Your first message starts a new session in this folder.","chat.openSessionList":"Open session list","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.attachStoredTooLarge":"{name} exceeds the {limit} per-file limit.","chat.attachUploadFailed":"Could not save {name}: {error}","chat.attachTranscribePending":"Needs your choice","chat.transcribeGroup":"Audio transcription","chat.transcribeChecking":"Checking length","chat.transcribeConfirmTitle":"Transcribe {name}?","chat.transcribePlanSummary":"{duration} \xb7 transcription calls: about {calls}","chat.transcribeDurationUnknown":"Length unknown","chat.transcribeUsageNotice":"Transcription counts toward the connected account's usage. Nothing is sent until you start.","chat.transcribeStart":"Start transcription","chat.transcribeSkip":"Don't transcribe","chat.transcribeCancel":"Cancel transcription","chat.transcribeRunning":"Transcribing {name}","chat.transcribeRetry":"Try again","chat.transcribeAction":"Transcribe","chat.transcribeSkipped":"{name} has no transcript; only the saved file path is sent.","chat.transcribeFailedRow":"{name}: transcription failed. {error}","chat.transcribeToolMissing":"The audio tool (ffmpeg) is not available, so this audio cannot be prepared for transcription.","chat.transcribePartialFailed":"Stopped after {done} of {total} parts; no partial transcript is attached.","chat.transcribeTooLong":"The transcript does not fit beside the other attachments.","chat.attachmentSettingsNav":"Attachments","chat.attachmentSettingsTitle":"Attachments","chat.attachmentSettingsDescription":"Files you attach in chat are saved on this computer so the agent can open them.","chat.attachmentSettingsLoadFailed":"Could not load attachment settings","chat.attachmentUploadLimit":"Upload limit per file (MB)","chat.attachmentUploadLimitHelp":"Larger files are refused before they are sent. Text read straight into the message keeps its own limits: 8 MB per document and 240,000 characters in total.","chat.attachmentUploadLimitInvalid":"Enter a whole number of MB, 1 or more.","chat.attachmentAutoCleanup":"Delete unused attachments automatically","chat.attachmentAutoCleanupHelp":"Attachments used by a conversation, a branch, or an unsent draft are kept. A file is deleted {days} days after it is confirmed unused everywhere; a file whose use cannot be confirmed is kept.","chat.attachmentSettingsSaved":"Saved","characterMode.nav":"Characters","characterMode.title":"Characters","characterMode.description":"Choose the faces, names, stickers and completion voices you see on screen.","characterMode.label":"Character set","characterMode.default":"Default","characterMode.office":"Office mode","characterMode.help":"Applies to this whole PC server. In office mode, the character set in this PC's profile takes the openai-codex seat. The other seats stay as they are.","characterMode.noRoster":"This PC has no office character set, so the default characters stay in use.","characterMode.saved":"Saved","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","roles.harnessNote":"CUELO Maker slots are listed even before you assign them. Pick your own model only for the slots you use; saving does not sign in or test the model.","roles.harnessUnset":"not set","roles.harness.implSonnet":"Maker \xb7 NORMAL non-UI (first choice)","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL fallback","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD code","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD code fallback","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.currentReasoning":"Current reasoning level: {level}","chat.fastModeActive":"Fast on \xb7 applied to this model. Priority service may cost more or use more quota. Click to turn off","chat.fastModeInactive":"Fast requested \xb7 not applied for this model or account. Click to turn off","chat.fastModeOff":"Fast off \xb7 click to request priority service (may cost more or use more quota, depending on the provider)","chat.fastModeUnknown":"Fast state not checked yet \xb7 click to read this session's actual state and change it","chat.fastModeBusy":"Changing Fast","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.liveVoiceSettingsNav":"Call voice","chat.liveVoiceSettingsTitle":"Call voice","chat.liveVoiceSettingsDescription":"Choose the Codex voice that speaks in live and interpreter calls. The choice applies from the next call.","chat.liveVoiceSpeakerGroup":"Voice","chat.liveVoiceCodexLabel":"Codex voice","chat.liveVoiceCodexHelp":"Speaks in live calls and interpreter calls.","chat.liveVoiceLoadFailed":"Could not load voice settings","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.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":"The run stopped before it finished, for example when the server or PC went down. If it does not resume automatically, send a message to continue.","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","toolImage.dialogLabel":"Enlarged image","toolImage.requestEdit":"Request changes to this screen","toolImage.requestEditHint":"Attach this image to the message box. Describe the change, then send.","toolImage.noComposer":"There is no message box to attach to. Open a conversation, then press Request changes to this screen.","toolImage.loadFailed":"Couldn't load the image. Press Request changes to this screen again.","toolImage.markHint":"Drag over the part to change","toolImage.markLimit":"You can mark up to {count} areas","toolImage.clearMarks":"Clear marks","toolImage.regionLabel":"Area {n}","toolImage.locatorIntro":"The parts to change are marked with red boxes on the attached screen (areas {range}). A close-up of each area follows.","toolImage.locatorRegion":"Area {n}: x={x}, y={y}, width {w}, height {h} (original {width}\xd7{height} pixels)","files.pickElement":"Pick element","files.pickElementHint":"Click the element to change in the preview","files.pickedElement":"Picked element","files.requestElementEdit":"Request changes to this element","files.clearPick":"Clear selection","files.pickLocatorElement":"Element: {selector}","files.pickLocatorText":'Text: "{text}"',"files.pickLocatorPosition":"Position: x={x}, y={y}, width {w}, height {h} ({vw}\xd7{vh} preview)","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","models.navGroupRoles":"Role assignments","models.navGroupAccounts":"Connected accounts","models.navGroupCustom":"Custom providers","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.reloadSessionHint":"Reloads settings and skills for the open session. It does not unload plugins; restart CUELO for that.","i18n.reloading":"Reloading...","i18n.packageRemoved":"Package removed.","i18n.packageInstalled":"Package installed.","i18n.packageUpdated":"Package updated.","i18n.packageDisabled":"Package disabled.","i18n.packageDisabledRestartRequired":"Disabled setting saved. The plugin already loaded keeps running until CUELO restarts; reloading the session does not unload it.","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.showOriginalReply":"Show English original","i18n.hideOriginalReply":"Hide English original","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","usage.title":"Usage","usage.reorder":"Reorder","usage.reorderDone":"Done","usage.reorderGroup":"Account display order","usage.moveUp":"Move {account} up","usage.moveDown":"Move {account} down","usage.moved":"{account} moved to position {position}","usage.authExpired":"sign-in expired","usage.authUnavailable":"unavailable","usage.relogin":"Sign in again","usage.reloginFor":"Sign in again as {account}","usage.authIssues":"Account issues: {count}","relogin.title":"Account to sign in again","relogin.guide":"Press {action} and finish in the browser with this account. Signing in with a different account leaves this one failing.","relogin.done":"Sign-in finished.","relogin.checking":"Re-reading usage to check {account}…","relogin.recovered":"{account} is signed in again.","relogin.stillFailing":"Sign-in finished, but {account} still reports an auth error. You may have signed in with a different account.","relogin.unknown":"Could not find {account} in usage, so recovery is not confirmed.","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.mixedPairingNote":"Mixed configuration: which model and reasoning effort each request used, and in what order, could not be determined. These runs cannot be assumed to share the same conditions.","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.toolFailedValue":"failed {value}","efficiency.toolNoMatchValue":"no match {value}","efficiency.toolCancelledValue":"cancelled {value}","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","efficiency.harness":"Harness","efficiency.harnessValue":"Harness {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"All harnesses","efficiency.groupByHarness":"Split by harness","efficiency.harnessNote":"Harness is the CUELO version installed when the run started. It comes only from this PC's update records; runs without a record, or in a span changed outside the records, are unknown.","efficiency.sawSection":"What the model saw","efficiency.sawApproxNote":"Approximate, rebuilt from the session log. The system prompt sent with each request and context-hook rewrites are not recorded.","efficiency.sawOpen":"Show requests","efficiency.sawLoading":"Loading requests…","efficiency.sawError":"Could not load requests.","efficiency.sawEmpty":"No model requests are recorded for this run.","efficiency.sawFilterEmpty":"No requests with injections.","efficiency.sawRole":"Transcript","efficiency.sawSummary":"{turns} requests \xb7 {injections} injected \xb7 {tools} tool calls \xb7 {failed} failed","efficiency.sawOnlyInjected":"Only requests with injections","efficiency.sawTurnLabel":"Request {index}","efficiency.sawBefore":"Arrived before this request","efficiency.sawTrailing":"Arrived after the last request (not part of any model request in this run)","efficiency.sawShowFull":"Show full text","efficiency.sawShowArgs":"Show arguments","efficiency.sawShowResult":"Show result","efficiency.sawHideFull":"Collapse","efficiency.sawTruncated":"Showing the first {value} characters.","efficiency.sawMore":"Load {value} more","efficiency.sawShown":"Showing {shown} of {total}","efficiency.sawHiddenFromChat":"Hidden in chat","efficiency.sawNotSent":"Not sent to the model","efficiency.sawSecretsMasked":"Strings that look like secrets are replaced with [REDACTED].","efficiency.sawKindInjection":"Injected","efficiency.sawKindDeveloper":"Developer message","efficiency.sawKindUser":"User message","efficiency.sawKindCompaction":"Compaction","efficiency.sawKindModel":"Model change","efficiency.sawKindEffort":"Effort change","efficiency.sawKindPrompt":"System prompt changed","efficiency.sawKindRules":"Rules injected","efficiency.sawKindMemory":"Memory recall","efficiency.sawCompactionValue":"{before} → {after} tokens","efficiency.sawMemoryIds":"{value} memories recalled (text not recorded)","efficiency.sawToolOk":"OK","efficiency.sawToolFailed":"Failed","efficiency.sawToolNoMatch":"No match","efficiency.sawToolCancelled":"Cancelled","efficiency.sawToolMissing":"No result","efficiency.sawResultChars":"result {value} chars","efficiency.sawUsage":"in {input} \xb7 out {output} \xb7 cache read {cacheRead}","efficiency.sawStop":"stop: {value}","efficiency.sawToolsChanged":"Tool list changed: +{added} −{removed}","efficiency.sawPreludeTitle":"System prompt and tools","efficiency.sawPreludeRecorded":"Recorded","efficiency.sawPreludeTools":"{value} tools active in the last request (recorded)","efficiency.sawPreludeDigest":"System prompt fingerprint: {value}","efficiency.sawPreludeDigestNone":"No system prompt fingerprint is recorded for this run.","efficiency.sawPreludeMemory":"Memory recall block (part of the system prompt, recorded)","efficiency.sawPreludeReconstruct":"Rebuild from current settings","efficiency.sawPreludeLoading":"Rebuilding…","efficiency.sawPreludeApprox":"Rebuilt now from the current configuration, not as sent.","efficiency.sawPreludeNotLoaded":"This session is not loaded right now, so it cannot be rebuilt. The system prompt text is not recorded.","efficiency.sawPreludeMatch":"The current prompt's fingerprint matches this run's record.","efficiency.sawPreludeMismatch":"The current prompt's fingerprint differs from this run's record; it may have changed since.","toolRun.running":"Running","toolRun.failed":"Failed","toolRun.exitCode":"exit {code}","toolRun.diffStats":"{added} lines added, {removed} lines removed","panel.expand":"Widen panel","panel.restore":"Restore size","panel.more":"More","panel.liveSync":"Live updates","panel.subagentsCount":"{count} records","panel.refresh":"Refresh records","panel.close":"Close panel","makerDetail.region":"{title} record","makerDetail.noFiles":"This Maker changed no files","makerDetail.noChecks":"No checks were run","makerDetail.archiveUnobserved":"The record holds no tool results, so this cannot be confirmed","makerDetail.unavailable":"No run record matches this attempt exactly, so its detail cannot be opened","makerDetail.checkPassed":"passed","makerDetail.checkUnverified":"verdict not confirmed","makerDetail.checkFailed":"failed","makerDetail.checkUnobserved":"result not observed","dispatchLane.label":"Maker attempts","dispatchLane.runPhase":"{run} ({phase})","dispatchLane.checks":"checks {passed}/{total}","dispatchLane.checksUnobserved":"checks not observed","dispatchLane.checksLoading":"reading checks","dispatchLane.attempt":"attempt {attempt}","dispatchLane.attemptUnknown":"attempt","dispatchLane.verdict.accepted":"accepted","dispatchLane.verdict.rework":"rework","dispatchLane.verdict.held":"held","dispatchLane.open":"Details","dispatchLane.openLabel":"Open details for {title}","dispatchLane.unavailable":"No detail"}}),l({id:"zh-CN",label:"简体中文",messages:{"cloudProjects.launch":"打开 GitHub 仓库","cloudProjects.title":"云端项目","cloudProjects.description":"将 GitHub 仓库导入此服务器并继续工作。","cloudProjects.github":"GitHub 仓库","cloudProjects.serverFolder":"打开服务器文件夹","cloudProjects.account":"GitHub 连接","cloudProjects.connectTitle":"连接你的 GitHub 仓库","cloudProjects.connectHelp":"登录后也可以从列表中选择私有仓库。","cloudProjects.connected":"已连接 GitHub","cloudProjects.refresh":"重新检查","cloudProjects.waiting":"等待登录","cloudProjects.connect":"连接 GitHub","cloudProjects.deviceHelp":"在 GitHub 登录页面输入以下代码。","cloudProjects.copyCode":"复制代码","cloudProjects.copied":"已复制","cloudProjects.copyFailure":"无法复制代码。请选择并手动复制。","cloudProjects.openLogin":"在 GitHub 上登录","cloudProjects.permissionHelp":"请在 GitHub 上确认账号和请求的权限后再授权。令牌仅保存在服务器上。","cloudProjects.preparingCode":"正在准备登录代码。","cloudProjects.repositories":"你的仓库","cloudProjects.search":"搜索仓库","cloudProjects.searchPlaceholder":"按名称或描述搜索","cloudProjects.loading":"正在加载仓库。","cloudProjects.private":"私有","cloudProjects.public":"公开","cloudProjects.empty":"没有匹配的仓库。请尝试其他名称或输入 URL。","cloudProjects.more":"显示更多","cloudProjects.urlLabel":"选中的仓库或 GitHub URL","cloudProjects.publicHelp":"公开仓库无需登录即可导入。已存在的工作区会直接打开,不修改文件。","cloudProjects.error":"操作未能完成。","cloudProjects.openingHelp":"正在将仓库导入服务器。大型仓库可能需要一些时间。","cloudProjects.opening":"正在打开项目","cloudProjects.open":"打开项目","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":"没有打开的文件","files.docs.noProject":"选择项目后可查看其文档。","files.docs.loading":"正在查找项目文档…","files.docs.projectDenied":"此项目文件夹不在 CUELO 可读取的文件夹范围内。","files.docs.loadFailed":"无法加载项目文档:{error}","files.docs.projectDir":"项目文件夹:{path}","files.docs.noneFound":"直到仓库根目录都没有 HANDOFF.md,此文件夹中也没有 doc/README.md 或 doc/history。","files.docs.current":"当前状态","files.docs.map":"文档地图","files.docs.records":"最近记录","files.docs.missing":"未找到 {file}","files.docs.denied":"{file} 不在可读取的文件夹范围内","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":"清空列表","navigator.resultsToCheck":"待查看","navigator.resultsToCheckCount":"待查看 {count}","navigator.resultsToCheckHint":"自你在此浏览器上次打开后又有新进展且已结束的对话","navigator.resultsToCheckEmpty":"没有待查看的结果。","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":"消息… / 命令 \xb7 @ 文件","chat.steer":"引导","chat.followUp":"后续消息","chat.send":"发送","chat.attachImageLimit":"每条消息最多可附加 {count} 张图片。","chat.attachImageTooLarge":"{name} 超出每张图片 {limit} 的限制。","chat.attachFile":"附加文件","chat.emptyProjectLabel":"工作文件夹","chat.emptyProjectHint":"发送第一条消息后,将在此文件夹中开始新会话。","chat.openSessionList":"打开会话列表","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.attachStoredTooLarge":"{name} 超出每个文件 {limit} 的限制。","chat.attachUploadFailed":"无法保存 {name}:{error}","chat.attachTranscribePending":"需要选择","chat.transcribeGroup":"音频转写","chat.transcribeChecking":"正在检查时长","chat.transcribeConfirmTitle":"要转写 {name} 吗?","chat.transcribePlanSummary":"{duration} \xb7 约 {calls} 次转写调用","chat.transcribeDurationUnknown":"时长未知","chat.transcribeUsageNotice":"转写会计入已连接账户的用量。点击开始之前不会发送任何内容。","chat.transcribeStart":"开始转写","chat.transcribeSkip":"不转写","chat.transcribeCancel":"取消转写","chat.transcribeRunning":"正在转写 {name}","chat.transcribeRetry":"重试","chat.transcribeAction":"转写","chat.transcribeSkipped":"{name} 没有转写,只发送已保存的文件路径。","chat.transcribeFailedRow":"{name} 转写失败:{error}","chat.transcribeToolMissing":"音频工具(ffmpeg)不可用,无法为转写准备此音频。","chat.transcribePartialFailed":"在 {total} 段中的第 {done} 段后停止;未附加部分转写。","chat.transcribeTooLong":"转写内容与其他附件合计超出字数限制。","chat.attachmentSettingsNav":"附件","chat.attachmentSettingsTitle":"附件","chat.attachmentSettingsDescription":"在聊天中附加的文件会保存在这台电脑上,供代理打开。","chat.attachmentSettingsLoadFailed":"无法加载附件设置","chat.attachmentUploadLimit":"每个文件的上传上限(MB)","chat.attachmentUploadLimitHelp":"超过上限的文件会在发送前被拒绝。直接读入消息的文本仍有单独限制:每个文档 8 MB,总计 240,000 个字符。","chat.attachmentUploadLimitInvalid":"请输入不小于 1 的整数(MB)。","chat.attachmentAutoCleanup":"自动删除未使用的附件","chat.attachmentAutoCleanupHelp":"对话、分支或未发送草稿中使用的附件会保留。确认在任何地方都不再使用后,{days} 天后删除;无法确认是否使用的文件会保留。","chat.attachmentSettingsSaved":"已保存","characterMode.nav":"角色","characterMode.title":"角色","characterMode.description":"选择屏幕上显示的头像、名称、贴纸和完成语音。","characterMode.label":"角色集","characterMode.default":"默认","characterMode.office":"办公室模式","characterMode.help":"适用于这台电脑的整个服务器。办公室模式下,这台电脑配置中的角色集会替换 openai-codex 席位,其余席位保持不变。","characterMode.noRoster":"这台电脑没有办公室角色集,因此继续使用默认角色。","characterMode.saved":"已保存","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":"使用配置的默认推理级别","roles.harnessNote":"CUELO Maker 角色在分配之前也会列出。只为要用的角色自行选择模型;保存不会登录或试调用模型。","roles.harnessUnset":"未设置","roles.harness.implSonnet":"Maker \xb7 NORMAL 非 UI(优先)","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL 备选","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD 代码","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD 代码备选","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.currentReasoning":"当前推理级别:{level}","chat.fastModeActive":"Fast 已开启 \xb7 正在应用于此模型。优先处理可能产生更多费用或用量。点击关闭","chat.fastModeInactive":"已请求 Fast \xb7 此模型或账户未应用。点击关闭","chat.fastModeOff":"Fast 已关闭 \xb7 点击请求优先处理(视提供商可能产生更多费用或用量)","chat.fastModeUnknown":"尚未确认 Fast 状态 \xb7 点击读取此会话的实际状态并切换","chat.fastModeBusy":"正在切换 Fast","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.liveVoiceSettingsNav":"通话语音","chat.liveVoiceSettingsTitle":"通话语音","chat.liveVoiceSettingsDescription":"选择实时通话和口译通话中使用的 Codex 语音。该选择从下一次通话开始生效。","chat.liveVoiceSpeakerGroup":"语音","chat.liveVoiceCodexLabel":"Codex 语音","chat.liveVoiceCodexHelp":"实时通话和口译通话都使用这个语音。","chat.liveVoiceLoadFailed":"无法加载语音设置","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.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":"放大","toolImage.dialogLabel":"放大的图片","toolImage.requestEdit":"请求修改此画面","toolImage.requestEditHint":"把这张图片附加到输入框。写下要改的地方后再发送。","toolImage.noComposer":"没有可附加的输入框。请先打开对话,再点击“请求修改此画面”。","toolImage.loadFailed":"无法获取图片。请再次点击“请求修改此画面”。","toolImage.markHint":"拖动框出要修改的地方","toolImage.markLimit":"最多可标记 {count} 个区域","toolImage.clearMarks":"清除标记","toolImage.regionLabel":"区域 {n}","toolImage.locatorIntro":"已在附加的画面上用红框标出要修改的地方(区域 {range})。后面依次附上各区域的放大图。","toolImage.locatorRegion":"区域 {n}:x={x}, y={y}, 宽 {w}, 高 {h}(以原图 {width}\xd7{height} 像素为准)","files.pickElement":"指定元素","files.pickElementHint":"在预览中点击要修改的元素","files.pickedElement":"已指定的元素","files.requestElementEdit":"请求修改此元素","files.clearPick":"取消指定","files.pickLocatorElement":"元素:{selector}","files.pickLocatorText":"文本:“{text}”","files.pickLocatorPosition":"画面位置:x={x}, y={y}, 宽 {w}, 高 {h}(以预览 {vw}\xd7{vh} 为准)","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":"撤销","models.navGroupRoles":"角色分配","models.navGroupAccounts":"已连接账户","models.navGroupCustom":"自定义提供商","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.reloadSessionHint":"重新加载当前会话的设置和技能。不会卸载插件;如需卸载,请重启 CUELO。","i18n.reloading":"重新加载中...","i18n.packageRemoved":"包已移除。","i18n.packageInstalled":"包已安装。","i18n.packageUpdated":"包已更新。","i18n.packageDisabled":"包已禁用。","i18n.packageDisabledRestartRequired":"已保存禁用设置。已加载的插件会继续运行,直到 CUELO 重启;重新加载会话无法卸载它。","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.showOriginalReply":"查看英文原文","i18n.hideOriginalReply":"收起英文原文","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":"未测量","usage.title":"用量","usage.reorder":"调整顺序","usage.reorderDone":"完成","usage.reorderGroup":"账户显示顺序","usage.moveUp":"上移 {account}","usage.moveDown":"下移 {account}","usage.moved":"{account} 已移到第 {position} 位","usage.authExpired":"登录已过期","usage.authUnavailable":"不可用","usage.relogin":"重新登录","usage.reloginFor":"重新登录 {account}","usage.authIssues":"账户异常 {count}","relogin.title":"需要重新登录的账户","relogin.guide":"点击「{action}」后,请在浏览器中用此账户完成登录。用其他账户登录时,此账户仍保持错误。","relogin.done":"登录已完成。","relogin.checking":"正在重新读取用量以确认 {account}…","relogin.recovered":"{account} 已重新登录。","relogin.stillFailing":"登录已完成,但 {account} 仍报告认证错误。可能登录了其他账户。","relogin.unknown":"用量中找不到 {account},无法确认是否恢复。","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.mixedPairingNote":"混合配置:无法确认每个请求使用的模型与推理强度组合及其顺序。不能断定这些 run 处于相同条件。","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.toolFailedValue":"失败 {value}","efficiency.toolNoMatchValue":"无匹配 {value}","efficiency.toolCancelledValue":"中断 {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","efficiency.harness":"Harness","efficiency.harnessValue":"Harness {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"全部 harness","efficiency.groupByHarness":"按 harness 拆分","efficiency.harnessNote":"Harness 指 run 开始时已安装的 CUELO 版本,只根据本机的更新记录确定;没有记录或在记录之外变更的区间显示为 unknown。","efficiency.sawSection":"模型看到的内容","efficiency.sawApproxNote":"根据会话记录重建的近似视图。每次请求发送的系统提示词和上下文钩子的改写都没有记录。","efficiency.sawOpen":"按请求查看","efficiency.sawLoading":"正在读取请求…","efficiency.sawError":"无法读取请求记录。","efficiency.sawEmpty":"此运行没有模型请求记录。","efficiency.sawFilterEmpty":"没有包含注入的请求。","efficiency.sawRole":"记录","efficiency.sawSummary":"请求 {turns} 次 \xb7 注入 {injections} 条 \xb7 工具 {tools} 次 \xb7 失败 {failed} 次","efficiency.sawOnlyInjected":"仅含注入的请求","efficiency.sawTurnLabel":"请求 {index}","efficiency.sawBefore":"此请求之前到达","efficiency.sawTrailing":"最后一次请求之后到达(未进入本次运行的任何模型请求)","efficiency.sawShowFull":"查看全文","efficiency.sawShowArgs":"查看参数","efficiency.sawShowResult":"查看结果","efficiency.sawHideFull":"收起","efficiency.sawTruncated":"仅显示前 {value} 个字符。","efficiency.sawMore":"再加载 {value} 个","efficiency.sawShown":"已显示 {shown}/{total}","efficiency.sawHiddenFromChat":"聊天中不显示","efficiency.sawNotSent":"未发送给模型","efficiency.sawSecretsMasked":"疑似密钥的字符串已替换为 [REDACTED]。","efficiency.sawKindInjection":"注入","efficiency.sawKindDeveloper":"开发者消息","efficiency.sawKindUser":"用户消息","efficiency.sawKindCompaction":"压缩","efficiency.sawKindModel":"模型切换","efficiency.sawKindEffort":"推理强度变更","efficiency.sawKindPrompt":"系统提示词已变更","efficiency.sawKindRules":"注入规则","efficiency.sawKindMemory":"记忆召回","efficiency.sawCompactionValue":"{before} → {after} tokens","efficiency.sawMemoryIds":"召回 {value} 条记忆(正文未记录)","efficiency.sawToolOk":"成功","efficiency.sawToolFailed":"失败","efficiency.sawToolNoMatch":"无匹配","efficiency.sawToolCancelled":"中断","efficiency.sawToolMissing":"无结果","efficiency.sawResultChars":"结果 {value} 字符","efficiency.sawUsage":"输入 {input} \xb7 输出 {output} \xb7 缓存读取 {cacheRead}","efficiency.sawStop":"结束:{value}","efficiency.sawToolsChanged":"工具列表变化:+{added} −{removed}","efficiency.sawPreludeTitle":"系统提示词与工具","efficiency.sawPreludeRecorded":"已记录","efficiency.sawPreludeTools":"最后一次请求启用的工具 {value} 个(已记录)","efficiency.sawPreludeDigest":"系统提示词指纹:{value}","efficiency.sawPreludeDigestNone":"没有此运行时的系统提示词指纹记录。","efficiency.sawPreludeMemory":"记忆召回块(系统提示词的一部分,已记录)","efficiency.sawPreludeReconstruct":"按当前设置重建","efficiency.sawPreludeLoading":"正在重建…","efficiency.sawPreludeApprox":"依据当前配置重建,并非实际发送的内容。","efficiency.sawPreludeNotLoaded":"此会话当前未加载,无法重建。系统提示词正文没有记录。","efficiency.sawPreludeMatch":"当前提示词指纹与此运行的记录一致。","efficiency.sawPreludeMismatch":"当前提示词指纹与此运行的记录不同,之后可能已变更。","toolRun.running":"运行中","toolRun.failed":"失败","toolRun.exitCode":"exit {code}","toolRun.diffStats":"新增 {added} 行,删除 {removed} 行","panel.expand":"加宽面板","panel.restore":"恢复原大小","panel.more":"更多","panel.liveSync":"实时同步","panel.subagentsCount":"{count} 条记录","panel.refresh":"刷新记录","panel.close":"关闭面板","makerDetail.region":"{title} 记录","makerDetail.noFiles":"此 Maker 未修改任何文件","makerDetail.noChecks":"未运行检查","makerDetail.archiveUnobserved":"记录中没有工具结果,无法确认","makerDetail.unavailable":"没有与此次尝试完全对应的运行记录,无法打开详情","makerDetail.checkPassed":"通过","makerDetail.checkUnverified":"判定未确认","makerDetail.checkFailed":"失败","makerDetail.checkUnobserved":"结果未观测","dispatchLane.label":"Maker 尝试","dispatchLane.runPhase":"{run}({phase})","dispatchLane.checks":"检查 {passed}/{total}","dispatchLane.checksUnobserved":"检查未观测","dispatchLane.checksLoading":"正在读取检查","dispatchLane.attempt":"尝试 {attempt}","dispatchLane.attemptUnknown":"尝试","dispatchLane.verdict.accepted":"已接受","dispatchLane.verdict.rework":"返工","dispatchLane.verdict.held":"搁置","dispatchLane.open":"详情","dispatchLane.openLabel":"查看 {title} 详情","dispatchLane.unavailable":"无详情"}}),l({id:"ko",label:"한국어",messages:a});var d=n(2730);let u="pi-locale",p=(0,i.createContext)(null);function h({children:e}){let[t,n]=(0,i.useState)("en"),[a,l]=(0,i.useState)(!1),f=(0,i.useMemo)(()=>c().map(e=>o.get(e)).filter(e=>!!e),[]),m=(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)&&s.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 g=(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,m,n),[t,m]),v=(0,i.useMemo)(()=>({locale:a?t:"en",setLocale:g,t:x,supportedLocales:f}),[a,t,g,x,f]);return(0,r.jsx)(p.Provider,{value:v,children:e})}function f(){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,[4697,7935,6072,7330,2545,3459,8441,3794,7358],()=>e(e.s=80455)),_N_E=e.O()}]);