cuelo 0.10.229 → 0.10.231
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +42 -42
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +3 -3
- package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/updates/apply/route.js +2 -2
- package/.next/server/app/api/updates/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +5 -5
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +5 -5
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +3 -3
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/page.js +23 -23
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover.html +1 -1
- package/.next/server/app/recover.rsc +3 -3
- package/.next/server/app/recover.segments/_full.segment.rsc +3 -3
- package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
- package/.next/server/app/recover.segments/_index.segment.rsc +3 -3
- package/.next/server/app/recover.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +42 -42
- package/.next/server/chunks/5228.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/app/{layout-bb5a2abb7335a2ec.js → layout-78992950595761ae.js} +1 -1
- package/.next/static/chunks/app/page-9a042d9510a4d9d1.js +78 -0
- package/.next/static/css/b17decbff4182973.css +1 -0
- package/.next/trace +111 -111
- package/.next/trace-build +1 -1
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
- package/Tools/CUELO_Setup/files/usage-server.js +6 -2
- package/package.json +1 -1
- package/.next/static/chunks/app/page-5f95f76dcb3429a4.js +0 -78
- package/.next/static/css/c97fff468c574ac0.css +0 -1
- /package/.next/static/{0bVgHjc3LMIqvoUU3Jofs → jZwEDDQlSi7wWchdQZc49}/_buildManifest.js +0 -0
- /package/.next/static/{0bVgHjc3LMIqvoUU3Jofs → jZwEDDQlSi7wWchdQZc49}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2498:e=>{e.exports={view:"MemoryTraceView_view__62Ck_",body:"MemoryTraceView_body__gELit",message:"MemoryTraceView_message__pDO_k",errorText:"MemoryTraceView_errorText__GkoKJ",sectionTitle:"MemoryTraceView_sectionTitle__lmuuo",sectionCount:"MemoryTraceView_sectionCount__9yRSn",requests:"MemoryTraceView_requests__scPBk",requestScroller:"MemoryTraceView_requestScroller__4ALfU",requestList:"MemoryTraceView_requestList__rQ4G0",requestRow:"MemoryTraceView_requestRow__LZd3A",stationButton:"MemoryTraceView_stationButton__BztyW",requestIndex:"MemoryTraceView_requestIndex__TacwG",requestTime:"MemoryTraceView_requestTime__fJjQF",noticeChip:"MemoryTraceView_noticeChip__gz9AO",requestPreview:"MemoryTraceView_requestPreview__HwG7v",miniRail:"MemoryTraceView_miniRail__84C2v",flow:"MemoryTraceView_flow__UCgmI",titleText:"MemoryTraceView_titleText__38Tl7",flowPreview:"MemoryTraceView_flowPreview__HjgKe",rail:"MemoryTraceView_rail__HlWbE",station:"MemoryTraceView_station__ulNBH",stationStep:"MemoryTraceView_stationStep__CgFYZ",stationCount:"MemoryTraceView_stationCount__2_rrN",stationLabel:"MemoryTraceView_stationLabel__QGYpC",stationNote:"MemoryTraceView_stationNote__Jc30I",detail:"MemoryTraceView_detail__Rnn_d",stageEmpty:"MemoryTraceView_stageEmpty__x0H_J",group:"MemoryTraceView_group__1SCqK",bucket:"MemoryTraceView_bucket__Vmuau",groupTitle:"MemoryTraceView_groupTitle__6Q1oM",groupCode:"MemoryTraceView_groupCode__qgzOG",query:"MemoryTraceView_query__DK87N",items:"MemoryTraceView_items__D8Wz8",item:"MemoryTraceView_item__wyulb",idList:"MemoryTraceView_idList__mQArH",path:"MemoryTraceView_path__97O3u",itemHead:"MemoryTraceView_itemHead__B0bQo",memoryId:"MemoryTraceView_memoryId__5KjoX",itemMeta:"MemoryTraceView_itemMeta__wbj6K",itemText:"MemoryTraceView_itemText__O92R_",graph:"MemoryTraceView_graph__RHbn9",graphHead:"MemoryTraceView_graphHead__sEDhc",scopeSwitch:"MemoryTraceView_scopeSwitch__3HBI2",legend:"MemoryTraceView_legend__52_dq",legendMark:"MemoryTraceView_legendMark__hS7sK",legendTitle:"MemoryTraceView_legendTitle__z_lgW",legendMemory:"MemoryTraceView_legendMemory__mkYqP",graphCaption:"MemoryTraceView_graphCaption__ot7gW",captionKind:"MemoryTraceView_captionKind__e1fLD",graphFrame:"MemoryTraceView_graphFrame__SgiqG",graphSvg:"MemoryTraceView_graphSvg___JeWV",columnHeads:"MemoryTraceView_columnHeads__drsYb",edges:"MemoryTraceView_edges__4zMSL",node:"MemoryTraceView_node__ymwrL",hit:"MemoryTraceView_hit__HS6HS",mark:"MemoryTraceView_mark__WxCZl",arrow:"MemoryTraceView_arrow__oz9U4",nodeText:"MemoryTraceView_nodeText__Tp4ud",ring:"MemoryTraceView_ring___LM5n"}},2730:(e,t,r)=>{"use strict";function n(e,t,r,a={}){let i=r[e]?.[t]??r.en?.[t];return void 0===i?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,r)=>{let n=t[r];return void 0===n?e:String(n)})}(i,a)}r.d(t,{u0:()=>n})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,r)=>{"use strict";r.d(t,{C1:()=>i,IN:()=>a,getPresetFromTools:()=>o,xG:()=>l});let n=[],a=["read","bash","edit","write"],i=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(i.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let r=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return r===[...a].sort().join(",")?"default":r===[...i].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...n]:"full"===e?[...i]:[...a]}},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"}},29213:e=>{e.exports={view:"PluginLabPanel_view__Sot51",toolbar:"PluginLabPanel_toolbar__co_Uq",hint:"PluginLabPanel_hint__kb7Hq",body:"PluginLabPanel_body__T_QMu",message:"PluginLabPanel_message__QbEDh",errorText:"PluginLabPanel_errorText__EI47_",list:"PluginLabPanel_list__BnAn6",card:"PluginLabPanel_card__5479R",cardHead:"PluginLabPanel_cardHead__SCiZ3",titleBlock:"PluginLabPanel_titleBlock__zfcvo",titleLine:"PluginLabPanel_titleLine__OmG7U",name:"PluginLabPanel_name__t4Ea0",id:"PluginLabPanel_id__osclH",control:"PluginLabPanel_control___gzgN",switch:"PluginLabPanel_switch__m3agg",switchLabel:"PluginLabPanel_switchLabel__DGX6y",description:"PluginLabPanel_description__PfruO",enhancement:"PluginLabPanel_enhancement__TOHjM",enhancementHead:"PluginLabPanel_enhancementHead__sgewN",enhancementDate:"PluginLabPanel_enhancementDate__4YWB1",enhancementSummary:"PluginLabPanel_enhancementSummary__srTnj",tools:"PluginLabPanel_tools__raR8s",metaLabel:"PluginLabPanel_metaLabel__LY5ak",toolList:"PluginLabPanel_toolList___rd6_",tool:"PluginLabPanel_tool___AjRR",problem:"PluginLabPanel_problem__Sx4aQ",problemLabel:"PluginLabPanel_problemLabel__rBSUT",cardActions:"PluginLabPanel_cardActions__GI_Bb",stage:"PluginLabPanel_stage__1l0FR",frame:"PluginLabPanel_frame__sP_V0",status:"PluginLabPanel_status__BYiAs",lines:"PluginLabPanel_lines__ONctT",notice:"PluginLabPanel_notice__mn_vu"}},40960:e=>{e.exports={active:"ComputerTakeoverControl_active__7430b"}},66592:e=>{e.exports={root:"TypedInterpreter_root__q_c0E",results:"TypedInterpreter_results__6j7HQ",turn:"TypedInterpreter_turn__BELhE",label:"TypedInterpreter_label__tFGb1",original:"TypedInterpreter_original__IxOOM",translation:"TypedInterpreter_translation__bR55x",composer:"TypedInterpreter_composer__IgxpT",direction:"TypedInterpreter_direction__8Chyz",field:"TypedInterpreter_field__6QmFe",submit:"TypedInterpreter_submit__tRKd5",error:"TypedInterpreter_error__h7BTN",modes:"TypedInterpreter_modes__Krr0C",toolbar:"TypedInterpreter_toolbar__L_2u0"}},80455:(e,t,r)=>{Promise.resolve().then(r.bind(r,81353)),Promise.resolve().then(r.bind(r,84183))},81353:(e,t,r)=>{"use strict";r.d(t,{AppShell:()=>yC});var n=r(95155),a=r(12115),i=r(73321),s=r(16871),o=r(81886),l=r(68890),c=r(66919);let d=["chat","process","subagents","files","resource","sidechat","efficiency","plugins","memory"],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}),m=Object.fromEntries(d.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let r,n=f(t.view);return{activeView:n,transientLayer:null,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"open-layer":{let r,n=f(e.activeView);return{activeView:n,transientLayer:t.layer,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"toggle-layer":{let r,n=f(e.activeView);return{activeView:n,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"close-layer":{let t,r=f(e.activeView);return{activeView:r,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==r&&t)}}case"set-deck-expanded":{let r,n=f(e.activeView);return{activeView:n,transientLayer:e.transientLayer,deckExpanded:(r=t.expanded,"chat"!==n&&r)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function T(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[r,n]of Object.entries(t.opened))"number"==typeof n&&Number.isFinite(n)&&(e[r]=n);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let r=null;for(let[n,a]of Object.entries(t.opened))(e.opened[n]??-1/0)>=a||((r??={...e.opened})[n]=a);return!r&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:r??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function E(e,t,r){let n=Math.max(r,M(t)??0);return(e.opened[t.id]??-1/0)>=n?e:{since:e.since,opened:{...e.opened,[t.id]:n}}}let $=new Set;function R(e,t){let r=null;for(let n of t)Object.hasOwn(e.opened,n)&&(r??={...e.opened},delete r[n]);return r?{since:e.since,opened:r}:e}function L(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 A(e){let t=new Map;for(let r of e){let e=r.projectRoot??r.cwd;if(!e)continue;let n=L(e),a=t.get(n);(!a||r.modified>a.modified)&&t.set(n,{project:e,modified:r.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function P(e,t){let r=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&r.set(L(e.key),e.order);let n=[...e],a=new Set(e.map(L));for(let e of t){let t=L(e.key);!t||a.has(t)||(n.push(e.path??e.key),a.add(t))}return n.map((e,t)=>({project:e,defaultIndex:t,order:r.get(L(e))})).sort((e,t)=>{let r=void 0!==e.order,n=void 0!==t.order;return r!==n?r?-1:1:r&&n&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let F=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function _(e){let t=e.match(F);if(!t)return null;let[,r,,,n]=t;return n?`/skill:${r} ${n}`:`/skill:${r}`}var z=r(84183);let W=`(max-width: ${p.navigator-1}px)`;function O(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let r=window.matchMedia(e);return r.addEventListener("change",t),()=>r.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=O("(max-width: 640px)"),H=O(W);function U(){return!1}function B(){return(0,a.useSyncExternalStore)(D.subscribe,D.getSnapshot,U)}var q=r(47650);async function V(e){let t=e?`?path=${encodeURIComponent(e)}`:"",r=await fetch(`/api/cwd/browse${t}`),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return n}function K(){return(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function G(){return(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,n.jsx)("path",{d:"M2 9h12"}),(0,n.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function J({onCancel:e,onSelect:t,busy:r=!1,error:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(""),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(""),[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)(null),[w,k]=(0,a.useState)(null),[j,S]=(0,a.useState)(!0),C=(0,a.useCallback)(async e=>{S(!0),k(null);try{let t=await V(e),r=t.path??e??"/";d(r),p(t.parentPath??null),m(!0===t.upToDrives),g(r),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,a.useEffect)(()=>{l(document.body),C()},[C]);let N=f.trim()!==c,T=!!c&&!N&&!r,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,q.createPortal)((0,n.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||r||e()},onKeyDown:t=>{"Escape"!==t.key||r||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,n.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1},children:(0,n.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,n.jsx)("button",{type:"button",onClick:e,disabled:r,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:r?"default":"pointer",opacity:r?.5:1},children:"\xd7"})]}),(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!I,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:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:I?"pointer":"default",opacity:I?1:.45},children:(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,n.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,n.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,n.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,n.jsx)(n.Fragment,{children:b.length>0?b.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(G,{}),(0,n.jsx)("span",{children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(K,{}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||i)&&(0,n.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??i})]}),(0,n.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:r,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:r?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!T,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:T?1:.6,cursor:T?"pointer":"default"},children:s(r?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Z=r(21443),Y=r.n(Z);async function X(e,t){let r=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),n=await r.json();if(!r.ok)throw Error(n.error||`HTTP ${r.status}`);return n}function Q({onCancel:e,onSelect:t,busy:r=!1,error:i}){let{t:s}=(0,z.s)(),o=(0,a.useRef)(null),[l,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(!1),[p,h]=(0,a.useState)(null),[m,f]=(0,a.useState)([]),[g,x]=(0,a.useState)(""),[v,b]=(0,a.useState)(""),[y,w]=(0,a.useState)(!0),[k,j]=(0,a.useState)(!1),[S,C]=(0,a.useState)(!1),[N,T]=(0,a.useState)(null),[I,M]=(0,a.useState)(!1),[E,$]=(0,a.useState)(50),R=p?.device?.state==="pending",L=r||S,A=(0,a.useCallback)(async()=>{w(!0),T(null);try{let e=await X("/api/github/projects");h(e),e.connected&&f((await X("/api/github/projects?view=repositories")).repositories)}catch(e){T(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function P(){j(!0),T(null);try{let{device:e}=await X("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){T(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function F(e){if(e.preventDefault(),v.trim()&&!L){C(!0),T(null);try{let{cwd:e}=await X("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){T(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,a.useEffect)(()=>{c(!0),A()},[A]),(0,a.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,a.useEffect)(()=>{let e;if(!R||d)return;let t=!1,r=async()=>{try{let e=await X("/api/github/projects");if(t)return;if(h(e),e.connected)return void await A();if(e.device?.state!=="pending")return}catch(e){t||T(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(r,3e3))};return e=window.setTimeout(r,1500),()=>{t=!0,clearTimeout(e)}},[R,d,A]),!l)return null;if(d)return(0,n.jsx)(J,{onCancel:()=>u(!1),onSelect:t,busy:r,error:i});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),W=N??i??p?.device?.error;return(0,q.createPortal)((0,n.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),L||e()},children:(0,n.jsxs)("form",{onSubmit:F,className:Y().form,children:[(0,n.jsxs)("header",{className:Y().header,children:[(0,n.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,n.jsx)("p",{children:s("cloudProjects.description")})]}),(0,n.jsxs)("div",{className:Y().sources,children:[(0,n.jsx)("span",{className:Y().activeSource,children:s("cloudProjects.github")}),(0,n.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:L,children:s("cloudProjects.serverFolder")})]}),(0,n.jsxs)("div",{className:Y().body,children:[(0,n.jsxs)("section",{className:Y().account,"aria-label":s("cloudProjects.account"),children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,n.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:y||L,children:s("cloudProjects.refresh")}):(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:y||k||R||L,children:k||R?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),R&&(0,n.jsxs)("div",{className:Y().login,role:"status",children:[(0,n.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:Y().codeRow,children:[(0,n.jsx)("code",{children:p.device.code}),(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>T(s("cloudProjects.copyFailure")))},children:I?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,n.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Y().loginLink,children:s("cloudProjects.openLogin")}),(0,n.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,n.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,n.jsxs)("section",{className:Y().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,n.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,n.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),$(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:L}),y?(0,n.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:Y().list,children:_.slice(0,E).map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":v===e.fullName,disabled:L,onClick:()=>b(e.fullName),children:[(0,n.jsxs)("span",{className:Y().repoHeading,children:[(0,n.jsx)("strong",{children:e.fullName}),(0,n.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,n.jsx)("span",{className:Y().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,n.jsx)("p",{children:s("cloudProjects.empty")}),_.length>E&&(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>$(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,n.jsxs)("div",{className:Y().repositoryInput,children:[(0,n.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,n.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:L,"aria-describedby":"cloud-repo-help"}),(0,n.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),W&&(0,n.jsxs)("div",{className:Y().error,role:"alert",children:[(0,n.jsx)("strong",{children:s("cloudProjects.error")}),(0,n.jsx)("p",{children:W}),(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:L,children:s("cloudProjects.refresh")})]}),S&&(0,n.jsx)("p",{role:"status",className:Y().progress,children:s("cloudProjects.openingHelp")})]}),(0,n.jsxs)("footer",{className:Y().footer,children:[(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:L,children:s("i18n.cancel")}),(0,n.jsx)("button",{type:"submit",className:Y().primary,disabled:L||!v.trim(),children:L?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function ee({label:e="CUELO",markSize:t=22,gap:r=10,style:a,labelStyle:i}){return(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:r,minWidth:0,color:"var(--text)",...a},children:[(0,n.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,n.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...i},children:e})]})}var et=r(2730);let er={ko:{"translator.modeVoice":"대화","translator.modeType":"타자","translator.source":"입력 언어","translator.swapDirection":"방향 바꾸기","translator.typeLabel":"번역할 문장","translator.typePlaceholder":"여행 중 전할 말을 입력하세요.","translator.typeSubmit":"번역","translator.typePending":"번역 중…","translator.typeError":"번역하지 못했어요. 다시 시도해 주세요.","translator.typeAuth":"Codex 로그인 상태를 확인해 주세요.","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":"통역 기록","translator.mood":"분위기","translator.mood.casual":"편하게","translator.mood.polite":"정중하게","translator.mood.formal":"격식 있게","translator.mood.haggling":"흥정","translator.mood.urgent":"긴급","translator.gender":"내 성별","translator.gender.male":"남성","translator.gender.female":"여성","translator.age":"내 나이대","translator.age.20s":"20대","translator.age.30s":"30대","translator.age.40s":"40대","translator.age.50s":"50대","translator.age.60s":"60대 이상","translator.partnerGender":"상대 성별","translator.partnerAge":"상대 나이","translator.partnerAge.child":"아이","translator.partnerAge.younger":"나보다 어리거나 비슷","translator.partnerAge.older":"나보다 위","translator.partnerAge.parent":"부모님 또래","translator.partnerAge.grandparent":"조부모님 또래","translator.notSet":"선택 안 함","translator.face":"마주보기","translator.faceHint":"상대 쪽 자막을 뒤집어 마주 앉은 사람이 읽게 합니다","translator.reconnecting":"다시 연결 중…","translator.idleStopped":"한동안 대화가 없어 통역을 멈췄습니다. 다시 시작하면 앞 대화에 이어집니다.","translator.generationSkipped":"방금 말은 통역하지 못하고 넘어갔습니다. 이어서 말씀하시면 계속 통역합니다.","translator.setup":"언어\xb7상황 설정","translator.sizeDown":"글자 작게","translator.sizeUp":"글자 크게","translator.faceExit":"마주보기 끄기","translator.translating":"옮기는 중…","translator.errorStatus":"통역이 멈췄습니다","translator.translation":"통역","translator.unknownLanguage":"언어 모름","translator.jumpLatest":"최근 말로","translator.voice":"통역 음성 듣기","translator.voiceHint":"끄면 통역을 글로만 보여 줍니다. 스피커가 조용하니 마이크를 막지 않아 통역 중에 끼어든 말도 들립니다.","translator.echoGuard":"통역 음성이 나올 때 마이크 끄기","translator.echoGuardHint":"스피커로 나온 통역이 다시 통역되지 않게 합니다. 그동안 상대가 한 말은 들리지 않으니 이어폰을 쓰면 꺼 두세요.","translator.noiseSuppression":"AI 소음 제거","translator.fastDrafts":"빠른 초안 자막","translator.fastDraftsHint":"전용 번역 모델이 초안 자막을 먼저 띄우고 Codex가 곧 바로잡습니다. 켜 둔 동안 추가 요금이 들 수 있습니다.","translator.noiseSuppressionHint":"시끄러운 곳에서 마이크 소음을 줄여 통역이 말을 더 잘 알아듣게 합니다. 목소리가 뭉개지면 꺼 두세요."},en:{"translator.modeVoice":"Voice","translator.modeType":"Type","translator.source":"Input language","translator.swapDirection":"Swap direction","translator.typeLabel":"Text to translate","translator.typePlaceholder":"Type what you want to say.","translator.typeSubmit":"Translate","translator.typePending":"Translating…","translator.typeError":"Translation failed. Try again.","translator.typeAuth":"Check your Codex sign-in.","translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and Codex Live 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","translator.mood":"Mood","translator.mood.casual":"Casual","translator.mood.polite":"Polite","translator.mood.formal":"Formal","translator.mood.haggling":"Haggling","translator.mood.urgent":"Urgent","translator.gender":"My gender","translator.gender.male":"Male","translator.gender.female":"Female","translator.age":"My age","translator.age.20s":"20s","translator.age.30s":"30s","translator.age.40s":"40s","translator.age.50s":"50s","translator.age.60s":"60+","translator.partnerGender":"Their gender","translator.partnerAge":"Their age","translator.partnerAge.child":"Child","translator.partnerAge.younger":"Younger or same age","translator.partnerAge.older":"Older than me","translator.partnerAge.parent":"My parents' age","translator.partnerAge.grandparent":"My grandparents' age","translator.notSet":"Not set","translator.face":"Face to face","translator.faceHint":"Flip the other side's captions so the person across from you can read them","translator.reconnecting":"Reconnecting…","translator.idleStopped":"Interpreting stopped after a long silence. Start again to continue the conversation.","translator.generationSkipped":"That last line couldn't be interpreted and was skipped. Keep talking; interpreting continues.","translator.setup":"Languages and setting","translator.sizeDown":"Smaller text","translator.sizeUp":"Larger text","translator.faceExit":"Leave face to face","translator.translating":"Interpreting…","translator.errorStatus":"Interpreting stopped","translator.translation":"Interpretation","translator.unknownLanguage":"Language unknown","translator.jumpLatest":"Jump to latest","translator.voice":"Play the interpretation aloud","translator.voiceHint":"Off, the interpretation is shown as text only. With the speaker silent the mic stays open, so words spoken over an interpretation are heard too.","translator.echoGuard":"Mute the mic while the interpretation plays","translator.echoGuardHint":"Keeps the speaker's interpretation from being interpreted again. Words spoken meanwhile are not heard, so turn it off with earphones.","translator.noiseSuppression":"AI noise suppression","translator.fastDrafts":"Quick draft captions","translator.fastDraftsHint":"A dedicated translation model shows a quick draft first and Codex corrects it. Extra charges may apply while this is on.","translator.noiseSuppressionHint":"Cuts background noise from the mic in a loud place so the interpreter hears you better. Turn it off if your voice sounds muffled."}};function en(){let{locale:e}=(0,z.s)();return{tt:(0,a.useCallback)((t,r)=>(0,et.u0)(e,t,er,r),[e]),locale:e}}let ea="omp-web:unread-session-ids",ei="omp-web:pinned-session-ids",es="omp-web:removed-projects";function eo(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 el(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function ec({text:e,style:t}){return(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,n.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function ed({open:e,children:t,style:r}){let[i,s]=(0,a.useState)(e),[o,l]=(0,a.useState)(e);return((0,a.useEffect)(()=>{let t,r;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),r=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),r&&clearTimeout(r)}},[e]),i)?(0,n.jsx)("div",{style:{...r,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 eu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ep(){let[e,t]=(0,a.useState)(!1),[r,i]=(0,a.useState)(!1),s=(0,a.useRef)(null),o=function(e,t){let[r,n]=(0,a.useState)(e),i=(0,a.useRef)(null),s=(0,a.useRef)(0);return(0,a.useEffect)(()=>{if(!t)return void n(e);s.current=0;let r=4*e.length,a=()=>{s.current+=1;let t=Math.floor(s.current/r*e.length);n(e.split("").map((e,r)=>" "===e?" ":r<t?e:eu[Math.floor(Math.random()*eu.length)]).join("")),s.current<r?i.current=requestAnimationFrame(a):n(e)};return i.current=requestAnimationFrame(a),()=>{i.current&&cancelAnimationFrame(i.current)}},[e,t]),r}(e?"0.10.231/18.19.0":"CUELO",r),l=(0,a.useCallback)(e=>{t(e),i(!0),setTimeout(()=>i(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,a.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,a.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,n.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,n.jsx)(ee,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eh(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 em({selectedSessionId:e,optimisticSession:t,onSelectSession:r,onNewSession:i,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:m,translatorActive:f=!1,onTranslatorActiveChange:g}){let x,{tt:v}=en(),{t:b,locale:y}=(0,z.s)(),w=B(),[F,_]=(0,a.useState)([]),W=(0,a.useMemo)(()=>t&&!F.some(e=>e.id===t.id)?[t,...F]:F,[F,t]),[O,D]=(0,a.useState)(!0),[H,U]=(0,a.useState)(null),[q,V]=(0,a.useState)(null),[K,G]=(0,a.useState)(""),[Z,Y]=(0,a.useState)(!1),[X,ee]=(0,a.useState)(""),[et,er]=(0,a.useState)("projects"),[eu,eg]=(0,a.useState)(()=>new Set),[ey,ew]=(0,a.useState)(()=>new Set),[ek,eS]=(0,a.useState)(null),[eC,eN]=(0,a.useState)(null),[eT,eI]=(0,a.useState)({version:1,projects:[]}),[eM,eE]=(0,a.useState)(!1),[e$,eR]=(0,a.useState)(!1),[eL,eA]=(0,a.useState)(!1),[eP,eF]=(0,a.useState)(null),[e_,ez]=(0,a.useState)(""),[eW,eO]=(0,a.useState)(!1),[eD,eH]=(0,a.useState)(null),[eU,eB]=(0,a.useState)(""),[eq,eV]=(0,a.useState)(!1),[eK,eG]=(0,a.useState)(null),[eJ,eZ]=(0,a.useState)(!1),[eY,eX]=(0,a.useState)(null),[eQ,e0]=(0,a.useState)(!1),[e1,e2]=(0,a.useState)(!1),[e8,e4]=(0,a.useState)(""),[e5,e6]=(0,a.useState)(null),[e3,e7]=(0,a.useState)(!1),[e9,te]=(0,a.useState)(null),tt=(0,a.useRef)(null),tr=(0,a.useRef)(null),tn=(0,a.useRef)(null),ta=(0,a.useRef)(!1),ti=(0,a.useRef)(!1),[ts,to]=(0,a.useState)(!1),[tl,tc]=(0,a.useState)(()=>new Set),[td,tu]=(0,a.useState)(()=>new Set),[tp,th]=(0,a.useState)(()=>(function(){try{let e=window.localStorage.getItem(ea);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}})()),[tm,tf]=(0,a.useState)(()=>new Set),[tg,tx]=(0,a.useState)(null),[tv,tb]=(0,a.useState)(!1),ty=(0,a.useRef)(new Set),tw=(0,a.useRef)(!1),tk=(0,a.useRef)(null);(0,a.useEffect)(()=>{tf(function(){try{let e=window.localStorage.getItem(ei);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,a.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}tx(T(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=T(e.newValue,Date.now());tx(e=>e?I(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let tj=(0,a.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eI(await e.json())}catch{eI({version:1,projects:[]})}finally{eE(!0)}},[]);(0,a.useEffect)(()=>{tj()},[tj,c]),(0,a.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(es)}catch{return}if(!e)return;let t=[];try{let r=JSON.parse(e);Array.isArray(r)&&(t=r.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let r=t.slice(e,e+500);await eh(r.map(e=>({key:L(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(es)}catch{}await tj()})()},[tj]);let tS=(0,a.useCallback)(async e=>{if(ti.current)throw Error("Project update in progress");ti.current=!0,eO(!0);try{await eh(e),await tj()}finally{ti.current=!1,eO(!1)}},[tj]);(0,a.useEffect)(()=>{eP&&tn.current?.select()},[eP]);let tC=(0,a.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();_(n.sessions),tw.current||tc(new Set(n.runningSessionIds??[])),U(null),e||(to(!0),tk.current&&clearTimeout(tk.current),tk.current=setTimeout(()=>to(!1),2e3))}catch(e){U(String(e))}finally{e&&D(!1)}},[]),tN=(0,a.useCallback)(e=>{th(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),tf(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),tx(t=>t&&R(t,[e])),d?.(e),tC()},[tC,d]),[tT,tI]=(0,a.useState)(null),[tM,tE]=(0,a.useState)(!1),[t$,tR]=(0,a.useState)(null),tL=(0,a.useCallback)(()=>{tM||(tI(null),tR(null))},[tM]),tA=(0,a.useCallback)(async e=>{tE(!0),tR(null);let t=[],r=[],n=[];for(let a of e)if(!a.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(a.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){r.push(a.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(a.id)}catch{n.push(a.name?.trim()||a.id.slice(0,8))}if(r.length>0&&(tw.current=!0,tc(e=>{if(r.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of r)t.add(e);return t})),t.length>0){let e=new Set(t),r=r=>t.some(e=>r.has(e))?new Set([...r].filter(t=>!e.has(t))):r;for(let e of(th(r),tf(r),tx(e=>e&&R(e,t)),t))d?.(e)}(await tC(),tE(!1),n.length>0)?tR(b("sidebar.clearSessionsFailed",{count:n.length,names:n.join(", ")})):r.length>0||tI(null)},[tC,d,b]),[tP,tF]=(0,a.useState)(0),t_=(0,a.useCallback)(()=>{tF(e=>e+1),tC()},[tC]),tz=(0,a.useRef)(!1);(0,a.useEffect)(()=>{let e=!tz.current;tz.current=!0,tC(e,!e)},[tC,c]),(0,a.useEffect)(()=>{try{er(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 tW=(0,a.useCallback)(e=>{er(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,a.useEffect)(()=>{if("priority"!==et)return;let e=()=>{"visible"===document.visibilityState&&tC(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tC,et]),(0,a.useEffect)(()=>{try{0===tp.size?window.localStorage.removeItem(ea):window.localStorage.setItem(ea,JSON.stringify([...tp]))}catch{}},[tp]),(0,a.useEffect)(()=>{try{0===tm.size?window.localStorage.removeItem(ei):window.localStorage.setItem(ei,JSON.stringify([...tm]))}catch{}},[tm]),(0,a.useEffect)(()=>{if(tg)try{var e,t,r;let n,a,i=window.localStorage;i.setItem(N,(e=i.getItem(N),t=Date.now(),a=(n=Object.entries((r=I(tg,T(e,t))).opened)).length>500?n.sort((e,t)=>t[1]-e[1]).slice(0,500):n,JSON.stringify({since:r.since,opened:Object.fromEntries(a)})))}catch{}},[tg]);let tO=(0,a.useCallback)(e=>{tf(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]);(0,a.useEffect)(()=>{let e=!1,t=null,r=null,n=()=>{t&&clearTimeout(t),t=null},a=async()=>{if(e||"visible"!==document.visibilityState)return;let i=new AbortController;r?.abort(),r=i;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:i.signal});if(!t.ok)return;let n=await t.json();if(e||r!==i)return;tw.current=!0,tc(new Set(n.runningSessionIds??[])),tu(new Set(n.waitingSessionIds??[]))}catch{}finally{r===i&&(r=null),n(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void a(),2500))}},i=()=>{"visible"===document.visibilityState?a():(n(),r?.abort(),r=null)};return a(),document.addEventListener("visibilitychange",i),()=>{e=!0,n(),r?.abort(),document.removeEventListener("visibilitychange",i)}},[]),(0,a.useEffect)(()=>{let t=ty.current,r=[...t].filter(t=>!tl.has(t)&&t!==e),n=[...tl].filter(e=>!t.has(e));(r.length>0||n.length>0)&&th(e=>{let t=new Set(e);return tl.forEach(e=>t.delete(e)),r.forEach(e=>t.add(e)),t});let a=n.some(e=>!F.some(t=>t.id===e));(r.length>0||a)&&tC(!1,!0),r.length>0&&h?.(),ty.current=tl},[tl,e,F,tC,h]),(0,a.useEffect)(()=>{e&&th(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r})},[e]);let tD=e?W.find(t=>t.id===e)?.modified:void 0,tH=null!==tg;(0,a.useEffect)(()=>{e&&void 0!==tD&&tH&&tx(t=>t&&E(t,{id:e,modified:tD},Date.now()))},[e,tD,tH]),(0,a.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&G(e.home),Y(!0===e.cloudProjects)}).catch(()=>{})},[]);let tU=(0,a.useRef)(!1),tB=(0,a.useCallback)(e=>{if(!e)return null;if(eY&&eY.forCwd===e||eY?.worktrees.some(t=>t.path===e))return eY.projectRoot;let t=W.find(t=>t.cwd===e);return t?.projectRoot??e},[eY,W]),tq=(0,a.useRef)(null);(0,a.useEffect)(()=>{tq.current!==q&&(tq.current=q,p?.(q,tB(q)))},[q,p,tB]);let tV=(0,a.useRef)(null);(0,a.useEffect)(()=>{u&&u!==tV.current&&(tV.current=u,V(u))},[u]);let[tK,tG]=(0,a.useState)(0);(0,a.useLayoutEffect)(()=>{if(!q)return void eX(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(q)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eX(null);eX({forCwd:q,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eX(null)}),()=>{e=!0}},[q,tK,c]),(0,a.useEffect)(()=>{if(0!==F.length&&!o&&null===q){if(s&&!tU.current){tU.current=!0;let e=F.find(e=>e.id===s);if(e){V(e.cwd),r(e,!0);return}l?.()}if(!eM)return;let e=new Map(eT.projects.map(e=>[e.key,e])),t=P(F.length>0?A(F):[],eT.projects).filter(t=>!e.get(L(t))?.hidden);t.length>0&&V(t[0])}},[F,q,s,o,r,l,eT,eM]);let tJ=(0,a.useCallback)(async e=>{let t=e.trim();if(t&&!eJ){eZ(!0),eG(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await e.json().catch(()=>({}));if(!e.ok||r.error)return void eG(r.error??b("workspace.unable"));let n=r.cwd??t,a=L(n),i=eT.projects.find(e=>e.key===a);if(i?.hidden===!0)try{await tS([{key:a,path:n,hidden:!1}])}catch{}V(n),eV(!1)}catch{eG(b("workspace.unable"))}finally{eZ(!1)}}},[tS,eJ,eT.projects,b]),tZ=(0,a.useCallback)(()=>{eV(!0),eG(null)},[]),tY=(0,a.useCallback)(async()=>{let e=e8.trim();if(e&&!e3&&eY){e7(!0),e6(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eY.projectRoot,branch:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error||!r.path)return void e6(r.error??`HTTP ${t.status}`);e2(!1),e4(""),e0(!1),eX(t=>t?{...t,forCwd:r.path,worktrees:[...t.worktrees,{path:r.path,branch:e,isMain:!1}]}:t),V(r.path),tG(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e7(!1)}}},[e8,e3,eY]),tX=(0,a.useCallback)(async(e,t)=>{if(eY&&!e3){e7(!0),e6(null);try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eY.projectRoot,path:e,force:t})}),n=await r.json().catch(()=>({}));if(!r.ok){if(n.dirty&&!t)return void te(e);e6(n.error??`HTTP ${r.status}`);return}te(null),q===e&&V(eY.projectRoot),tG(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e7(!1)}}},[eY,e3,q]);(0,a.useEffect)(()=>{let e=e=>{tt.current&&!tt.current.contains(e.target)&&(eN(null),e0(!1),e2(!1),e4(""),e6(null),te(null),eB(""),eS(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tQ=(0,a.useCallback)(e=>{e.cwd&&V(e.cwd),r(e)},[r]),t0=(0,a.useCallback)((e=q)=>{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)}`;V(e),i?.(t,e)},[q,i]),[t1,t2]=(0,a.useState)(!1),[t8,t4]=(0,a.useState)(null),t5=(0,a.useCallback)(async()=>{t2(!0),t4(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}`);t0(t.cwd)}catch(e){t4(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{t2(!1)}},[t0,b]),t6=(0,a.useCallback)(e=>{ew(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]),t3=tB(q),t7=null===t3?null:L(t3),t9=(0,a.useMemo)(()=>new Map(eT.projects.map(e=>[e.key,e])),[eT.projects]),re=A(W);if(null!==t3){let e=L(t3);re.some(t=>L(t)===e)||re.unshift(t3)}let rt=P(re,eT.projects),rr=rt.filter(e=>e$||!t9.get(L(e))?.hidden),rn=rt.some(e=>t9.get(L(e))?.hidden),ra=()=>{eN(null),e0(!1),e2(!1),e4(""),e6(null),te(null),eB("")},ri=async(e,t)=>{ra();try{await tS([{key:L(e),path:e,hidden:t}]),t&&t7&&t7===L(e)&&V(null),t||rt.some(t=>L(t)!==L(e)&&t9.get(L(t))?.hidden)||eR(!1)}catch{}},rs=async e=>{if(ta.current){ta.current=!1,eF(null);return}let t=e_.trim();if(t===(t9.get(L(e))?.alias??""))return void eF(null);eH(null);try{await tS([{key:L(e),path:e,alias:t||null}]),eF(null)}catch{eH(b("sidebar.projectUpdateFailed"))}},ro=async(e,t)=>{if(X)return;let r=rr.indexOf(e),n=r+t;if(r<0||n<0||n>=rr.length)return;let a=new Set(rr),i=rt.map((e,t)=>a.has(e)?t:-1).filter(e=>e>=0),s=[...rt],o=i[r],l=i[n];[s[o],s[l]]=[s[l],s[o]],ra();try{await tS(s.map((e,t)=>({key:L(e),path:e,order:t})))}catch{}},rl=new Map;for(let e of W){let t=e.projectRoot??e.cwd;if(!t)continue;let r=L(t),n=rl.get(r);n?n.push(e):rl.set(r,[e])}let rc=(0,a.useMemo)(()=>{let e=new Map;for(let t of W){let r=t.projectRoot??t.cwd;if(!r)continue;let n=L(r),a=e.get(n);a||(a={running:0,unread:0},e.set(n,a)),tl.has(t.id)&&a.running++,tp.has(t.id)&&a.unread++}return e},[W,tl,tp]),rd=X.trim().toLowerCase(),ru=X.length>0,rp=rr.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,r=L(e),n=t9.get(r),a=n?.alias??t,i=(rl.get(r)??[]).slice().sort((e,t)=>{let r=Number(tm.has(t.id))-Number(tm.has(e.id));return 0!==r?r:t.modified.localeCompare(e.modified)});if(!rd)return[{project:e,key:r,name:a,sessions:i,hidden:n?.hidden===!0}];let s=a.toLowerCase().includes(rd)||t.toLowerCase().includes(rd),o=i.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(rd));return s||0!==o.length?[{project:e,key:r,name:a,sessions:s?i:o,hidden:n?.hidden===!0}]:[]}),rh=[],rm=[];for(let e of rp){let t=e.key===t7||(rc.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?rm.push(e):rh.push(e)}let rf={running:0,unread:0};for(let e of rm){let t=rc.get(e.key);t&&(rf.running+=t.running,rf.unread+=t.unread)}let rg=ru||eL,rx=[...rh.map(e=>({kind:"project",group:e})),...rm.length>0?[{kind:"temporary"}]:[],...rg?rm.map(e=>({kind:"project",group:e})):[]],rv=function(e){let t=new Map;for(let r of e){let e=r.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(rx.flatMap(e=>"project"===e.kind?[e.group.name]:[])),rb=(0,a.useMemo)(()=>tg?W.filter(e=>(function(e,t,r,n=$){if(e.transient||e.trial)return!1;if(n.has(e.id))return!0;if(t.has(e.id))return!1;let a=M(e);return null!==a&&a>(r.opened[e.id]??r.since)})(e,tl,tg,td)):[],[tg,tl,W,td]),ry=tv&&null!==tg,[rw,rk]=(0,a.useState)(null),rj=(0,a.useMemo)(()=>(function(e,t,r,n,a="Priority",i=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let r=Date.parse(e.modified),n=Date.parse(t.modified);return(Number.isFinite(n)?n:0)-(Number.isFinite(r)?r:0)}),c=l.filter(e=>i.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(i.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let r=new Date(e.modified);if(p>=o)continue;p+=1;let n=[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"),a=u.get(n);a?a.push(e):u.set(n,[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:a,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,r){let[n,a,i]=e.split("-").map(Number),s=new Date(n,a-1,i),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(r,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(r,{weekday:"long"}).format(s):new Intl.DateTimeFormat(r,{month:"short",day:"numeric"}).format(s)}(e,r,n),running:!1,sessions:u.get(e)??[]});return h})(ry?W.filter(e=>e.id===rw&&!tl.has(e.id)||rb.includes(e)):W,tl,new Date,y,b("navigator.priority"),tm,b("sidebar.pinned"),ry?1/0:void 0),[rw,y,tm,rb,ry,tl,W,b]),rS=(0,a.useCallback)(e=>{rk(e.id),tQ(e)},[tQ]),rC=!!(eY?.isGit&&eY.isTopLevel&&q&&t3===eY.projectRoot),rN=eY?.worktrees.find(e=>e.path===q)??eY?.worktrees.find(e=>e.isMain),rT=(eY?.worktrees.length??0)>=8,rI=rT&&eU.trim()?(eY?.worktrees??[]).filter(e=>(e.branch??el(e.path,K)).toLowerCase().includes(eU.trim().toLowerCase())):eY?.worktrees??[],rM=(()=>{if(!tT)return[];let e="project"===tT.kind?rl.get(L(tT.project))??[]:rj.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),rE=rM.filter(e=>!tl.has(e.id)),r$=e=>{let t=new Set;for(let r of e)r.transient||tl.has(r.id)||t.has(r.id)||t.add(r.id);return t.size},rR=void 0!==m&&f;return(0,n.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eq&&(0,n.jsx)(Z?Q:J,{busy:eJ,error:eK,onCancel:()=>{eV(!1),eG(null)},onSelect:e=>void tJ(e)}),tT&&(0,n.jsx)(ef,{scope:tT,eligible:rE.length,runningExcluded:rM.length-rE.length,busy:tM,error:t$,onCancel:tL,onConfirm:()=>void tA(rE)}),(0,n.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,n.jsx)(ep,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,n.jsx)("button",{className:"navigator-icon-action",onClick:()=>t0(),disabled:!q,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:q?"var(--text-muted)":"var(--text-dim)",cursor:q?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:"var(--radius-control)",fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:q?b("sidebar.newSessionTitle",{path:q}):b("sidebar.selectProject"),"aria-label":q?b("sidebar.newSessionTitle",{path:q}):b("sidebar.selectProject"),onMouseEnter:e=>{q&&(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=q?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,n.jsx)("button",{className:`navigator-icon-action${ts?" is-success":""}`,onClick:()=>tC(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ts?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ts?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ts?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:"var(--radius-control)",padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{ts||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{ts||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:ts?(0,n.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),Z&&!rR&&(0,n.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tZ,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,n.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,n.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),r=!rR&&et===e;return(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":r,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tW(e),rR&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"transparent",color:r?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:r?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":rR,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!rR),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:rR?"var(--bg-selected)":"transparent",color:rR?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:rR?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!rR&&"projects"===et&&(0,n.jsx)("button",{type:"button",onClick:()=>eR(e=>!e),disabled:!rn,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":e$,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:e$?"var(--bg-selected)":"transparent",color:e$?"var(--accent)":"var(--text-dim)",cursor:rn?"pointer":"default",opacity:rn?1:.45,flexShrink:0},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!e$&&(0,n.jsx)("path",{d:"m4 4 16 16"})]})}),!rR&&"projects"===et&&(0,n.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tZ,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,n.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),rR&&m,!rR&&"projects"===et&&(0,n.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,n.jsx)("input",{className:"navigator-search-input",type:"search",value:X,onChange:e=>ee(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),ee(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!rR&&"projects"===et&&(0,n.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(O||!eM)&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),eD&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!O&&eM&&!H&&0===rp.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:rd?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!O&&eM&&!H&&rx.map(t=>{let r,a,i;if("temporary"===t.kind)return(0,n.jsx)("div",{className:"navigator-project-group",children:(0,n.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":rg,title:b("sidebar.temporaryProjects"),onClick:()=>eA(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,n.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:rg?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:rm.length}),ej(rf,b)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t7,p=rv.has(l.toLowerCase())&&el((a=Math.max((r=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),r.lastIndexOf("/")))<=0?"":r.slice(0,a),K)||null,h=!ey.has(s)&&!rd,m=eu.has(s),f=eP===s,g=rr.indexOf(s),x=eW||ru||g<=0,v=eW||ru||g>=rr.length-1,y=function(e){let t=new Map;for(let r of e)t.set(r.id,{session:r,children:[]});let r=new Map;for(let t of e)t.parentSessionId&&r.set(t.id,t.parentSessionId);let n=[];for(let e of t.values()){let a=function(e){let n=r.get(e),a=new Set;for(;n&&!a.has(n);){if(a.add(n),t.has(n))return n;n=r.get(n)}return null}(e.session.id);a?t.get(a).children.push(e):n.push(e)}let a=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>a(e.children))};return a(n),n}(m?c:c.slice(0,5)),k=c.length>5;return(0,n.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,n.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:eC===s?tt:void 0,onMouseEnter:()=>eS(s),onMouseLeave:()=>eS(e=>e===s&&eC!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:"var(--radius-control)",background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t6(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,n.jsx)("input",{ref:tn,value:e_,onChange:e=>ez(e.target.value),onBlur:()=>void rs(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),ta.current=!0,eF(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,n.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>V(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,n.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,n.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),ej(rc.get(o),b)]}),(0,n.jsx)("button",{type:"button",onClick:()=>t0(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||ek===s?1:0,pointerEvents:w||ek===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>eS(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,n.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,n.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,n.jsx)("button",{type:"button",onClick:()=>{eN(eC===s?null:s),e0(!1),e2(!1),e6(null),u||V(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":eC===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eC===s?"var(--bg-selected)":"transparent",color:u&&rN&&!rN.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ek===s||eC===s?1:0,pointerEvents:w||ek===s||eC===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>eS(s),children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,n.jsxs)(ed,{open:eC===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:"var(--radius-surface)",boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[rC&&eY&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",onClick:()=>e0(e=>!e),title:rN?b("sidebar.switchWorktreeTitle",{path:rN.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eQ,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eQ?"1px solid var(--border)":"none",background:eQ?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,n.jsxs)(ed,{open:eQ,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:[rT&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("input",{value:eU,onChange:e=>eB(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eB(""),e0(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,n.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[rI.map(e=>{let t=e.path===q||e.isMain&&!eY.worktrees.some(e=>e.path===q);return e9===e.path?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,n.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,n.jsx)("button",{onClick:()=>void tX(e.path,!0),disabled:e3,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,n.jsx)("button",{onClick:()=>te(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:b("sidebar.cancel")})]},e.path):(0,n.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("button",{onClick:()=>{V(e.path),e0(!1),e6(null),eB("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)(ec,{text:e.branch??el(e.path,K),style:{flex:1}}),e.isMain&&(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,n.jsx)("button",{onClick:()=>void tX(e.path,!1),disabled:e3,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:"var(--radius-control)",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),rT&&0===rI.length&&eU.trim()&&(0,n.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e1?(0,n.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,n.jsx)("input",{ref:tr,value:e8,onChange:e=>{e4(e.target.value),e6(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tY()),"Escape"===e.key&&(e2(!1),e4(""),e6(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,n.jsx)("button",{onClick:()=>void tY(),disabled:e3||!e8.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e3||!e8.trim()?"not-allowed":"pointer",opacity:e3||!e8.trim()?.65:1},children:e3?b("sidebar.creating"):b("sidebar.create")}),(0,n.jsx)("button",{onClick:()=>{e2(!1),e4(""),e6(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),e2(!0),e6(null),setTimeout(()=>tr.current?.focus(),0)},title:b("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,n.jsx)("span",{children:b("sidebar.newWorktree")})]}),e5&&(0,n.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e5})]})]}),(0,n.jsxs)("button",{type:"button",disabled:eW,onClick:()=>{let e;return e=t9.get(L(s))?.alias??"",void(ta.current=!1,eH(null),ez(e),eF(s),ra())},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:eW?"default":"pointer",textAlign:"left",fontSize:11,opacity:eW?.55:1},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,n.jsx)("path",{d:"m13.5 8 3 3"})]}),b(t9.get(L(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,n.jsxs)("button",{type:"button",disabled:x,title:ru?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ro(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,n.jsxs)("button",{type:"button",disabled:v,title:ru?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ro(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,n.jsxs)("button",{type:"button",disabled:eW,onClick:()=>void ri(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:eW?"default":"pointer",textAlign:"left",fontSize:11,opacity:eW?.55:1},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,n.jsx)("path",{d:"m4 4 16 16"})]}),b(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(i=0===r$(rl.get(o)??[])||tM,(0,n.jsxs)("button",{type:"button",disabled:i,onClick:()=>{ra(),tR(null),tI({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:i?"default":"pointer",textAlign:"left",fontSize:11,opacity:i?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,n.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,n.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,n.jsx)(eb,{node:t,selectedSessionId:e,runningSessionIds:tl,unreadSessionIds:tp,pinnedSessionIds:tm,onSelectSession:tQ,onTogglePinnedSession:tO,onRenamed:tC,onSessionDeleted:tN,onSessionArchived:t_,depth:0},t.session.id))}),!h&&k&&(0,n.jsx)("button",{type:"button",onClick:()=>{eg(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!rR&&(0,n.jsx)(ev,{refreshKey:tP,selectedSessionId:e,onSelectSession:tQ,onRestored:t_}),!rR&&"priority"===et&&(0,n.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[O&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,n.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),!O&&!H&&(x=r$(rj.flatMap(e=>e.sessions)),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,n.jsx)("button",{type:"button",disabled:t1,onClick:()=>void t5(),title:b("sidebar.newScratchSessionTitle"),style:eo(t1,w),children:b("sidebar.newScratchSession")}),rj.length>0&&!ry&&(0,n.jsx)("button",{type:"button",disabled:0===x||tM,onClick:()=>{tR(null),tI({kind:"priority"})},style:eo(0===x||tM,w),children:b("sidebar.clearPriorityList")})]})),!O&&!H&&tg&&(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,n.jsxs)("button",{type:"button","aria-pressed":ry,"aria-label":b("navigator.resultsToCheckCount",{count:rb.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{rk(null),tb(e=>!e)},style:{...eo(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ry?"var(--border-strong)":"var(--border)",background:ry?"var(--bg-selected)":"transparent",color:ry||rb.length>0?"var(--text)":"var(--text-muted)",fontWeight:ry?600:500,whiteSpace:"nowrap"},children:[b("navigator.resultsToCheck"),(0,n.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:rb.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:rb.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:rb.length})]}),rb.some(e=>!td.has(e.id))&&(0,n.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{rk(null),tx(e=>e&&function(e,t,r){let n=e;for(let e of t)n=E(n,e,r);return n}(e,rb,Date.now()))},style:eo(!1,w),children:b("navigator.acknowledgeResults")})]}),t8&&(0,n.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:t8}),!O&&!H&&0===rj.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ry?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!O&&!H&&rj.map((t,r)=>(0,n.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,n.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===r?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,n.jsx)(ex,{session:t,selected:t.id===e,running:tl.has(t.id),waiting:td.has(t.id),unread:tp.has(t.id),pinned:tm.has(t.id),onSelect:ry?rS:tQ,onTogglePin:tO},t.id))]},t.key))]})]})}function ef({scope:e,eligible:t,runningExcluded:r,busy:i,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,z.s)(),d=i||0===t,u=(0,a.useRef)(null),p=(0,a.useRef)(null),h=(0,a.useRef)(i);h.current=i;let m=(0,a.useRef)(o);return m.current=o,(0,a.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,r=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let n=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let a=r[0],i=r[r.length-1];t.shiftKey&&(n===a||!e.contains(n))?(t.preventDefault(),i.focus()):t.shiftKey||n!==i&&e.contains(n)||(t.preventDefault(),a.focus())};return e.addEventListener("keydown",n),()=>{e.removeEventListener("keydown",n);let t=r?.isConnected?r:e.closest(".session-navigator");t?.focus()}},[]),(0,n.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{i||e.target!==e.currentTarget||o()},children:(0,n.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,n.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,n.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),r>0&&(0,n.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:r})}),0===t&&(0,n.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{ref:p,type:"button",onClick:o,disabled:i,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:i?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,n.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":i,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(i?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function eg({filled:e=!1}){return(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 17v5"}),(0,n.jsx)("path",{d:"M5 17h14"}),(0,n.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ex({session:e,selected:t,running:r,waiting:a,unread:i,pinned:s,onSelect:o,onTogglePin:l}){let{t:c}=(0,z.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),u=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,n.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${r?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,n.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>o(e),title:`${d}
|
|
2
|
+
${e.cwd}
|
|
3
|
+
${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:d}),a&&(0,n.jsx)(ey,{}),r&&!a&&(0,n.jsx)(ew,{}),!r&&i&&(0,n.jsx)(ek,{})]}),(0,n.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:u})]}),(0,n.jsx)("button",{type:"button","aria-pressed":s,"aria-label":c(s?"sidebar.unpin":"sidebar.pin"),title:c(s?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:s?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,n.jsx)(eg,{filled:s})})]})}function ev({refreshKey:e,selectedSessionId:t,onSelectSession:r,onRestored:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)([]);(0,a.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();e||d(r.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,a.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})}),i(t)}catch{}},[i]);return 0!==c.length||o?(0,n.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,n.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,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:o?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),s("sidebar.archived")," (",c.length,")"]}),o&&(0,n.jsxs)("div",{style:{paddingLeft:12},children:[0===c.length&&(0,n.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:s("sidebar.noArchivedSessions")}),c.map(e=>{let a=_(e.firstMessage)??e.firstMessage,i=e.name||a.slice(0,50)||e.id.slice(0,12);return(0,n.jsxs)("div",{onClick:()=>r(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,n.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),(0,n.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function eb({node:e,selectedSessionId:t,runningSessionIds:r,unreadSessionIds:i,pinnedSessionIds:s,onSelectSession:o,onRenamed:l,onSessionDeleted:c,onTogglePinnedSession:d,onSessionArchived:u,depth:p}){let[h,m]=(0,a.useState)(!1),f=e.children.length>0;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,n.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,n.jsx)(eS,{session:e.session,isSelected:e.session.id===t,isRunning:r.has(e.session.id),isUnread:i.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:f,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),f&&!h&&(0,n.jsx)("div",{children:e.children.map(e=>(0,n.jsx)(eb,{node:e,selectedSessionId:t,runningSessionIds:r,unreadSessionIds:i,pinnedSessionIds:s,onSelectSession:o,onTogglePinnedSession:d,onRenamed:l,onSessionDeleted:c,onSessionArchived:u,depth:p+1},e.session.id))})]})}function ey(){let{t:e}=(0,z.s)();return(0,n.jsx)("span",{title:e("sidebar.waitingForAnswerHint"),style:{flexShrink:0,padding:"0 6px",borderRadius:"var(--radius-surface)",border:"1px solid var(--warning-line)",background:"var(--warning-soft)",color:"var(--warning)",fontSize:10.5,fontWeight:600,lineHeight:"16px",whiteSpace:"nowrap"},children:e("sidebar.waitingForAnswer")})}function ew(){let{t:e}=(0,z.s)();return(0,n.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,n.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,n.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function ek(){let{t:e}=(0,z.s)();return(0,n.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,n.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function ej(e,t){return e&&(0!==e.running||0!==e.unread)?(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,n.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,n.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,n.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function eS({session:e,isSelected:t,isRunning:r,isUnread:i,isPinned:s,onClick:o,onTogglePin:l,onRenamed:c,onDeleted:d,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:f}){let{t:g}=(0,z.s)(),[x,v]=(0,a.useState)(!1),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)(""),[j,S]=(0,a.useState)(!1),[C,N]=(0,a.useState)(!1),T=(0,a.useRef)(null);(0,a.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>T.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let I=_(e.firstMessage)??e.firstMessage,M=e.name||I.slice(0,50)||e.id.slice(0,12),E=(0,a.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||I.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,I,e.id]),$=(0,a.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[w,e.id,e.name,c,M]),R=(0,a.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,a.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]),A=(0,a.useCallback)(e=>{e.stopPropagation(),e.shiftKey?R():S(!0)},[R]),P=(0,a.useCallback)(e=>{e.stopPropagation(),R()},[R]),F=(0,a.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),W=(0,a.useCallback)(t=>{(function(e,t=window){let r=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(r)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[c,e.cwd,e.id,e.name,e.path]);return(0,n.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${r?" is-running":""}${i?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:o,onContextMenu:j||b?void 0:W,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||b?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,n.jsxs)("button",{onClick:P,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,n.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,n.jsx)("input",{ref:T,value:w,onChange:e=>k(e.target.value),onBlur:$,onKeyDown:e=>{"Enter"===e.key&&$(),"Escape"===e.key&&y(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,n.jsxs)(n.Fragment,{children:[p>0&&(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),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,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),r&&(0,n.jsx)(ew,{}),!r&&i&&(0,n.jsx)(ek,{}),e.worktreeBranch&&(0,n.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,n.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,n.jsx)("button",{className:"navigator-session-action",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:"var(--radius-control)",color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,n.jsx)(eg,{filled:s})}),(0,n.jsx)("button",{className:"navigator-session-action",onClick:E,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,n.jsx)("button",{className:"navigator-session-action",onClick:L,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,n.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,n.jsx)("path",{d:"M10 12h4"})]})}),(0,n.jsx)("button",{className:"navigator-session-action",onClick:A,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let eC=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eN=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eT=/\x1B\[([0-9;]*)m/g,eI=/\x1B_pi:c\x07/g,eM=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eE=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function e$(e){return e.replace(eI,"").replace(eC,"")}function eR(e){let t=[],r=0;for(;r<e.length;){if(27===e.charCodeAt(r)){let t=e.slice(r).match(eN);if(t){r+=t[0].length;continue}}let n=e.codePointAt(r);if(void 0===n)break;let a=String.fromCodePoint(n);t.push({start:r,end:r+a.length,char:a}),r+=a.length}return t}function eL(e,t){let r=eR(e)[t];return r?e.slice(0,r.start)+e.slice(r.end):e}function eA(e){return eR(e)[0]?.char}function eP(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,r=[];for(let n of e){let e=n.replace(eI,""),a=e$(e).trimEnd();if(t.test(a))continue;let i=e,s=eA(i);("│"===s||"┃"===s)&&" "===eA(i=eL(i,0))&&(i=eL(i,0));let o=function(e){let t=eR(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(i),l=o>=0?eR(i)[o]?.char:void 0;("│"===l||"┃"===l)&&(i=eL(i,o)),r.push(function(e){let t=e;for(;;){let e=eR(t),r=e[e.length-1];if(!r||""!==r.char.trim())return t;t=t.slice(0,r.start)+t.slice(r.end)}}(i))}for(;r.length>0&&""===e$(r[0]).trim();)r.shift();for(;r.length>0&&""===e$(r[r.length-1]).trim();)r.pop();return r.length?r:e}function eF(e){let t,r=[],n={},a=0;for(eT.lastIndex=0;null!==(t=eT.exec(e));)t.index>a&&r.push({text:e.slice(a,t.index),style:n}),n=function(e,t){let r={...e};for(let e=0;e<t.length;e++){let n=t[e];if(0===n)for(let e of Object.keys(r))delete r[e];else if(1===n)r.fontWeight=700;else if(2===n)r.opacity=.65;else if(3===n)r.fontStyle="italic";else if(4===n)r.textDecoration="underline";else if(22===n)delete r.fontWeight,delete r.opacity;else if(23===n)delete r.fontStyle;else if(24===n)delete r.textDecoration;else if(39===n)delete r.color;else if(49===n)delete r.backgroundColor;else if(n>=30&&n<=37)r.color=eM[n-30];else if(n>=90&&n<=97)r.color=eE[n-90];else if(n>=40&&n<=47)r.backgroundColor=eM[n-40];else if(n>=100&&n<=107)r.backgroundColor=eE[n-100];else if((38===n||48===n)&&2===t[e+1]){let[a,i,s]=[t[e+2],t[e+3],t[e+4]];[a,i,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===n?r.color=`rgb(${a}, ${i}, ${s})`:r.backgroundColor=`rgb(${a}, ${i}, ${s})`),e+=4}else if((38===n||48===n)&&5===t[e+1]){let a=function(e){if(e>=0&&e<8)return eM[e];if(e>=8&&e<16)return eE[e-8];if(e>=16&&e<=231){let t=e-16,r=Math.floor(t/36),n=Math.floor(t%36/6),a=e=>0===e?0:55+40*e;return`rgb(${a(r)}, ${a(n)}, ${a(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);a&&(38===n?r.color=a:r.backgroundColor=a),e+=2}}return r}(n,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),a=t.index+t[0].length;return a<e.length&&r.push({text:e.slice(a),style:n}),r}let e_={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:""},ez={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eW={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"},eO={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 eD(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eH(e){return null!==(eW[eD(e)]??null)}function eU(e){let t;return null!==("pdf"===(t=eD(e))||"docx"===t?t:null)}function eB(e,t,r={}){let n={...e,content:t};return r.omitUsage&&(n.usage=void 0),n}function eq(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 eV(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eK(e,t){let r=e[t];if(r?.role!=="assistant"||"error"!==r.stopReason)return!1;for(let r=t+1;r<e.length;r++){let t=e[r].role;if("user"===t)break;if("assistant"===t)return!0}return!1}function eG(e,t={}){let r=[];for(let n of function(e,t={}){return(e.content??[]).filter(e=>!eq(e,t))}(e,t)){let e="image"===n.type||"text"===n.type&&n.text.trim().length>0?"answer":"process",t=r[r.length-1];t?.kind===e?t.blocks.push(n):r.push({kind:e,blocks:[n]})}return r}function eJ(e){return e.filter(e=>"toolCall"===e.type).length}let eZ=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function eY(e){let t=0,r=0;for(let n of e)eZ.test(n)?t++:r++;return t+r/4}function eX(e){return"text"===e.type?e.text:"thinking"===e.type?e.thinking:"toolCall"===e.type?JSON.stringify(e.input??{})??"":null}function eQ(e,t){if(!e)return eY(t);let r=Math.min(e.text.length,t.length),n=0;for(;n<r&&e.text.charCodeAt(n)===t.charCodeAt(n);)n++;let a=n>0?t.charCodeAt(n-1):0;return a>=55296&&a<=56319&&n--,e.tokens-eY(e.text.slice(n))+eY(t.slice(n))}function e0(e,t,r){let n=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==r&&n.set("index",String(r)),`/api/tool-image?${n}`}let e1=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function e2(e){let t=new Map;for(let r of e)"toolResult"===r.role&&t.set(r.toolCallId,r);let r=[],n=-1;return{collect(e,a){for(let i of a)"toolCall"===i.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let r=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===r.path;if("eval"===e.toolName){let e;return e=t.content?.at(-1),e?.type==="text"&&e1.test(e.text)}return"read"===e.toolName&&"string"==typeof r.path&&eH(r.path)}(i,t.get(i.toolCallId))&&(r.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:i.toolCallId}}),n=e)},attach(e){if(0===r.length)return e;let t=[...r,...e];return r=[],t},takeRemaining(){if(0===r.length)return null;let e={idx:n,blocks:r};return r=[],e}}}let e8=new Map,e4=new Map,e5="[한국어 번역]\n";function e6(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function e3(e){if("custom"!==e.role||"korean-reply-translation"!==e.customType)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let r="sourceTimestamp"in t&&"number"==typeof t.sourceTimestamp?t.sourceTimestamp:void 0,n="sourceHash"in t&&"string"==typeof t.sourceHash?t.sourceHash:void 0;return void 0===r&&void 0===n?null:{sourceTimestamp:r,sourceHash:n}}let e7="command",e9="autolearn-saved";function te(e){return"custom"===e.role&&(e.customType===e7||e.customType===e9&&!1!==e.display)}function tt(e,t){let r=e[t];if(r?.role!=="custom"||"user-input-translation"!==r.customType)return -1;for(let r=t-1;r>=0;r--)if("user"===e[r].role)return r;return -1}let tr="local-command:";function tn(e){return e?.startsWith(tr)===!0}function ta(e,t,r){let n=new Set(r.map(e=>e.message)),a=[],i=[];for(let r=0;r<e.length;r++){let s=r<t.length;!(n.has(e[r])||s&&tn(t[r]))&&(a.push(e[r]),s&&i.push(t[r]))}for(let e of r){let t=0;if(null!==e.baseEntryId){let r=i.indexOf(e.baseEntryId);if(-1===r)continue;t=r+1}let r=e.message.timestamp??0;for(;t<a.length;){let e=a[t];if(!n.has(e)&&"number"==typeof e.timestamp&&e.timestamp>r)break;t+=1}a.splice(t,0,e.message),t<=i.length&&i.splice(t,0,e.entryId)}return{messages:a,entryIds:i}}function ti(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let ts={create:!0,update:!0};function to(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function tl(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let r of e)r&&"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&"string"==typeof r.text&&t.push(r.text);return t.join("\n")}function tc(e,t){if(0===e.length)return -1;if(!t)return 0;let r=-1;for(let n=0;n<e.length;n++){let a=e[n];if(a.item===t.item){if(a.k===t.k)return n;r=n}}return -1===r?0:r}function td(e){try{return decodeURIComponent(e)}catch{return e}}function tu(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tp(e){let t=tu(e),r=/^[a-zA-Z]:\//.test(t),n=t.startsWith("//"),a=t.startsWith("/")&&!r&&!n,i=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){i.length>0&&".."!==i[i.length-1]?i.pop():a||r||n||i.push(e);continue}i.push(e)}let s=i.join("/");return r?s:n?`//${s}`:a?`/${s}`:s}function th(e,t,r=t){let n,a,i,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=td(l),p=u.startsWith("\\\\"),h=tu(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let r=td(t.pathname);if(t.hostname)return`//${t.hostname}${r.startsWith("/")?r:`/${r}`}`;if(/^\/[a-zA-Z]:\//.test(r))return r.slice(1);return r}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(c=h,d="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(c=`${tu(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let f=tp(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&r&&(n=tp(f).replace(/\/+$/,""),a=tp(r).replace(/\/+$/,""),s=(i=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(a))?n.toLowerCase():n,!(s===(o=i?a.toLowerCase():a)||s.startsWith(`${o}/`)))?null:f}function tm(e,t){let r;if(!e)return null;let n=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),a=e=>n?e.replace(/\\/g,"/"):e,i=a(e),s=t?a(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(i),l=i.startsWith("//");if(o||l)r=i;else if(i.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];r=e?`${e}${i}`:i}else{if(!s)return null;r=`${s}/${i}`}return tp(r)}function tf(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function tg(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 tx(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tv(e,t){if(!e||"object"!=typeof e||"delete"===e.op&&!t)return null;let r=e.path??e.resolvedPath;return"string"==typeof r&&r.length>0?r:null}function tb(e,t,r=!1){let n=t.details,a=tx(e);if(a)return!r&&n&&"object"==typeof n&&"delete"===n.op?[]:[a];if(!n||"object"!=typeof n)return[];if(Array.isArray(n.perFileResults))return n.perFileResults.map(e=>tv(e,r)).filter(e=>null!==e);let i=tv(n,r);return i?[i]:[]}function ty(e,t){let r=tx(e);return(t?tb(e,t,!0):r?[r]:[]).filter(tC)}function tw(e,t,r){let n=ty(e,t);return n.length>0&&n.every(e=>tS(e,r))}let tk=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])),tj=[/^\/(?: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 tS(e,t){let r=tm(e,t),n=t?tm(t)?.replace(/\/+$/,""):void 0,a=r??e.replace(/\\/g,"/"),i=/^(?:[a-zA-Z]:\/|\/\/|\/mnt\/[a-zA-Z](?:\/|$))/.test(a)||void 0!==n&&/^(?:[a-zA-Z]:\/|\/\/)/.test(n),s=e=>i?e.toLowerCase():e,o=null===r||void 0!==n&&(s(r)===s(n)||s(r).startsWith(`${s(n)}/`));return!!function(e,t){let r=(e,r)=>void 0!==e&&(t?e.toLowerCase()===r:e===r),n=e.findIndex(e=>r(e,".omp"));if(n<0||n===e.length-1)return!1;let a=e[n+1];if(r(a,"agent")||r(a,"wt")||r(a,"profiles")&&r(e[n+3],"agent"))return!1;let i=tk.get(a.toLowerCase());return!(void 0!==i&&(t||i===a))}((null!==r&&o&&void 0!==n?r.slice(n.length):a).split("/").filter(e=>""!==e&&"."!==e),i)||!o&&tj.some(e=>e.test(a))}function tC(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tN(e,t,r){let n=new Set,a=[];for(let s of e){var i;if("toolCall"!==s.type||!(tf(i=s.toolName)||tg(i)))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of tb(s.input,e)){if(!tC(t))continue;let e=tm(t,r);!(!e||tS(t,r))&&(n.has(e)||(n.add(e),a.push({filePath:e})))}}return a}function tT(e){let t=[];for(let r of e){if(!r||"object"!=typeof r||!("name"in r)||!("tasks"in r))return{phases:t,malformed:!0};let{name:e,tasks:n}=r;if("string"!=typeof e||!Array.isArray(n))return{phases:t,malformed:!0};let a=Array.isArray(n)?n.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:r}=e;if("string"!=typeof t||"pending"!==r&&"in_progress"!==r&&"completed"!==r&&"abandoned"!==r&&"blocked"!==r)return[];let n="blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0,a="dependsOn"in e&&Array.isArray(e.dependsOn)?e.dependsOn.filter(e=>"string"==typeof e):[];return[{content:t,status:r,blocker:n,...a.length>0?{dependsOn:a}:{}}]}):[];if(a.length!==n.length)return{phases:t,malformed:!0};a.length>0&&t.push({name:e,tasks:a})}return{phases:t,malformed:!1}}function tI(e){if(!Array.isArray(e))return null;let{phases:t,malformed:r}=tT(e);return r?null:t}function tM(e,t){var r;let n;if(t){let e=t.details,r=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(r))return{kind:"unknown"};let{phases:n,malformed:a}=tT(r);return a?{kind:"unknown"}:{kind:"authoritative",phases:n}}let a=Array.isArray(n=(r=e.input)&&"object"==typeof r&&"list"in r?r.list:void 0)?n.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:r}=e;if("string"!=typeof t||!Array.isArray(r))return[];let n=r.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return n.length>0?[{name:t,tasks:n}]:[]}):[];return a.length>0?{kind:"preview",phases:a}:{kind:"unknown"}}function tE(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}function t$(e,t,r=null,n=null){return r||(function(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r],a=n.trackerTodos??[];for(let e=a.length-1;e>=0;e-=1){let t=tI(a[e]);if(t)return t}if("assistant"!==n.role)continue;let i=n.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let r=i[e];if("toolCall"!==r.type||!tE(r.toolName))continue;let n=tM(r,t.get(r.toolCallId));if("unknown"!==n.kind)return n.phases}}return null}(e,t)??n)}function tR(e,t){if(!e.dependsOn?.length)return[];let r=new Set(t.flatMap(e=>e.tasks.filter(e=>"completed"===e.status).map(e=>e.content)));return e.dependsOn.filter(e=>!r.has(e))}function tL(e){let t=0,r=0,n=null,a=null,i=null;for(let s of e)for(let o of s.tasks){if("completed"===o.status){t+=1;continue}"abandoned"!==o.status&&(r+=1,tR(o,e).length>0?i||(i={phase:s,task:o}):"in_progress"===o.status?n||(n={phase:s,task:o}):"blocked"===o.status?i||(i={phase:s,task:o}):a||(a={phase:s,task:o}))}let s=n??a??i,o=t+r;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:r,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}function tA(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tP(e){return tA(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tF(e){let t=tA(e).replace(/\/+$/,"");return t.split("/").pop()??t}function t_(e,t){if(!t)return e;let r=tA(e),n=tA(t).replace(/\/$/,"");return r.startsWith(n+"/")?r.slice(n.length+1):e}var tz=r(65063),tW=r(7644),tO=r(32316),tD=r(88374),tH=r(63280),tU=r(94764),tB=r(63835),tq=r(54152),tV=r(84678),tK=r(98164);let tG={...tU.j,attributes:{...tU.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...tU.j.strip||[],"iframe","object","style","form"]};function tJ(e){let t=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/),n=[],a=null,i=0,s=null,o=new Map;for(let e=0;e<r.length;e++){var l;let t=r[e];if(s){n.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],r=c[1].length;a?e===a.marker&&r>=a.size&&(a=null):a={marker:e,size:r},i=0,n.push(t);continue}if(a){n.push(t);continue}let d=t.match(/<(code|pre|script|style)\b/i);if(d){let e=d[1].toLowerCase(),r=t.slice((d.index??0)+d[0].length);RegExp(`</${e}\\s*>`,"i").test(r)||(s=e),i=0,n.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){i=0,n.push(t);continue}if(i||t.includes("`")){i=function(e,t){let r=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let n=t+1;for(;"`"===e[n];)n++;let a=n-t;0===r?r=a:a===r&&(r=0),t=n}return r}(t,i),n.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){n.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let r=t;r<e.length;r++){let t=e[r];if(/^ {0,3}\\\][ \t]*$/.test(t))return r;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(r,e+1);if(-1!==t){n.push(`${p[1]}$$`,...r.slice(e+1,t).map(e=>tY(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){n.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],a=m[2].trimEnd();if(a&&!a.includes("$$")){let i=tZ(r,e+1,t,o);if(i){n.push(`${t}$$`,`${t}${a}`);for(let a=e+1;a<i.index;a++)n.push(tY(r[a],t));i.content&&n.push(`${t}${i.content}`),n.push(`${t}$$`),e=i.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],a=tZ(r,e+1,t,o);if(a&&(a.glued||""!==t)){n.push(`${t}$$`);for(let i=e+1;i<a.index;i++)n.push(tY(r[i],t));a.content&&n.push(`${t}${a.content}`),n.push(`${t}$$`),e=a.index;continue}}n.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 n.join(t)}function tZ(e,t,r,n){let a=n.get(r);if(void 0!==a&&t<a)return null;for(let a=t;a<e.length;a++){var i,s,o,l;let t=e[a];if(i=t,""===(s=r)?/^ {0,3}\$\$\s*$/.test(i):i.startsWith(s)&&/^\$\$\s*$/.test(i.slice(s.length)))return{index:a,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 n.set(r,a),null;let c=function(e,t){if(!e.startsWith(t))return null;let r=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!r)return null;let n=r[1].trimEnd();return n&&!n.includes("$$")?n:null}(t,r);if(null!==c)return{index:a,content:c,glued:!0}}return n.set(r,e.length),null}function tY(e,t){if(!t||!e||e.startsWith(" "))return e;let r=e.match(/^ */)?.[0].length??0;return r>=t.length?e:`${t.slice(r)}${e}`}let tX={singleTilde:!1},tQ=[[tq.A,["yaml"]],[tV.A,tX],tK.A],t0=[[tq.A,["yaml"]],[tV.A,tX],tK.A],t1=[tH.A,[tB.A,tG],[tD.A,{throwOnError:!1,strict:!1}]],t2=[tH.A,[tB.A,tG],[tD.A,{throwOnError:!1,strict:!1}]],t8="pi-theme",t4=["light","dark","auto"],t5={preference:"auto",theme:"light"},t6="omp-theme",t3=null,t7=0,t9=new Set,re=null,rt=!1;function rr(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function rn(e){return"auto"===e?rr():e}let ra="--omp-md-";function ri(e){let t=document.documentElement,r=t3?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let r=t.style.item(e);r.startsWith("--")&&!r.startsWith(ra)&&t.style.removeProperty(r)}if(r){for(let[e,n]of Object.entries(r.variables))e.startsWith(ra)&&t.style.setProperty(e,n);t.dataset.ompThemeName=r.name}try{localStorage.setItem(t6,e)}catch{}}function rs(){if(re)return re;let e=function(){try{let e=localStorage.getItem(t8);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(t6);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=rn(e);return ri(t),re={preference:e,theme:t}}function ro(e,t,r){if(ri(t),r)try{localStorage.setItem(t8,e)}catch{}re={preference:e,theme:t},t9.forEach(e=>e())}function rl(){let e=rs();if("auto"!==e.preference)return;let t=rr();t!==e.theme&&ro("auto",t,!1)}function rc(e){return t9.add(e),rs(),rt||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",rl),window.addEventListener("focus",rl),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&rl()}),rt=!0),rl(),()=>{t9.delete(e)}}function rd(){return rs()}function ru(){return t5}async function rp(e){let t=++t7,r=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/theme${r}`,{cache:"no-store"});if(!n.ok)throw Error(`Theme request failed (${n.status})`);let a=await n.json();if(t===t7){t3=a;try{localStorage.setItem("omp-theme-config",JSON.stringify(t3))}catch{}ri(rs().theme)}}function rh(e){let t=(0,a.useSyncExternalStore)(rc,rd,ru);(0,a.useEffect)(()=>{e?.syncWithOmp&&rp(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let r=(0,a.useCallback)((e,t)=>{let r=rn(e),n=()=>{ro(e,r,!0)},a=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||a)return void n();let i=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(i,window.innerWidth-i),Math.max(s,window.innerHeight-s));document.startViewTransition(n).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${i}px ${s}px)`,`circle(${o}px at ${i}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),n=(0,a.useCallback)(e=>{var t;let n;r((t=rs().preference,n=t4.indexOf(t),t4[(n+1)%t4.length]),e)},[r]),i=(0,a.useCallback)((e,t)=>{r(e,t)},[r]);return{theme:t.theme,preference:t.preference,toggleTheme:n,setPreference:i,isDark:"dark"===t.theme}}function rm(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 rf={...tW.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tW.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function rg({code:e,isStreaming:t}){let{isDark:i}=rh(),{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1),h=`${i?"dark":"light"}
|
|
4
|
+
${e}`,m=o&&!t;(0,a.useEffect)(()=>{if(!m)return;let t=!1;return d({key:h,status:"loading"}),(async()=>{let{default:n}=await Promise.all([r.e(866),r.e(8367),r.e(3308)]).then(r.bind(r,43328)),a=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${a}`,e),await document.fonts.ready,t)return;if(n.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:i?"dark":"default",fontFamily:a}),!await n.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 n.render(s,e);t||d({key:h,status:"ready",svg:o.svg})})().catch(()=>{t||d({key:h,status:"error"})}),()=>{t=!0}},[e,h,i,m]);let f=(0,a.useMemo)(()=>(0,n.jsx)("button",{type:"button",onClick:()=>l(e=>!e),disabled:t,title:t?s("i18n.previewAfterStreaming"):m?s("i18n.showMermaidSource"):s("i18n.previewMermaid"),className:["markdown-code-action",m?"is-active":""].filter(Boolean).join(" "),children:m?s("i18n.source"):s("i18n.preview")}),[t,m,s]);if(!m)return(0,n.jsx)(rv,{code:e,lang:"mermaid",headerAction:f,isStreaming:t});let g=c?.key===h&&"error"===c.status?(0,n.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==h||"ready"!==c.status?(0,n.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,n.jsxs)(n.Fragment,{children:[!u&&(0,n.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,n.jsx)(rx,{svg:c.svg,onClose:()=>p(!1)})]});return(0,n.jsxs)("div",{className:"markdown-code-block",children:[(0,n.jsxs)("div",{className:"markdown-code-header",children:[(0,n.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),f]}),g]})}function rx({svg:e,onClose:t}){let{t:r}=(0,z.s)(),i=(0,a.useRef)(null),[s,o]=(0,a.useState)(1);return(0,a.useEffect)(()=>{let e=i.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,n.jsx)("dialog",{ref:i,className:"mermaid-zoom-dialog","aria-label":r("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,n.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,n.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,n.jsx)("span",{className:"mermaid-zoom-title",children:r("i18n.mermaidDiagram")}),(0,n.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,n.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,n.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:r("i18n.zoomOut"),"aria-label":r("i18n.zoomOut"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M5 12h14"})})}),(0,n.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,n.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:s>=3,title:r("i18n.zoomIn"),"aria-label":r("i18n.zoomIn"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,n.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>o(1),title:r("i18n.fitToWidth"),"aria-label":r("i18n.fitToWidth"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,n.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:r("i18n.close"),"aria-label":r("i18n.close"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,n.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,n.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let rv=(0,a.memo)(function({code:e,lang:t,headerAction:r,isStreaming:i}){let{isDark:s}=rh(),{t:o}=(0,z.s)(),[l,c]=(0,a.useState)(!1);return(0,n.jsxs)("div",{className:"markdown-code-block",children:[(0,n.jsxs)("div",{className:"markdown-code-header",children:[(0,n.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,n.jsxs)("div",{className:"markdown-code-actions",children:[r,(0,n.jsx)("button",{onClick:()=>{rm(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),i?(0,n.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,n.jsx)(tz.A,{language:t||"text",style:s?tW.xJ:rf,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 rb({children:e,className:t,isStreaming:r,cwd:i,onOpenFile:s}){let o=(0,a.useMemo)(()=>tJ(e),[e]),l=(0,a.useMemo)(()=>({code({className:e,children:t,...a}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,n.jsx)(rg,{code:s.replace(/\n$/,""),isStreaming:r}):(0,n.jsx)(rv,{code:s.replace(/\n$/,""),lang:i,isStreaming:r}):(0,n.jsx)("code",{className:"markdown-inline-code",...a,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:t,...r}){delete r.node;let a=s?th(e,i):null;return a&&s?(0,n.jsx)("a",{href:e,...r,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(a))},children:t}):(0,n.jsx)("a",{href:e,...r,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...r}){delete r.node;let a="string"==typeof e?th(e,i):null,s=a?`/api/files/${tP(a)}?type=read`:e;return(0,n.jsx)("img",{src:s,alt:t??"",loading:"lazy",...r})},table:({children:e})=>(0,n.jsx)("div",{className:"markdown-table-wrap",children:(0,n.jsx)("table",{children:e})})}),[i,r,s]);return(0,n.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,n.jsx)(tO.oz,{remarkPlugins:tQ,rehypePlugins:t1,components:l,children:o})})}function ry(e){let[t,r]=(0,a.useState)(()=>Date.now());return(0,a.useEffect)(()=>{let t=setInterval(()=>r(Date.now()),e);return()=>clearInterval(t)},[e]),t}let rw=new Map,rk=new Set;function rj(){rk.forEach(e=>e())}function rS(e){return rk.add(e),()=>{rk.delete(e)}}function rC(e,t){return e&&t?`${e}\u0000${t}`:null}function rN(e){let t=!1;for(let r of e)t=rw.delete(r)||t;t&&rj()}var rT=r(54265);let rI=(0,a.createContext)(null);function rM(e,t,r){return Math.min(r,Math.max(t,e))}function rE(e,t,r){let n=t.width>0?r.width/t.width:0,a=t.height>0?r.height/t.height:0;return{x:rM((e.x-t.left)*n,0,r.width),y:rM((e.y-t.top)*a,0,r.height)}}function r$(e){let t=rM(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let rR="#e5191f",rL="#ffffff";function rA(e){let{promise:t,resolve:r,reject:n}=Promise.withResolvers();return e.toBlob(e=>e?r(e):n(Error("canvas encode failed")),"image/png"),t}function rP(e,t){let r=document.createElement("canvas");r.width=e,r.height=t;let n=r.getContext("2d");if(!n)throw Error("canvas 2d unavailable");return[r,n]}async function rF(e,t){let r=await createImageBitmap(e);try{let e={width:r.width,height:r.height},{inner:n,outer:a}=r$(e),i=Math.max(14,7*r$(e).inner),[s,o]=rP(e.width,e.height);o.drawImage(r,0,0),t.forEach((t,r)=>{let s=function(e,t){let{inner:r,outer:n}=r$(t),a=(r,n)=>{let a=rM(e.x-r,n,t.width-n),i=rM(e.y-r,n,t.height-n),s=rM(e.x+e.w+r,n,t.width-n);return{x:a,y:i,w:Math.max(0,s-a),h:Math.max(0,rM(e.y+e.h+r,n,t.height-n)-i)}};return{inner:a(r/2,r/2),outer:a(r+n/2,n/2)}}(t,e);o.lineJoin="miter",o.strokeStyle=rL,o.lineWidth=a,o.strokeRect(s.outer.x,s.outer.y,s.outer.w,s.outer.h),o.strokeStyle=rR,o.lineWidth=n,o.strokeRect(s.inner.x,s.inner.y,s.inner.w,s.inner.h);let l=String(r+1);o.font=`700 ${i}px sans-serif`;let c=Math.round(.35*i),d=Math.ceil(o.measureText(l).width)+2*c,u=Math.round(1.3*i),p=Math.min(Math.max(0,t.x-n),e.width-d),h=t.y-n-u,m=h>=0?h:Math.min(t.y,e.height-u);o.fillStyle=rL,o.fillRect(p-1,m-1,d+2,u+2),o.fillStyle=rR,o.fillRect(p,m,d,u),o.fillStyle=rL,o.textBaseline="middle",o.textAlign="center",o.fillText(l,p+d/2,m+u/2)});let l=await Promise.all(t.map(t=>{let n=function(e,t,r=.12){let n=Math.round(e.w*r),a=Math.round(e.h*r),i=rM(e.x-n,0,t.width),s=rM(e.y-a,0,t.height),o=rM(e.x+e.w+n,0,t.width);return{x:i,y:s,w:o-i,h:rM(e.y+e.h+a,0,t.height)-s}}(t,e),[a,i]=rP(n.w,n.h);return i.drawImage(r,n.x,n.y,n.w,n.h,0,0,n.w,n.h),rA(a)}));return{marked:await rA(s),crops:l}}finally{r.close()}}function r_({src:e,regions:t,max:r,onAdd:i,onNaturalSize:s,regionLabel:o}){let l=(0,a.useRef)(null),[c,d]=(0,a.useState)(null),u=(0,a.useRef)(null),[p,h]=(0,a.useState)(null),m=e=>{let t=l.current,r=u.current;return t&&r&&c?function(e,t,r,n){let a=rM(Math.min(e.x,t.x),r.left,r.left+r.width),i=rM(Math.max(e.x,t.x),r.left,r.left+r.width),s=rM(Math.min(e.y,t.y),r.top,r.top+r.height),o=rM(Math.max(e.y,t.y),r.top,r.top+r.height);if(i-a<6||o-s<6)return null;let l=rE({x:a,y:s},r,n),c=rE({x:i,y:o},r,n),d=Math.floor(l.x),u=Math.floor(l.y),p=Math.min(n.width,Math.ceil(c.x))-d,h=Math.min(n.height,Math.ceil(c.y))-u;return p>0&&h>0?{x:d,y:u,w:p,h}:null}(r.start,e,t.getBoundingClientRect(),c):null},f=(e,t)=>{if(u.current?.pointerId!==e.pointerId)return;let r=t?m({x:e.clientX,y:e.clientY}):null;u.current=null,h(null),r&&i(r)};return(0,n.jsxs)("div",{className:"tool-image-marker","data-drawing":c&&t.length<r?"true":void 0,onPointerDown:e=>{c&&!(t.length>=r)&&("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(m({x:e.clientX,y:e.clientY}))},onPointerUp:e=>f(e,!0),onPointerCancel:e=>f(e,!1),children:[(0,n.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,n.jsx)(rz,{region:e,natural:c,label:String(t+1),title:o(t+1)},`${t}-${e.x}-${e.y}`)),c&&p&&(0,n.jsx)(rz,{region:p,natural:c})]})}function rz({region:e,natural:t,label:r,title:a}){let i={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,n.jsx)("span",{className:"tool-image-region","data-draft":r?void 0:"true",role:r?"img":void 0,"aria-label":a,style:{left:`${i.left}%`,top:`${i.top}%`,width:`${i.width}%`,height:`${i.height}%`},children:r&&(0,n.jsx)("span",{className:"tool-image-region-number","aria-hidden":"true",children:r})})}function rW(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),r=e.length-t;for(let t=0;t<r;t+=1){var n;if(!((n=e.charCodeAt(t))>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||43===n||47===n))return null}for(let t=r;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}function rO(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let r=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),n=/Command exited with code (-?\d+)\s*$/.exec(r.trimEnd());return n?Number(n[1]):null}let rD=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,rH=/(?:\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 rU(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let rB={hideThinkingBlock:!1},rq=new Set,rV=rB,rK=0;function rG(e){return rq.add(e),()=>{rq.delete(e)}}function rJ(){return rV}function rZ(){return rB}async function rY(e){let t=++rK,r=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/display-settings${r}`,{cache:"no-store"});if(!n.ok)throw Error(`Display settings request failed (${n.status})`);let a=await n.json();t!==rK||a.hideThinkingBlock!==rV.hideThinkingBlock&&(rV={hideThinkingBlock:!0===a.hideThinkingBlock},rq.forEach(e=>e()))}function rX(){return(0,a.useSyncExternalStore)(rG,rJ,rZ)}function rQ(e){let t=new Date(e),r=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}:${r(t.getMinutes())}`}let r0=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","MITSU(미츠)","SHION(시온)","HIKARI(히카리)"],r1={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","MITSU(미츠)":"mitsu","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},r2=["approval","choice","done","failed","blocked","working"],r8={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},r4={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0},r5="/api/office-characters/",r6={voice:"/audio/completion/",sticker:"/stickers/"};function r3(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function r7(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(r8,e)?e:null}function r9(e,t){let r=new Map,n=new Map;if(!Array.isArray(e))return{files:r,lines:n};for(let a of e){if("object"!=typeof a||null===a)continue;let{file:e,tag:i,ko:s}=a;if("string"!=typeof e||""===e)continue;let o=r7(i);if(null===o)continue;let l=t+e.replace(/^\/+/,""),c=r.get(o);c?c.push(l):r.set(o,[l]),"string"==typeof s&&""!==s.trim()&&n.set(l,s.trim())}return{files:r,lines:n}}function ne(e,t=r6){let r=new Map;if("object"!=typeof e||null===e)return r;let{characters:n}=e;if(!Array.isArray(n))return r;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:a,stickers:i,captions:s}=e;if("string"!=typeof n||""===n)continue;let o=r9(a,t.voice),l=r9(i,t.sticker),c=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if("object"!=typeof r||null===r)continue;let{tag:e,ko:n}=r;if("string"!=typeof n||""===n.trim())continue;let a=r7(e);if(null===a)continue;let i=t.get(a);i?i.push(n.trim()):t.set(a,[n.trim()])}return t}(s),d=new Map;for(let e of r2){let t=o.files.get(e)??[],r=new Map;for(let e of t){let t=o.lines.get(e);void 0!==t&&r.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:r,captions:c.get(e)??[]})}r.set(n,d)}return r}function nt(e,t,r){let n=t&&Object.hasOwn(r1,t)?r1[t]:null;return n?e.get(n)?.get(r)??null:null}function nr(e,t,r){return e.get(t)?.get(r)??null}async function nn(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return ne(await t.json())}catch{return new Map}}function na(e,t,r=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let n=null===t?-1:e.indexOf(t),a=-1===n?e.length:e.length-1,i=Math.min(a-1,Math.max(0,Math.floor(r()*a)));return e[-1!==n&&i>=n?i+1:i]}function ni(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let r of e.content)if("text"===r.type)t.push(r.text.trim());else if("toolCall"===r.type){let e="id"in r&&"string"==typeof r.id?r.id:"";t.push(`toolCall:${r.toolCallId||e}`)}}let r="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,r,t.filter(Boolean)])}function ns(e,t,r,n){if(t&&("web6"!==t.provider||t.model!==no))return{provider:t.provider,model:t.model,credentialId:t.credentialId};for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)break;if("assistant"===r.role&&("web6"!==r.provider||r.model!==no))return{provider:r.provider,model:r.model,credentialId:r.credentialId}}return{provider:r,model:n,credentialId:void 0}}let no="ChatGPT 6PRO",nl="/api/sidecars/resource";function nc(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},r=e=>{let r=t[e];return"number"==typeof r&&Number.isFinite(r)?r:null},n=r("usedFraction");if(null!==n&&n>=1)return!0;let a=r("remainingFraction");if(null!==a&&a<=0)return!0;let i=r("used"),s=r("limit");if(null!==i&&null!==s&&i>=s)return!0;let o=r("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==i&&i>=100}let nd=[{alias:"RIN(린)",file:"rin.webp"},{alias:"MIO(미오)",file:"mio.webp"},{alias:"MITSU(미츠)",file:"mitsu.webp",provider:"hive",model:"zai-org/glm-5.3-flash"},{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-vertex",model:"gemini-4-argon"}],nu={"gemini-4-argon":"HIKARI(히카리)"},np=[{seed:3,alias:nd[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:nd[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:nd[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:nd[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:nd[2].alias,provider:"hive",model:"zai-org/glm-5.3-flash",voice:"부지런한 배달\xb7통통 튀는 보고\xb7끈질긴 재도전",summonExample:"미츠 불러와",switchExample:"미츠로 교체해"},{seed:6,alias:nd[6].alias,provider:"google-vertex",model:"gemini-4-argon",voice:"빠른 관찰\xb7톡 쏘는 한마디\xb7장난스러운 여유",summonExample:"히카리 불러와",switchExample:"히카리로 교체해"},{seed:5,alias:nd[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],nh=np.filter(e=>null!==e.switchExample),nm={mode:"default",rosterAvailable:!1,seats:[]},nf=nm,ng=new Map,nx=new Map,nv=np,nb=new Set,ny=null,nw=0,nk=new Map,nj=new Map,nS=null,nC=!1;function nN(e){let t="office"===e.mode?e.seats.filter(e=>!nd.some(t=>t.alias===e.alias)&&"MITSU(미츠)"!==e.seat):[];nw+=1;let r=JSON.stringify([e.mode,e.rosterAvailable,t]);if(r!==nS)for(let n of(nS=r,nf={...e,seats:t},nx=new Map([...ng=new Map(t.flatMap(e=>{let t=nd.findIndex(t=>t.alias===e.seat);return t>=0?[[t,e]]:[]}))].flatMap(([e,t])=>{let r=nd[e];return"provider"in r&&!("model"in r)?[[r.provider,{seed:e,alias:t.alias}]]:[]})),nk=new Map([...ng].flatMap(([e,t])=>{let r=nd[e];return"model"in r?[[`${r.provider}/${r.model}`,{seed:e,alias:t.alias}]]:[]})),nj=new Map(Object.entries(nu).flatMap(([e,t])=>{let r=nd.findIndex(e=>e.alias===t),n=ng.get(r);return n?[[e,{seed:r,alias:n.alias}]]:[]})),nv=0===ng.size?np:np.map(e=>{let t,r,n,a=ng.get(nd.findIndex(t=>t.alias===e.alias));return a?(t=a.names.findLast(e=>/[가-힣]/.test(e))??a.names[0]??a.alias.split("(",1)[0],{...e,alias:a.alias,voice:a.voice.temperament.split(/(?<=[.。])\s/,1)[0].replace(/[.。]$/,""),summonExample:`${t} 불러와`,switchExample:`${n=(r=t.charCodeAt(t.length-1)-44032)>=0&&r<=11171?r%28:0,`${t}${0===n||8===n?"로":"으로"}`} 교체해`}):e}),nb))n()}function nT(){return nf}function nI(e){return nb.add(e),()=>{nb.delete(e)}}async function nM(e=fetch){let t=nw;try{let r=await e("/api/character-mode",{cache:"no-store"});if(!r.ok)return!1;let n=await r.json();if("object"!=typeof n||null===n)return!1;if(t!==nw)return!0;let{mode:a,rosterAvailable:i,seats:s}=n;return nN({mode:"office"===a?"office":"default",rosterAvailable:!0===i,seats:Array.isArray(s)?s:[]}),!0}catch{return!1}}let nE=new WeakMap;function n$(e){let t=nE.get(e);return t||(t=ne(e.manifest,{voice:r5,sticker:r5}),nE.set(e,t)),t}function nR(e){return e?nf.seats.find(t=>t.seat===e||t.alias===e)??null:null}function nL(e){return nf.seats.find(t=>t.seat===e)?.alias??e}let nA=nd.filter(e=>!("provider"in e)).length,nP=new Map(nd.flatMap((e,t)=>"provider"in e&&!("model"in e)?[[e.provider,t]]:[])),nF=new Map(nd.flatMap((e,t)=>"model"in e?[[`${e.provider}/${e.model}`,{seed:t,alias:e.alias}]]:[])),n_=new Map(Object.entries(nu).map(([e,t])=>[e,{seed:nd.findIndex(e=>e.alias===t),alias:t}])),nz=new Map([...nP].map(([e,t])=>[e,{seed:t,alias:nd[t].alias}])),nW=new Map(Object.entries({"google-antigravity":"HIKARI(히카리)"}).map(([e,t])=>[e,nd.findIndex(e=>e.alias===t)]));function nO(e,t){if(void 0===t)return null;let r=`${e}/${t}`;return nk.get(r)??nj.get(t)??nF.get(r)??n_.get(t)??null}function nD(e){return nx.get(e)??nz.get(e)??null}function nH(e){let t=e%nd.length;return ng.get(t)?.alias??nd[t].alias}function nU(e){let t=e%nd.length;return ng.get(t)?.faceUrl??`/avatars/${nd[t].file}`}function nB(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function nq(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,r)=>`${t?" ":""}${r.toUpperCase()}`)}function nV(e){let t=new Map;for(let r of e){if(!Number.isSafeInteger(r.oauthPosition)||r.oauthPosition<0)continue;let e=t.get(r.provider)??new Set;e.add(r.oauthPosition),t.set(r.provider,e)}return e.map(e=>{var r;let n=e.metadata?.email,a=e.metadata?.accountId,i="string"==typeof n&&n.length>0?n:"string"==typeof a?a:"",s=i.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return nB(e);let r=e.slice(t+1),n=r.lastIndexOf("."),a=n<0?r:r.slice(0,n),i=n<0?"":r.slice(n);return`${nB(e.slice(0,t))}@${0===a.length?"":`${a[0]}•••`}${i}`}(i):"",o=(r=e.provider,nP.get(r)??-1);if(o>=0)return{seed:o,alias:nH(o),masked:s,raw:i};let l=e.oauthPosition;if(!Number.isSafeInteger(l)||l<0){let r=t.get(e.provider)??new Set;for(l=0;r.has(l);)l++;r.add(l),t.set(e.provider,r)}let c=nW.get(e.provider)??-1;if(c>=0)return{seed:c,alias:`${nH(c)}${l+1}`,masked:s,raw:i};let d=l%nA,u=l<nA?nH(d):`${nH(d)}${l+1}`;return{seed:d,alias:u,masked:s,raw:i}})}class nK extends Error{constructor(e,t,r,n){super(e,n),this.kind=t,this.status=r,this.name="ResourceClientError",this.code=n?.code,this.outcomeUnknown=n?.outcomeUnknown}}function nG(e,t){return`${nl}${e}${t?"?refresh=1":""}`}function nJ(e,t,r=!1){return e instanceof nK?e:t?new nK("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):r||e instanceof DOMException&&"AbortError"===e.name?new nK("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new nK(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function nZ(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function nY(e,t){let r,n=t.fetchImpl??fetch,a=new AbortController,i=!1,s=()=>a.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0}),null!=t.timeoutMs&&(r=setTimeout(()=>{i=!0,a.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,r=await n(e,{signal:a.signal});try{t=await r.json()}catch(e){throw new nK("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",r.status,{cause:e})}let i=t&&"object"==typeof t?t:null,s="string"==typeof i?.error?i.error:null;if(!r.ok||s)throw new nK(s??`HTTP ${r.status}`,"http",r.status,{code:"string"==typeof i?.code?i.code:void 0,outcomeUnknown:i?.outcomeUnknown===!0});return t}catch(e){throw nJ(e,i,a.signal.aborted)}finally{clearTimeout(r),t.signal?.removeEventListener("abort",s)}}function nX(e){return"google-antigravity"===e.provider&&Array.isArray(e.limits)?{...e,limits:e.limits.filter(e=>"google"===e.id.split(":")[1]||/gemini/i.test(e.label??""))}:e}async function nQ(e={}){try{let t=await nY(nG("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new nK("사용량 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:{...t,reports:t.reports.map(nX)},error:null}}catch(t){return nZ(e.previous,nJ(t,!1))}}async function n0(e,t={}){if(!e)return nZ(void 0,new nK("세션 id가 올바르지 않습니다.","invalid-response"));try{let r=await nY(`/api/agent/${encodeURIComponent(e)}/account`,t),n=r?.state==="resolved"||r?.state==="unresolved"||r?.state==="not-running"||r?.state==="unsupported";if(!r||r.sessionId!==e||"number"!=typeof r.observedAt||!n||!Array.isArray(r.resetRecommendations))throw new nK("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:r,error:null}}catch(e){return nZ(void 0,nJ(e,!1))}}async function n1(e={}){try{let t=await nY(nG("/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 nK("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return nZ(e.previous,nJ(t,!1))}}async function n2(e={}){try{let t=await nY(`${nl}/credits${!0===e.refresh?"?refresh=1":""}`,{...e,timeoutMs:e.timeoutMs??6e4});if(!(t&&"object"==typeof t&&t.settings&&"object"==typeof t.settings&&t.hive&&Array.isArray(t.hive.rows)&&(void 0===t.anthropic||Array.isArray(t.anthropic?.rows))&&(void 0===t.balances||Array.isArray(t.balances)&&t.balances.every(e=>!!e&&"string"==typeof e.wallet&&(null===e.recorded||"object"==typeof e.recorded&&Number.isFinite(e.recorded?.amountUsd)&&Number.isFinite(e.recorded?.observedAt))))))throw new nK("API 크레딧 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return nZ(e.previous,nJ(t,!1))}}async function n8(e,t={}){await n5({wallet:"hive",value:e},t)}async function n4(e,t,r={}){await n5({kind:"balance",wallet:e,value:t},r)}async function n5(e,t){await nY(`${nl}/credits/settings`,{...t,timeoutMs:t.timeoutMs??2e4,fetchImpl:async(r,n)=>{let a=new Headers(n?.headers);return a.set("Content-Type","application/json"),(t.fetchImpl??fetch)(r,{...n,method:"POST",headers:a,body:JSON.stringify(e)})}})}async function n6(e,t,r={}){if(!Number.isSafeInteger(e)||e<=0)throw new nK("credential id가 올바르지 않습니다.","invalid-response");let n=await nY(`${nl}/credential/${e}/${t?"enable":"disable"}`,{...r,timeoutMs:r.timeoutMs??2e4,fetchImpl:async(e,t)=>(r.fetchImpl??fetch)(e,{...t,method:"POST"})});if(!n||!0!==n.ok||n.credentialId!==e||!t!==n.disabled)throw new nK("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return n}async function n3(e,t,r={}){if(!Number.isSafeInteger(e)||e<=0)throw new nK("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new nK("credit id가 올바르지 않습니다.","invalid-response");let n=await nY(`${nl}/credential/${e}/reset`,{...r,timeoutMs:r.timeoutMs??2e4,fetchImpl:async(e,n)=>{let a=new Headers(n?.headers);return a.set("Content-Type","application/json"),(r.fetchImpl??fetch)(e,{...n,method:"POST",headers:a,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!n||"boolean"!=typeof n.ok||n.credentialId!==e||n.creditId!==t||"string"!=typeof n.code||n.ok!==("reset"===n.code))throw new nK("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return n}function n7(e,t){if(e.has(t))return null;e.add(t);let r=!1;return()=>{r||(r=!0,e.delete(t))}}let n9={faces:new Map,pins:new Map},ae=[],at=n9,ar=null,an=ae,aa=new Map,ai=new Set;function as(e){let t=(ai.add(e),()=>{ai.delete(e)}),r=nI(e);return()=>{t(),r()}}function ao(e){at=e,ai.forEach(e=>e())}function al(e){return Number.isSafeInteger(e)&&e>0}function ac(e,t){return`${e}:${t}`}function ad(e){let t=e??ae;an=t;let r=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(r===ar)return;ar=r;let n=nV(t),a=new Map;t.forEach((e,t)=>{let r=e.credentialId;if(!al(r))return;let i=ac(e.provider,r);a.has(i)||a.set(i,{seed:n[t].seed,alias:n[t].alias})}),ao({faces:a,pins:at.pins})}function au(e,t,r,n){if(!t)return null;let a=nO(t,n);if(a)return a;if(al(r)){let e=at.faces.get(ac(t,r));if(e)return e}let i=e?at.pins.get(e):void 0;if(i&&i.provider===t){let e=at.faces.get(ac(t,i.credentialId));if(e)return e}return nD(t)??("anthropic"!==t||al(r)||i?.provider===t?null:nv.find(e=>e.provider===t&&0===e.oauthPosition)??null)}async function ap(e,t,r,n){if(!t||al(r)||nD(t))return au(e,t,r,n);try{let{data:r}=await n0(e);if(r?.state==="resolved"&&r.provider===t&&al(r.credentialId)){let n=new Map(at.pins);n.set(e,{provider:t,credentialId:r.credentialId,observedAt:Date.now()}),ao({faces:at.faces,pins:n})}}catch{}return au(e,t,void 0,n)}function ah(e,t,r,n){let i=!!t&&!al(r)&&!!e;return(0,a.useEffect)(()=>{i&&e&&t&&function(e,t){let r=Date.now(),n=at.pins.get(e);if(n&&n.provider===t&&r-n.observedAt<3e4)return;let a=`${e}\u0000${t}`,i=aa.get(a);void 0!==i&&r-i<3e4||(aa.set(a,r),n0(e).then(t=>{let r=t.data;if(!r||"resolved"!==r.state)return;let{provider:n,credentialId:a}=r;if("string"!=typeof n||""===n||!al(a))return;let i=new Map(at.pins);i.set(e,{provider:n,credentialId:a,observedAt:Date.now()}),ao({faces:at.faces,pins:i})}).catch(()=>{}))}(e,t)},[i,e,t]),(0,a.useSyncExternalStore)(as,()=>au(e,t,r,n),()=>null)}function am(){return(0,a.useEffect)(()=>{if(!nC){nC=!0;let e=()=>{"visible"===document.visibilityState&&nM()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e)}null===ny&&(ny=nM().then(e=>{e||(ny=null)}))},[]),(0,a.useSyncExternalStore)(nI,nT,()=>nm)}nI(()=>{ar=null,ad(an)});let af={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.why.next":"다음에 할 일","flow.why.check.syntax":"{label} 명령의 종료 코드. 명령에 $(…)\xb7백틱\xb7( ) 묶음\xb7{ } 같은 셸 구문이 있어서, 그 종료 코드가 셸 종료 코드까지 그대로 왔는지 이 화면은 따지지 않아요. 그래서 통과로 세지 않았어요.","flow.why.check.optional":"{label} 스크립트가 실제로 실행된 기록. --if-present를 쓰면 스크립트가 없을 때 실행기가 아무것도 실행하지 않고 종료 코드 0으로 끝나요.","flow.why.noExit":"이 호출의 종료 코드. 결과 기록에 종료 코드가 없어요.","flow.why.noResult":"이 호출의 결과. 결과 기록이 없어요.","flow.why.interrupted":"이 호출의 결과. 호출이 끝나기 전에 끊겼어요.","flow.why.noCompletion":"이 호출의 종료 코드. 호출이 백그라운드 job으로 넘어갔고, 그 job의 완료 기록이 없어요.","flow.next.rerun":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 검사 명령 자체의 종료 코드를 찾을 수 없을 때만 파이프, ;, ||, 감싸는 구문 없이 검사 명령을 단독으로 다시 실행하세요. 긴 출력은 tail이나 grep으로 자르지 말고 결과 artifact에서 확인하세요.","flow.next.optional":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 스크립트 실행 기록을 찾을 수 없을 때만 --if-present 없이 스크립트 이름으로 다시 실행하세요.","flow.next.compound":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 어느 단계가 실패했는지 찾을 수 없을 때만 단계마다 명령을 나눠 다시 실행하세요.","flow.next.again":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 종료 코드를 찾을 수 없을 때만 같은 검사를 다시 실행하세요.","flow.repeats":"반복 실행 {count}건","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.why.next":"Next","flow.why.check.syntax":"The exit code of the {label} command itself. The command contains shell syntax such as $(…), backticks, ( ) grouping or { } braces, and this panel does not trace whether that exit code reaches the shell exit code, so it was not counted as passed.","flow.why.check.optional":"A record that the {label} script actually ran. With --if-present, the runner exits 0 without running anything when the script does not exist.","flow.why.noExit":"The exit code of this call. The result record has no exit code.","flow.why.noResult":"The result of this call. There is no result record for it.","flow.why.interrupted":"The result of this call. The call was interrupted before it finished.","flow.why.noCompletion":"The exit code of this call. The call moved to a background job and has no completion record for that job.","flow.next.rerun":"First check this call's completion record and output. Rerun the check command on its own without a pipe, ;, || or wrapping syntax only if the run has ended and the check's own exit code cannot be recovered. Read long output from the result artifact instead of cutting it with tail or grep.","flow.next.optional":"First check this call's completion record and output. Rerun the script by name without --if-present only if the run has ended and proof that the script ran cannot be recovered.","flow.next.compound":"First check this call's completion record and output. Rerun each stage as a separate command only if the run has ended and the failing stage cannot be recovered.","flow.next.again":"First check this call's completion record and output. Rerun the same check only if the run has ended and no exit code can be recovered.","flow.repeats":"{count} repeated runs","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"}};function ag(){let{locale:e}=(0,z.s)();return{st:(0,a.useCallback)((t,r)=>(0,et.u0)(e,t,af,r),[e]),locale:e}}function ax({seed:e,size:t,provider:r}){am();let i=nU(e),[s,o]=(0,a.useState)(null),l=s===i,[c,d]=(0,a.useState)(!1);return l?(0,n.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:nH(e).slice(0,1)}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),d(!0)},"aria-label":nH(e),children:(0,n.jsx)("img",{className:"account-avatar",src:i,width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>o(i)})}),c&&(0,n.jsx)(av,{seed:e,provider:r,onClose:()=>d(!1)})]})}function av({seed:e,provider:t,onClose:r}){let{t:i}=(0,z.s)(),s=(0,a.useRef)(null);(0,a.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=nH(e);return(0,q.createPortal)((0,n.jsxs)("dialog",{ref:s,className:"account-avatar-dialog","aria-label":o,onCancel:e=>{e.preventDefault(),r()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),r())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&r()},children:[(0,n.jsx)("img",{className:"account-avatar-full",src:nU(e),width:256,height:256,alt:o,draggable:!1}),(0,n.jsxs)("p",{className:"account-avatar-caption",children:[(0,n.jsx)("span",{className:"account-avatar-caption-alias",children:o}),t?(0,n.jsx)("span",{className:"account-avatar-caption-provider",children:nq(t)}):null]}),(0,n.jsx)("button",{type:"button",className:"account-avatar-close",onClick:r,children:i("i18n.close")})]}),document.body)}function ab(e){let t,r=[],n=null,a=0,i=0,s=0,o=0,l=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!n){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(),r=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();n.rows.push({type:"line",left:e,right:r})}l=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(s>0||o>0)){if(d.startsWith("--- ")){u(),t=ay(d.slice(4));continue}if(d.startsWith("+++ ")){u(),n={oldPath:t,newPath:ay(d.slice(4)),rows:[]},r.push(n);continue}}let e=d.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){n||(n={rows:[]},r.push(n)),u(),a=Number(e[1]),i=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]),n.rows.push({type:"hunk",text:d});continue}if(!n)continue;if(d.startsWith("\\ ")){u(),n.rows.push({type:"hunk",text:d});continue}let p=d[0],h=d.slice(1);" "===p?(u(),n.rows.push({type:"line",left:{lineNo:a++,text:h,type:"context"},right:{lineNo:i++,text:h,type:"context"}}),s>0&&s--,o>0&&o--):"-"===p?(l.push({lineNo:a++,text:h}),s>0&&s--):"+"===p?(c.push({lineNo:i++,text:h}),o>0&&o--):""!==d&&(u(),n.rows.push({type:"hunk",text:d}))}u();let p=r.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function ay(e){return e.split(" ")[0].trim()}function aw({task:e,phases:t}){let{t:r}=(0,z.s)(),a="completed"===e.status,i="abandoned"===e.status,s="in_progress"===e.status,o="blocked"===e.status,l=!t||a||i?[]:tR(e,t),c=l.length>0?r("todo.waiting",{tasks:l.join(", ")}):!t||a||i||o?null:r("todo.ready"),d=a?"✓":i?"\xd7":o?"!":s?"›":"",u=a?"is-completed":i?"is-abandoned":o?"is-blocked":s?"is-active":"is-pending";return(0,n.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}${c?`; ${c}`:""}`,className:`todo-checklist-row ${u}`,children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:d}),(0,n.jsxs)("span",{className:"todo-checklist-content",children:[e.content,o&&e.blocker?(0,n.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null,c&&(0,n.jsxs)("span",{className:`todo-checklist-readiness${l.length>0?" is-waiting":""}`,children:[" \xb7 ",c]})]})]})}let ak="/icons/catppuccin";function aj({name:e,size:t=14}){let r={width:t,height:t,"--catppuccin-icon-light":`url(${ak}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${ak}/mocha/${e}.svg)`};return(0,n.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:r})}function aS({size:e=14,open:t=!1}){return(0,n.jsx)(aj,{name:t?"_folder_open":"_folder",size:e})}function aC({size:e=14}){return(0,n.jsx)(aj,{name:"_file",size:e})}let aN={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 aT(e,t=14){let r=e.toLowerCase(),a="dockerfile"===r||r.startsWith("dockerfile.")?"docker":".env"===r||r.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(r)?"git":"package-lock.json"===r?"npm-lock":"bun.lock"===r?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(r)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(r)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(r)?"lock":r.endsWith(".config.ts")||r.endsWith(".config.js")||r.endsWith(".config.mjs")||r.endsWith(".config.cjs")?"config":void 0;if(a)return(0,n.jsx)(aj,{name:a,size:t});let i=aN[r.split(".").pop()??""];return i?(0,n.jsx)(aj,{name:i,size:t}):(0,n.jsx)(aC,{size:t})}function aI({files:e,onOpenFile:t}){let{t:r}=(0,z.s)();return 0===e.length?null:(0,n.jsx)("div",{"aria-label":r("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let a=tF(e);return(0,n.jsxs)("button",{type:"button",title:e,"aria-label":r("chat.openWrittenFile",{name:a}),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:"var(--radius-control)",cursor:"pointer"},children:[aT(a,12),(0,n.jsx)("span",{children:a})]},e)})})}let aM=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function aE(e){if(!e)return null;let t=/^\s*TASK_GUARD\s*:\s*$/im.exec(e),r=e;if(t){let n=t.index+t[0].length;"\r"===e[n]&&(n+=1),"\n"===e[n]&&(n+=1);let a=n;for(;n<e.length;){let t=e.indexOf("\n",n),r=-1===t?e.length:t,i=r>n&&"\r"===e[r-1]?r-1:r;if(!aM.test(e.slice(n,i)))break;a=i,n=-1===t?e.length:t+1}let i=t[0].length-t[0].trimStart().length;r=`${e.slice(0,t.index+i)}${e.slice(a)}`}let n=[...r.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===n.length&&n[0]&&n[0]===n[0].trim()&&/[가-힣]/u.test(n[0])?n[0]:null}function a$(e){let t=e.live,r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,n=[t?.assignment,t?.progress?.assignment,t?.task].map(aE).find(e=>null!==e)??(r?.taskTitle?.trim()||null),a=t?.progress?.lastIntent?.trim()||"",i=t?.progress?.currentTool?.trim()||"";return{title:n??"담당 업무 미확인",stage:a&&i?`${a} \xb7 ${i}`:a||(i?`${i} 실행 중`:null),explicitTitle:null!==n}}function aR(e){let t=e.live?.progress,r="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",n=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,a="string"==typeof t?.resolvedThinkingLevel?t.resolvedThinkingLevel.trim():"",i="string"==typeof n?.thinkingLevel?n.thinkingLevel.trim():"";if(r){let e=r.split("/").pop()||r;return{model:r,modelShort:a&&e.endsWith(`:${a}`)?e.slice(0,-(a.length+1)):e,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:a||i||null}}let s="string"==typeof n?.model?n.model.trim():"";return{model:s||null,modelShort:s?s.split("/").pop()||s:null,modelIsFallback:!!s&&n?.modelIsFallback===!0,effort:i||null}}class aL extends Error{constructor(e,t,r){super(t),this.kind=e,this.status=r,this.name="SubagentClientError"}}async function aA(e){try{return await e.json()}catch{throw new aL("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function aP(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 aF(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 a_(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 az(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 aW(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let r=async(t,r,n)=>{let a;try{a=await e(t,r)}catch(e){if(r.signal?.aborted)throw e;throw new aL(n,"sidecar-unreachable"===n?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let i=await aA(a);if(!a.ok)throw new aL("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}(i,`HTTP ${a.status}`),a.status);return{response:a,body:i}};return{async getLiveSnapshots(e,t){let{body:n}=await r(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!n||"object"!=typeof n)throw new aL("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof n.error&&n.error)throw new aL("http",n.error);if(!0!==n.running)return{runtime:"detached",subagents:[]};let a=n.state?.subagents;if(void 0!==a&&(!Array.isArray(a)||!a.every(a_)))throw new aL("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:a??[]}},async getLiveTranscript(e,t,n,a){let{body:i}=await r(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:n}),signal:a},"live-unreachable");if(!i||"object"!=typeof i)throw new aL("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof i.error&&i.error)throw new aL("http",i.error);if(!0!==i.success||!i.data||"object"!=typeof i.data)throw new aL("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let s=i.data;if(!Array.isArray(s.entries)||!s.entries.every(az)||"number"!=typeof s.fromByte||"number"!=typeof s.nextByte||"boolean"!=typeof s.reset)throw new aL("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:s.fromByte,nextByte:s.nextByte,reset:s.reset,entries:s.entries}},async getArchive(e,n){let a=`${t}/archive?session=${encodeURIComponent(e)}`,{body:i}=await r(a,{method:"GET",signal:n},"sidecar-unreachable");if(!i||"object"!=typeof i||"string"!=typeof i.sessionId||"string"!=typeof i.dir||"boolean"!=typeof i.found||!Array.isArray(i.subagents)||!i.subagents.every(aP))throw new aL("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:i.sessionId,dir:i.dir,found:i.found,subagents:i.subagents,...!0===i.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,n,a=400,i){let s=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(n)}&limit=${encodeURIComponent(String(a))}`,{body:o}=await r(s,{method:"GET",signal:i},"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(aF))throw new aL("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}let aO=["feature","maintenance","diagnostic"],aD=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function aH(e){if("string"!=typeof e)return null;let t=e.split(/\r?\n/),r=t.findIndex(e=>/^\s*TASK_GUARD\s*:\s*$/.test(e));if(r<0)return null;for(let e=r+1;e<t.length;e+=1){let r=aD.exec(t[e]);if(!r)break;if("WORK_CLASS"!==r[1])continue;let n=r[2].toLowerCase();return aO.includes(n)?n:null}return null}let aU={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function aB(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function aq(e){return"string"==typeof e&&e.trim()?e:null}function aV(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function aK(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 aG(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function aJ(e,t){if(t?.isError)return null;let r=aB(e.input.tasks),n=aB(t?.details?.progress),a=Math.max(r.length,n.length),i=[];for(let s=0;s<a;s++){let a=n.find(e=>e.index===s)??n[s],o=r[s],l=aq(a?.id)??aq(o?.name);l&&i.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:l,agent:aq(a?.agent)??aq(o?.agent),task:aq(a?.task)??aq(o?.task)??"",workClass:aH(o?.task)??aH(a?.task),spawned:!!t})}return i}let aZ=/<task-result\b([^>]*)>/g,aY=/(\w+)="([^"]*)"/g;function aX(e,t,r){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&r.latestByAgent.get(e.agentId)===e.key)}function aQ(e,t,r){var n;let a,i,s,o,l=aX(e,t,r),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=a$(c),u=r.runs.get(e.key),p=null;l&&"unknown"!==l.status?(a=l.status,p="live"):u&&"unknown"!==u.status?(a=u.status,p="record"):a=e.spawned?"unobserved":"dispatching";let h=r.verdicts.get(e.key),m=h&&h.length>0?h[h.length-1]:null,f=m?.at??null,g=null===f?null:(n=e.key,i=r.runStartedAt.get(n)??null,s=l?.progress?.durationMs,o=l&&("pending"===l.status||"running"===l.status)&&"number"==typeof s&&l.lastUpdate>0?l.lastUpdate-s:null,null===i?o:null===o?i:Math.max(i,o)),x=null!==f&&null!==g&&g>f;return{member:e,title:d.title,explicitTitle:d.explicitTitle,stage:l?d.stage:null,model:l?aR(c):null,run:a,runSource:p,verdict:x?null:m,priorVerdict:x?m:null,runTitle:x?aE(l?.progress?.task):null,observedParallelWith:r.parallelWith.get(e.key)}}function a0(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function a1(e,t){let r=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),n=new Map,a=[];for(let e of r){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?a.push(t):n.set(e.attempt,t)}return[...a,...[...n.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}function a2(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function a8(e,t,r){let n=-1;r.forEach((e,t)=>{"user"===e.role&&(n=t)});let a=r.slice(0,n+1).flatMap(a2),i=r.slice(n+1).flatMap(a2),s=t.findIndex(e=>"user"===e.role),o=0===i.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===o?{continuing:null,atCompaction:[...a,...i]}:{continuing:{position:o,calls:i},atCompaction:a}}let a4="끊기기 전에 바깥에 영향을 주는 행동(커밋\xb7push, `git_finalize`\xb7`git_integrate`, 배포\xb7`update.sh`, CI 재실행, 이슈\xb7PR 댓글, 메시지 전송)을 하던 중이었다면 다시 하기 전에 그 결과가 이미 반영됐는지 `git log`\xb7`git status`\xb7원격 브랜치, `gh run list`, 배포 로그, 해당 페이지로 먼저 확인하고, 반영됐으면 되풀이하지 않는다. ",a5="[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+a4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a6="[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. "+a4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a3="[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+a4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a7=new Set(["[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.","[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.","[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."]),a9={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function ie(e){return e.trim()}function it(e){return ie(e.text)||(e.images>0?"[Image]":"")}function ir(e){let t=e.filter(e=>!a9[e.stage]);if(t.length<=4)return e;let r=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!r.has(e.id))}function ia(e,t){switch(t.type){case"submit":return ir([...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 ir(e.map(e=>e.id===t.id&&a9[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,r){let n=new Map,a=(e,t)=>{let r=`${e}\u0000${ie(t)}`;n.set(r,(n.get(r)??0)+1)};for(let e of t)a("steer",e);for(let e of r)a("followUp",e);let i=!1,s=e.map(e=>{if(!a9[e.stage])return e;let t=`${e.kind}\u0000${it(e)}`,r=n.get(t)??0;return r>0?(n.set(t,r-1),e.inQueue&&"accepted"===e.stage)?e:(i=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(i=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return i?s:e}(e,t.steering,t.followUp);case"user-message":{let r=ie(t.text);if(!r&&0===t.images)return e;let n=e.find(e=>(a9[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&ie(e.text)===r&&e.images===t.images);if(!n)return e;return ir(e.map(e=>e===n?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let r=e=>a9[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!r(e));let n=ie(t.text),a=e.find(e=>r(e)&&e.kind===t.kind&&(ie(e.text)===n||it(e)===n));return a?e.filter(e=>e!==a):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 ii(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 is(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}let io=["investigate","edit","check","review","commit","ci","deploy"];function il(e,t){let r="",n=t;for(;n<e.length&&'"'!==e[n];){let t=e[n];if("\\"===t&&n+1<e.length){let a=e[n+1];"\n"!==a&&(r+='$`"\\'.includes(a)?a:t+a),n+=2}else if("$"===t&&"("===e[n+1]){let t=ic(e,n+1);r+=e.slice(n,t),n=t}else if("`"===t){let t=id(e,n+1);r+=e.slice(n,t),n=t}else r+=t,n+=1}return{text:r,end:Math.min(n+1,e.length)}}function ic(e,t){let r=e[t],n="{"===r?"}":")",a=0,i=t;for(;i<e.length;){let t=e[i];if("\\"===t)i+=2;else if("'"===t){let t=e.indexOf("'",i+1);i=t<0?e.length:t+1}else if('"'===t)i=il(e,i+1).end;else if("`"===t)i=id(e,i+1);else{if(t===r)a+=1;else if(t===n&&0==--a)return i+1;i+=1}}return e.length}function id(e,t){let r=t;for(;r<e.length&&"`"!==e[r];)r+="\\"===e[r]?2:1;return Math.min(r+1,e.length)}function iu(e){let{tokens:t,groups:r,expandingHeredoc:n}=function(e){let t=[],r=[],n=!1,a=[],i=[],s="",o=-1,l=!1,c=e=>{if(o<0)return;let r={value:s,start:o,end:e,risky:l};for(let e of(t.push(r),i.splice(0)))e.at===t.length-1&&(e.owner=r);s="",o=-1,l=!1},d=0;for(;d<e.length;){let u=e[d];if("\\"===u)"\n"!==e[d+1]&&(o<0&&(o=d),s+=e[d+1]??""),d+=2;else if("'"===u){o<0&&(o=d);let t=e.indexOf("'",d+1),r=t<0?e.length:t;s+=e.slice(d+1,r),d=r+1}else if('"'===u){o<0&&(o=d);let t=il(e,d+1);/\$[({]|`/.test(e.slice(d,t.end))&&(l=!0),s+=t.text,d=t.end}else if("$"===u&&("("===e[d+1]||"{"===e[d+1])){o<0&&(o=d);let t=ic(e,d+1);s+=e.slice(d,t),l=!0,d=t}else if("`"===u){o<0&&(o=d);let t=id(e,d+1);s+=e.slice(d,t),l=!0,d=t}else if("#"===u&&o<0){let t=e.indexOf("\n",d);d=t<0?e.length:t}else if(" "===u||" "===u||"\r"===u)c(d),d+=1;else if("\n"===u){c(d);let r=t[t.length-1];for(let s of("&&"!==r&&"||"!==r&&"|"!==r&&t.push(";"),d+=1,i.length=0,a.splice(0)))for(;d<e.length;){let t=e.indexOf("\n",d),r=t<0?e.length:t,a=e.slice(d,r);if(d=r+1,(s.stripTabs?a.replace(/^\t+/,""):a)===s.delimiter)break;!s.quoted&&/\$[({]|`/.test(a)&&(s.owner?s.owner.risky=!0:n=!0)}}else if("<"===u&&"<"===e[d+1]&&"<"!==e[d+2]){c(d);let r=d+2,n="-"===e[r];for(n&&(r+=1);" "===e[r]||" "===e[r];)r+=1;let s="",o=!1;for(;r<e.length&&!/[\s;&|<>()]/.test(e[r]);){let t=e[r];if("'"===t||'"'===t){o=!0;let n=e.indexOf(t,r+1),a=n<0?e.length:n;s+=e.slice(r+1,a),r=a+1}else"\\"===t&&(o=!0),s+="\\"===t?e[r+1]??"":t,r+="\\"===t?2:1}if(s){let e=t[t.length-1],r={delimiter:s,stripTabs:n,quoted:o,owner:void 0!==e&&"string"!=typeof e?e:null,at:t.length};a.push(r),r.owner||i.push(r)}d=r}else";"===u?(c(d),t.push(";"),d+=";"===e[d+1]?2:1):"&"===u?"&"===e[d+1]?(c(d),t.push("&&"),d+=2):(">"===e[d+1]||/[<>]$/.test(s)?(o<0&&(o=d),s+=u):(c(d),t.push("&")),d+=1):"|"===u?"|"===e[d+1]?(c(d),t.push("||"),d+=2):s.endsWith(">")?(s+=u,d+=1):(c(d),t.push("|"),d+="&"===e[d+1]?2:1):("("===u||")"===u?(c(d),r.push(d)):(o<0&&(o=d),("{"===u||"}"===u||"!"===u)&&(l=!0),s+=u),d+=1)}return c(e.length),{tokens:t,groups:r,expandingHeredoc:n}}(e),a=[],i=[],s={pipelines:[],operators:[],background:!1},o={commands:[],negated:!1},l=[],c=()=>{let t=l.map(e=>e.value).filter(e=>"{"!==e&&"}"!==e);if(0===o.commands.length&&"!"===t[0]&&(o.negated=!0,t.shift()),t.length>0){let n=l[0].start,a=l[l.length-1].end,s=l.some(e=>e.risky)||r.some(e=>e>=n&&e<=a),c={words:t,text:e.slice(n,a),uncertain:s};o.commands.push(c),i.push(c)}l=[]},d=()=>{c(),o.commands.length>0&&s.pipelines.push(o),o={commands:[],negated:!1}},u=e=>{d(),s.pipelines.length>0&&a.push({...s,background:e}),s={pipelines:[],operators:[],background:!1}};for(let e of t)"string"!=typeof e?l.push(e):"|"===e?c():"&&"===e||"||"===e?(d(),s.operators.push(e)):u("&"===e);return u(!1),{lists:a,commands:i,uncertain:r.length>0||n||t.some(e=>"string"!=typeof e&&e.risky)}}function ip(e){return e.slice(e.lastIndexOf("/")+1)}let ih={bash:!0,sh:!0,zsh:!0,dash:!0},im={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},ix={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},iv={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function ib(e){let t=ik(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(ih,ip(e[t]))||iy(e,t))return null;for(let r=t+1;r<e.length&&/^[-+]/.test(e[r]);r+=1){if(/^-[a-zA-Z]*c[a-zA-Z]*$/.test(e[r]))return e[r+1]??null;(/^[-+][a-zA-Z]*[oO]$/.test(e[r])||"--rcfile"===e[r]||"--init-file"===e[r])&&(r+=1)}return null}function iy(e,t){for(let r=t+1;r<e.length&&/^[-+]/.test(e[r]);r+=1){if(/^-[a-zA-Z]*n[a-zA-Z]*$/.test(e[r])||/^-[a-zA-Z]*o$/.test(e[r])&&"noexec"===e[r+1])return!0;(/^[-+][a-zA-Z]*[oO]$/.test(e[r])||"--rcfile"===e[r]||"--init-file"===e[r])&&(r+=1)}return!1}let iw={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function ik(e){let t=!1,r="";for(let n=0;n<e.length;n+=1){let a=e[n];if(!(/^[A-Za-z_]\w*=/.test(a)||!t&&Object.hasOwn(iv,a))){if(t&&(a.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(a))){if(Object.hasOwn(iw,r)&&iw[r].test(a))return -1;"command"!==r&&Object.hasOwn(ig,a)&&(n+=1);continue}if(!Object.hasOwn(im,ip(a)))return n;t=!0,r=ip(a)}}return -1}let ij=/(?:^|\/)wsl\/update\.sh$/;function iS(e,t=0){let r=ib(e);if(null!==r)return t<3&&iu(r).commands.some(e=>iS(e.words,t+1));let n=ik(e);if(n<0)return!1;if(ij.test(e[n]))return!0;if(!Object.hasOwn(ih,ip(e[n]))||iy(e,n))return!1;let a=e.slice(n+1).find(e=>!e.startsWith("-"));return void 0!==a&&ij.test(a)}function iC(e){let t=ik(e),r=t<0?e:e.slice(0,t),n=r.map(ip);return n.includes("systemd-run")?!r.some(e=>Object.hasOwn(ix,e)):!!(n.includes("sudo")&&r.some(e=>"--background"===e||/^-[a-zA-Z]*b[a-zA-Z]*$/.test(e)))||n.includes("setsid")&&!r.includes("-w")&&!r.includes("--wait")}function iN(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function iT(e){if(e.every(e=>/^[A-Za-z_]\w*=/.test(e)))return!0;let[t,...r]=e;return"cd"===t?r.length<=1:"export"===t?r.every(e=>/^[A-Za-z_]\w*=/.test(e)):"set"===t&&r.every(e=>/^[-+][a-zA-Z]+$/.test(e)&&!/^-[a-zA-Z]*n/.test(e)||"pipefail"===e)}let iI={tail:!0,head:!0,cat:!0,tee:!0},iM=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,iE={bun:!0,bunx:!0,npm:!0,npx:!0,pnpm:!0,yarn:!0,node:!0,python:!0,python3:!0,deno:!0},i$={"--help":!0,"-h":!0,"--version":!0},iR=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 iL(e){let t=ik(e);if(t<0)return!1;let r=ip(e[t]);if("test"===r||"["===r||e.slice(t+1).some(e=>Object.hasOwn(i$,e)))return!1;if(iM.test(r))return!0;if(!Object.hasOwn(iE,r))return!1;if("node"===r&&function(e,t){for(let r=t;r<e.length;r+=1){let t=e[r];if("--test"===t)return!0;if("--"===t||!t.startsWith("-"))break;Object.hasOwn(iR,t)&&(r+=1)}return!1}(e,t+1))return!0;let n=function(e,t){for(let r=t;r<e.length;r+=1){let t=e[r];if("-m"===t)return e[r+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(r+1).find(e=>!e.startsWith("-"));return t}}}(e,t+1);return void 0!==n&&iM.test(n)}let iA={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},iP={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function iF(e){let t=ik(e);if(t<0||"git"!==ip(e[t]))return null;for(let r=t+1;r<e.length;r+=1)if(Object.hasOwn(iA,e[r]))r+=1;else if(!e[r].startsWith("-"))return{name:e[r],at:r};return null}function i_(e,t=0,r){let n=ib(e);if(null!==n)return t<3&&iu(n).commands.some(e=>i_(e.words,t+1,r));let a=iF(e);if(!a||"commit"!==a.name&&"push"!==a.name||void 0!==r&&a.name!==r)return!1;let i=iP[a.name];return!e.slice(a.at+1).some(e=>Object.hasOwn(i,e)||"push"===a.name&&/[nd]/.test(function(e){if(!/^-[a-zA-Z0-9]/.test(e))return"";let t="";for(let r of e.slice(1)){if("o".includes(r)||!/[a-zA-Z0-9]/.test(r))break;t+=r}return t}(e)))}function iz(e){return iT(e)||null!==iF(e)}let iW={check:({words:e})=>iL(e),commit:({words:e})=>i_(e),ci:({words:e})=>{let t=ik(e);return t>=0&&"gh"===ip(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>iS(e.words)},iO={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 iD(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 iH={"$?":!1,"${PIPESTATUS[0]}":!0};function iU(e,t){let r=i1(t);if("notRun"===r)return[];let n=r?void 0:t,a=iu(e),i=[];if(a.commands.some(({words:e})=>(function e(t,r=0){let n=ib(t);return null!==n?r<3&&iu(n).commands.some(t=>e(t.words,r+1)):iL(t)})(e))&&i.push("check"),a.commands.some(({words:e})=>i_(e))&&i.push("commit"),a.commands.some(({words:e})=>(function e(t,r=0){let n=ib(t);if(null!==n)return r<3&&iu(n).commands.some(t=>e(t.words,r+1));let a=ik(t);return a>=0&&"gh"===ip(t[a])&&"run"===t[a+1]&&["watch","view","list"].includes(t[a+2])})(e))&&i.push("ci"),a.commands.some(iW.deploy)&&i.push("deploy"),0===i.length)return[];let s=n?rO(n):null,o=null===s?!!n?.isError:0!==s,l=i.length>1?{stages:i,failed:o}:void 0,c=n?sp(n):"";return i.map(e=>{var t;let i,d,u,p="commit"===e?iz:iT,h=function e(t,r,n=iT,a=0){let{lists:i}=t,s=[],o=t.uncertain,l=!1;return i.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=a<3?ib(p.words):null,m=null===h?null:e(iu(h),r,n,a+1);if(m&&m.decisive.length>0)s.push(...m.decisive);else if(r(p))s.push(p);else{let e=ik(p.words);u&&l&&e>=0&&Object.hasOwn(iI,ip(p.words[e]))||n(p.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let r=iN(e[t])?.words;return r?.[0]==="exit"&&(1===r.length||2===r.length&&"$?"===r[1])}(i,c)||(o=!0);continue}u=!0,(m?.reach==="masked"||d.negated||d.commands.length>1&&!l||t.operators.includes("||")||t.background||iC(p.words)||!function(e,t){if(t===e.length-1)return!0;let r=e[e.length-1],n=iN(r)?.words;return!!n&&"exit"===n[0]&&!r.background&&t===e.length-2&&(1===n.length||2===n.length&&"$?"===n[1])}(i,c))&&(o=!0)}}let d=iN(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}}(a,iW[e],p),m="check"===e&&h.decisive.some(({words:e})=>e.includes("--if-present")),f=n?(t=iW[e],i=new Map,d=a.lists.map(e=>(function(e){let t=e&&!e.background?iN(e)?.words:void 0;if(!t||"echo"!==t[0]||t.length<2)return null;let r=t.slice(1);if(r.some(e=>e.startsWith("-")||/^(?:\d*[<>]|&>)/.test(e)))return null;let n=r.join(" ");for(let[e,t]of Object.entries(iH)){let r=n.indexOf(e);if(r<0||n.indexOf(e,r+1)>=0)continue;let a=n.slice(0,r),i=n.slice(r+e.length);if(/[$`\\]/.test(a+i)||!/[^\s\d]/.test(a))break;return{prefix:a,suffix:i,first:t}}return null})(e)),u=c.split("\n").map(e=>e.trimEnd()),a.lists.forEach((e,r)=>{let n=d[r+1];if(!n||e.background||e.operators.includes("||"))return;let a=e.pipelines[e.pipelines.length-1],s=e.pipelines.slice(0,-1);if(a.negated||s.some(e=>e.negated||1!==e.commands.length||!p(e.commands[0].words)))return;let o=n.first||1===a.commands.length?a.commands[0]:void 0;if(!o||!t(o)||iC(o.words)||o.uncertain)return;let l=d.filter(e=>e?.prefix===n.prefix&&e.suffix===n.suffix),c=RegExp(`^${n.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(-?\\d+)${n.suffix.trimEnd().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`),h=u.flatMap(e=>{let t=c.exec(e);return t?[{code:Number(t[1]),line:e}]:[]});if(h.length!==l.length)return;let m=d.slice(0,r+2).filter(e=>l.includes(e)).length-1;i.set(o,h[m])}),i):new Map,g=h.decisive.flatMap(e=>f.get(e)??[]),x=g.length>0&&g.length===h.decisive.length?g.find(({code:e})=>0!==e)??g[0]:null,v=x?0!==x.code?"failed":m?"unverified":"passed":o?l?"unverified":"failed":null===s?"unobserved":"carried"!==h.reach||m?"unverified":"passed",b="unobserved"===v?"interrupted"===r?"interrupted":n?"noExit":"noResult":"unverified"!==v?null:m?"optional":o&&l?"compound":a.uncertain?"syntax":"masked";return{stage:e,state:v,exitCode:s,labels:"check"===e?function(e){let t=[];for(let{words:r}of e){let e=ik(r);r.forEach((r,n)=>{if(n!==e||"test"!==r)for(let e of r.replace(/^-+/,"").toLowerCase().split(":")){let r=Object.hasOwn(iO,e)?iO[e]:void 0;r&&!t.includes(r)&&t.push(r)}})}return t}(h.decisive):[],...l?{compound:l}:{},...x?{evidence:x.line}:{},...b?{reason:b}:{}}})}function iB(e,t){let r=iD(e),n=null===r?void 0:iU(r,t).find(e=>"check"===e.stage);return null!==r&&n?{toolCallId:e.toolCallId,command:r,state:n.state,exitCode:n.exitCode,labels:n.labels,...n.compound?{compound:n.compound}:{},...n.reason?{reason:n.reason}:{}}:null}let iq=/\.(?:md|mdx|markdown|txt)$/i,iV=/^docs?$/i;function iK(e){return iq.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>iV.test(e))}let iG={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},iJ={multiedit:!0,notebookedit:!0,draft:!0},iZ={rename:!0,rename_file:!0},iY={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function iX(e){return e.split("\n")[0].trim()||void 0}let iQ=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,i0=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function i1(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 i2=/\btool\.git_(?:finalize|integrate)\s*\(/,i8=/\b(?:Committed|Integrated \S+) and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,i4=/\bgit_(?:finalize|integrate) failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,i5=/\bstage["']?\s*:\s*["'](?:up-to-date|aborted)["']/,i6=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/;function i3(e,t){if("string"==typeof t.commitSha&&""!==t.commitSha.trim())return t.commitSha.trim();let r=i8.exec(sp(e));return r?.[1]??r?.[2]??null}let i7=/^bg_\d+$/;function i9(e){let t=e.details,r=t&&"object"==typeof t&&"async"in t?t.async:null;if(r&&"object"==typeof r&&"jobId"in r&&"string"==typeof r.jobId&&i7.test(r.jobId))return r.jobId;let n=sp(e).trimStart();return n.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(n)?.[1]??null:null}function se(e,t){let r=/Command exited with code (-?\d+)\s*$/.exec(t.trimEnd());return{jobId:e,text:t,exitCode:r?Number(r[1]):null}}function st(e){return"passed"===e||"failed"===e||"done"===e}function sr(e){let t=null;for(let r of e.values())"failed"===r.outcome&&(!t||r.order>t.order)&&(t=r);return t?.stage??null}function sn(e){return e.commandKey??JSON.stringify([e.cwd??"",e.command])}function sa(e){let t=new Map;for(let r of e){if("check"!==r.stage)continue;let e=sn(r),n=t.get(e);(n?.outcome!=="failed"||st(r.outcome))&&t.set(e,r)}return[...t.values()]}function si(e){return"compound"in e&&e.compound?.failed===!0}let ss={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function so(e){return"stale"!==e&&(st(e)||"running"===e)}function sl(e){if("ci"!==e.stage)return null;let t=iu(e.command).commands.flatMap(({words:e})=>sm(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?sv(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let sc={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},sd={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},su=/^[0-9a-f]{40}$/i;function sp(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 sh(e){let t=[];for(let r of e.split("\n")){let e,n=r.trim();if(n.startsWith("{")||n.startsWith("[")){try{e=JSON.parse(n)}catch{continue}for(let r of Array.isArray(e)?e:[e])r&&"object"==typeof r&&!Array.isArray(r)&&t.push(r)}}return t}function sm(e,t=0){let r=ib(e);if(null!==r)return t<3?iu(r).commands.flatMap(e=>sm(e.words,t+1)):[];let n=ik(e);return n>=0&&"gh"===ip(e[n])?[e.slice(n+1)]:[]}function sf(e,t){for(let r=0;r<e.length;r+=1)for(let n of t){if(e[r]===n)return e[r+1]??null;if(n.startsWith("--")&&e[r].startsWith(`${n}=`))return e[r].slice(n.length+1)}return null}let sg={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function sx(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(sg,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function sv(e){let t=sx(e);return null!==t&&/^\d+$/.test(t)?t:null}let sb=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function sy(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==rO(t))return[];let r=iu(e).commands.flatMap(({words:e})=>sm(e)).filter(e=>"run"===e[0]&&("list"===e[1]||"view"===e[1]));if(0===r.length)return[];let n=1===r.length?r[0]:null,a=n?.[1]==="list"?sf(n,["-c","--commit"])?.toLowerCase():void 0,i=a&&/^[0-9a-f]{7,40}$/.test(a)?a:null,s=sp(t);return i||s.includes("headSha")?sh(s).flatMap(e=>{let t="string"==typeof e.headSha?e.headSha.toLowerCase():i;if(null===t)return[];let r="string"==typeof e.url?sb.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):n?.[1]==="view"?sv(n):null,repo:(r??(n?sf(n,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:n?sf(n,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:n?sf(n,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let sw=/\b\d{9,12}\b/g,sk=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function sj(e,t){if(e?.type!=="toolCall")return[];let r=iD(e);return null===r?[]:sy(r,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(sd,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let sS="Public tree already matches; nothing to publish";function sC(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function sN(e){let t="run"===e[0]&&"list"===e[1]?sf(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(sc,t)}function sT(e,t){let r=new Map,n=[];for(let{words:a}of iu(e).commands){let e=a.map(e=>/^([A-Za-z_]\w*)=([\s\S]*)$/.exec(e));if(a.length>0&&e.every(e=>null!==e)){for(let t of e){if(!t)continue;let e=/^\$\(([\s\S]*)\)$/.exec(t[2])?.[1],n=void 0===e?[]:iu(e).commands.flatMap(e=>sm(e.words));r.set(t[1],1===n.length&&sN(n[0]))}continue}for(let e of sm(a)){if(sN(e)){n.push({args:e,publish:!0});continue}let a="run"===e[0]&&("watch"===e[1]||"view"===e[1])?sx(e):null,i=sC(a),s=null!==i?!0===r.get(i):null!==a&&/^\d+$/.test(a)&&t(a);n.push({args:e,publish:s})}}return n}function sI(e,t){let r=sT(e,t);return r.length>0&&r.every(({publish:e})=>e)}function sM(e,t){if(!e||!t)return!1;let[r,n]=e.length<=t.length?[e.toLowerCase(),t.toLowerCase()]:[t.toLowerCase(),e.toLowerCase()];return r.length>=7&&/^[0-9a-f]+$/.test(n)&&n.startsWith(r)}function sE(e,t,r){if(sM(e.sha,t.step.commit))return!0;let{title:n}=t.step;return!!n&&!!e.title&&!!e.repo&&!(e.order<=t.order)&&!!e.workflow&&!!Object.hasOwn(sd,e.workflow)&&[...r.publishRuns.values()].some(r=>r.order>t.order&&null!==r.sha&&sM(r.sha,t.step.commit)&&null!==r.repo&&r.repo!==e.repo)&&function(e,t){if(e===t)return!0;let r=e.endsWith("…")?e.slice(0,-1):null;return null!==r&&r.length>=20&&t.startsWith(r)}(e.title,n)}let s$={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},sR=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,sL=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) (ROLLED_BACK|ROLLBACK_FAILED|FAIL)\b/,sA=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) START old=\S* target=([0-9a-f]{7,40})\b/;function sP(e,t,r=!1,n=[],a,i=[]){let s,o,l=[],c=[],d=1,u=new Map,p=-1,h=-1,m=new Map,f={publishRuns:new Map,watched:[],heads:[],ciHeads:[],nothingToPublish:[],runs:[]},g=Array.isArray(e)?e:[],x=t instanceof Map?t:new Map,v=function(e,t,r=[]){let n=new Map,a=new Map,i=new Map;for(let e of r)null!==e.after&&i.set(e.after,[...i.get(e.after)??[],e]);let s=(e,t)=>{for(let r of e){let e=a.get(r.jobId);e&&(a.delete(r.jobId),n.set(e.toolCallId,{...e.result,isError:!1,content:[{type:"text",text:r.text}],details:{...null===r.exitCode?{}:{exitCode:r.exitCode},backgroundJob:{jobId:r.jobId,after:t}}}))}};for(let r of Array.isArray(e)?e:[]){if(!r||"toolCall"!==r.type)continue;let e=t.get(r.toolCallId);if(e){let t="bash"===r.toolName||"eval"===r.toolName?i9(e):null;t?a.set(t,{toolCallId:r.toolCallId,result:e}):n.set(r.toolCallId,e),"wait"===r.toolName&&s(function(e){let t=e.details,r=t&&"object"==typeof t&&"jobs"in t?t.jobs:null,n=(Array.isArray(r)?r:[]).flatMap(e=>{if(!e||"object"!=typeof e||!("id"in e)||!("status"in e)||!("resultText"in e)||"string"!=typeof e.id||!i7.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[{...se(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(n.length>0)return n;let a=sp(e),i=[...a.matchAll(/^### (bg_\d+) \[\w+\] — (?:completed|failed)$/gm)];return i.map((e,t)=>{let r=(e.index??0)+e[0].length,n=a.slice(r,t+1<i.length?i[t+1].index:a.length),s=n.indexOf("\n```\n"),o=n.lastIndexOf("\n```");return se(e[1],s>=0&&o>s?n.slice(s+5,o):"")})}(e),r.toolCallId);let i="read"===r.toolName?function(e,t){let r=e.input.path,n="string"==typeof r?/^proc:\/\/(bg_\d+)$/.exec(r)?.[1]:void 0;if(!n)return null;let[a,...i]=sp(t).split("\n");return RegExp(`^1\\|${n} \\[\\w+\\] — (?:completed|failed)\\b`).test(a)?se(n,i.map(e=>e.replace(/^\d+\|/,"")).join("\n")):null}(r,e):null;i&&s([i],r.toolCallId)}for(let e of i.get(r.toolCallId)??[])s(function(e){let t=e.replace(/^\s*<system-notice>\s*\n?/,"").replace(/\s*<\/system-notice>\s*$/,""),r=/^Background job (bg_\d+) has (?:completed|failed)\b[^\n]*(?:\n|$)/.exec(t);if(r)return[se(r[1],t.slice(r[0].length))];let n=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return n.flatMap((e,r)=>{if(!i7.test(e[1]))return[];let a=(e.index??0)+e[0].length;return[se(e[1],t.slice(a,r+1<n.length?n[r+1].index:t.length).replace(/^\n/,""))]})}(e.text),r.toolCallId)}return n}(g,x,Array.isArray(i)?i:[]),b=[];g.forEach((e,t)=>{let n;if(!e||"toolCall"!==e.type)return;let i=v.get(e.toolCallId);for(let s of(!function(e,t,r,n){let a=iD(t);if(null===a||!a.includes("gh"))return;let i=(t,r)=>{let a=e.publishRuns.get(t);a&&(null===r.sha||null!==a.sha)||e.publishRuns.set(t,{...r,order:a?.order??n})};for(let t of sy(a,r))e.runs.push({...t,order:n}),t.id&&t.sha&&t.workflow&&Object.hasOwn(sc,t.workflow)&&i(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==rO(t))return[];let r=iu(e).commands.flatMap(({words:e})=>sm(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==r.length)return[];let n=sf(r[0],["-w","--workflow"])?.toLowerCase(),a=void 0!==n&&Object.hasOwn(sc,n),i=sf(r[0],["-R","--repo"])?.toLowerCase()??null;return sp(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let r=t.toLowerCase();if(!a&&!Object.keys(sc).some(e=>r.includes(e)))return[];let n=t.match(sw)??[];return 1===n.length?[{id:n[0],sha:sk.exec(r)?.[0]??null,repo:i}]:[]})}(a,r))i(e.id,e);for(let a of sj(t,r))e.ciHeads.push({...a,order:n});for(let t of function(e,t){let r=iu(e),n=r.commands.flatMap(({words:e})=>sm(e)).filter(e=>"api"===e[0]),a=!r.uncertain&&1===r.commands.length&&1===n.length,i=t&&!t.isError&&0===rO(t)?sp(t).trim():"",s=[];for(let e of n){let t=e.slice(1).find(e=>/^\/?repos\//.test(e)),r=t?/^\/?repos\/([^/]+\/[^/]+)\/commits\/([^/?\s]+)$/.exec(t):null;if(!r)continue;let n=sf(e,["-q","--jq"]),o=null;if(a&&".sha"===n)o=i.split("\n")[0]?.trim();else if(a&&null===n&&i.startsWith("{"))try{o=JSON.parse(i.slice(0,i.lastIndexOf("}")+1)).sha}catch{}let l="string"==typeof o&&su.test(o)?o.toLowerCase():null;s.push({repo:r[1].toLowerCase(),ref:r[2],sha:l})}return s}(a,r))e.heads.push({...t,order:n});let s=function(e,t){if(!t||t.isError||0!==rO(t)||2!==e.split(sS).length)return null;let{lists:r}=iu(e),n=0;for(;n<r.length&&["set","cd"].includes(iN(r[n])?.words[0]??"");)n+=1;let a=n<r.length-1?function(e){let t=iN(e)?.words,r=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!r)return null;let n=iu(r[2]),a=1===n.lists.length?iN(n.lists[0]):null,i=a?.words[0]==="gh"?sm(a.words):[];if(1!==i.length||"run"!==i[0][0]||"list"!==i[0][1])return null;let s=sf(i[0],["-c","--commit"]),o=sf(i[0],["-w","--workflow"])?.toLowerCase();return s&&su.test(s)&&o&&Object.hasOwn(sc,o)?{name:r[1],sha:s.toLowerCase()}:null}(r[n]):null;return a&&function(e,t){if(e.background||1!==e.pipelines.length)return!1;let[r]=e.pipelines,[n,a,...i]=r.commands;if(r.negated||!a||i.length>1||"gh"!==n.words[0])return!1;let s=sm(n.words);if(1!==s.length||"run"!==s[0][0]||"view"!==s[0][1]||!s[0].includes("--log"))return!1;let o=sx(s[0]);if(sC(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]=a.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]!==sS)return!1;let[p]=i;return!p||("head"===p.words[0]||"tail"===p.words[0])&&p.words.slice(1).every(e=>/^(?:-n?\d*|\d+)$/.test(e))}(r[r.length-1],a.name)&&r.slice(n+1,-1).flatMap(e=>e.pipelines.flatMap(({commands:e})=>e)).every(({words:e})=>(function(e,t){let[r,...n]=e;if("["===r||"[["===r||"test"===r||"exit"===r||"true"===r||":"===r||"sleep"===r)return!0;if("echo"===r||"printf"===r)return n.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"!==r)return!1;let a=sm(e);return 1===a.length&&"run"===a[0][0]&&"watch"===a[0][1]&&sC(sx(a[0]))===t})(e,a.name))&&sp(t).split("\n").some(e=>e.trim()===sS)?a.sha:null}(a,r);s&&e.nothingToPublish.push({sha:s,order:n})}(f,e,i,t),Array.isArray(n=function(e,t,r,n){if(!e.input||"object"!=typeof e.input||Array.isArray(e.input)||"string"!=typeof e.toolName)return null;let a=i1(t);if("notRun"===a)return null;let i={toolCallId:e.toolCallId,attempt:0},s=r&&!a?"running":"unobserved",o=iD(e);if(null!==o){var l;let r,a,c=(l=t,(a=(r=l?.details)&&"object"==typeof r&&"backgroundJob"in r?r.backgroundJob:null)&&"object"==typeof a&&"jobId"in a&&"after"in a&&"string"==typeof a.jobId&&"string"==typeof a.after?{jobId:a.jobId,after:a.after}:null);return iU(o,t).map(r=>{var a,l,d,u;let p,h;if("commit"===r.stage){let e,n,l=t?"unobserved"===r.state&&function(e,t){if(t.isError)return!1;let{commands:r}=iu(e),n=sp(t),a=e=>r.some(({words:t})=>i_(t,0,e));return(!a("commit")||iQ.test(n))&&(!a("push")||i0.test(n))}(o,t)?"done":iY[r.state]:s;return{...i,stage:"commit",..."done"===l?(e=(a=t)?sp(a):"",(n=iQ.exec(e))?{commit:n[1],title:n[2].trim()}:{commit:i0.exec(e)?.[1]??null}):{commit:null},docsOnly:!1,outcome:l}}let m=r.evidence??(c&&null!==r.exitCode?`Command exited with code ${r.exitCode}`:void 0),f=m&&c?`${c.jobId} \xb7 ${m}`:m,g="ci"===r.stage&&"failed"===r.state&&t?function(e,t){let r=iu(e).commands.flatMap(({words:e})=>sm(e)),n=r.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),a=n?sx(n):null;if(null===a||!r.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&sx(e)===a))return null;let i=sh(sp(t)).filter(e=>"completed"===e.status&&"string"==typeof e.conclusion),s=1===i.length?i[0].conclusion:null;return"string"!=typeof s||""===s||"success"===s||Object.hasOwn(s$,s)?null:s}(o,t):null,x=g?"unverified":t?r.state:s,v="check"===r.stage&&x===r.state?r.reason:void 0;return{...i,stage:r.stage,command:o,..."check"===r.stage?{cwd:(l=e.input,d=n,u=e.toolCallId,p=d?tm(d)??d:void 0,(h="string"==typeof l.cwd?l.cwd:"")?tm(h,p)??(p?tm(`${p.replace(/\/+$/,"")}/${h}`):null)??`?${u}`:p??"")}:{},exitCode:r.exitCode,labels:r.labels,outcome:x,...r.compound?{compound:r.compound}:{},...f?{evidence:g?`${f} \xb7 ${g}`:f}:{},...g?{otherRun:{kind:"unjudged",conclusion:g}}:{},...v?{reason:v}:{}}})}let c=e.toolName.toLowerCase().split(/[.:/]/).pop()??"",d=a?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{...i,stage:"review",action:t,findings:null,outcome:d?"failed":s};if("resolve"===t){if(!0===u.pass)return{...i,stage:"review",action:t,findings:0,outcome:"passed"};let e=Array.isArray(u.open)?u.open.length:null;return{...i,stage:"review",action:t,findings:e,outcome:!1===u.pass?"failed":"unobserved"}}let r=Array.isArray(u.findings)?u.findings.length:null;if(null!==r&&r>0)return{...i,stage:"review",action:t,findings:r,outcome:"failed"};let n=Array.isArray(u.reviewers)?u.reviewers:[];return!1===u.passable||n.some(e=>!e||"object"!=typeof e||!("status"in e)||"ok"!==e.status)?{...i,stage:"review",action:t,findings:r,outcome:"unverified",unusable:!0}:{...i,stage:"review",action:t,findings:r,outcome:null===r?"unobserved":"done"}}if("git_finalize"===c){let t="string"==typeof e.input.message?iX(e.input.message):void 0,r=t?{title:t}:{};if(!d)return{...i,stage:"commit",commit:null,docsOnly:!1,...r,outcome:s};let n=i3(d,u),a=d.isError||!1===u.ok,o=!a&&(!0===u.ok||null!==n),l=e.input.files,c=o&&Array.isArray(l)&&l.length>0&&l.every(e=>"string"==typeof e&&iK(e));return{...i,stage:"commit",commit:o?n:null,docsOnly:c,...r,outcome:o?"done":a?"failed":"unobserved"}}if("git_integrate"===c){if("abort"===e.input.action||"up-to-date"===u.stage)return null;if(!d)return{...i,stage:"commit",commit:null,docsOnly:!1,outcome:s};let t=i3(d,u),r=d.isError||!1===u.ok,n=!r&&null!==t,a=u.files,o=n&&Array.isArray(a)&&a.length>0&&a.every(e=>"string"==typeof e&&iK(e));return{...i,stage:"commit",commit:n?t:null,docsOnly:o,outcome:n?"done":r?"failed":"unobserved"}}if("eval"===c)return function(e,t,r){let n=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(!i2.test(n))return null;let a=i6.exec(n)?.[2],i=void 0===a?void 0:iX(a.replace(/\\n/g,"\n").replace(/\\(["'`\\])/g,"$1")),s={toolCallId:e.toolCallId,attempt:0,stage:"commit",docsOnly:!1,...i?{title:i}:{}};if(!t)return{...s,commit:null,outcome:r};let o=sp(t),l=i8.exec(o),c=l?(l[1]??l[2]).toLowerCase():null;if(!c&&i5.test(o))return null;let d=i4.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(iJ,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(iZ,e.input.action);if(!tf(e.toolName)&&!tg(e.toolName))return!1;let r=e.input.file_path??e.input.path;return"string"!=typeof r||/^[a-zA-Z]:[\\/]/.test(r)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(r)}(e,c))return!a&&t?.isError?null:(tf(e.toolName)||tg(e.toolName))&&tw(e.input,d,n)?{...i,stage:"investigate",outcome:a?"unobserved":t||!r?"done":"running"}:{...i,stage:"edit",outcome:d?"done":s,..."task"===c?{dispatch:!0}:{},...!function(e,t,r){if(!t||!(tf(e.toolName)||tg(e.toolName)))return!1;let n=ty(e.input,t);return n.length>0&&n.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let r=t?tm(t)??t:void 0,n=t_(tm(e,t)??e,r);if(/^[\\/]/.test(n)||/^[a-zA-Z]:[\\/]/.test(n))return!1;let a=n.split(/[\\/]/).filter(e=>""!==e&&"."!==e);return"HANDOFF.md"===a.at(-1)||"doc"===a[0]&&"history"===a[1]&&a.length>2})(e,r))}(e,d,n)?{}:{recordOnly:!0}};return Object.hasOwn(iG,c)?{...i,stage:"investigate",outcome:a?"unobserved":t||!r?"done":"running"}:null}(e,i,r,a))?n:n?[n]:[])){let r=i?void 0:x.get(e.toolCallId);"check"===s.stage&&"noResult"===s.reason&&r&&i9(r)&&(s.reason="noCompletion"),b.push({step:s,order:t})}}),s=null,o=!1,b.forEach((e,t)=>{let{step:r,order:n}=e;if("commit"===r.stage&&"done"===r.outcome&&r.commit&&(s={step:{...r,commit:r.commit},order:n},o=!1),"edit"!==r.stage||"done"!==r.outcome||r.dispatch||r.recordOnly||(o=!0),"ci"!==r.stage||!s)return;let a=s,i=iu(r.command).commands.flatMap(({words:e})=>sm(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(i){let e,s=sv(i),l=e=>(f.publishRuns.get(e)?.order??1/0)<=n;if((e=sT(r.command,l).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){sI(r.command,l)||"passed"!==r.outcome&&"failed"!==r.outcome||(s&&"passed"===r.outcome&&f.watched.push({id:s,order:n}),b[t]={order:n,step:{...r,outcome:"unverified",evidence:void 0,otherRun:{kind:"publish",outcome:r.outcome}}});return}let c=s?f.runs.filter(e=>e.id===s):[],d=c.find(e=>null!==e.sha)?.sha;if(!d||c.some(e=>sE(e,a,f))){d&&o&&"passed"===r.outcome&&(b[t]={order:n,step:{...r,stale:!0}});return}if("passed"===r.outcome||"failed"===r.outcome){let e=d.slice(0,7);b[t]={order:n,step:{...r,outcome:"unverified",evidence:`run ${s} \xb7 ${e}`,otherRun:{kind:"commit",sha:e,outcome:r.outcome}}}}return}if("unverified"!==r.outcome)return;let l=f.runs.find(e=>e.order===n&&null!==e.workflow&&Object.hasOwn(sd,e.workflow)&&sE(e,a,f));if(!l||"completed"!==l.status||"string"!=typeof l.conclusion)return;let c="success"===l.conclusion?"passed":Object.hasOwn(s$,l.conclusion)?"failed":null;c&&(b[t]={order:n,step:{...r,outcome:c,evidence:`run ${l.id??"?"} \xb7 ${l.status} ${l.conclusion}`,..."passed"===c&&o?{stale:!0}:{}}})}),b.forEach((e,t)=>{let{step:r,order:n}=e;if("deploy"!==r.stage||"unverified"!==r.outcome&&"unobserved"!==r.outcome)return;let a=function(e){let t=[],r=(e,n)=>{let a=ib(e);if(null!==a){if(n<3)for(let e of iu(a).commands)r(e.words,n+1);return}if(!iS(e))return;let i=ik(e),s=ij.test(e[i])?i:e.findIndex((e,t)=>t>i&&!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 iu(e).commands)r(t,0);return 1===t.length?t[0]:null}(r.command),i=x.get(r.toolCallId);if("number"!=typeof i?.timestamp)return;let s=i.details,o=s&&"object"==typeof s&&"wallTimeMs"in s&&"number"==typeof s.wallTimeMs?s.wallTimeMs:0,l=1e3*Math.floor((i.timestamp-o)/1e3);for(let e=n;e<g.length;e+=1){let i=g[e],s=i?.type==="toolCall"?v.get(i.toolCallId):void 0;if(s)for(let e of sp(s).split("\n")){let i=e.trim().replace(/^\d+[:-](?=\d{4}-\d\d-\d\dT)/,"");if(null===a){let e=sA.exec(i);e&&Date.parse(e[1])>=l&&(a=e[2]);continue}let s=sR.exec(i);if(s&&Date.parse(s[1])>=l&&sM(s[2],a)){b[t]={order:n,step:{...r,outcome:"passed",evidence:`${s[1]} READY ${s[2].slice(0,12)}`}};return}let o=sL.exec(i);if(o&&Date.parse(o[1])>=l){b[t]={order:n,step:{...r,outcome:"failed",evidence:i.length>120?`${i.slice(0,119)}…`:i}};return}}}});let y=(e,t)=>null!==e&&(f.publishRuns.get(e)?.order??1/0)<=t;for(let{step:e,order:t}of b){let r=e;if("ci"===r.stage){let e=iu(r.command).commands.flatMap(({words:e})=>sm(e)).find(e=>"run"===e[0]&&"watch"===e[1]),n=e?sv(e):null;n&&"passed"===r.outcome&&f.watched.push({id:n,order:t}),!r.compound&&sI(r.command,e=>y(e,t))&&(r={toolCallId:r.toolCallId,attempt:r.attempt,stage:"investigate",outcome:"passed"===r.outcome||"unverified"===r.outcome?"done":r.outcome})}if("edit"!==r.stage||"done"!==r.outcome||r.dispatch){if("check"===r.stage||"review"===r.stage||"ci"===r.stage){let e="check"===r.stage?`check:${sn(r)}`:r.stage,t=u.get(e);(t?.outcome!=="failed"||st(r.outcome))&&u.set(e,{stage:r.stage,outcome:r.outcome,order:l.length})}}else{let e=sr(u);e&&(c.push({from:e,attempt:d}),d+=1),u=new Map,p=l.length,r.recordOnly||(h=l.length)}r.attempt=d,m.set(r,t),l.push(r)}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?m.get(k)??-1:-1,S=k&&!k.stale&&k.commit&&su.test(k.commit)?{sha:k.commit.toLowerCase(),order:j}:null,C=S?function(e,t,r){let n=e.watched.find(({id:r,order:n})=>{let a=e.publishRuns.get(r);return n>t.order&&a?.sha===t.sha&&a.order>t.order&&a.order<=n});if(!n)return null;let a=new Map;for(let t of e.heads)t.order>n.order&&a.set(`${t.repo}#${t.ref}`,t);let i=[...r,...e.ciHeads.filter(e=>e.order<t.order)];for(let e of a.values())if(null!==e.sha&&e.sha!==t.sha&&i.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:n.id};return null}(f,S,n)??(f.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,r)=>{var n;let a,i=m.get(t)??-1;if("ci"!==t.stage||"unverified"!==t.outcome||i<=j||!f.nothingToPublish.some(t=>t.order===i&&t.sha===e)&&(n=t.command,!((a=iu(n).commands.flatMap(({words:e})=>sm(e))).length>0&&a.every(t=>"run"===t[0]&&"list"===t[1]&&sf(t,["-c","--commit"])?.toLowerCase()===e))))return;let s={toolCallId:t.toolCallId,attempt:t.attempt,stage:"investigate",outcome:"done"};l[r]=s,m.set(s,i)})}let N=io.map(e=>{let t=l.filter(t=>t.stage===e),r="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,r=null;for(let n of t){let t=n.stale?"stale":n.outcome;if("failed"!==r||st(n.outcome)){if(null!==r&&!("ci"!==n.stage||so(t))&&!iu(n.command).commands.some(({words:e})=>sm(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===r&&(sl(n)?.every(t=>e.has(t))??!1);if(so(r)||t)continue}if(r=t,"stale"===t||"passed"===n.outcome||"failed"===n.outcome)for(let t of sl(n)??[])e.add(t)}}return r??"waiting"}let r="done";for(let e of sa(t)){let t=e.stale?"stale":e.outcome;ss[t]>ss[r]&&(r=t)}return r}(e,r),steps:r,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),T=N[io.indexOf("deploy")],I=l.some(e=>"commit"===e.stage&&"done"===e.outcome&&!e.docsOnly);!k?.docsOnly||k.stale||I||"waiting"!==T.status||(T.status="notNeeded");let M=N[io.indexOf("ci")],E=M.steps.some(e=>(m.get(e)??1/0)>j);C&&("waiting"===M.status||("unverified"===M.status||"stale"===M.status)&&!E)?M.status="notNeeded":C=null;let $=-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&&!si(e))&&($=t)});let R=null;if(r&&l.length>0)if(sr(u))R={stage:"edit",returning:!0};else if($<0)R={stage:N.find(e=>"waiting"!==e.status)?.stage??io[0],returning:!1};else{let e=N[$].steps.at(-1);if(e?.stage==="review"&&e.unusable)R={stage:"review",returning:!1};else{let e=N.slice($+1).find(e=>"skipped"!==e.status&&"notNeeded"!==e.status);R=e?{stage:e.stage,returning:!1}:null}}if(N.forEach((e,t)=>{t<$&&"waiting"===e.status&&(e.status="skipped")}),!r&&l.length>0){let e=!I;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,r){let n=e.at(-1);if(!n)return null;if(!r||r.stale)return n.stage;let a=t.filter(e=>("commit"===e.stage||"ci"===e.stage||"deploy"===e.stage)&&e.steps.length>0&&"notNeeded"!==e.status&&"skipped"!==e.status),i=a.find(e=>"commit"!==e.stage&&Object.hasOwn(sF,e.status));return i?.stage??a.at(-1)?.stage??n.stage}(l,N,k),reached:$<0?null:io[$],next:R,publication:C}}let sF={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0};function s_(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 sz(e,t,r){let n=[],a=[],i=null;for(let r of e){if("toolCall"!==r.type)continue;if("task"===r.toolName){a.push(r);continue}if(tE(r.toolName)){let e=tM(r,t.get(r.toolCallId));"authoritative"===e.kind&&(i=e.phases);continue}let e=iB(r,t.get(r.toolCallId));e&&n.push(e)}return{checks:n,dispatchCalls:a,files:tN(e,t,r),remaining:i?s_(i):null}}function sW(e,t,r){let n=[];for(let a=Math.max(0,t);a<Math.min(e.length,r);a++){let t=e[a];"assistant"===t.role&&n.push(...t.content??[])}return n}function sO(e,t,r){let n=[],a=null;for(let i=Math.max(0,t);i<Math.min(e.length,r);i++){let t=e[i];if("assistant"===t.role)for(let e of t.content??[])"toolCall"===e.type&&(a=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");n.push({text:e,after:a})}}return n}function sD(e,t){var r;let n=t;for(;n>=0&&(r=e[n],r?.role==="custom"?"compaction"===r.customType:r?.role==="user"&&("steer"===is(r)||function(e){if(e===a5||e===a6||e===a3||a7.has(e))return!0;let[t,r]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==r&&r.startsWith("requestId=")}(ii(r))));){let t=n-1;for(;t>=0&&"user"!==e[t].role;)t-=1;n=t}return n}function sH(e,t,r,n){let a=Math.min(e.length,n),i=new Map;for(let t=Math.max(0,r);t<a;t++){let r=e[t];"toolResult"===r.role&&i.set(r.toolCallId,t)}let s=[];for(let n=Math.max(0,r-1);n<a;n++){let a=e[n];if(n>=r&&"assistant"===a.role)for(let e of a.content??[]){if("toolCall"!==e.type||!tE(e.toolName))continue;let r=tM(e,t.get(e.toolCallId));"authoritative"===r.kind&&s.push({at:i.get(e.toolCallId)??n,phases:r.phases})}for(let e of a.trackerTodos??[]){let t=tI(e);t&&s.push({at:n+.5,phases:t})}}let o=null;for(let e of s)(!o||e.at>=o.at)&&(o=e);return o?o.phases:null}function sU(e,t,r,n=0,a=[]){for(let i=Math.max(0,n);i<Math.min(e.length,r);i++){let r=e[i];if("assistant"===r.role)for(let e of r.content??[])"toolCall"===e.type&&a.push(...sj(e,t.get(e.toolCallId)))}return a}function sB(e,t,r){let n=null,a=null;for(let i=Math.max(0,t-1);i<Math.min(e.length,r);i++){let t=e[i];for(let e of[t.timestamp,"assistant"===t.role?t.completedAt:void 0])"number"==typeof e&&Number.isFinite(e)&&((null===n||e<n)&&(n=e),(null===a||e>a)&&(a=e))}return{startedAt:n,endedAt:a}}function sq(e,t){if(0===e.length)return null;let r=[...e].sort((e,t)=>e-t),n=(r.length-1)*t,a=Math.floor(n),i=Math.ceil(n);return r[a]+(r[i]-r[a])*(n-a)}let sV=["investigate","implement","verify","report"],sK={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},sG={bash:!0,eval:!0};function sJ(e){let t=[],r=new Map;for(let n of e)if("toolResult"===n.role&&r.set(n.toolCallId,n),"assistant"===n.role&&Array.isArray(n.content))for(let e of n.content)"toolCall"===e.type&&t.push(e);return{blocks:t,results:r}}function sZ(e,t,r,n){return!0===sK[t]&&!tw(e.input,r.get(e.toolCallId),n)}function sY(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function sX(e){return"yield"===sY(e)&&!Array.isArray(e.input?.type)}function sQ(e,t){if(0===e.length)return null;let{blocks:r,results:n}=sJ(e),a=-1;r.forEach((e,t)=>{sX(e)&&(a=t)});let i=a>=0&&a===r.length-1,s=i?r.findLastIndex((e,t)=>t<a&&sX(e))+1:a+1,o={calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:i,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1},l=!1;for(let e of r.slice(s)){let r=sY(e);if(sZ(e,r,n,t))"verify"===o.phase&&(o.reedits+=1),l=!0,o.phase="implement",o.verifiedAfterEdit=!1;else if(sG[r]){if(o.phase=l?"verify":"investigate",l){o.verifiedAfterEdit=!0;let t=iB(e,n.get(e.toolCallId));t?.state==="passed"?o.checks.passed+=1:t?.state==="failed"?o.checks.failed+=1:t&&(o.checks.unknown+=1)}}else"yield"===r&&(o.phase="report",l=!1);o.calls[o.phase]+=1}return o}function s0(e,t){if(!e)return{run:null,stations:sV.map(e=>({phase:e,state:"unobserved",calls:0}))};let r=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,n=t?sV.indexOf(r.phase):sV.findLastIndex(e=>r.calls[e]>0),a=sV.map((e,a)=>{let i,s=r.calls[e];return i=t&&e===r.phase?"active":s>0?"verify"!==e||r.verifiedAfterEdit?"done":"stale":a<n?"skipped":t?"waiting":"none",{phase:e,state:i,calls:s}});return{run:r,stations:a}}function s1(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function s2(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let r=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:r}}function s8(e){return"pending"===e||"running"===e}let s4=new Map;function s5(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function s6(e){return e instanceof aL&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function s3(e,{sessionId:t,client:r,enabled:n}){let[i,s]=(0,a.useState)(s4),o=(0,a.useRef)(new Map),l=(0,a.useRef)(e);l.current=e;let c=(0,a.useCallback)(()=>{let e=o.current;s(t=>{let r=!1,n=new Map;for(let[a,i]of e){let e=t.get(a),s=e&&e.entries===i.collected&&e.state===i.state?e:{state:i.state,entries:i.collected};s!==e&&(r=!0),n.set(a,s)}return n.size!==t.size&&(r=!0),r?n:t})},[]),d=e.map(e=>`${e.key}|${s5(e)}`).join("\n");return(0,a.useEffect)(()=>{if(!n)return;let e=!1,a=!1,i=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=s5(e);s.get(e.key)?.signature!==t&&s.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(n,a,i,s)=>{if(!n.archiveName){a.state={kind:"empty",source:"live",note:s};return}try{let o=await r.getArchiveTranscript(t,n.archiveName,400,i);if(e)return;0===a.collected.length&&(a.collected=o.entries.flatMap((e,t)=>{let r=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:r,message:e.message}]:e.irc?[{id:r,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),a.state=0===o.entries.length?{kind:"empty",source:"archive",note:s}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:s}}catch(r){if(e||i.aborted)return;let t=s6(r);a.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(n,a)=>{let i=s.get(n.key);if(i){if(!n.liveId)return void await u(n,i,a);try{var o,l;let s=await r.getLiveTranscript(t,n.liveId,i.nextByte,a);if(e)return;let c=(o=s.entries,l=s.fromByte,o.flatMap((e,t)=>{let r=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:r,message:s2(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:r,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?i.collected=c:c.length>0&&(i.collected=[...i.collected,...c]),i.nextByte=s.nextByte,i.collected.length>0?("ready-live"!==i.state.kind||i.state.entries!==i.collected)&&(i.state={kind:"ready-live",entries:i.collected}):await u(n,i,a)}catch(t){if(e||a.aborted)return;if(n.archiveName){let e=s6(t);await u(n,i,a,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=s6(t);i.state="unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message}}}}},h=async()=>{if(e||a||"u">typeof document&&"visible"!==document.visibilityState)return;a=!0;let t=new AbortController;i=t;try{for(let e of l.current)await p(e,t.signal)}finally{a=!1}e||c()};h();let m=l.current.some(e=>s8(e.status))?setInterval(()=>void h(),3e3):void 0,f=()=>{"visible"===document.visibilityState&&h()};return document.addEventListener("visibilitychange",f),()=>{e=!0,i?.abort(),clearInterval(m),document.removeEventListener("visibilitychange",f)}},[r,n,c,t,d]),i}let s7=(0,a.createContext)({ledger:aU,subagents:[],toolResults:new Map}),s9="omp-web:flow-motion",oe=new Set,ot=null;function or(){if(null===ot)try{ot="paused"===window.localStorage.getItem(s9)}catch{ot=!1}return ot}function on(e){return oe.add(e),()=>{oe.delete(e)}}function oa(){return(0,a.useSyncExternalStore)(on,or,()=>!1)}function oi({paused:e}){let{st:t}=ag();return(0,n.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){ot=e;try{e?window.localStorage.setItem(s9,"paused"):window.localStorage.removeItem(s9)}catch{}for(let e of oe)e()})(!e),children:t("graph.motion.pause")})}function os(e,t,r){return r&&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 oo(e){return e.stale?"stale":e.outcome}let ol=(0,n.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,n.jsx)("polyline",{points:"6 9 12 15 18 9"})});function oc({look:e}){return(0,n.jsxs)("span",{className:"flow-node","aria-hidden":"true",children:[("done"===e||"stale"===e)&&(0,n.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,n.jsx)("polyline",{points:"5 12 10 17 19 7"})}),"unverified"===e&&(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"6",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"18",x2:"12",y2:"18.5"})]}),"failed"===e&&(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"7",y1:"7",x2:"17",y2:"17"}),(0,n.jsx)("line",{x1:"17",y1:"7",x2:"7",y2:"17"})]}),"skipped"===e&&(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:(0,n.jsx)("line",{x1:"6",y1:"12",x2:"18",y2:"12"})})]})}function od({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,n.jsxs)("svg",{...t,strokeWidth:2,children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"}),(0,n.jsx)("path",{d:"M12 7v5l4 2"})]}):"passed"===e||"done"===e?(0,n.jsx)("svg",{...t,strokeWidth:2.5,children:(0,n.jsx)("polyline",{points:"5 12 10 17 19 7"})}):"failed"===e?(0,n.jsxs)("svg",{...t,strokeWidth:2.5,children:[(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"}),(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"})]}):"running"===e?(0,n.jsxs)("svg",{...t,strokeWidth:2,children:[(0,n.jsx)("path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0"}),(0,n.jsx)("path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0"}),(0,n.jsx)("path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7"}),(0,n.jsx)("path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8"}),(0,n.jsx)("path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69"}),(0,n.jsx)("path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8"}),(0,n.jsx)("path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69"}),(0,n.jsx)("path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7"})]}):(0,n.jsxs)("svg",{...t,strokeWidth:2,children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,n.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,n.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}function ou({step:e,st:t}){let r=t(`flow.state.${e.outcome}`);if(e.stale)r=t("passed"===e.outcome?"flow.state.stale":"flow.state.staleDone");else if("review"===e.stage&&"failed"===e.outcome&&null!==e.findings){let n=1===e.findings?"flow.state.findings.one":"flow.state.findings";r=t("resolve"===e.action?"flow.state.open":n,{count:e.findings})}else"review"===e.stage&&e.unusable?r=t("flow.state.reviewUnusable"):"review"===e.stage&&"done"===e.outcome&&(r=t("flow.state.noFindings"));return(0,n.jsxs)("span",{className:"flow-tone","data-tone":oo(e),children:[r,"commit"===e.stage&&e.commit&&(0,n.jsxs)(n.Fragment,{children:[" ",(0,n.jsxs)("span",{className:"flow-sha-tail",children:["\xb7\xa0",(0,n.jsx)("code",{className:"flow-sha",children:e.commit.slice(0,7)})]})]})]})}let op={syntax:"flow.why.check.syntax",optional:"flow.why.check.optional",noExit:"flow.why.noExit",noResult:"flow.why.noResult",noCompletion:"flow.why.noCompletion",interrupted:"flow.why.interrupted"},oh={masked:"flow.next.rerun",syntax:"flow.next.rerun",optional:"flow.next.optional",compound:"flow.next.compound",noExit:"flow.next.again",noResult:"flow.next.again",noCompletion:"flow.next.again",interrupted:"flow.next.again"};function om({step:e,label:t,st:r}){let a=si(e),i=e.compound?.stages.map(e=>r(`flow.stage.${e}`)).join("\xb7")??"",s=e.otherRun,o=e.reason?op[e.reason]:void 0,l=a?r("flow.why.compoundConfirmed",{stages:i}):s?.kind==="unjudged"?r("flow.why.watched.unjudged",{conclusion:s.conclusion}):s?r(`flow.why.watched.${s.outcome}`):r("flow.why.exitZero"),c=a?r("flow.why.compoundMissing"):o?r(o,{label:t}):"check"===e.stage?r("flow.why.check",{label:t}):s?.kind==="commit"?r("flow.why.ciOtherRun",{sha:s.sha}):s?.kind==="publish"?r("flow.why.ciPublishRun"):s?.kind==="unjudged"?r("flow.why.ciUnjudged",{conclusion:s.conclusion}):r(`flow.why.${e.stage}`),d=e.reason?r(oh[e.reason]):a?r("flow.next.compound"):null,u="unverified"===e.outcome||"unobserved"===e.outcome&&void 0!==e.reason,p=null!==e.exitCode?r("flow.exit",{code:e.exitCode}):r("failed"===e.outcome?"flow.exit.error":"running"===e.outcome?"flow.state.running":"flow.exit.none");return(0,n.jsxs)("div",{className:"flow-raw",children:[u&&(0,n.jsxs)("p",{className:"flow-why",children:["unverified"===e.outcome&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("b",{children:r("flow.why.confirmed")})," ",l,(0,n.jsx)("br",{})]}),(0,n.jsx)("b",{children:r("flow.why.missing")})," ",c,d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("br",{}),(0,n.jsx)("b",{children:r("flow.why.next")})," ",d]})]}),e.stale&&(0,n.jsx)("p",{className:"flow-why",children:r("flow.why.stale")}),void 0===e.commandKey?(0,n.jsx)("code",{className:"flow-raw-command",children:e.command}):(0,n.jsx)("p",{className:"flow-why",children:r("flow.commandOmitted")}),(0,n.jsx)("div",{className:"flow-exit",children:p}),e.evidence&&(0,n.jsxs)("div",{className:"flow-exit",children:[r("flow.evidence")," ",(0,n.jsx)("code",{className:"flow-evidence",children:e.evidence})]})]})}function of({steps:e,st:t,attempts:r=!1}){return(0,n.jsx)("ul",{className:"flow-checks",children:e.map(e=>{let a="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}`),i=oo(e),s=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(od,{outcome:i}),(0,n.jsx)(ou,{step:e,st:t}),(0,n.jsxs)("span",{className:"flow-check-label",children:[r?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${a}`:a,si(e)&&(0,n.jsx)("span",{className:"flow-compound",children:t("flow.compound.failed")})]})]});return"check"!==e.stage&&"ci"!==e.stage&&"deploy"!==e.stage?(0,n.jsx)("li",{className:"flow-check","data-result":i,children:(0,n.jsx)("div",{className:"flow-check-head",children:s})},e.toolCallId):(0,n.jsx)("li",{className:"flow-check","data-result":i,children:(0,n.jsxs)("details",{children:[(0,n.jsxs)("summary",{className:"flow-check-head",children:[s,(0,n.jsxs)("span",{className:"flow-disclose",children:[t("flow.details"),ol]})]}),(0,n.jsx)(om,{step:e,label:a,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function og({steps:e,st:t}){return 0===e.length?null:(0,n.jsxs)("details",{className:"flow-earlier",children:[(0,n.jsxs)("summary",{className:"flow-earlier-toggle",children:[t("flow.earlier",{count:e.length}),ol]}),(0,n.jsx)(of,{steps:e,st:t,attempts:!0})]})}function ox({view:e,steps:t,st:r}){if(0===t.length)return null;if("check"!==e.stage)return(0,n.jsx)(of,{steps:t,st:r});let a=sa(t),i=e=>{let t=ov.indexOf(oo(e));return t<0?ov.length:t},s=[...a].sort((e,t)=>i(e)-i(t)),o=t.filter(e=>!a.includes(e));return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(of,{steps:s,st:r}),o.length>0&&(0,n.jsxs)("details",{className:"flow-earlier",children:[(0,n.jsxs)("summary",{className:"flow-earlier-toggle",children:[r("flow.repeats",{count:o.length}),ol]}),(0,n.jsx)(of,{steps:o,st:r})]})]})}let ov=["failed","unverified","unobserved","stale","running","passed"];function ob({view:e,flow:t,live:r,st:a,compact:i=!1}){if(r&&t.current===e.stage)return a("flow.state.running");if("waiting"===e.status)return a("flow.state.waiting");if("skipped"===e.status||"notNeeded"===e.status)return a(`flow.state.${e.status}`);let s=e.steps[e.steps.length-1];if("investigate"===e.stage)return a("running"===e.status?"flow.state.running":"flow.state.done");if("edit"===e.stage&&"done"===e.status)return a(t.attempt>1?"flow.state.redone":"flow.state.done");if("check"===e.stage&&!i){let t=new Map;for(let r of sa(e.steps))t.set(oo(r),(t.get(oo(r))??0)+1);return ov.filter(e=>t.has(e)).map((e,r)=>(0,n.jsxs)("span",{children:[r>0&&" \xb7 ",(0,n.jsx)("span",{className:"flow-tone","data-tone":e,children:a(`flow.count.${e}`,{count:t.get(e)??0})})]},e))}return"check"===e.stage||"edit"===e.stage?(0,n.jsx)("span",{className:"flow-tone","data-tone":e.status,children:a(`flow.state.${e.status}`)}):(0,n.jsx)(ou,{step:s,st:a})}function oy({flow:e,live:t,st:r,id:a}){let i=e.loops[e.loops.length-1],s=i?e.steps.filter(e=>e.stage===i.from):[],o=r("flow.loop.badge",{attempt:e.attempt});return(0,n.jsxs)("div",{className:"flow-chain-panel",id:a,children:[(0,n.jsxs)("div",{className:"flow-chain-wrap","data-loop":i?"":void 0,style:i?{"--loop-from":io.indexOf(i.from)}:void 0,children:[(0,n.jsx)("ol",{className:"flow-chain","aria-label":r("flow.aria"),children:e.stages.map(a=>{let i=os(a,e,t);return(0,n.jsxs)("li",{className:"flow-link","data-state":i,"aria-current":"active"===i?"step":void 0,children:[(0,n.jsx)(oc,{look:i}),(0,n.jsx)("span",{className:"flow-link-name",children:r(`flow.stage.${a.stage}`)}),(0,n.jsx)("span",{className:"flow-link-state",children:(0,n.jsx)(ob,{view:a,flow:e,live:t,st:r,compact:!0})})]},a.stage)})}),i&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flow-loop","aria-hidden":"true",children:[(0,n.jsx)("svg",{width:"22",height:"15",viewBox:"0 0 22 15",children:(0,n.jsx)("polyline",{points:"3 12 11 3 19 12",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,n.jsx)("span",{className:"flow-loop-count",children:o})]}),(0,n.jsxs)("p",{className:"flow-loop-caption",children:[(0,n.jsx)("span",{className:"flow-loop-caption-count",children:o}),r("review"===i.from?"flow.loop.findings":"flow.loop.failed",{stage:r(`flow.stage.${i.from}`),attempt:i.attempt})]})]})]}),s.length>0&&(0,n.jsx)("div",{className:"flow-chain-attempts",children:(0,n.jsx)(of,{steps:s,st:r,attempts:!0})})]})}function ow({sessionId:e,snapshots:t,client:r,enabled:n,transcripts:i=!0,cwd:s}){let o=(0,a.useMemo)(()=>t.filter(e=>s8(e.status)),[t]),l=n&&!!e&&o.length>0,c=s3((0,a.useMemo)(()=>o.map(e=>({key:e.id,liveId:e.id,status:e.status})),[o]),{sessionId:e??"",client:r,enabled:l&&i}),[d,u]=(0,a.useState)(null),p=o.map(e=>e.id).sort().join("\n");return(0,a.useEffect)(()=>{let t;if(!l||!e)return;let r=new AbortController,n=p.split("\n"),a=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,i=!0,s=0;async function o(){try{let t=await fetch(a,{signal:AbortSignal.any([r.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!r.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),i=n.some(e=>!s.histories[e]))}catch{}finally{if(!r.signal.aborted){let e=i&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{r.abort(),window.clearTimeout(t)}},[p,l,e]),(0,a.useMemo)(()=>{let t=new Map;if(!l)return t;let r=d&&d.sessionId===e?d.histories:void 0;for(let e of o){let n=(i?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:r,results:n}=sJ(e),a="investigate",i=!1;for(let e of r){let r=sY(e);sZ(e,r,n,t)?(i=!0,a="implement"):sG[r]?a=i?"verify":"investigate":"yield"===r&&(a="report",i=!1)}return a}(n,s),trace:sQ(n,s),todo:function(e){let t=new Map;for(let r of e)"toolResult"===r.role&&t.set(r.toolCallId,r);let r=t$([...e],t);if(!r)return null;let n=tL(r);return 0===n.total||null===n.percent?null:{completed:n.completed,total:n.total,percent:n.percent,activeTask:n.activeTask?.content??null}}(n),history:r?.[e.id]??null})}return t},[o,s,d,l,c,e,i])}function ok(e,t){let r=s1(t);return r?0===r.hours?e("duration.minutes",{minutes:r.minutes}):0===r.minutes?e("duration.hours",{hours:r.hours}):e("duration.hoursMinutes",{hours:r.hours,minutes:r.minutes}):e("duration.underMinute")}function oj(e,t){let r=Math.floor(t/1e3);return r<60?e("duration.seconds",{seconds:r}):r<3600?e("duration.minutesSeconds",{minutes:Math.floor(r/60),seconds:r%60}):ok(e,t)}function oS({phase:e}){let{st:t}=ag();return(0,n.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,n.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,n.jsx)("span",{"aria-hidden":"true",children:sV.map((r,a)=>(0,n.jsxs)("span",{children:[a>0&&(0,n.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,n.jsx)("span",{"data-current":r===e?"":void 0,style:r===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${r}`)})]},r))})]})}let oC={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function oN(e,t){let r=t.passed+t.failed+t.unknown,a=t.failed>0?"failed":t.unknown>0?"unverified":"passed";return(0,n.jsx)("span",{className:"flow-tone","data-tone":a,children:e("subflow.checks",{passed:t.passed,total:r})})}function oT({flow:e,live:t,verdict:r,attempts:a}){let{st:i}=ag(),s=oa(),o=e.stations.findIndex(e=>"active"===e.state),l=sV.indexOf("implement"),c=a.filter(e=>"rework"===e.verdict).length,d=r?"accepted"===r.verdict?"done":"unverified":"waiting",u=r?`${i(`verdict.${r.verdict}`)}${null!==r.attempt&&r.attempt>1?` \xb7 ${i("verdict.attempt",{attempt:r.attempt})}`:""}`:i(t?"flow.state.waiting":"verdict.none");return(0,n.jsxs)("div",{className:"subagent-flow",children:[t&&o>=0&&(0,n.jsx)(oi,{paused:s}),(0,n.jsxs)("ol",{className:"flow-graph","aria-label":i("subflow.aria"),"data-live":t?"":void 0,"data-motion":s?"paused":void 0,children:[e.stations.map((t,r)=>{let a=oC[t.state];return(0,n.jsx)("li",{className:"flow-graph-station","data-stage":t.phase,"data-state":a,"data-loop":c>0&&r>=l?"":void 0,"aria-current":"active"===t.state?"step":void 0,style:{"--col":r+1},children:(0,n.jsxs)("div",{className:"flow-graph-stop",children:[(0,n.jsx)("span",{className:"flow-graph-stop-name",children:i(`phase.${t.phase}`)}),(0,n.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,n.jsx)(oc,{look:a}),(0,n.jsx)("span",{className:"flow-graph-stop-word",children:function(e,t,r){let a="verify"===t.phase&&null!==r&&r.checks.passed+r.checks.failed+r.checks.unknown>0;switch(t.state){case"active":return a&&r?(0,n.jsxs)(n.Fragment,{children:[e("flow.state.running")," \xb7 ",oN(e,r.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(r&&r.checks.passed>0?"flow.state.stale":"flow.state.staleDone");case"done":if("report"===t.phase)return e("subflow.reported");if(a&&r)return oN(e,r.checks);if("implement"===t.phase&&r&&r.reedits>0)return`${e("subflow.calls",{count:t.calls})} \xb7 ${e("subflow.reedits",{count:r.reedits})}`;return e("subflow.calls",{count:t.calls})}}(i,t,e.run)})]})]})},t.phase)}),(0,n.jsx)("li",{className:"flow-graph-station","data-stage":"verdict","data-state":d,style:{"--col":sV.length+1},children:(0,n.jsxs)("div",{className:"flow-graph-stop",children:[(0,n.jsx)("span",{className:"flow-graph-stop-name",children:i("graph.join")}),(0,n.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,n.jsx)(oc,{look:d}),(0,n.jsx)("span",{className:"flow-graph-stop-word",children:u})]})]})}),c>0&&(0,n.jsxs)("li",{className:"flow-graph-return",style:{"--from":l+1,"--to":sV.length+1},children:[(0,n.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,n.jsx)("span",{className:"flow-graph-return-text",children:i("subflow.rework",{count:c})})]})]})]})}function oI(e,t){let r=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${r} \xb7 ${t.activeTask}`:r}function oM({snapshot:e,view:t,id:r}){var a,i,s;let o,l,c,{st:d}=ag(),u=ry(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 r=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(r.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:r.length};let n=sq(r,.5)??0;return{kind:"remaining",p25Ms:sq(r,.25)??0,medianMs:n,p75Ms:sq(r,.75)??0,samples:r.length,percent:Math.round(t/(t+n)*100)}}(t.history,p),m=(a=t.todo,!a||null===p||0===a.completed||a.completed>=a.total?null:p*(a.total-a.completed)/a.completed),f={color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},g=t.history,x=g?.rework&&null!==g.firstDispatchedAtMs?u-g.firstDispatchedAtMs:null;return(0,n.jsxs)("span",{id:r,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,n.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:d("eta.elapsed",{duration:oj(d,p)})}),g?.rework&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:f,title:d("eta.reworkHint"),children:null!==x&&x>=0?d("eta.rework",{attempt:g.attempt,duration:oj(d,x)}):d("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{title:d("eta.hint"),children:d("eta.remaining",{range:(i=h.p25Ms,s=h.p75Ms,l=s1(i),c=s1(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:ok(d,i),high:ok(d,s)})),samples:h.samples})})," \xb7 ",(0,n.jsx)("span",{style:f,children:d("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:{color:"var(--warning)"},title:d("eta.hint"),children:0===h.longerRuns?d("eta.overrun",{longest:ok(d,h.longestMs)}):d("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==m&&t.todo&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:f,title:d("eta.byTodoHint"),children:m<6e4?d("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):d("eta.byTodo",{duration:ok(d,m),completed:t.todo.completed,total:t.todo.total})})]})]})}let oE={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},o$={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function oR({maker:e,st:t}){let r=e.verdict?.verdict??"none",a=e.verdict?.attempt;return(0,n.jsxs)("span",{className:"answer-status-pair",children:[(0,n.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(oE[e.run])}),(0,n.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,n.jsxs)("span",{className:"answer-status-verdict","data-verdict":r,children:[t(o$[r]),null!=a&&a>1?` \xb7 ${t("verdict.attempt",{attempt:a})}`:null]})]})}function oL(e,t){let r=[],n=new Map;for(let t of e)"message"in t&&("assistant"===t.message.role?r.push(...t.message.content??[]):"toolResult"===t.message.role&&n.set(t.message.toolCallId,t.message));return sz(r,n,t)}function oA(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function oP(e,t){let r=e?.state;return r?.kind!=="ready-live"?null:sQ(r.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function oF({maker:e,st:t}){let r=e.runTitle??e.title;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"answer-dispatch-name",title:r,children:r}),e.priorVerdict&&!e.runTitle&&(0,n.jsx)("span",{className:"answer-dispatch-title-note",children:t("subflow.firstTitle")})]})}function o_({calls:e}){let{ledger:t,subagents:r,toolResults:i,onOpenPanel:s,sessionId:o,cwd:l,onOpenMaker:c,selectedMaker:d}=(0,a.useContext)(s7),{st:u}=ag(),{t:p}=(0,z.s)(),[h,m]=(0,a.useState)(!1),f=(0,a.useId)(),g=(0,a.useMemo)(()=>aW(),[]),x=(0,a.useMemo)(()=>e.flatMap(e=>aJ(e,i.get(e.toolCallId))??[]).map(e=>aQ(e,r,t)),[e,i,r,t]),v=(0,a.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let n=aX(e.member,r,t);return n?[n]:[]}),[x,r,t]),b=ow({sessionId:o,snapshots:v,client:g,enabled:!0,transcripts:h,cwd:l}),y=(0,a.useMemo)(()=>new Map(x.flatMap(e=>{let t=a0(e.member,r);return t?[[e.member.key,t]]:[]})),[x,r]),w=(0,a.useMemo)(()=>h?[...y].filter(([,e])=>!s8(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:oA(t)})):[],[y,h]),k=s3(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,a.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,T=0,I=0;for(let e of x)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(N+=1),"completed"===e.run&&(T+=1),e.verdict?.verdict==="accepted"&&(I+=1);return(0,n.jsxs)("section",{className:"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,n.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":h,"aria-controls":f,title:u(h?"dispatch.collapse":"dispatch.expand"),onClick:()=>m(e=>!e),children:[(0,n.jsx)("span",{className:"answer-dispatch-heading",children:u("dispatch.title",{count:x.length})}),(0,n.jsx)("span",{className:"answer-dispatch-tally",children:u("dispatch.tally",{running:N,done:T,accepted:I})}),(0,n.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,n.jsx)("ul",{className:"answer-dispatch-list",id:f,"aria-label":h?p("dispatchLane.label"):void 0,children:x.map(e=>{var r;let a,i="pending"===e.run||"running"===e.run,s=i?v.find(t=>t.id===e.member.agentId):void 0,o=s?b.get(s.id):void 0,p=y.get(e.member.key),m=e.member.key===d?.origin,f=i&&"live"===e.runSource,g=h?s0(f?o?.trace??null:oP(k.get(e.member.key),l),f):null,x=h?a1(e.member,t):[];return(0,n.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":m?"":void 0,children:[h?(0,n.jsx)(oz,{maker:e,phase:f&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,r){if(!t)return{kind:"unobserved"};if(s8(t.status))return{kind:"running"};let n=e?.state;if(!n||"loading"===n.kind)return{kind:"loading"};if("ready-live"===n.kind){let{checks:e}=oL(n.entries,r);return{kind:"counted",passed:e.filter(e=>"passed"===e.state).length,total:e.length}}return"empty"===n.kind&&"live"===n.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,n.jsxs)("div",{className:"answer-dispatch-line",children:[(0,n.jsx)(oF,{maker:e,st:u}),(0,n.jsx)(oR,{maker:e,st:u})]}),g&&(0,n.jsx)(oT,{flow:g,live:f,verdict:e.verdict,attempts:x}),h&&(0,n.jsx)(oO,{attempts:x}),s&&o&&(0,n.jsxs)("div",{className:"answer-dispatch-progress",children:[o.todo?`${oI(u,o.todo)} \xb7 `:null,(0,n.jsx)(oM,{snapshot:s,view:o})]}),h&&(0,n.jsxs)("dl",{className:"answer-dispatch-detail",children:[i&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.stage")}),(0,n.jsx)("dd",{children:e.stage??u("detail.stageNone")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.model")}),(0,n.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${u("detail.fallback")}`:""}`:u("detail.modelNone")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.agentId")}),(0,n.jsxs)("dd",{children:[(0,n.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,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("subflow.prior")}),(0,n.jsx)("dd",{children:(a=null!==(r=e.priorVerdict).attempt&&r.attempt>1?` \xb7 ${u("verdict.attempt",{attempt:r.attempt})}`:"",`${u(o$[r.verdict])}${a}${r.reason?` \xb7 ${r.reason}`:""}`)})]}),e.priorVerdict&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u(e.runTitle?"subflow.firstTitle":"subflow.runTitle")}),(0,n.jsx)("dd",{children:e.runTitle?e.title:u("detail.stageNone")})]}),e.verdict?.reason&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.reason")}),(0,n.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),h&&s&&(0,n.jsxs)("div",{className:"answer-dispatch-links",children:[(0,n.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:u("detail.openSubagents")}),(0,n.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:u("detail.openProcess")})]})]})}function oz({maker:e,phase:t,checks:r,onOpen:a}){let{st:i}=ag(),{t:s}=(0,z.s)(),o=e.verdict?.verdict??"none",l=i(oE[e.run]),c="running"===r.kind?null:"counted"===r.kind?s("dispatchLane.checks",{passed:r.passed,total:r.total}):s("loading"===r.kind?"dispatchLane.checksLoading":"dispatchLane.checksUnobserved");return(0,n.jsxs)("div",{className:"answer-dispatch-line is-lane",children:[(0,n.jsx)(oF,{maker:e,st:i}),(0,n.jsxs)("span",{className:"answer-status-pair",children:[(0,n.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?s("dispatchLane.runPhase",{run:l,phase:t}):l}),c&&(0,n.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===r.kind&&r.passed<r.total?"failed":r.kind,children:c}),(0,n.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,n.jsx)("span",{className:"answer-status-verdict","data-verdict":o,children:i(o$[o])})]}),a?(0,n.jsx)("button",{type:"button",className:"answer-link answer-dispatch-open","aria-label":s("dispatchLane.openLabel",{title:e.title}),onClick:a,children:s("dispatchLane.open")}):(0,n.jsx)("span",{className:"answer-dispatch-unavailable",title:s("makerDetail.unavailable"),children:s("dispatchLane.unavailable")})]})}function oW({maker:e}){let{ledger:t,subagents:r,sessionId:i,cwd:s}=(0,a.useContext)(s7),o=(0,a.useMemo)(()=>aW(),[]),l="pending"===e.run||"running"===e.run,c=l&&"live"===e.runSource,d=l?aX(e.member,r,t):void 0,u=ow({sessionId:i,snapshots:(0,a.useMemo)(()=>d?[d]:[],[d]),client:o,enabled:!0,transcripts:!0,cwd:s}),p=a0(e.member,r),h=(0,a.useMemo)(()=>p&&!s8(p.status)?[{key:e.member.key,liveId:p.id,status:p.status,archiveName:oA(p)}]:[],[p,e.member.key]),m=s3(h,{sessionId:i??"",client:o,enabled:!!i&&h.length>0}),f=d?u.get(d.id):void 0,g=s0(c?f?.trace??null:oP(m.get(e.member.key),s),c),x=a1(e.member,t);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oT,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,n.jsx)(oO,{attempts:x})]})}function oO({attempts:e}){let{t}=(0,z.s)();return e.length<2?null:(0,n.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":t("dispatchLane.label"),children:e.map((e,r)=>(0,n.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[r>0&&(0,n.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"}-${r}`))})}let oD={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},oH={html:0,document:1,image:2},oU=/\.(?:md|mdx|markdown|txt)$/i;function oB(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function oq(e,t,r){return"investigate"!==e.stage&&("edit"===e.stage?r>0||e.earlier.length>0:e.steps.length>0||e.earlier.length>0||"ci"===e.stage&&null!==t.publication)}function oV({entry:e,st:t}){let r="running"===e.maker.run||"pending"===e.maker.run||"dispatching"===e.maker.run;return e.bar&&null!==e.durationMs?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"flow-graph-track","aria-hidden":"true",children:(0,n.jsx)("span",{className:"flow-graph-bar",style:{left:oB(e.bar.offset),width:oB(e.bar.width)}})}),(0,n.jsx)("span",{className:"flow-graph-time",children:oj(t,e.durationMs)})]}):(0,n.jsx)("span",{className:"flow-graph-time-missing",children:t(r?"summary.time.running":"summary.time.unobserved")})}function oK({entry:e,together:t,batch:r=!1,st:a}){let i=e.maker.member.workClass;return(0,n.jsxs)("span",{className:"flow-graph-maker-tags",children:[(0,n.jsx)("span",{className:"flow-graph-chip","data-unknown":i?void 0:"",children:a(`graph.kind.${i??"unknown"}`)}),r&&e.batchSize>1&&(0,n.jsx)("span",{className:"flow-graph-chip",children:a("graph.parallel.batch")}),t&&(0,n.jsx)("span",{className:"flow-graph-chip","data-unknown":"unknown"===e.concurrency?"":void 0,"data-concurrency":e.concurrency,children:a(`graph.concurrency.${e.concurrency}`)})]})}function oG({selectable:e,selected:t,detailId:r,onSelect:a,className:i,children:s,style:o}){return e?(0,n.jsx)("button",{type:"button",className:i,style:o,"aria-pressed":t,"aria-controls":r,onClick:a,children:s}):(0,n.jsx)("div",{className:i,style:o,children:s})}function oJ({summary:e,makers:t,timings:r,live:i=!1,onOpenFile:s}){let o,l,c,{subagents:d,onOpenMaker:u}=(0,a.useContext)(s7),{st:p}=ag(),h=(0,a.useId)(),{flow:m}=e,f=(0,a.useMemo)(()=>(function(e,t,r,n){let a=function(e,t){let r=t.map(e=>null!==e.startedAt&&null!==e.durationMs?{start:e.startedAt,end:e.startedAt+e.durationMs}:null),n=e.startedAt,a=e.endedAt;for(let e of r)e&&((null===n||e.start<n)&&(n=e.start),(null===a||e.end>a)&&(a=e.end));let i=null!==n&&null!==a?a-n:0;return r.map(e=>e?i<=0||null===n?{offset:0,width:1}:{offset:(e.start-n)/i,width:(e.end-e.start)/i}:null)}(r,t),i=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((r,n)=>{let o="unknown";for(let t=0;t<e.length;t+=1)if(t!==n&&(i[n]&&i[t]||r.observedParallelWith?.has(e[t].member.key))){o="overlapped";break}return{maker:r,bar:a[n],durationMs:t[n]?.durationMs??null,concurrency:o,batchSize:s.get(r.member.toolCallId)??1,liveRunning:i[n]}});return{makers:o,parallel:o.some(e=>"overlapped"===e.concurrency)?"observed":o.some(e=>e.batchSize>1)?"batch":"none",files:n.filter(e=>!oU.test(e.filePath)),docs:n.filter(e=>oU.test(e.filePath))}})(t,r,e.span,e.files),[t,r,e.span,e.files]),[g,x]=(0,a.useState)(void 0),v=oa(),b=e.files.length,y=i&&m.current?m.stages.find(e=>e.stage===m.current):void 0,w=void 0===g?y&&oq(y,m,b)?`stage:${y.stage}`:(o=m.stages.filter(e=>oq(e,m,b)),l=m.loops[m.loops.length-1],(c=(m.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}`:b>0?"files":null):g,k=m.loops[m.loops.length-1],j=k?io.indexOf(k.from):-1,S=io.indexOf("edit"),C=y?io.indexOf(y.stage):-1,N=f.makers.some(e=>e.liveRunning),T=f.files.length>0||f.docs.length>0,I=(0,a.useMemo)(()=>i?[]:function(e,t,r,n){let a=io.indexOf("edit"),i=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,s=[],o=r,l=e=>{let t=io.indexOf(e.stage);o&&t>a&&(s.push("branch"),o=!1),s.push(e.stage),o&&t===a&&(s.push("branch"),o=!1)},c=t[t.length-1];if(c){let t=io.indexOf(c.from);for(let r of e)io.indexOf(r.stage)<=t&&(i(r)||r.earlier.length>0||r.stage===c.from)&&l(r);for(let t of(o&&(s.push("branch"),o=!1),s.push("return"),e))io.indexOf(t.stage)>=a&&i(t)&&l(t)}else for(let t of e)i(t)&&l(t);return o&&s.push("branch"),n&&s.push("outputs"),s}(m.stages,m.loops,f.makers.length>0,T),[i,m.stages,m.loops,f.makers.length,T]),[M,E]=(0,a.useState)(null),$=null!==M&&M<I.length?M:null;(0,a.useEffect)(()=>{if(null===$)return;let e=window.setTimeout(()=>E($+1<I.length?$+1:null),800);return()=>window.clearTimeout(e)},[$,I.length]);let R=e=>{if(null!==$&&I.includes(e))return I[$]===e?"now":I.slice(0,$).includes(e)?"past":"ahead"},L=new Map;for(let e of f.makers){let t=e.maker.verdict?.verdict??"none";L.set(t,(L.get(t)??0)+1)}let A=1===L.size&&L.has("accepted"),P=m.stages[S+1],F=P?os(P,m,i):"skipped",_=f.makers.length>0&&(0,n.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":R("branch"),children:[(0,n.jsxs)("p",{className:"flow-graph-branch-head",children:[(0,n.jsx)("span",{children:p(1===f.makers.length?"graph.branch.one":"graph.branch",{count:f.makers.length})}),"none"!==f.parallel&&(0,n.jsx)("span",{className:"flow-graph-chip","data-parallel":f.parallel,children:p(`graph.parallel.${f.parallel}`)})]}),(0,n.jsx)("ul",{className:"flow-graph-lanes",children:f.makers.map(e=>{let t=`maker:${e.maker.member.key}`;return(0,n.jsx)("li",{className:"flow-graph-lane","data-run":e.maker.run,"data-live":e.liveRunning?"":void 0,children:(0,n.jsxs)(oG,{selectable:!0,selected:w===t,detailId:h,onSelect:()=>x(w===t?null:t),className:"flow-graph-maker",children:[(0,n.jsx)("span",{className:"flow-graph-maker-name",title:e.maker.title,children:e.maker.title}),(0,n.jsx)(oK,{entry:e,together:f.makers.length>1,st:p}),(0,n.jsx)("span",{className:"flow-graph-maker-time",children:(0,n.jsx)(oV,{entry:e,st:p})}),(0,n.jsx)(oR,{maker:e.maker,st:p})]})},e.maker.member.key)})}),(0,n.jsxs)("p",{className:"flow-graph-join","data-state":A?"done":"unverified",children:[(0,n.jsx)(oc,{look:A?"done":"unverified"}),(0,n.jsx)("span",{className:"flow-graph-join-label",children:p("graph.join")}),(0,n.jsx)("span",{className:"flow-graph-join-counts",children:["accepted","rework","held","none"].filter(e=>L.has(e)).map(e=>(0,n.jsxs)("span",{className:"answer-status-verdict","data-verdict":e,children:[p(o$[e])," ",L.get(e)]},e))})]})]},"branch"),z=k&&(0,n.jsxs)("li",{className:"flow-graph-return","data-beat":R("return"),style:{"--from":S+1,"--to":j+1},children:[(0,n.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,n.jsxs)("span",{className:"flow-graph-return-text",children:[(0,n.jsx)("b",{children:p("flow.loop.badge",{attempt:m.attempt})})," ",p("review"===k.from?"flow.loop.findings":"flow.loop.failed",{stage:p(`flow.stage.${k.from}`),attempt:k.attempt})]})]},"return"),W=m.stages.map((e,t)=>{let r=os(e,m,i),a=`stage:${e.stage}`,s=e.steps.some(si);return(0,n.jsx)("li",{className:"flow-graph-station","data-stage":e.stage,"data-state":r,"data-again":e.earlier.length>0?"":void 0,"data-loop":k&&t>=S&&t<j?"":void 0,"data-beat":R(e.stage),"aria-current":"active"===r?"step":void 0,style:{"--col":t+1},children:(0,n.jsxs)(oG,{selectable:oq(e,m,b),selected:w===a,detailId:h,onSelect:()=>x(a),className:"flow-graph-stop",children:[(0,n.jsx)("span",{className:"flow-graph-stop-name",children:p(`flow.stage.${e.stage}`)}),(0,n.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,n.jsx)(oc,{look:r}),(0,n.jsx)("span",{className:"flow-graph-stop-word",children:(0,n.jsx)(ob,{view:e,flow:m,live:i,st:p})})]}),s&&(0,n.jsx)("span",{className:"flow-compound",children:p("flow.compound.failed")})]})},e.stage)}),O=[];W.forEach((e,t)=>{O.push(e),t===S&&_&&O.push(_),t===j&&z&&O.push(z)});let D=null;if(w?.startsWith("stage:")){let t=m.stages.find(e=>`stage:${e.stage}`===w);if(t){let r="ci"===t.stage&&null!==m.publication&&"notNeeded"===t.status,a="edit"===t.stage||r?[]:t.steps;D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"flow-graph-detail-title",children:p(`flow.stage.${t.stage}`)}),"ci"===t.stage&&m.publication&&(0,n.jsx)("p",{className:"flow-graph-note",children:"nothingToPublish"===m.publication.kind?p("flow.ci.nothingToPublish",{sha:m.publication.commit.slice(0,7)}):p("flow.ci.notNeeded",{run:m.publication.runId,repo:m.publication.repo,ref:m.publication.ref,sha:m.publication.sha.slice(0,7)})}),"edit"===t.stage&&(0,n.jsx)(aI,{files:e.files,onOpenFile:s}),(0,n.jsx)(ox,{view:t,steps:a,st:p}),(0,n.jsx)(og,{steps:t.earlier,st:p})]})}}else if(w?.startsWith("maker:")){let e=f.makers.find(e=>`maker:${e.maker.member.key}`===w);if(e){let t=a0(e.maker.member,d);D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,n.jsx)(oK,{entry:e,together:f.makers.length>1,batch:!0,st:p}),(0,n.jsx)("p",{className:"flow-graph-detail-line",children:(0,n.jsx)(oR,{maker:e.maker,st:p})}),(0,n.jsx)("div",{className:"flow-graph-maker-time",children:(0,n.jsx)(oV,{entry:e,st:p})}),(0,n.jsx)(oW,{maker:e.maker}),t&&u?(0,n.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,n.jsx)("p",{className:"flow-graph-note",children:p("graph.maker.unavailable")})]})}}else("files"===w||"docs"===w)&&(D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"flow-graph-detail-title",children:"files"===w?p(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length}):p(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})}),(0,n.jsx)(aI,{files:"files"===w?f.files:f.docs,onOpenFile:s})]}));return(0,n.jsxs)("section",{className:"flow-section",children:[(0,n.jsxs)("div",{className:"flow-graph-head",children:[(0,n.jsx)("h4",{className:"flow-heading",children:p("flow.heading")}),(C>=0||N)&&(0,n.jsx)(oi,{paused:v}),I.length>1&&(0,n.jsx)("button",{type:"button",className:"flow-graph-replay",onClick:()=>E(null===$?0:null),children:p(null===$?"graph.replay":"graph.replay.stop")})]}),(0,n.jsx)("div",{className:"flow-graph-frame",children:(0,n.jsxs)("ol",{className:"flow-graph","aria-label":p("flow.aria"),"data-live":i?"":void 0,"data-motion":v?"paused":void 0,"data-replay":null===$?void 0:"",children:[O,T&&(0,n.jsxs)("li",{className:"flow-graph-outputs","data-beat":R("outputs"),children:[(0,n.jsx)("span",{className:"flow-graph-outputs-label",children:p("graph.outputs")}),f.files.length>0&&(0,n.jsx)(oG,{selectable:!0,selected:"files"===w,detailId:h,onSelect:()=>x("files"),className:"flow-graph-output",children:p(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length})}),f.docs.length>0&&(0,n.jsx)(oG,{selectable:!0,selected:"docs"===w,detailId:h,onSelect:()=>x("docs"),className:"flow-graph-output",children:p(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})})]})]})}),D&&(0,n.jsx)("div",{className:"flow-graph-detail",id:h,role:"region","aria-label":p("graph.detail.aria"),children:D})]})}function oZ(e,t,r){let n=new URLSearchParams({type:t});return r&&n.set("sessionId",r),`/api/files/${tP(e)}?${n}`}function oY(e,t){let[r,n]=(0,a.useState)({kind:"loading"});return(0,a.useEffect)(()=>{let r=new AbortController;return n({kind:"loading"}),fetch(e,{method:"head"===t?"HEAD":"GET",cache:"no-store",signal:r.signal}).then(async e=>{if(!e.ok)return null;if("head"===t)return"";if("text"===t)return e.text();let r=await e.json();return"string"==typeof r.content?r.content:null}).then(e=>{r.signal.aborted||n(null===e?{kind:"failed"}:{kind:"ready",content:e})}).catch(()=>{r.signal.aborted||n({kind:"failed"})}),()=>r.abort()},[e,t]),r}function oX({messageKey:e}){let{st:t}=ag();return(0,n.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function oQ({deliverable:e,sessionId:t,title:r}){let{filePath:a,kind:i}=e;if("image"===i){let e=oZ(a,"read",t);return(0,n.jsx)(o8,{src:e,title:r},e)}if("html"===i){let e=oZ(a,"read",t);return(0,n.jsx)(o0,{url:e,title:r},e)}if(a.toLowerCase().endsWith(".pdf")){let e=oZ(a,"read",t);return(0,n.jsx)(o1,{url:e,title:r},e)}let s=oZ(a,"preview",t);return(0,n.jsx)(o2,{url:s,title:r},s)}function o0({url:e,title:t}){let r=oY(e,"json");return"ready"!==r.kind?(0,n.jsx)(oX,{messageKey:"failed"===r.kind?"result.previewFailed":"result.previewLoading"}):(0,n.jsx)("iframe",{className:"answer-result-media",srcDoc:r.content,sandbox:"allow-scripts",title:t,scrolling:"no",inert:!0})}function o1({url:e,title:t}){let r=oY(e,"head");return"ready"!==r.kind?(0,n.jsx)(oX,{messageKey:"failed"===r.kind?"result.previewFailed":"result.previewLoading"}):(0,n.jsx)("iframe",{className:"answer-result-media",src:`${e}#toolbar=0&view=FitH`,title:t,inert:!0})}function o2({url:e,title:t}){let r=oY(e,"text");return"ready"!==r.kind?(0,n.jsx)(oX,{messageKey:"failed"===r.kind?"result.previewFailed":"result.previewLoading"}):(0,n.jsx)("iframe",{className:"answer-result-media",srcDoc:r.content,sandbox:"allow-same-origin",title:t,inert:!0})}function o8({src:e,title:t}){let[r,i]=(0,a.useState)("loading");return"failed"===r?(0,n.jsx)(oX,{messageKey:"result.previewFailed"}):(0,n.jsxs)(n.Fragment,{children:["loading"===r?(0,n.jsx)(oX,{messageKey:"result.previewLoading"}):null,(0,n.jsx)("img",{className:"answer-result-media","data-fit":"contain",src:e,alt:t,draggable:!1,hidden:"loading"===r,onLoad:()=>i("ready"),onError:()=>i("failed")})]})}function o4({deliverables:e,onOpenFile:t}){let{sessionId:r}=(0,a.useContext)(s7),{st:i}=ag(),[o,l]=function(){let e=(0,a.useRef)(null),[t,r]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{let n=e.current;if(!n||t)return;if("u"<typeof IntersectionObserver)return void r(!0);let a=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&r(!0)},{rootMargin:"200px 0px"});return a.observe(n),()=>a.disconnect()},[t]),[e,t]}(),[c,...d]=e;if(!c)return null;let u=tF(c.filePath),p=i("result.previewTitle",{name:u}),h=t?()=>t(c.filePath):void 0;return(0,n.jsxs)("section",{className:"answer-result","aria-label":i("result.label"),children:[(0,n.jsxs)("div",{ref:o,className:"answer-result-frame","data-kind":c.kind,children:[l&&(0,n.jsx)(oQ,{deliverable:c,sessionId:r,title:p}),h&&(0,n.jsx)("button",{type:"button",className:"answer-result-cover",tabIndex:-1,"aria-hidden":"true",onClick:h})]}),(0,n.jsxs)("div",{className:"answer-result-bar",children:[(0,n.jsxs)("span",{className:"answer-result-title",children:[(0,n.jsx)("span",{className:"answer-result-kind",children:i("html"===c.kind?"result.kind.html":"image"===c.kind?"result.kind.image":c.filePath.toLowerCase().endsWith(".pdf")?"result.kind.pdf":"result.kind.document")}),(0,n.jsx)("span",{className:"answer-result-name",title:c.filePath,children:u})]}),h&&(0,n.jsx)(s.r,{className:"answer-result-open",variant:"neutralSolid",size:"medium",onClick:h,"aria-label":i("result.openNamed",{name:u}),children:i("result.open")})]}),d.length>0&&(0,n.jsxs)("div",{className:"answer-result-more",children:[(0,n.jsx)("span",{className:"answer-result-more-label",children:i("result.more",{count:d.length})}),(0,n.jsx)(aI,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}function o5({summary:e,live:t=!1,onOpenFile:r}){let{ledger:i,subagents:s,toolResults:o}=(0,a.useContext)(s7),{st:l}=ag(),c=(0,a.useMemo)(()=>t?[]:function(e){let t=[];for(let r of e){if(function(e){let t=e.toLowerCase().replace(/\\/g,"/").split("/");for(let e=0;e<t.length;e+=1){let r=t[e];if(Object.hasOwn(oD,r)||r.startsWith(".next")||"doc"===r&&"history"===t[e+1])return!0}return!1}(r.filePath))continue;let e=function(e){let t=eD(e);return"html"===t||"htm"===t?"html":eU(e)?"document":eH(e)?"image":null}(r.filePath);e&&t.push({filePath:r.filePath,kind:e})}return t.map((e,t)=>({deliverable:e,index:t})).sort((e,t)=>oH[e.deliverable.kind]-oH[t.deliverable.kind]||e.index-t.index).map(({deliverable:e})=>e)}(e.files),[t,e.files]),[d,u]=(0,a.useState)(null),p=d??(e.latest&&0===c.length),h=(0,a.useId)(),m=(0,a.useMemo)(()=>e.dispatchCalls.flatMap(e=>aJ(e,o.get(e.toolCallId))??[]).map(e=>aQ(e,s,i)),[e.dispatchCalls,o,s,i]),f=(0,a.useMemo)(()=>m.map(e=>({startedAt:i.spawnedAt.get(e.member.key)??null,durationMs:i.durations.get(e.member.key)??null})),[m,i]),{flow:g,remaining:x}=e,v=sa(g.steps),b=v.filter(e=>"failed"===e.outcome).length,y=v.filter(e=>"failed"===e.outcome||"unobserved"===e.outcome).length,w=v.filter(e=>e.compound?.failed).length,k=v.filter(e=>"unverified"===e.outcome&&!e.compound?.failed).length,j=v.filter(e=>e.stale).length,S=y+m.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===m.length&&!x?.length))return null;let C=[l(1===e.files.length?"summary.files.one":"summary.files",{count:e.files.length}),l(1===v.length?"summary.checks.one":"summary.checks",{count:v.length})];t&&C.unshift(l("summary.live")),b>0&&C.push(l("summary.checksFailed",{count:b})),w>0&&C.push(l("summary.compoundFailed",{count:w})),m.length>0&&C.push(l(1===m.length?"summary.makers.one":"summary.makers",{count:m.length})),x&&C.push(l("summary.remaining",{count:x.length})),!t&&S>0&&C.push(l("summary.unverified",{count:S})),k>0&&C.push(l(1===k?"summary.verdictUnverified.one":"summary.verdictUnverified",{count:k})),j>0&&C.push(l("summary.stale",{count:j}));let N=!t&&S>0||b>0||k>0||w>0||j>0;return(0,n.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,n.jsx)(o4,{deliverables:c,onOpenFile:r}),(0,n.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,n.jsx)("span",{className:"answer-summary-text","data-unverified":N?"":void 0,children:C.join(" \xb7 ")}),(0,n.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,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),p&&(0,n.jsxs)("div",{className:"answer-summary-body",id:h,children:[g.steps.length>0&&(0,n.jsx)(oJ,{summary:e,makers:m,timings:f,live:t,onOpenFile:r}),x&&(0,n.jsxs)("section",{className:"flow-remaining",children:[(0,n.jsx)("h4",{className:"flow-heading",children:l("summary.heading.remaining")}),0===x.length?(0,n.jsx)("p",{className:"answer-summary-empty",children:l("summary.todo.none")}):(0,n.jsx)("ul",{className:"flow-remaining-list",children:x.map((e,t)=>(0,n.jsxs)("li",{className:"answer-remaining","data-status":e.status,title:e.phase||void 0,children:[(0,n.jsx)("span",{className:"answer-remaining-status",children:l(`summary.todo.${e.status}`)}),(0,n.jsx)("span",{className:"answer-remaining-text",children:e.content}),e.blocker&&(0,n.jsx)("span",{className:"answer-remaining-blocker",children:l("summary.todo.blocker",{blocker:e.blocker})})]},`${e.phase}#${t}`))})]})]})]})}let o6=/^att_[0-9a-f]{32}$/,o3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function o7(e){return"string"==typeof e&&o6.test(e)}function o9(e){return"string"==typeof e&&o3.test(e)}class le extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let lt={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},lr={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},ln={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function la(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let r=t.lastIndexOf(".");if(r>0&&lr[t.slice(r)])return"text";let n=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===n?"markdown":"application/pdf"===n?"pdf":n&&ln[n]?"text":null}let li={".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 ls(e){let t=e.name.toLocaleLowerCase(),r=t.lastIndexOf("."),n=r>0?li[t.slice(r)]:void 0;if(n)return n;let a=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return a?.startsWith("audio/")?a:null}function lo(e,t){try{let r=new TextDecoder(e,{fatal:!0}).decode(t);return r.includes("\0")?null:r}catch{return null}}function ll(e){if(!Array.isArray(e))return[];let t=[],r=0,n=0;for(let a of e){if(a&&"object"==typeof a&&"string"==typeof a.name&&a.name.length>0&&("text/markdown"===a.mimeType||"text/plain"===a.mimeType||"application/pdf"===a.mimeType)&&"number"==typeof a.size&&Number.isSafeInteger(a.size)&&a.size>=0&&a.size<=8388608&&"string"==typeof a.text&&a.text.length<=12e4){if(t.length>=3)break;!(r+a.size>0x1000000)&&(n+a.text.length>24e4||(t.push({name:a.name,mimeType:a.mimeType,size:a.size,text:a.text,...o7(a.attachmentId)?{attachmentId:a.attachmentId}:{}}),r+=a.size,n+=a.text.length))}}return t}async function lc(e){let t,r=la(e);if(!r)throw new le("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new le("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===r)t=await lb(e);else{try{t=await e.text()}catch(e){throw new le("read_failed",e instanceof Error?e.message:String(e))}ly(t)}return{name:e.name,mimeType:lt[r],size:e.size,text:t}}function ld(e,t){let r=ll(t);if(0===r.length)return e;let n={userMessageLength:e.length,documents:r.map(({name:e,mimeType:t,size:r,text:n})=>({name:e,mimeType:t,size:r,textLength:n.length}))},a=`${lw}${JSON.stringify(n)}${lk}
|
|
5
|
+
${lj}${e}${lS}`;return r.forEach((e,t)=>{a+=lC(t,e),a+=e.text,a+=lN(t)}),a}function lu(e){let t;if(!e.startsWith(lw))return null;let r=e.indexOf("\n");if(r<0)return null;let n=e.slice(0,r);if(!n.endsWith(lk))return null;try{t=JSON.parse(n.slice(lw.length,-lk.length))}catch{return null}if(!function(e){if(!e||"object"!=typeof e||!Number.isSafeInteger(e.userMessageLength)||(e.userMessageLength??-1)<0||!Array.isArray(e.documents)||0===e.documents.length||e.documents.length>3)return!1;let t=0,r=0;for(let n of e.documents){if(!n||"object"!=typeof n||"string"!=typeof n.name||0===n.name.length||"text/markdown"!==n.mimeType&&"text/plain"!==n.mimeType&&"application/pdf"!==n.mimeType||!Number.isSafeInteger(n.size)||(n.size??-1)<0||(n.size??0)>8388608||!Number.isSafeInteger(n.textLength)||(n.textLength??-1)<0||(n.textLength??0)>12e4)return!1;t+=n.size??0,r+=n.textLength??0}return t<=0x1000000&&r<=24e4}(t))return null;let a=r+1;if(!e.startsWith(lj,a))return null;let i=(a+=lj.length)+t.userMessageLength;if(i>e.length)return null;let s=e.slice(a,i);if(a=i,!e.startsWith(lS,a))return null;a+=lS.length;let o=[];for(let r=0;r<t.documents.length;r+=1){let n=t.documents[r],i=lC(r,n);if(!e.startsWith(i,a))return null;let s=(a+=i.length)+n.textLength;if(s>e.length)return null;let l=e.slice(a,s);a=s;let c=lN(r);if(!e.startsWith(c,a))return null;a+=c.length,o.push({name:n.name,mimeType:n.mimeType,size:n.size,text:l})}return a===e.length?{message:s,documents:o}:null}function lp(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:`${(e/1048576).toFixed(1)} MB`}let lh="\n[transcript truncated to fit the attachment limit]",lm="File saved at: ";function lf(e){return"application/pdf"===e.mimeType?"pdf":"text/markdown"===e.mimeType?"markdown":e.text.startsWith(lm)?ls({name:e.name,type:""})?"audio":"file":"text"}function lg(e,t=12e4){let r=`${lm}${e.path}
|
|
6
|
+
(${e.mimeType}, ${e.size} bytes) Open it with a tool when its contents are needed.`;if(void 0!==e.transcript){let n=`${r}
|
|
7
|
+
|
|
8
|
+
Transcript of the audio (speech-to-text; may contain recognition errors):
|
|
9
|
+
`,a=n+e.transcript;return a.length<=t?a:n+e.transcript.slice(0,Math.max(0,t-n.length-lh.length))+lh}return e.transcriptError?`${r}
|
|
10
|
+
The audio could not be transcribed: ${e.transcriptError}`:r}async function lx(e,{sessionId:t,draftId:r,signal:n}={}){let a=new FormData;t&&a.append("sessionId",t),r&&a.append("draftId",r),a.append("file",e,e.name);let i=await fetch("/api/attachments",{method:"POST",body:a,signal:n}),s=await i.json().catch(()=>null);if(!i.ok||"string"!=typeof s?.path||"number"!=typeof s.size||"string"!=typeof s.mimeType||!o7(s.id)||!o9(s.draftId))throw Error("string"==typeof s?.error?s.error:`HTTP ${i.status}`);return{path:s.path,size:s.size,mimeType:s.mimeType,id:s.id,draftId:s.draftId}}async function lv(e,t,{sentAttachmentIds:r,signal:n}={}){let a=await fetch("/api/attachments/draft",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({draftId:e,attachmentIds:t,...r?.length?{sentAttachmentIds:r}:{}}),signal:n}),i=await a.json().catch(()=>null);if(!a.ok||!o9(i?.draftId)||!Array.isArray(i.attachmentIds)||!i.attachmentIds.every(o7))throw Error("string"==typeof i?.error?i.error:`HTTP ${a.status}`);return{draftId:i.draftId,attachmentIds:i.attachmentIds}}async function lb(e){let t;try{t=await fetch("/api/document-text",{method:"POST",headers:{"Content-Type":"application/pdf"},body:e})}catch(e){throw new le("read_failed",e instanceof Error?e.message:String(e))}let r=await t.json().catch(()=>null);if(!t.ok){var n;throw new le("string"==typeof r?.code&&("unsupported"===(n=r.code)||"file_too_large"===n||"text_too_large"===n||"too_many_pages"===n||"no_extractable_text"===n||"password_protected"===n||"invalid_pdf"===n||"read_failed"===n)?r.code:"invalid_pdf","string"==typeof r?.error?r.error:`Unable to read ${e.name}`)}if("string"!=typeof r?.text)throw new le("invalid_pdf",`Unable to read ${e.name}`);return ly(r.text),r.text}function ly(e){if(e.length>12e4)throw new le("text_too_large","Document exceeds the extracted text limit")}let lw="\x3c!-- omp-web-document-context-v1:",lk=" --\x3e",lj="User message:\n",lS="\n\nAttached documents (locally extracted text supplied by the user):\n";function lC(e,t){return`
|
|
11
|
+
--- Begin attached document ${e+1}: ${JSON.stringify(t.name)} (${t.mimeType}, ${t.size} bytes) ---
|
|
12
|
+
`}function lN(e){return`
|
|
13
|
+
--- End attached document ${e+1} ---`}let lT=new Map;function lI({children:e,className:t,...r}){let{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(!1);if(e.length<=1e5)return(0,n.jsx)(rb,{className:t,...r,children:e});if(!s){var l;return(0,n.jsxs)("button",{onClick:()=>o(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",i("i18n.largeMessageReveal",{size:(l=e.length)>=1e6?`${(l/1e6).toFixed(1)} MB`:l>=1e3?`${Math.round(l/1e3)} KB`:`${l} B`})]})}return(0,n.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:12,lineHeight:1.5},children:(0,n.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:e})})}let lM=null,lE=null,l$=null;function lR(e){if(!e)return null;let t=new Date(e),r=new Date,n=t.getFullYear()===r.getFullYear()&&t.getMonth()===r.getMonth()&&t.getDate()===r.getDate(),a=(lM??=new Intl.DateTimeFormat([],{hour:"2-digit",minute:"2-digit"})).format(t);if(n)return a;let i=t.getFullYear()!==r.getFullYear()?(l$??=new Intl.DateTimeFormat([],{month:"short",day:"numeric",year:"numeric"})).format(t):(lE??=new Intl.DateTimeFormat([],{month:"short",day:"numeric"})).format(t);return`${i} ${a}`}let lL=(0,a.memo)(function({message:e,isStreaming:t,toolResults:r,modelNames:a,cwd:i,onOpenFile:s,entryId:o,onFork:l,forking:c,onNavigate:d,prevAssistantEntryId:u,onEditContent:p,showTimestamp:h,prevTimestamp:m,sessionId:f,writtenFiles:g,dispatchSlot:x,turnSummary:v,inputTranslation:b,recoveredError:y}){return"user"===e.role?(0,n.jsx)(lA,{message:e,cwd:i,onOpenFile:s,entryId:o,onFork:l,forking:c,onNavigate:d,prevAssistantEntryId:u,onEditContent:p,inputTranslation:b}):"assistant"===e.role?(0,n.jsx)(lF,{message:e,isStreaming:t,toolResults:r,modelNames:a,cwd:i,onOpenFile:s,showTimestamp:h,prevTimestamp:m,sessionId:f,entryId:o,writtenFiles:g,dispatchSlot:x,turnSummary:v,recoveredError:y}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,n.jsx)(l6,{message:e}):(0,n.jsx)(l9,{message:e,cwd:i,onOpenFile:s}):"bashExecution"===e.role?(0,n.jsx)(cr,{message:e,sessionId:f}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,r){if(t===r||"assistant"!==e.role)return!0;for(let n of e.content??[])if("toolCall"===n.type&&t?.get(n.toolCallId)!==r?.get(n.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.entryId===t.entryId&&e.onFork===t.onFork&&e.forking===t.forking&&e.onNavigate===t.onNavigate&&e.prevAssistantEntryId===t.prevAssistantEntryId&&e.onEditContent===t.onEditContent&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.sessionId===t.sessionId&&e.dispatchSlot===t.dispatchSlot&&e.turnSummary===t.turnSummary&&e.inputTranslation===t.inputTranslation&&e.recoveredError===t.recoveredError);function lA({message:e,cwd:t,onOpenFile:r,entryId:i,onFork:s,forking:o,onNavigate:l,prevAssistantEntryId:c,onEditContent:d,inputTranslation:u}){let{t:p}=(0,z.s)(),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),x="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),v=lu(x),b=v?.message??x,y=v?.documents??[],w="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),k=lR(e.timestamp),j=!!i&&!!s,S=!!c&&!!l;return(0,n.jsxs)("div",{className:"message-user",style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,n.jsxs)("div",{className:"message-user-bubble",style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--accent-line)",borderRadius:"var(--seed-radius-r3)",padding:"8px 12px",fontSize:14,lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:[w.length>0&&(0,n.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:w.map((e,t)=>{let r=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,n.jsx)("img",{src:r,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t)})}),y.length>0&&(0,n.jsx)("div",{role:"list","aria-label":p("chat.attachments"),style:{display:"flex",flexDirection:"column",gap:5,marginBottom:8*!!b},children:y.map((e,t)=>{var r;return(0,n.jsxs)("div",{role:"listitem",style:{display:"flex",alignItems:"center",gap:7,minWidth:0,padding:"5px 7px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"color-mix(in srgb, var(--user-bg) 70%, var(--bg-panel))"},children:[aT(e.name,14),(0,n.jsx)("span",{title:e.name,style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:e.name}),(0,n.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:[(r=lf(e),"pdf"===r?"PDF":"markdown"===r?"Markdown":"audio"===r?p("chat.attachKindAudio"):"file"===r?p("chat.attachKindFile"):"Text")," \xb7 ",lp(e.size)]})]},`${e.name}-${t}`)})}),b&&(0,n.jsx)(lI,{className:"markdown-user-message",cwd:t,onOpenFile:r,children:b})]})}),void 0!==u&&(0,n.jsx)(lP,{text:u,cwd:t,onOpenFile:r}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,n.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!h,pointerEvents:h?"auto":"none",transition:"opacity 0.12s"},children:(0,n.jsxs)("button",{className:"message-meta-action",onClick:()=>{rm(function(e){let t=lu(e);if(!t)return e;let r=t.documents.map(e=>e.name).join(", ");return t.message.trim()?`${t.message}
|
|
14
|
+
|
|
15
|
+
Attached: ${r}`:`Attached: ${r}`}(x)).then(()=>{g(!0),setTimeout(()=>g(!1),1500)})},title:p("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:f?"var(--accent)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{f||(e.currentTarget.style.color="var(--text-muted)")},children:[f?(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,n.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),f?p("i18n.copied"):p("i18n.copy")]})}),(j||S)&&(0,n.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||o?1:0,pointerEvents:h||o?"auto":"none",transition:"opacity 0.12s"},children:[S&&(0,n.jsxs)("button",{onClick:()=>{l(c),d?.(e)},title:p("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,n.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),p("i18n.editFromHere")]}),j&&(0,n.jsxs)("button",{onClick:()=>{s(i)},disabled:o,title:o?p("i18n.creatingSession"):p("i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:o?"var(--accent)":"var(--text-dim)",cursor:o?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{o||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),o?p("i18n.creating"):p("i18n.newSession")]})]}),k&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-muted)"},children:k})]})]})}function lP({text:e,cwd:t,onOpenFile:r}){let{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(!1),l=(0,a.useId)();return(0,n.jsxs)("div",{className:"message-user-translation",style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4,maxWidth:"85%",marginTop:3},children:[(0,n.jsx)("button",{type:"button",onClick:()=>o(e=>!e),"aria-expanded":s,"aria-controls":s?l:void 0,style:{padding:"2px 0",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:i(s?"i18n.hideInputTranslation":"i18n.showInputTranslation")}),s&&(0,n.jsx)("div",{id:l,lang:"en",className:"message-user-translation-body",style:{alignSelf:"stretch",paddingLeft:10,borderLeft:"2px solid var(--border)"},children:(0,n.jsx)(lI,{cwd:t,onOpenFile:r,children:e})})]})}function lF({message:e,isStreaming:t,toolResults:r,modelNames:i,cwd:s,onOpenFile:o,showTimestamp:l,prevTimestamp:c,sessionId:d,entryId:u,writtenFiles:p,dispatchSlot:h,turnSummary:m,recoveredError:f}){var g;let x,{t:v}=(0,z.s)(),{hideThinkingBlock:b}=rX(),y=l?lR(e.timestamp):null,w=ah(d,e.provider,e.credentialId,e.model),k=e.liveSpeaker?nv.find(t=>t.alias===e.liveSpeaker?.alias)??np.find(t=>t.alias===e.liveSpeaker?.alias):void 0,j=k?{seed:k.seed,alias:nL(k.alias)}:w,S=!!k&&e.liveSpeaker?.mode==="native",{st:C}=ag(),N=i?.[`${e.provider}:${e.model}`]??i?.[e.model]??e.model,T=(0,a.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!eq(e,{isStreaming:t,hideThinking:b})),[e.content,t,b]),I=(0,a.useMemo)(()=>T.map(({block:e})=>e),[T]),M=eV(e,{isStreaming:t}),[E,$]=(0,a.useState)(!1),[R,L]=(0,a.useState)(!1),[A,P]=(0,a.useState)(!1),F=(0,a.useRef)(null),[_,W]=(0,a.useState)(null),O=(0,a.useRef)(T);O.current=T;let D=(0,a.useRef)(new Map),H=(0,a.useMemo)(()=>{if(!t)return D.current=new Map,0;let e=new Map,r=0;for(let{block:t,originalIndex:n}of T){let a=eX(t);if(null===a)continue;let i=eQ(D.current.get(n),a);e.set(n,{text:a,tokens:i}),r+=i}return D.current=e,r},[T,t]),U=(0,a.useRef)(H);U.current=H;let B=(0,a.useRef)(new Map),[q,V]=(0,a.useState)(new Map),K=(0,a.useMemo)(()=>{if(!e.timestamp||!c)return;let t=Math.round((e.timestamp-c)/1e3);return t>0?t:void 0},[e.timestamp,c]),G=(0,a.useMemo)(()=>(function(e,t){let r=new Map,n=e.completedAt;if(!t||!n)return r;for(let[e,a]of t){if(!a.timestamp||a.details?.executed===!1)continue;let t=Math.round((a.timestamp-n)/1e3);t>0&&r.set(e,t)}return r})(e,r),[e,r]),J=e.replyTranslation,Z=J?.kind==="translated"?J:void 0,Y=Z?T.findIndex(({block:e})=>"text"===e.type):-1,X=Z?Z.text:I.filter(e=>"text"===e.type).map(e=>e.text).join("\n");return((0,a.useEffect)(()=>{if(!t){let e=new Date().getTime();V(t=>{let r=new Map(t);for(let[t,n]of B.current)r.has(t)||r.set(t,Math.round((e-n)/1e3));return r}),F.current=null,W(null);return}let e=setInterval(()=>{let e=O.current,t=Date.now();e.forEach(({originalIndex:e})=>{B.current.has(e)||B.current.set(e,t)}),V(r=>{let n=!1,a=new Map(r);for(let r=0;r<e.length-1;r++){let i=e[r].originalIndex,s=e[r+1].originalIndex;if(!a.has(i)&&B.current.has(i)){let e=B.current.get(i),r=B.current.get(s)??t;a.set(i,Math.round((r-e)/1e3)),n=!0}}return n?a:r});let r=U.current;if(0===r)return;null===F.current&&(F.current=t);let n=(t-F.current)/1e3;n>.5&&W(r/n)},300);return()=>clearInterval(e)},[t]),0!==I.length||t||M)?(0,n.jsxs)("div",{className:`message-assistant${t?" is-streaming":""}`,style:{marginBottom:16},onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1),children:[(0,n.jsx)("div",{className:"message-assistant-role",style:{fontSize:11,color:"var(--text-dim)",marginBottom:2,display:"flex",alignItems:"center",gap:9,...j?{minHeight:40}:null},children:e.provider&&(0,n.jsxs)(n.Fragment,{children:[j&&(0,n.jsx)(ax,{seed:j.seed,size:40,provider:e.provider}),j&&(0,n.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:j.alias}),S&&(0,n.jsx)("span",{children:C("live.nativeVoice")}),(0,n.jsx)("span",{children:`${function(e,t){if("anthropic"===e.provider){let r=e.usage?.credentialKind;if("oauth"===r)return t("i18n.providerAnthropicSubscription");if("api-key"===r)return t("i18n.providerAnthropicApi")}return nq(e.provider)}(e,v)} \xb7 ${N}`})]})}),h?.placement==="before"&&(0,n.jsx)(o_,{calls:h.calls}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[T.map(({block:a,originalIndex:i},l)=>Z&&"text"===a.type?l===Y?(0,n.jsx)(l_,{translation:Z.text,original:Z.original,cwd:s,onOpenFile:o},`${u??"stream"}-${i}`):null:(0,n.jsx)(lz,{block:a,toolResults:r,isStreaming:t,streamingDuration:q.get(i)??("thinking"===a.type?K:void 0),toolCallDurations:G,runStartedAt:e.completedAt,cwd:s,onOpenFile:o,sessionId:d,entryId:u,blockIndex:i},`${u??"stream"}-${i}`)),J&&!Z&&(0,n.jsx)("div",{className:"reply-translation-note",style:{fontSize:12,color:"var(--text-dim)"},children:J.text})]}),h?.placement==="after"&&(0,n.jsx)(o_,{calls:h.calls}),M&&f?(0,n.jsxs)("details",{className:"message-recovered-error",style:{marginTop:6*(I.length>0),fontSize:12,color:"var(--text-dim)"},children:[(0,n.jsxs)("summary",{style:{cursor:"pointer"},children:[v("chat.recoveredError")," ",(0,n.jsx)("span",{style:{textDecoration:"underline"},children:v("chat.recoveredErrorDetail")})]}),(0,n.jsx)("div",{style:{marginTop:4,fontFamily:"var(--font-mono)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:M})]}):M&&(0,n.jsxs)("div",{role:"alert",style:{marginTop:8*(I.length>0),padding:"7px 10px",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",background:"var(--danger-soft)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",M]}),m?(0,n.jsx)(o5,{summary:m,onOpenFile:o}):p&&p.length>0&&(0,n.jsx)(aI,{files:p,onOpenFile:o}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,n.jsx)("button",{type:"button",className:"message-meta-action",onClick:()=>P(e=>!e),onFocus:()=>$(!0),onBlur:()=>$(!1),"aria-expanded":A,title:v("i18n.messageUsageTitle"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:A?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:E||A?1:0,pointerEvents:E||A?"auto":"none",transition:"opacity 0.12s, color 0.12s"},children:A?(g=e.usage,x=[],g.input&&x.push(`${g.input.toLocaleString()} in`),g.output&&x.push(`${g.output.toLocaleString()} out`),g.cacheRead&&x.push(`${g.cacheRead.toLocaleString()} cache R`),g.cacheWrite&&x.push(`${g.cacheWrite.toLocaleString()} cache W`),g.cost?.total&&x.push(`$${g.cost.total.toFixed(4)}`),x.join(" \xb7 ")):v("i18n.messageUsage")}),t&&Math.round(H)>0&&(0,n.jsx)("button",{type:"button",className:"message-meta-action",onClick:()=>P(e=>!e),"aria-expanded":A,title:v("i18n.estimatedTokens"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:A?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:A?`~${Math.round(H)}${null!==_?` \xb7 ${_.toFixed(1)} t/s`:""}`:v("i18n.messageUsage")}),X&&!t&&(0,n.jsxs)("button",{className:"message-meta-action",onClick:()=>{rm(X).then(()=>{L(!0),setTimeout(()=>L(!1),1500)})},title:v("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:R?"var(--accent)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!E,pointerEvents:E?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{R||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{R||(e.currentTarget.style.color="var(--text-muted)")},children:[R?(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,n.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),v(R?"i18n.copied":"i18n.copy")]}),y&&!t&&(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-muted)",marginLeft:"auto"},children:y})]})]}):null}function l_({translation:e,original:t,cwd:r,onOpenFile:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(!1);return(0,n.jsxs)("div",{className:"reply-translation",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)(lI,{cwd:r,onOpenFile:i,children:e}),(0,n.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,style:{alignSelf:"flex-start",padding:"2px 0",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:s(o?"i18n.hideOriginalReply":"i18n.showOriginalReply")}),o&&(0,n.jsx)("div",{className:"reply-translation-original",style:{paddingLeft:10,borderLeft:"2px solid var(--border)",color:"var(--text-muted)"},children:(0,n.jsx)(lI,{cwd:r,onOpenFile:i,children:t})})]})}function lz({block:e,toolResults:t,isStreaming:r,streamingDuration:a,toolCallDurations:i,runStartedAt:s,cwd:o,onOpenFile:l,sessionId:c,entryId:d,blockIndex:u}){if("text"===e.type)return(0,n.jsx)(lU,{block:e,isStreaming:r,cwd:o,onOpenFile:l});if("thinking"===e.type)return(0,n.jsx)(lB,{block:e,duration:a,sessionId:c,entryId:d,blockIndex:u});if("toolCall"===e.type){let r=t?.get(e.toolCallId),a=i?.get(e.toolCallId);return(0,n.jsx)(lq,{block:e,result:r,duration:a,runStartedAt:s,sessionId:c})}if("image"===e.type)return"image"===e.type&&"toolImage"in e?c?(0,n.jsx)(lO,{sessionId:c,toolCallId:e.toolImage.toolCallId}):null:(0,n.jsx)(lW,{block:e});return null}function lW({block:e}){let t=ct(e);return t?(0,n.jsx)("img",{src:t,alt:"",style:{maxWidth:"100%",maxHeight:420,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}}):null}function lO({sessionId:e,toolCallId:t}){let{t:r}=(0,z.s)(),[i,s]=(0,a.useState)(()=>e8.get(`${e}
|
|
16
|
+
${t}`)),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(()=>new Set);if((0,a.useEffect)(()=>{if(void 0!==i)return;let r=!0;return(function(e,t){let r=`${e}
|
|
17
|
+
${t}`,n=e8.get(r);if(void 0!==n)return Promise.resolve(n);let a=e4.get(r);if(a)return a;let i=fetch(e0(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),n=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return e8.set(r,n),n}).catch(()=>0).finally(()=>e4.delete(r));return e4.set(r,i),i})(e,t).then(e=>{r&&s(e)}),()=>{r=!1}},[i,e,t]),!i)return null;let u=Array.from({length:i},(e,t)=>t).filter(e=>!c.has(e));return 0===u.length?null:(0,n.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(a=>(0,n.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":r("i18n.zoomIn"),onClick:()=>l(a),children:(0,n.jsx)("img",{src:e0(e,t,a),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(a))})},a)),null!==o&&(0,n.jsx)(lH,{src:e0(e,t,o),fileName:`screen-${t.slice(-8)}-${o+1}`,onClose:()=>l(null)})]})}let lD={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function lH({src:e,fileName:t,onClose:r}){let{t:i}=(0,z.s)(),o=(0,a.useContext)(rI),l=(0,a.useRef)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)([]),[f,g]=(0,a.useState)(null),x=(0,a.useRef)(null);(0,a.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(),r()},b=async()=>{let n,a;if(!o)return void p(i("toolImage.noComposer"));x.current?.abort();let s=new AbortController;x.current=s,d(!0),p(null);try{let r=await fetch(e,{signal:s.signal});if(!r.ok)throw Error(`HTTP ${r.status}`);let o=await r.blob(),l=lD[o.type];if(!l)throw Error(`unsupported ${o.type}`);if(0!==h.length&&f){let e=await rF(o,h);n=[new File([e.marked],`${t}-marked.png`,{type:"image/png"}),...e.crops.map((e,r)=>new File([e],`${t}-region-${r+1}.png`,{type:"image/png"}))];let r=1===h.length?"1":`1~${h.length}`;a=[i("toolImage.locatorIntro",{range:r}),...h.map((e,t)=>i("toolImage.locatorRegion",{n:t+1,x:e.x,y:e.y,w:e.w,h:e.h,width:f.width,height:f.height}))].join("\n")+"\n"}else n=[new File([o],`${t}.${l}`,{type:o.type})]}catch{if(s.signal.aborted)return;d(!1),p(i("toolImage.loadFailed"));return}if(!s.signal.aborted&&l.current?.open){if(!o(n,a)){d(!1),p(i("toolImage.noComposer"));return}r()}};return(0,q.createPortal)((0,n.jsxs)("dialog",{ref:l,className:"tool-image-dialog","aria-label":i("toolImage.dialogLabel"),onCancel:e=>{e.preventDefault(),v()},onClick:e=>{e.target===e.currentTarget&&v()},children:[(0,n.jsx)(r_,{src:e,regions:h,max:9,onAdd:e=>m(t=>t.length<9?[...t,e]:t),onNaturalSize:g,regionLabel:e=>i("toolImage.regionLabel",{n:e})}),u?(0,n.jsx)("p",{role:"alert",className:"tool-image-error",children:u}):(0,n.jsx)("p",{className:"tool-image-hint","data-hidden":h.length>0&&h.length<9?"true":void 0,children:h.length>=9?i("toolImage.markLimit",{count:9}):i("toolImage.markHint")}),(0,n.jsxs)("div",{className:"tool-image-actions",children:[(0,n.jsx)(s.r,{variant:"neutralSolid",size:"medium",loading:c,onClick:()=>void b(),title:i("toolImage.requestEditHint"),children:i("toolImage.requestEdit")}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"medium",disabled:0===h.length,onClick:()=>m([]),children:i("toolImage.clearMarks")}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"medium",onClick:v,children:i("i18n.close")})]})]}),document.body)}function lU({block:e,isStreaming:t,cwd:r,onOpenFile:a}){return(0,n.jsx)(lI,{isStreaming:t,cwd:r,onOpenFile:a,children:e.text})}function lB({block:e,duration:t,sessionId:r,entryId:i,blockIndex:s}){let{t:o}=(0,z.s)(),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!0===e.deferred),[p,h]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(!e.deferred){c(null),u(!1),h(null);return}let t=!1;return r&&i?(u(!0),h(null),(function(e,t,r){let n=`${e}:${t}:${r}`,a=lT.get(n);if(a)return lT.delete(n),lT.set(n,a),a;let i=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${r}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw lT.delete(n),e});if(lT.set(n,i),lT.size>100){let e=lT.keys().next().value;e&&lT.delete(e)}return i})(r,i,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,i,r,o]);let m=e.deferred?l:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,n.jsxs)("div",{className:"markdown-thinking","aria-label":o("i18n.thinking"),children:[(0,n.jsx)("div",{className:"markdown-thinking-content",children:d?(0,n.jsx)("span",{className:"markdown-thinking-status",children:o("i18n.loadingThinking")}):p?(0,n.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,n.jsx)(rb,{className:"markdown-thinking-body",children:m}):(0,n.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&f&&(0,n.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function lq({block:e,result:t,duration:r,runStartedAt:i,sessionId:s}){var o;let l,{t:c}=(0,z.s)(),d=(0,a.useId)(),[u]=(0,a.useState)(()=>Date.now()),[p,h]=(0,a.useState)(null),m=(o=t?null:rC(s,e.toolCallId),(0,a.useSyncExternalStore)(rS,()=>o?rw.get(o)??null:null,()=>null)),f=e.toolName.toLowerCase(),g=JSON.stringify(e.input,null,2),x="todo"===f||f.endsWith(".todo")||f.endsWith("_todo"),v="bash"===f||f.startsWith("bash ")||f.endsWith(".bash")||f.endsWith("_bash"),b=t&&!t.isError?function(e){var t;let r=e.details;if(!("object"==typeof(t=r)&&null!==t&&!Array.isArray(t)))return null;let n="string"==typeof r.patch?r.patch:null;if(n)return{text:n};let a="string"==typeof r.diff?r.diff:null;return a?{text:a}:null}(t):null,y=x?"unknown"===(l=tM(e,t)).kind||0===l.phases.length?null:l.phases:null,w=b?b.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,k=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,j=null!==k&&("(no output)"===k.trim()||""===k.trim()),S=t?rO(t):null,C=t?t.isError||null!==S&&0!==S?"failed":"done":"running",N="failed"===C,T=p??N;if(x&&y)return(0,n.jsx)(lX,{phases:y});let I=v&&"string"==typeof e.input.command?e.input.command:"",M=function(e,t,r){let n,a=t.html;if(!("ask"===(n=e.trim().toLowerCase())||n.endsWith(".ask")||n.endsWith("_ask"))||"string"!=typeof a)return null;let i="object"==typeof r&&null!==r?r:{},s=[];if(Array.isArray(i.answers))for(let e of i.answers)"string"==typeof e?.question&&"string"==typeof e.answer&&s.push({question:e.question,answer:e.answer});let o=!0===i.timedOut,l=s[0]?.question||a.replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi," ").replace(/<[^>]*>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s+/g," ").trim(),c=s.length>1?` (+${s.length-1})`:"",d=Math.max(0,120-c.length),u=l.length>d?`${l.slice(0,Math.max(0,d-1))}…`:l;return{target:`${u}${c}`,rows:s,timedOut:o}}(e.toolName,e.input,t?.details),E=null!==M&&M.rows.length>0?M:null,$=!!(y||b||E),R=v?I.split(/\r?\n/,1)[0]??"":M?.target??function(e,t){if(t){let e=t.flatMap(e=>e.tasks),r=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${r}/${e.length} tasks`}return function(e){var t;let r=e.input;if(!r||"object"!=typeof r)return"";let n=Object.keys(r);if(0===n.length)return"";let a=e.toolName.toLowerCase();if(t=a,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof r.i){let e=r.i.trim();if(e)return e.slice(0,120)}if(("eval"===a||a.endsWith(".eval")||a.endsWith("_eval"))&&"string"==typeof r.title){let e=r.title.trim();if(e)return e.slice(0,120)}if("command"in r)return String(r.command).slice(0,120);if("path"in r)return String(r.path).slice(-120);if("file_path"in r)return String(r.file_path).slice(-120);if("pattern"in r)return String(r.pattern).slice(0,120);if("query"in r)return String(r.query).slice(0,120);let i=n.map(e=>r[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==i)return String(i).slice(0,120);try{return JSON.stringify(r).slice(0,120)}catch{return n.join(", ").slice(0,120)}}(e)}(e,y),L=!v&&/^\S+$/.test(R)&&/[\\/]/.test(R),A=w?c("toolRun.diffStats",{added:w.added,removed:w.removed}):"";return(0,n.jsxs)("div",{className:`tool-call-card ${N?"is-error":"running"===C?"is-running":"is-done"}${v?" is-shell":""}`,"aria-busy":"running"===C||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,n.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>h(!T),"aria-expanded":T,"aria-controls":T?d: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,n.jsx)(lZ,{toolName:e.toolName}),(0,n.jsx)("span",{className:"tool-call-name",children:v?"bash":e.toolName}),v&&f.includes("(local)")&&(0,n.jsx)("span",{className:"shell-local-label",children:"local"}),(0,n.jsx)("span",{className:`tool-call-target${L?" is-path":""}`,title:v?I:R,children:L?(0,n.jsx)("bdi",{dir:"ltr",children:R}):R}),w&&(0,n.jsxs)("span",{className:"tool-call-diffstats",title:A,"aria-label":A,children:[(0,n.jsxs)("span",{style:{color:"var(--success)"},children:["+",w.added]}),(0,n.jsxs)("span",{style:{color:"var(--danger)"},children:["−",w.removed]})]}),(0,n.jsx)(lK,{state:C,duration:r,exitCode:S,startedAt:i??u}),(0,n.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:T?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),"running"===C&&m&&(0,n.jsx)("div",{className:"tool-call-progress",title:m,style:{padding:"0 10px 6px 29px",color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:m}),T&&(0,n.jsx)("div",{id:d,className:"tool-call-body",children:v?(0,n.jsx)(lQ,{command:I,output:k??"",pending:!t,isError:N}):(0,n.jsxs)(n.Fragment,{children:[b&&(0,n.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,n.jsx)(l0,{diff:b})}),t&&N&&(0,n.jsx)(l5,{text:k??"",isEmpty:j,isError:!0}),E&&!N&&(0,n.jsx)(lV,{summary:E}),!$&&(0,n.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:g}),t&&!$&&!N&&(0,n.jsx)(l5,{text:k??"",isEmpty:j,isError:!1})]})})]})}function lV({summary:e}){let{t}=(0,z.s)();return(0,n.jsxs)("div",{className:"tool-call-ask",style:{padding:"8px 10px"},children:[(0,n.jsx)("dl",{style:{margin:0,display:"grid",gap:8},children:e.rows.map((e,t)=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("dt",{style:{color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflowWrap:"anywhere"},children:e.question}),(0,n.jsx)("dd",{style:{margin:"2px 0 0",color:"var(--text)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:""===e.answer?"—":e.answer})]},t))}),e.timedOut&&(0,n.jsx)("p",{style:{margin:"8px 0 0",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:t("toolRun.askTimedOut")})]})}function lK({state:e,duration:t,exitCode:r,startedAt:a}){let{t:i}=(0,z.s)();return"running"===e?(0,n.jsx)(lG,{startedAt:a}):(0,n.jsxs)(n.Fragment,{children:[void 0!==t&&(0,n.jsxs)("span",{className:"tool-run-duration",children:[t,"s"]}),"failed"===e&&(0,n.jsxs)("span",{className:"tool-run-failed",children:[(0,n.jsx)(rT.E,{tone:"critical",variant:"weak",size:"medium",children:i("toolRun.failed")}),null!==r&&(0,n.jsx)("span",{className:"tool-run-exit",children:i("toolRun.exitCode",{code:r})})]})]})}function lG({startedAt:e}){let{t}=(0,z.s)(),r=ry(500)-e;return r<400?null:(0,n.jsxs)("span",{className:"tool-run-running",children:[t("toolRun.running"),(0,n.jsxs)("span",{className:"tool-run-duration",children:[Math.floor(r/1e3),"s"]})]})}function lJ(e,t){let r=e.trim().toLowerCase();return r===t||r.endsWith(`.${t}`)||r.endsWith(`_${t}`)||r.split(/[.\s:_-]+/).includes(t)}function lZ({toolName:e}){let t,r=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||lJ(t,"edit")?"edit":lJ(t,"read")||lJ(t,"cat")?"read":lJ(t,"write")||lJ(t,"save")?"write":lJ(t,"glob")||lJ(t,"find")?"glob":lJ(t,"grep")||lJ(t,"search")?"grep":lJ(t,"bash")||lJ(t,"shell")||lJ(t,"exec")?"bash":lJ(t,"todo")?"todo":lJ(t,"eval")?"eval":lJ(t,"task")||lJ(t,"agent")?"task":lJ(t,"browser")||lJ(t,"web_search")||lJ(t,"fetch")?"browser":lJ(t,"image")||lJ(t,"inspect_image")?"image":"generic";return(0,n.jsx)("span",{"aria-hidden":"true","data-tool-icon":r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:"var(--text-muted)"},children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)(lY,{kind:r})})})}function lY({kind:e}){switch(e){case"read":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,n.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,n.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,n.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,n.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,n.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,n.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,n.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,n.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,n.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,n.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,n.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,n.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,n.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,n.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,n.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function lX({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),r=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,n.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,n.jsxs)("div",{className:"todo-checklist-header",children:[(0,n.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,n.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,n.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,n.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),r>0&&r<t&&(0,n.jsxs)("span",{className:"todo-checklist-progress",children:[r,"/",t]})]}),(0,n.jsx)("div",{className:"todo-checklist-body",children:e.map((t,r)=>(0,n.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,n.jsx)(aw,{task:e},`${e.content}-${t}`))]},`${t.name}-${r}`))})]})}function lQ({command:e,output:t,pending:r,isError:a}){let{isDark:i}=rh(),{t:s}=(0,z.s)(),o=eP(t.split(/\r?\n/)),l=1===o.length&&""===o[0]?[]:o;return(0,n.jsxs)("div",{className:`shell-output-preview${a?" is-error":""}`,children:[(0,n.jsxs)("div",{className:"shell-command-line",children:[(0,n.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,n.jsx)(tz.A,{className:"shell-command-code",language:"bash",style:i?tW.xJ:tW.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,n.jsxs)("div",{className:"shell-output-panel",children:[(0,n.jsx)("div",{className:"shell-output-divider",children:(0,n.jsx)("span",{className:"shell-output-label",children:"Output"})}),(0,n.jsxs)("div",{className:"shell-output-body",children:[0===l.length&&!r&&(0,n.jsx)("span",{className:"shell-output-empty",children:s("i18n.noOutput")}),l.map((e,t)=>{let r=e$(e).trimStart(),i=a||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(r)?"is-error":/^(?:warning|warn|!)/i.test(r)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(r)?"is-success":"";return(0,n.jsxs)("div",{className:`shell-output-line ${i}`.trim(),children:[eF(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},t):(0,n.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)})]})]})]})}function l0({diff:e}){return(0,n.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,n.jsx)(l1,{text:e.text})})}function l1({text:e}){let{t}=(0,z.s)(),r=(0,a.useMemo)(()=>ab(e),[e]);if(!r)return(0,n.jsx)(l4,{text:e});let i=r.length>1;return(0,n.jsx)("div",{style:{background:"var(--bg)"},children:r.map((e,r)=>(0,n.jsxs)("div",{style:{minWidth:0,borderTop:0===r?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[i&&(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)(l2,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,n.jsx)(l2,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)(l8,{cell:e.left,side:"left"}),(0,n.jsx)(l8,{cell:e.right,side:"right"})]},t))})]},r))})}function l2({title:e,side:t}){return(0,n.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function l8({cell:e,side:t}){let r="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",a="added"===e.type?"+":"removed"===e.type?"-":" ",i="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",minWidth:0,background:r,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,n.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,n.jsx)("span",{style:{width:18,padding:"0 5px",color:i,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:a}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function l4({text:e}){let t=e.split(/\r?\n/);return(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let r=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,n.jsxs)("div",{style:{display:"flex",background:"added"===r?"var(--success-soft)":"removed"===r?"var(--danger-soft)":"hunk"===r?"var(--accent-soft)":"transparent",borderLeft:"added"===r?"3px solid var(--success)":"removed"===r?"3px solid var(--danger)":"hunk"===r?"3px solid var(--accent)":"3px solid transparent"},children:[(0,n.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,n.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===r?"var(--success)":"removed"===r?"var(--danger)":"hunk"===r?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function l5({text:e,isEmpty:t,isError:r}){let{t:a}=(0,z.s)();return(0,n.jsx)("div",{style:{borderTop:`1px solid ${r?"var(--danger-line)":"var(--success-line)"}`,background:r?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,n.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:r?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?a("i18n.noOutput"):e})})}function l6({message:e}){let{t}=(0,z.s)(),r=ce(e.content),i=(0,a.useMemo)(()=>{let e,t,n,a,i;return e=[],t=[],n=r.match(rH),a=n?.[1]??"",i=n?.index===void 0?r:r.slice(0,n.index),a.replace(rD,(r,n,a)=>{let i=a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===n?e.push(...i):t.push(...i),""}),{body:i.trim(),readFiles:e,modifiedFiles:t}},[r]),s=lR(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,n.jsx)("div",{style:{marginBottom:16},children:(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",overflow:"hidden",background:"var(--bg)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==o&&(0,n.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:rU(o)})}),s&&(0,n.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,n.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,n.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),i.body?(0,n.jsx)(rb,{className:"markdown-compaction-message",children:i.body}):(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,n.jsx)(l3,{readFiles:i.readFiles,modifiedFiles:i.modifiedFiles})]})]})})}function l3({readFiles:e,modifiedFiles:t}){let{t:r}=(0,z.s)();if(0===e.length+t.length)return null;let a=[];return e.length>0&&a.push(`${e.length} read`),t.length>0&&a.push(`${t.length} modified`),(0,n.jsxs)("details",{className:"compaction-file-details",children:[(0,n.jsx)("summary",{children:r("i18n.fileContext",{details:a.join(", ")})}),t.length>0&&(0,n.jsx)(l7,{title:r("i18n.modifiedFiles"),files:t}),e.length>0&&(0,n.jsx)(l7,{title:r("i18n.readFiles"),files:e})]})}function l7({title:e,files:t}){return(0,n.jsxs)("div",{className:"compaction-file-section",children:[(0,n.jsx)("div",{className:"compaction-file-title",children:e}),(0,n.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,n.jsx)("li",{children:e},e))})]})}function l9({message:e,cwd:t,onOpenFile:r}){var i;let s,{t:o}=(0,z.s)(),l=!1===e.display,[c,d]=(0,a.useState)(!l),[u,p]=(0,a.useState)(!1),[h,m]=(0,a.useState)(!1),f=ce(e.content),g="string"==typeof(i=e.content)?[]:i.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=lR(e.timestamp);return(0,n.jsx)("div",{style:{marginBottom:16},children:(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",overflow:"hidden",background:l?"var(--bg-subtle)":"var(--bg)",opacity:l&&!c?.82:1},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),l&&(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),y&&(0,n.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),c?(0,n.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,n.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let r=ct(e);return r?(0,n.jsx)("img",{src:r,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,n.jsx)(rb,{className:"markdown-custom-message",cwd:t,onOpenFile:r,children:f}):(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}):(0,n.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:f?(s=f.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":o("i18n.showExtensionMessage")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,n.jsx)("button",{className:"message-meta-action",onClick:()=>{rm(f||v).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(h?"i18n.copied":"i18n.copy")}):null,(x||l)&&(0,n.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,n.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function ce(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function ct(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 cr({message:e,sessionId:t}){let[r,i]=(0,a.useState)(null),[s,o]=(0,a.useState)(!1),[l,c]=(0,a.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===r,m=r??e.output;async function f(){if(p){o(!0),c(null);try{let e=await fetch(p),t=await e.json();t.success?i(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:m?[{type:"text",text:m}]:[],isError:u,details:void 0!==e.exitCode?{exitCode:e.exitCode}:void 0,timestamp:e.timestamp};return(0,n.jsxs)("div",{style:{margin:"6px 0"},children:[(0,n.jsx)(lq,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&p&&(0,n.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,n.jsx)("button",{onClick:f,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,n.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),l&&(0,n.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",l,")"]})]})]})}r(21340);let cn="cuelo-chat-search",ca="cuelo-chat-search-active";function ci(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 cs({open:e,onClose:t,containerRef:r,index:i,renderedStart:s,renderedEnd:o,contentKey:l,onReveal:c,onProgrammaticScroll:d,focusRequest:u,t:p}){let h=(0,a.useRef)(null),[m,f]=(0,a.useState)(""),[g,x]=(0,a.useState)(null),[v,b]=(0,a.useState)({index:-1,total:0}),y=(0,a.useDeferredValue)(m),w=e?y.trim().toLowerCase():"",k=(0,a.useRef)(g);k.current=g;let j=(0,a.useRef)([]),S=(0,a.useRef)({key:null,needle:"",rendered:!1});(0,a.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,a.useEffect)(()=>()=>{ci(cn,[]),ci(ca,[])},[]),(0,a.useLayoutEffect)(()=>{let t=r.current;if(!e||!w||!t){ci(cn,[]),ci(ca,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let n=requestAnimationFrame(()=>{let e=function(e,t){let r=new Map,n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=n.nextNode();e;e=n.nextNode()){let n=e.parentElement?.closest("[data-chat-item]"),a=n?Number(n.dataset.chatItem):NaN;if(!Number.isInteger(a))continue;let i=(e.textContent??"").toLowerCase(),s=r.get(a);s||(s=[],r.set(a,s));for(let r=i.indexOf(t);-1!==r;r=i.indexOf(t,r+t.length)){let n=document.createRange();n.setStart(e,r),n.setEnd(e,r+t.length),s.push(n)}}return r}(t,w),r=new Map;for(let[t,n]of e)r.set(t,n.length);let n=function(e,t,r,n,a){let i=[];if(!t)return i;for(let s=0;s<e.length;s++){let o=s>=n&&s<a?r.get(s)??0:function(e,t){if(!t)return 0;let r=0;for(let n=e.indexOf(t);-1!==n;n=e.indexOf(t,n+t.length))r+=1;return r}(e[s],t);for(let e=0;e<o;e++)i.push({item:s,k:e})}return i}(i,w,r,s,o);j.current=n;let a=tc(n,k.current);b(e=>e.index===a&&e.total===n.length?e:{index:a,total:n.length});let l=[];for(let t of e.values())for(let e of t)l.push(e);if(ci(cn,l),a<0){ci(ca,[]),S.current={key:null,needle:w,rendered:!1};return}let u=n[a],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=s&&u.item<o,m=S.current,f=m.needle!==w||m.key?.item!==u.item||m.key?.k!==u.k||!m.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){ci(ca,[]),f&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(ci(ca,g?[g]:[]),f)if(d(),g){let e,r;e=g.getBoundingClientRect(),r=t.getBoundingClientRect(),e.height<=0||e.top>=r.top+48&&e.bottom<=r.bottom-48||(t.scrollTop+=e.top-r.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(n)},[e,w,i,s,o,l,g,r,c,d]);let C=(0,a.useCallback)(e=>{let t=j.current;if(0===t.length)return;let r=tc(t,k.current);x(t[(r+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,n.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,n.jsx)("input",{ref:h,type:"search",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,n.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,n.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M18 6 6 18"}),(0,n.jsx)("path",{d:"m6 6 12 12"})]})})]})}function co({questions:e,containerRef:t,layoutKey:r,onJump:i,label:s}){let o=(0,a.useRef)(null),[l,c]=(0,a.useState)(-1),[d,u]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=d&&e.length>=2;(0,a.useEffect)(()=>{let r=t.current;if(!r||!p)return;let n=0,a=null,i=()=>{n=0,a?.[0]?.isConnected||(a=r.querySelectorAll("[data-chat-item]"));let t=r.getBoundingClientRect().top+8,i=0,s=a.length-1,o=a.length-1;for(;i<=s;){let e=i+s>>1,r=a[e].firstElementChild?.getBoundingClientRect();r&&r.bottom>t?(o=e,s=e-1):i=e+1}let l=o>=0?Number(a[o].dataset.chatItem):-1,d=-1;for(let t of e){if(t.item>l)break;d=t.item}c(d)},s=()=>{n||(n=requestAnimationFrame(i))};return n=requestAnimationFrame(i),r.addEventListener("scroll",s,{passive:!0}),()=>{r.removeEventListener("scroll",s),n&&cancelAnimationFrame(n)}},[e,p,r,t]),(0,a.useEffect)(()=>{let e=o.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let r=t.offsetTop-e.scrollTop;(r<0||r+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[l]);let h=e.length,m=(0,a.useCallback)((e,t)=>{let r="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===r)return;e.preventDefault();let n=Math.max(0,Math.min(h-1,r));o.current?.querySelectorAll("button")[n]?.focus()},[h]);if(!p)return null;let f=e.some(e=>e.item===l)?l:e[0].item;return(0,n.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,n.jsx)("div",{ref:o,className:"question-rail-list",children:e.map((e,t)=>(0,n.jsx)(cl,{question:e,position:t,count:h,active:e.item===l,focusable:e.item===f,onJump:i,onMoveFocus:m},e.item))})})}let cl=(0,a.memo)(function({question:e,position:t,count:r,active:a,focusable:i,onJump:s,onMoveFocus:o}){let l=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,n.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:i?0:-1,"aria-current":a?"true":void 0,"aria-label":`${t+1}/${r} ${l}`,title:l,onClick:()=>s(e.item),onKeyDown:e=>o(e,t),children:(0,n.jsx)("span",{"aria-hidden":"true"})})});function cc({label:e,tone:t,children:r}){return(0,n.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"run-status-label",children:e}),(0,n.jsx)("span",{className:"run-status-text",children:r})]})}let cd={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function cu({compaction:e,t}){let[r,i]=(0,a.useState)(()=>Date.now());if((0,a.useEffect)(()=>{if(!e)return;i(Date.now());let t=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((r-e.startedAt)/1e3)),o=e.reason&&!0===cd[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,n.jsxs)(cc,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),o?` \xb7 ${o}`:""]})}function cp({onDismiss:e,t}){return(0,n.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,n.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,n.jsxs)("span",{className:"interrupted-run-text",children:[(0,n.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,n.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,n.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M18 6 6 18"}),(0,n.jsx)("path",{d:"m6 6 12 12"})]})})]})}var ch=r(39092),cm=r.n(ch);let cf=["01","02","03"];function cg(e){let t=0x811c9dc5;for(let r=0;r<e.length;r+=1)t=Math.imul(t^e.charCodeAt(r),0x1000193);return(t>>>0)/0x100000000}function cx(e,t,r){if(e&&"streaming"!==t){let n=nR(e);if(n){let e="failed"===t?"failed":"done",a=na(nr(n$(n),n.id,e)?.stickers??[],null,()=>cg(r));return a?{src:a,alt:r8[e]}:null}}if(!e||"streaming"===t||!r0.includes(e))return null;let n="failed"===t?"failed":"done",a=e.slice(0,e.indexOf("(")).toLowerCase(),i=na(cf.map(e=>`/stickers/${a}/${n}/${e}.webp`),null,()=>cg(r));return i?{src:i,alt:r8[n]}:null}let cv=new Map,cb=(0,a.createContext)(cv);function cy({utterances:e,children:t}){return(0,n.jsx)(cb.Provider,{value:e,children:t})}function cw({turnIndex:e,turnEntryId:t,sessionId:r,cwd:i,onOpenFile:s}){let o=(0,a.useContext)(cb).get(e);return o&&0!==o.length?(0,n.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:o.map(e=>(0,n.jsx)(ck,{utterance:e,sessionId:r,cwd:i,onOpenFile:s},e.key))}):null}function ck({utterance:e,sessionId:t,cwd:r,onOpenFile:i}){let s=ah(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId,e.model),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(!1),u=(0,a.useRef)(null);(0,a.useLayoutEffect)(()=>{let e=u.current;e&&!o&&d(e.scrollHeight>e.clientHeight+1)},[e.text,o]);let p=e.text.trim().length>0,h=e.label?.trim(),m=s?.alias??h??nq(e.provider),f=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==f?`작업 \xb7 ${h}`:null,x=cx(s?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,n.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,n.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...s?{minHeight:40}:null},children:[s&&(0,n.jsx)(ax,{seed:s.seed,size:40,provider:e.provider}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,n.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,n.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,n.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,n.jsx)(rb,{isStreaming:"streaming"===e.status,cwd:r,onOpenFile:i,children:e.text})}):(0,n.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(c||o)&&(0,n.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:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:o?"접기":"더보기"}),x&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-e0a9ca790f024efb inline-utterance-sticker"}),(0,n.jsx)(cm(),{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 cj=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function cS(e,t,r,n){if("string"!=typeof r)return[];let a=cj.exec(r),i=a?.[1],s=a?.[2];return i&&s?[{toolCallId:e,...t?{name:t}:{},alias:i,model:s,batchSize:n}]:[]}function cC(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let r of e.content??[]){if("toolCall"!==r.type||"task"!==r.toolName)continue;let e=r.input,n=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...cS(r.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,n)),Array.isArray(e.tasks))for(let a of e.tasks)!a||"object"!=typeof a||Array.isArray(a)||t.push(...cS(r.toolCallId,"name"in a&&"string"==typeof a.name?a.name:void 0,"task"in a?a.task:void 0,n))}return t}function cN(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let r of e.content??[])"toolCall"===r.type&&"task"===r.toolName&&t.push(r.toolCallId);return t}let cT=/^agent:\/\/([^/?#]+)\/?$/i;function cI(e,t){if(!e||"assistant"!==e.role)return[];let r=[];for(let n of e.content??[]){if("toolCall"!==n.type||"write"!==n.toolName)continue;let e=n.input,a="string"==typeof e.path?cT.exec(e.path):null,i=a?.[1],s=e.content;if(!i||"string"!=typeof s)continue;let o=t?.get(n.toolCallId);r.push({toolCallId:n.toolCallId,to:i,message:s,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return r}function cM(e,t,r){for(let n of["string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",t?.model.trim()??""]){let e=n.indexOf("/");if(e>0&&n.slice(0,e)===r)return n.slice(e+1).trim()||void 0}}let cE=["greeting","utterance","message","text"],c$=function(e){let t=(0,a.useMemo)(()=>aW(),[]),r=function(e,t){let[r,n]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(!t)return void n(null);let r=!1,a=new AbortController;return n(null),e.getArchive(t,a.signal).then(e=>{r||n(e)}).catch(()=>{}),()=>{r=!0,a.abort()}},[e,t]),r}(t,e.sessionId),n=(0,a.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),n=[];if(r&&r.sessionId===e.sessionId){let a=e.turns.flatMap(e=>e.characterSummons);for(let i of r.subagents){if(t.has(i.name))continue;let r=[...a].reverse().find(e=>e.name===i.name);r&&n.push(function(e,t,r){let n=e.status??"unknown",a={id:e.name,index:r,agent:"",agentSource:"bundled",status:n,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},i="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!==i||void 0!==s)&&(a.progress={index:r,id:e.name,agent:"",status:n,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==i?{resolvedModel:i,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),a}(i,r,e.subagents.length+n.length))}}return function(e,t){let r=new Map;for(let t of e)for(let e of t.characterSummons){let n=r.get(e.toolCallId)??{turnIndex:t.index,requests:[]};n.requests.push(e),r.set(e.toolCallId,n)}return t.flatMap(t=>{let n=t.parentToolCallId?r.get(t.parentToolCallId):void 0;if(!n)return[];let a=n.requests.filter(e=>e.name),i="string"==typeof t.task?cj.exec(t.task):null,s=i?.[1],o=i?.[2],l=a.find(e=>e.name===t.id)??(s&&o?n.requests.find(e=>e.alias===s&&e.model===o):void 0)??(1===n.requests.length&&1===n.requests[0].batchSize?n.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:n.turnIndex,summon:l,sends:c}]})}(e.turns,[...e.subagents,...n])},[e.subagents,e.turns,e.sessionId,r]),i=(0,a.useMemo)(()=>n.map(({snapshot:t})=>{let r=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:r}:{key:t.id,status:t.status,archiveName:r}}),[n,e.subagents]),s=s3(i,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&i.length>0});return(0,a.useMemo)(()=>n.flatMap(t=>(function(e,t,r){var n;let{snapshot:a,summon:i}=e,s="completed"===(n=a.status)||"unknown"===n?"settled":"failed"===n||"aborted"===n?"failed":"streaming",o="failed"===s,l=i?.model.split("/",1)[0]?.trim()||void 0,c=o&&l?l:function(e,t,r){let n="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",a=n.indexOf("/");if(a>0)return n.slice(0,a);let i=t?.model.trim()??"",s=i.indexOf("/");return s>0?i.slice(0,s):r?.trim()||void 0}(a,i,r),d=a.id.trim()||void 0,u=`subagent:${a.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,r)=>{var n;let f;if("irc"in t){let{from:r,message:n,truncated:i}=t.irc;if(i||"string"!=typeof r||"string"!=typeof n)return;for(let t=m;t<e.sends.length;t+=1){let i=e.sends[t];if(i.send.message===n&&function(e,t){if(!e.from)return!1;let r=e.receipts;return!!r&&r.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(i.send,a.id)&&i.send.from===r){h=i.turnIndex,m=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=((f=((n=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let r of e.content??[]){if("toolCall"!==r.type||"yield"!==r.toolName)continue;let e=r.input.data,n="";if("string"==typeof e)n=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...cE]){let r=e[t];if("string"==typeof r&&r.trim().length>0){n=r;break}}let a=n.trim();a.length>0&&(t=a)}return t}(n))||(o?t.message.errorMessage?.trim()??"":"");if(0===x.length)return;let v=t.message.model||cM(a,i,g);p.push({key:`${a.id}:${r}`,turnIndex:h,speakerId:u,provider:g,...v?{model:v}:{},credentialId:t.message.credentialId,accountSessionId:null,label:o&&i?i.alias:d,text:x,status:s})}),0===p.length&&"settled"!==s&&c){let e=o?a.progress?.retryFailure?.errorMessage?.trim():void 0,t=cM(a,i,c);p.push({key:`${a.id}:pending`,turnIndex:h,speakerId:u,provider:c,...t?{model:t}:{},accountSessionId:null,label:o&&i?i.alias:d,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[n,s,e.sessionProvider])},cR="web6",cL=[],cA=[],cP=function(e){let t=(0,a.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(r,n){let a=r.trim();if(!a)throw Error("sessionId가 필요하다");let i=`${t}?sessionId=${encodeURIComponent(a)}`,s=await e(i,{signal:n});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 r=e.startedAt;if("number"!=typeof r||!Number.isFinite(r))return null;let n=e.status;if("ok"!==n&&"failed"!==n)return null;let a="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:r,{conversationId:i,text:s,error:o}=e;return{sessionId:t,startedAt:r,finishedAt:a,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:a-r,model:"string"==typeof e.model?e.model:"",status:n,conversationId:"string"==typeof i&&""!==i?i:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof o&&""!==o?o:void 0}}(e);return t?.sessionId===a?[t]:[]})}}})(),[]),[r,n]=(0,a.useState)(cA),i=(0,a.useRef)(""),s=e.sessionId??"",o=s.length>0;return(0,a.useEffect)(()=>{if(!o){i.current="",n(cA);return}let e=new AbortController,r=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let r=await t.listConsults(s,e.signal),a=r.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(a===i.current)return;i.current=a,n(r)}catch{}};r();let a=setInterval(()=>void r(),5e3);return()=>{e.abort(),clearInterval(a)}},[t,o,s]),(0,a.useMemo)(()=>(function(e,t,r){if(0===e.length)return cL;let n=function(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e[r];if("user"!==n.role)continue;let a=n.timestamp;"number"==typeof a&&Number.isFinite(a)&&t.push({index:r,openedAt:a})}return t}(t);if(0===n.length)return cL;let a=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==r||"failed"!==t.status)continue;let e=function(e,t){let r;for(let n of e)n.openedAt>t||(!r||n.openedAt>=r.openedAt)&&(r=n);return r?.index}(n,t.startedAt);if(void 0===e)continue;let i=t.error??"";0!==i.trim().length&&a.push({key:`${cR}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${cR}:${t.conversationId??"unknown"}`,text:i,status:"failed"})}return a.length>0?a:cL})(r,e.messages,s),[r,e.messages,s])},cF="lab:";function c_(e){return e.startsWith(cF)?e.slice(cF.length).split(":",1)[0]||null:null}let cz={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function cW(e){return e.multi&&e.options.length>1}function cO(e){return"text"===e.kind?{kind:"text",text:e.value}:{kind:"choice",checked:e.options.flatMap((e,t)=>e.checked?[t]:[]),otherOn:!1,other:""}}function cD(e,t){let r={};for(let[t,n]of e.hidden)cq(r,t,n);return e.fields.forEach((e,n)=>{let a=t[n];if(!e.name||!a)return;let i=function(e,t){if("text"===e.kind){var r,n,a="text"===t.kind?t.text:"";if(("number"===e.type||"range"===e.type)&&""!==a.trim()){let e=Number(a);if(Number.isFinite(e))return e}return a}if("choice"===t.kind){let a,i;return r=new Set(t.checked),n=t.otherOn?t.other:void 0,a=e.other?n?.trim():void 0,i=e.options.flatMap((e,t)=>r.has(t)&&!e.disabled?[e.value]:[]),cW(e)?a?[...i,a]:i:a||i[0]}}(e,a);void 0!==i&&cq(r,e.name,i)}),r}function cH(e,t){let r={};for(let n of e.fields){if(!n.name||cV(r,n.name))continue;let e=function(e,t){if("choice"===e.kind){let r=void 0===t||Array.isArray(t)&&0===t.length;if(!e.required||!r)return;return cW(e)?{code:"selectAtLeastOne"}:{code:"required"}}let r=void 0===t?"":String(t);if(""===r.trim())return e.required?{code:"required"}:void 0;if("number"===e.type||"range"===e.type){let t=Number(r);if(!Number.isFinite(t))return{code:"enterNumber"};if(void 0!==e.min&&t<e.min)return{code:"min",value:e.min};if(void 0!==e.max&&t>e.max)return{code:"max",value:e.max}}return void 0!==e.minLength&&r.length<e.minLength?{code:"minLength",value:e.minLength}:void 0!==e.maxLength&&r.length>e.maxLength?{code:"maxLength",value:e.maxLength}:"email"!==e.type||/^[^\s@]+@[^\s@]+$/.test(r)?"url"!==e.type||URL.canParse(r)?e.pattern&&(function(e){try{return RegExp(`^(?:${e})$`,"v")}catch{return}})(e.pattern)?.test(r)===!1?{code:"pattern",pattern:e.pattern.length>40?`${e.pattern.slice(0,39)}…`:e.pattern}:void 0:{code:"url"}:{code:"email"}}(n,cV(t,n.name));e&&cq(r,n.name,e)}return r}function cU(e){return e.map(e=>e.text).join("")}function cB(e,t,r){if(!e.multi)return{...t,checked:[r],otherOn:!1};let n=t.checked.includes(r)?t.checked.filter(e=>e!==r):[...t.checked,r].sort((e,t)=>e-t);return{...t,checked:n}}function cq(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0})}function cV(e,t){return Object.hasOwn(e,t)?e[t]:void 0}let cK={text:!0,search:!0,tel:!0,url:!0,email:!0,number:!0,password:!0,date:!0,time:!0,"datetime-local":!0,month:!0,week:!0,color:!0,range:!0},cG={width:"100%",minWidth:0,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)"},cJ={minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"};function cZ({spans:e}){return(0,n.jsx)(n.Fragment,{children:e.map((e,t)=>{let r=[];return(e.text.split("\n").forEach((e,t)=>{t>0&&r.push((0,n.jsx)("br",{},`br-${t}`)),r.push(e)}),"code"===e.style)?(0,n.jsx)("code",{style:{padding:"0 4px",borderRadius:4,background:"var(--bg-subtle)",fontFamily:"var(--font-mono)",fontSize:"0.92em"},children:r},t):"strong"===e.style?(0,n.jsx)("strong",{style:{fontWeight:600},children:r},t):"em"===e.style?(0,n.jsx)("em",{children:r},t):(0,n.jsx)("span",{children:r},t)})})}function cY({src:e,alt:t}){let{t:r}=(0,z.s)(),[i,s]=(0,a.useState)(!1);return!e||i?(0,n.jsx)("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",overflowWrap:"anywhere"},children:t||r("chat.formImageUnavailable")}):(0,n.jsx)("img",{src:e,alt:t,onError:()=>s(!0),style:{display:"block",maxWidth:"100%",maxHeight:320,height:"auto",objectFit:"contain",borderRadius:"var(--radius-control)"}})}function cX({block:e,id:t}){let r={margin:0,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.55,overflowWrap:"anywhere"};switch(e.kind){case"text":return(0,n.jsx)("p",{id:t,style:{...r,fontWeight:e.heading?600:400},children:(0,n.jsx)(cZ,{spans:e.spans})});case"list":{let t=e.ordered?"ol":"ul";return(0,n.jsx)(t,{style:{...r,paddingInlineStart:22},children:e.items.map((e,t)=>(0,n.jsx)("li",{children:(0,n.jsx)(cZ,{spans:e})},t))})}case"pre":return(0,n.jsx)("pre",{tabIndex:0,style:{margin:0,padding:"8px 10px",overflowX:"auto",maxWidth:"100%",border:"1px solid var(--hairline)",borderRadius:"var(--radius-control)",background:"var(--bg-subtle)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5},children:e.text});case"table":return(0,n.jsx)("div",{tabIndex:0,style:{maxWidth:"100%",overflowX:"auto",border:"1px solid var(--hairline)",borderRadius:"var(--radius-control)"},children:(0,n.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:(0,n.jsx)("tbody",{children:e.rows.map((t,r)=>(0,n.jsx)("tr",{children:t.map((t,a)=>{let i=r<e.headerRows?"th":"td";return(0,n.jsx)(i,{scope:r<e.headerRows?"col":void 0,style:{padding:"6px 10px",borderBottom:"1px solid var(--hairline)",color:r<e.headerRows?"var(--text-muted)":"var(--text)",fontWeight:r<e.headerRows?600:400,textAlign:"left",verticalAlign:"top",minWidth:72},children:(0,n.jsx)(cZ,{spans:t})},a)})},r))})})});case"image":return(0,n.jsx)(cY,{src:e.src,alt:e.alt})}}function cQ({field:e,id:t,index:r,error:a,children:i,hasLabel:s}){let{t:o}=(0,z.s)();return(0,n.jsxs)("div",{"data-field":r,style:{display:"grid",gap:6,minWidth:0},children:[(s||e.required)&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[s&&(0,n.jsx)("label",{id:`${t}-label`,htmlFor:"text"===e.kind||e.select?t:void 0,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:(0,n.jsx)(cZ,{spans:e.label})}),e.required&&(0,n.jsx)("span",{style:{marginLeft:s?0:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:o("chat.formRequired")})]}),i,a&&(0,n.jsxs)("p",{id:`${t}-error`,style:{margin:0,display:"flex",alignItems:"flex-start",gap:6,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:500,lineHeight:1.45},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",style:{flex:"none",marginTop:2},children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"5.5"}),(0,n.jsx)("path",{d:"M7 4v3.4M7 9.6v.1"})]}),(0,n.jsx)("span",{children:function(e,t){switch(e.code){case"min":case"max":case"minLength":case"maxLength":return t(`chat.formError.${e.code}`,{value:e.value});case"pattern":return t("chat.formError.pattern",{pattern:e.pattern});default:return t(`chat.formError.${e.code}`)}}(a,o)})]})]})}function c0({field:e,id:t,index:r,state:i,error:s,captionId:o,fallbackName:l,onChange:c}){let{t:d}=(0,z.s)(),u=(0,a.useRef)(null);if("choice"!==i.kind)return null;let p=e.label.length>0,h={"aria-labelledby":p?`${t}-label`:o,"aria-label":p||o?void 0:l,"aria-required":e.required||void 0,"aria-invalid":!!s||void 0,"aria-describedby":s?`${t}-error`:void 0};if(e.select&&!e.multi)return(0,n.jsx)(cQ,{field:e,id:t,index:r,error:s,hasLabel:p,children:(0,n.jsx)("select",{id:t,...h,value:String(i.checked[0]??""),onChange:t=>c(r,cB(e,i,Number(t.target.value))),style:{...cG,height:36},children:e.options.map((e,t)=>(0,n.jsx)("option",{value:t,disabled:e.disabled,children:cU(e.label)},t))})});let m=e.multi?"checkbox":"radio",f=(e,t)=>({display:"grid",gridTemplateColumns:"16px minmax(0, 1fr)",alignItems:"start",gap:9,minHeight:40,padding:"9px 10px",border:`1px solid ${e?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:e?"var(--bg-selected)":"transparent",color:t?"var(--text-dim)":"var(--text)",cursor:t?"not-allowed":"pointer",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5,overflowWrap:"anywhere"}),g={width:16,height:16,margin:"3px 0 0",accentColor:"var(--seed-color-fg-neutral)"},x=`${t}-choice`;return(0,n.jsx)(cQ,{field:e,id:t,index:r,error:s,hasLabel:p,children:(0,n.jsxs)("div",{role:e.multi?"group":"radiogroup",...h,style:{display:"grid",gap:4},children:[e.options.map((t,a)=>{let s=i.checked.includes(a);return(0,n.jsxs)("label",{style:f(s,t.disabled),children:[(0,n.jsx)("input",{type:m,name:x,checked:s,disabled:t.disabled,"aria-required":!!e.required&&!e.multi||void 0,onChange:()=>c(r,cB(e,i,a)),style:g}),(0,n.jsx)("span",{children:(0,n.jsx)(cZ,{spans:t.label})})]},a)}),e.other&&(0,n.jsxs)("div",{style:{display:"grid",gap:6},children:[(0,n.jsxs)("label",{style:f(i.otherOn,!1),children:[(0,n.jsx)("input",{type:m,name:x,checked:i.otherOn,onChange:()=>{c(r,e.multi?{...i,otherOn:!i.otherOn}:{...i,checked:[],otherOn:!0}),i.otherOn&&e.multi||u.current?.focus()},style:g}),(0,n.jsx)("span",{children:d("chat.formOther")})]}),(0,n.jsx)("input",{ref:u,type:"text",value:i.other,"aria-label":d("chat.formOther"),placeholder:d("chat.formOtherPlaceholder"),onChange:t=>{var n;let a;return c(r,(a=""!==(n=t.target.value).trim(),{...i,other:n,otherOn:!!a||i.otherOn,checked:a&&!e.multi?[]:i.checked}))},style:{...cG,height:36,width:"calc(100% - 35px)",marginInlineStart:35}})]})]})})}function c1({field:e,id:t,index:r,state:a,error:i,captionId:s,fallbackName:o,onChange:l}){if("text"!==a.kind)return null;let c=e.label.length>0,d=Object.hasOwn(cK,e.type)?e.type:"text",u={id:t,value:a.text,placeholder:e.placeholder||void 0,"aria-labelledby":c?void 0:s,"aria-label":c||s?void 0:o,"aria-required":e.required||void 0,"aria-invalid":!!i||void 0,"aria-describedby":i?`${t}-error`:void 0},p=i?"1px solid var(--danger)":cG.border;return(0,n.jsx)(cQ,{field:e,id:t,index:r,error:i,hasLabel:c,children:e.multiline?(0,n.jsx)("textarea",{...u,rows:Math.max(2,e.rows),onChange:e=>l(r,{kind:"text",text:e.target.value}),style:{...cG,padding:"8px 10px",border:p,lineHeight:1.5,resize:"vertical"}}):(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("input",{...u,type:d,min:"number"===d||"range"===d?e.min:void 0,max:"number"===d||"range"===d?e.max:void 0,step:"number"===d?"any":void 0,onChange:e=>l(r,{kind:"text",text:e.target.value}),style:{...cG,height:"color"===d?40:36,border:p,..."range"===d?{padding:0}:{},fontVariantNumeric:"tabular-nums"}}),"range"===d&&(0,n.jsx)("output",{htmlFor:t,style:{minWidth:32,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:a.text})]})})}function c2({request:e,onRespond:t,onActivity:r,delivery:i}){let{t:s}=(0,z.s)(),o=(0,a.useId)(),l=e.form,[c,d]=(0,a.useState)(()=>l.fields.map(cO)),u=(0,a.useRef)(c),[p,h]=(0,a.useState)(!1),m=(0,a.useRef)(null),f=(0,a.useRef)(r);f.current=r;let g=(0,a.useRef)(e);g.current=e;let x=i?.status==="sending",v=(0,a.useRef)(null);if(null===v.current){let e=Array.from(crypto.getRandomValues(new Uint8Array(12)),e=>e.toString(16).padStart(2,"0")).join(""),t=0;v.current=function(e,t=cz){let r,n=-1/0,a=!1,i=()=>{a&&t.clearTimeout(r),a=!1,n=t.now(),e()};return{notify(){let e=1e3-(t.now()-n);e<=0?i():a||(a=!0,r=t.setTimeout(i,e))},cancel(){a&&t.clearTimeout(r),a=!1}}}(()=>{var r,n;let a=g.current;t+=1,f.current?.(a,(r=t,n=cD(a.form,u.current),`activity:form:v2:${e}:${r}:${JSON.stringify(n)}`))})}(0,a.useEffect)(()=>()=>v.current?.cancel(),[]);let b=(0,a.useCallback)((e,t)=>{let r=u.current.slice();r[e]=t,u.current=r,d(r),g.current.timeout&&f.current&&v.current?.notify()},[]),y=cD(l,c),w=p?cH(l,y):{},k=Object.keys(w).length>0,j=()=>{if(x)return;let r=cD(l,u.current),n=cH(l,r);if(Object.keys(n).length>0){h(!0);let e=l.fields.findIndex(e=>""!==e.name&&void 0!==cV(n,e.name));m.current?.querySelector(`[data-field="${e}"] input, [data-field="${e}"] select, [data-field="${e}"] textarea`)?.focus();return}t(e,{value:JSON.stringify(r)})};return(0,n.jsxs)("div",{"data-ask-form":"",style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentFormHint")}),e.timeout?(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askFormAutoSubmitHint",{seconds:Math.round(e.timeout/1e3)})}):null]}),(0,n.jsx)("div",{ref:m,onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&j()},style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:16},children:(0,n.jsx)("div",{style:{display:"grid",gap:20,minWidth:0},children:l.sections.map((e,t)=>{let r,a=cU(e.title);return(0,n.jsxs)("section",{"aria-labelledby":a?`${o}-s${t}`:void 0,style:{display:"grid",gap:12,minWidth:0,paddingTop:20*(0!==t),borderTop:0===t?"none":"1px solid var(--hairline)"},children:[a&&(0,n.jsx)("h3",{id:`${o}-s${t}`,style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600,lineHeight:1.4},children:(0,n.jsx)(cZ,{spans:e.title})}),e.blocks.map((e,i)=>{var s;let d;if("field"!==e.kind){let a=`${o}-s${t}b${i}`;return r="text"===e.kind?a:void 0,(0,n.jsx)(cX,{block:e,id:a},i)}let u=l.fields[e.index],h=r;r=void 0;let m=(s=e.index,d=l.fields[s],{id:`${o}-f${s}`,index:s,state:c[s],error:p&&d.name?cV(w,d.name):void 0,captionId:h,fallbackName:a||d.name,onChange:b});return"choice"===u.kind?(0,n.jsx)(c0,{...m,field:u},i):(0,n.jsx)(c1,{...m,field:u},i)})]},t)})})}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[k&&(0,n.jsx)("p",{role:"alert",style:{margin:0,marginRight:"auto",color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.formInvalid")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:cJ,children:s("chat.cancel")}),(0,n.jsx)("button",{type:"button","aria-disabled":x||void 0,onClick:j,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:x?"var(--seed-color-bg-disabled)":"var(--seed-color-bg-neutral-inverted)",color:x?"var(--seed-color-fg-disabled)":"var(--seed-color-fg-neutral-inverted)",cursor:x?"not-allowed":"pointer",fontWeight:600},children:s(x?"chat.responseSending":"chat.submitAnswer")})]})]})}let c8={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},c4={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function c5({rows:e,removeLabel:t,onRemove:r}){let i,{st:s}=ag(),[o,l]=(0,a.useState)(!1),{rows:c,hidden:d}=(i=Math.max(0,e.length-4),o||0===i?{rows:e,hidden:i}:{rows:e.slice(i),hidden:i}),u=e.length>4;return(0,a.useEffect)(()=>{u||l(!1)},[u]),(0,n.jsxs)(n.Fragment,{children:[u&&(0,n.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,n.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:c.map(e=>{let a=lu(e.text),i=[a?[a.message,a.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,n.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,n.jsx)("span",{className:"answer-delivery-kind",children:s(c8[e.kind])}),(0,n.jsx)("span",{className:"answer-delivery-text",title:i,children:i}),(0,n.jsx)("span",{className:"answer-delivery-stage",children:s(c4[e.stage])}),e.removable&&r&&(0,n.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${i}`,onClick:()=>r(e.kind,e.text),children:(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}async function c6(e,t){let r=await fetch(e,{cache:"no-store",...t}),n=await r.json();if(!r.ok)throw Error(n.error||`HTTP ${r.status}`);return n}let c3=(0,a.forwardRef)(function({value:e,token:t,cwd:r,sessionTitle:i,style:s,maxHeight:o,onReplace:l,onClose:c},d){let{t:u}=(0,z.s)(),[p,h]=(0,a.useState)([]),[m,f]=(0,a.useState)(!0),[g,x]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null),[y,w]=(0,a.useState)(null),[k,j]=(0,a.useState)(-1),S=(0,a.useRef)([]),C=t.query.toLowerCase(),N=p.filter(e=>`${e.title}
|
|
18
|
+
${e.body}`.toLowerCase().includes(C)),T=e.slice(0,t.start)+e.slice(t.end),I=!!T.trim(),M=N.length+ +!!I,E=(0,a.useCallback)(async()=>{h((await c6("/api/saved-prompts")).prompts)},[]);(0,a.useEffect)(()=>{let e=!1;return c6("/api/saved-prompts").then(t=>{e||h(t.prompts)}).catch(t=>{e||b(String(t.message??t))}).finally(()=>{e||f(!1)}),()=>{e=!0}},[]),(0,a.useEffect)(()=>{j(N.length>0?0:-1),w(null)},[C,p,N.length,I]),(0,a.useEffect)(()=>{S.current[k]?.scrollIntoView({block:"nearest"})},[k]);let $=n=>{var a,s;let o=new Date,c=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`,d=(a=n.body,s={project_name:r?.replace(/[\\/]+$/,"").split(/[\\/]/).pop(),cwd:r,session_name:i,date:c},a.replace(/\{\{\s*([a-zA-Z_][\w]*)\s*\}\}/g,(e,t)=>(Object.hasOwn(s,t)?s[t]:void 0)||e));l(e,e.slice(0,t.start)+d+e.slice(t.end),t.start+d.length)},R=async()=>{if(!g&&I){x(!0),b(null);try{await c6("/api/saved-prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:T})}),l(e,T,t.start,!0),await E()}catch(e){b(e instanceof Error?e.message:String(e))}finally{x(!1)}}},L=async e=>{if(!g){if(y!==e)return void w(e);x(!0),b(null);try{await c6(`/api/saved-prompts/${encodeURIComponent(e)}`,{method:"DELETE"}),h(t=>t.filter(t=>t.id!==e)),w(null),await E()}catch(e){b(e instanceof Error?e.message:String(e))}finally{x(!1)}}};(0,a.useImperativeHandle)(d,()=>({handleKeyDown(e){if("Escape"===e.key)return c(),e.preventDefault(),!0;if(("ArrowDown"===e.key||"ArrowUp"===e.key)&&M>0)return e.preventDefault(),j(t=>"ArrowDown"===e.key?Math.min(M-1,t+1):t<0?M-1:Math.max(0,t-1)),!0;if("Tab"===e.key||"Enter"===e.key&&!e.shiftKey){if(k>=0&&k<M)return e.preventDefault(),g||(N[k]?$(N[k]):R()),!0;"Enter"===e.key&&c()}return!1}}));let A=e=>({width:"100%",minWidth:0,minHeight:44,border:"none",borderRadius:"var(--radius-control)",padding:"8px",background:e?"var(--bg-selected)":"none",color:"var(--text)",textAlign:"left",cursor:"pointer",fontSize:12});return(0,n.jsxs)("div",{id:"saved-prompt-menu",role:"region","aria-label":u("savedPrompts.title"),"data-saved-prompt-menu":"",onMouseDown:e=>e.preventDefault(),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),c())},style:{position:"absolute",left:0,right:0,zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",display:"flex",flexDirection:"column",overflow:"hidden",maxHeight:o,...s},children:[(0,n.jsx)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",flexShrink:0},children:m?u("savedPrompts.loading"):u("savedPrompts.title")}),(0,n.jsxs)("div",{style:{overflowY:"auto",minHeight:0,padding:4},children:[!m&&0===N.length&&(0,n.jsx)("div",{style:{padding:8,fontSize:12,color:"var(--text-dim)"},children:u("savedPrompts.empty")}),N.map((e,t)=>(0,n.jsxs)("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[(0,n.jsxs)("button",{type:"button",ref:e=>{S.current[t]=e},disabled:g,"data-saved-prompt-id":e.id,onClick:()=>$(e),onMouseEnter:()=>j(t),style:A(t===k),children:[(0,n.jsx)("span",{style:{display:"block",overflowWrap:"anywhere"},children:e.title}),(0,n.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:e.body.replace(/\s+/g," ")})]}),(0,n.jsx)("button",{type:"button",disabled:g,"data-delete-prompt":e.id,"aria-label":`${u("savedPrompts.delete")}: ${e.title}`,onClick:()=>void L(e.id),style:{...A(!1),width:"auto",flexShrink:0,color:"var(--danger, var(--text))"},children:u(y===e.id?"savedPrompts.confirmDelete":"savedPrompts.delete")}),y===e.id&&(0,n.jsx)("button",{type:"button",onClick:()=>w(null),style:{...A(!1),width:"auto",flexShrink:0},children:u("savedPrompts.cancel")})]},e.id)),I&&(0,n.jsx)("button",{type:"button","data-save-current-prompt":"",disabled:g||m,ref:e=>{S.current[N.length]=e},onClick:()=>void R(),onMouseEnter:()=>j(N.length),style:A(k===N.length),children:u("savedPrompts.save")})]}),v&&(0,n.jsx)("div",{role:"alert",style:{padding:"6px 10px",fontSize:12,color:"var(--danger, var(--text))",overflowWrap:"anywhere"},children:u("savedPrompts.error",{error:v})}),(0,n.jsx)("div",{style:{padding:"6px 10px",fontSize:10,color:"var(--text-dim)",borderTop:"1px solid var(--border)",overflowWrap:"anywhere",overflowY:"auto",flexShrink:0,maxHeight:"40%"},children:u("savedPrompts.hint")})]})}),c7=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),c9=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function de({soundEnabled:e,onToggle:t}){let r=e?"완료음 끄기":"완료음 켜기";return(0,n.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,n.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:r,"aria-label":r,children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?c7:c9})})})}let dt=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),dr=["normal","slow"],dn={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function da(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:r}=Promise.withResolvers(),n=()=>{clearTimeout(i),e.removeEventListener("icegatheringstatechange",a),r()},a=()=>{"complete"===e.iceGatheringState&&n()},i=setTimeout(n,3e3);return e.addEventListener("icegatheringstatechange",a),t}function di(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let ds={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},dl=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,n.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,n.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),dc=(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function dd({sessionId:e,onEnsureSession:t,onTranscriptPersisted:r}){let{t:i}=(0,z.s)(),s=function(e,t,r){let{locale:n}=(0,z.s)(),[i,s]=(0,a.useState)("idle"),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),x=(0,a.useRef)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null),y=(0,a.useRef)(null),w=(0,a.useRef)(null),k=(0,a.useRef)(0);(0,a.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,a.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,y.current?.close(),y.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let r=b.current;b.current=null,r&&(r.srcObject=null,r.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,a.useCallback)((e,t)=>{l(e),d(t??null),j("error")},[j]),C=(0,a.useCallback)(async()=>{let a,i=k.current+1;k.current=i,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!==i)return}if(!o){k.current===i&&(g(!1),S("failed"));return}try{a=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===i&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==i){for(let e of a.getTracks())e.stop();return}v.current=a;try{let e,t,l=new RTCPeerConnection;for(let e of(x.current=l,a.getTracks()))l.addTrack(e,a);let c=document.createElement("audio");if(c.autoplay=!0,b.current=c,l.ontrack=e=>{let[t]=e.streams;t&&(c.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await da(l),k.current!==i)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:n})}),h=await u.json().catch(()=>({})),m="",f="";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&&(m=h.callId),"sdp"in h&&"string"==typeof h.sdp&&(f=h.sdp)),!u.ok||!m||!f){k.current===i&&(g(!1),S(di(u.status,e),t));return}if(k.current!==i)return void fetch(`/api/live/call/${encodeURIComponent(m)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:f}),k.current!==i){l.close(),fetch(`/api/live/call/${encodeURIComponent(m)}`,{method:"DELETE"}).catch(()=>{});return}w.current=m;let v=new EventSource(`/api/live/events?callId=${encodeURIComponent(m)}`);y.current=v,v.onmessage=e=>{let t;if(k.current===i){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var n;if("string"!=typeof t.state||(n=t.state,!0!==dn[n]))return;"closed"===t.state?j("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&r&&Promise.resolve().then(()=>r(o)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&dt.test(e)&&j("idle")}return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},v.onerror=()=>{k.current===i&&w.current&&S("failed")},s("live")}catch(e){k.current===i&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===i&&g(!1)}},[e,t,r,n,S,j]),N=(0,a.useCallback)(()=>{if("idle"===i||"closed"===i||"error"===i){f||C();return}j("idle")},[f,i,C,j]);return(0,a.useEffect)(()=>()=>j("closed"),[j]),{state:i,failure:o,detail:c,transcript:u,supported:h,toggle:N}}(e,t,r),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=i(o?"chat.liveStop":"chat.liveStart"),d=!1===s.supported?ds.unsupported:s.failure?ds[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,n.jsxs)("div",{role:"group","aria-label":i("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[d&&(0,n.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:i(d)}),l&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i(l)}),(0,n.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":o,title:p?i(p):c,"aria-label":p?i(p):c,children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o?dc:dl})})]})}let du={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 dp({sessionId:e}){let{t}=(0,z.s)(),[r,i]=(0,a.useState)(null);return((0,a.useEffect)(()=>{if(!e)return void i(null);let t=!1,r=0,n=!1,a=async()=>{if("visible"===document.visibilityState)try{let r=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!r.ok)return;let a=await r.json();if(t)return;let s=Array.isArray(a.handles)?a.handles:[],o=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;n=null!==o,i(o)}catch{}},s=async()=>{await a(),t||(r=window.setTimeout(()=>void s(),n?5e3:3e4))};return s(),document.addEventListener("visibilitychange",a),()=>{t=!0,window.clearTimeout(r),document.removeEventListener("visibilitychange",a)}},[e]),r)?(0,n.jsx)("span",{style:du,title:t("gpt6.boundBadgeHint",{handle:r}),children:t("gpt6.boundBadge",{handle:r})}):null}let dh=new Map,dm="ompweb-drafts-for-reload-v1",df=!1,dg=new Map,dx=new Map,dv="\0stale",db=new Map,dy=0,dw=new Map,dk=new Map,dj=new Map,dS=new Map,dC=new Map,dN=(e,t,r)=>lv(e,t,r.length?{sentAttachmentIds:r}:{}),dT=null,dI=!1;function dM(){if(df||"u"<typeof sessionStorage)return;df=!0;let e=sessionStorage.getItem(dm);if(e){sessionStorage.removeItem(dm);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)&&(dh.set(e[0],d$(t)),"string"==typeof t.draftId&&t.draftId&&(dg.set(e[0],t.draftId),dx.set(t.draftId,dv)),dO(e[0]))}}catch{}}}function dE(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(dm,JSON.stringify([...dh.entries()].map(([e,t])=>{let r=dg.get(e);return[e,r?{...d$(t),draftId:r}:d$(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function d$(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function dR(e){return!e.value&&0===e.images.length&&0===e.documents.length}function dL(e){dM();let t=dh.get(e);return t?d$(t):null}function dA(e,t){dM(),dR(t)?dh.delete(e):dh.set(e,d$(t)),dO(e)}function dP(e){dh.delete(e),dO(e)}function dF(e,t,r,n,a,i=[]){let s=[...t??[],...n].filter(rW).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=ll([...a??[],...i]);return{value:e.trim()?r.trim()?`${e}
|
|
19
|
+
|
|
20
|
+
${r}`:e:r,images:s,documents:o}}function d_(e,t,r){if(e===t)return r?d$(r):dL(t);let n=dL(e),a=r&&!dR(r)?d$(r):n??(r?d$(r):null),i=dL(t),s=dg.get(e);if(dg.delete(e),s&&!dg.has(t)&&dg.set(t,s),dP(e),!a)return i;let o=i?dF(i.value,i.images,a.value,a.images,i.documents,a.documents):a;return dA(t,o),d$(o)}function dz(e){let t=[];for(let r of e??[])r.attachmentId&&!t.includes(r.attachmentId)&&t.push(r.attachmentId);return t}function dW(e){dM();let t=dg.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let r=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}(),dg.set(e,t)),t}function dO(e){let t=dz(dh.get(e)?.documents),r=t.length?dW(e):dg.get(e);for(let[e,r]of dk){for(let e of t)r.delete(e);0===r.size&&dk.delete(e)}let n=`${r??""}|${t.join(",")}`;dS.get(e)!==n&&(0!==t.length||r?dS.set(e,n):dS.delete(e),dK())}async function dD(e){let t=dW(e);dw.set(t,(dw.get(t)??0)+1),await dC.get(t);let r=!1;return{draftId:t,end(e){if(r)return;r=!0;let n=(dw.get(t)??1)-1;if(n>0?dw.set(t,n):dw.delete(t),e){let r=dk.get(t)??new Set;r.add(e),dk.set(t,r)}dx.set(t,dv),dK()}}}function dH(e,t){let r=dj.get(e);if(!r)return[];for(let e of t)r.delete(e);return 0===r.size&&dj.delete(e),[...r].sort()}async function dU(){if(!dN)return;let e=[...function(){let e=new Map,t=(t,r)=>{let n=e.get(t)??new Set;for(let e of r)n.add(e);e.set(t,n)};for(let[e,r]of dg)t(r,dz(dh.get(e)?.documents));for(let{draftId:e,ids:r}of db.values())t(e,r);for(let[e,r]of dk)t(e,r);for(let e of dx.keys())t(e,[]);for(let e of dj.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dw.has(e))return!1;let r=dx.get(e);return dH(e,t).length>0||(0===t.length?void 0!==r:r!==t.join(","))}),t=dw.size>0,r=!1;for(let[n,a]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===a.length&&t)continue;let e=dH(n,a),i=dN(n,a,e).then(()=>{0===a.length?dx.delete(n):dx.set(n,a.join(","));let t=dj.get(n);if(t){for(let r of e)t.delete(r);0===t.size&&dj.delete(n)}},()=>{r=!0,a.length>0&&(t=!0)});dC.set(n,i),await i,dC.get(n)===i&&dC.delete(n)}r?function(){if(dV)return;dV=!0;let e=setTimeout(()=>{dV=!1,dK()},dq);"object"==typeof e&&"unref"in e&&e.unref(),dq=Math.min(2*dq,6e4)}():dq=dB}let dB=5e3,dq=5e3,dV=!1;function dK(){if(dN){if(dT){dI=!0;return}dT=Promise.resolve().then(dU).finally(()=>{dT=null,dI&&(dI=!1,dK())})}}let dG=Math.floor(Number.MAX_SAFE_INTEGER/1048576),dJ=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function dZ(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=dG}async function dY(e){let t,r=await e.json().catch(()=>null);if(!e.ok||!r||!dZ(r.uploadLimitMb)||"boolean"!=typeof r.autoCleanupEnabled)throw Error("string"==typeof r?.error?r.error:`HTTP ${e.status}`);return{uploadLimitMb:dZ((t=r&&"object"==typeof r?r:{}).uploadLimitMb)?t.uploadLimitMb:dJ.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:dJ.autoCleanupEnabled,orphanGraceDays:7}}async function dX(e={}){return dY(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function dQ(e){return dY(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function d0(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let r=/(?:^|\s)@([^\s"]*)$/.exec(e);return r?{start:e.length-(r[1].length+1),query:r[1],quoted:!1}:null}function d1(e){let t=0;for(let r=0;r<e.length;r++)"/"===e[r]&&t++;return t}function d2(e,t){if(!e)return!0;let r=0;for(let n=0;n<t.length&&r<e.length;n++)t[n]===e[r]&&r++;return r===e.length}function d8(e,t){let r=t?`${e}/`:e;return r.includes(" ")?`@"${r}" `:`@${r} `}function d4(e,t,r){let n=Math.max(1,Math.min(t,r)),a=Math.max(1,Math.max(t,r)),i=e.includes(" ")?`@"${e}"`:`@${e}`,s=n===a?`:${n}`:`:${n}-${a}`;return`${i}${s} `}let d5="omp-web:model-picks";function d6(){try{let e=JSON.parse(window.localStorage.getItem(d5)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[r,n]of Object.entries(e))"number"==typeof n&&Number.isFinite(n)&&n>0&&(t[r]=Math.floor(n));return t}catch{return{}}}function d3(e,t,r,n,a={}){let i=a.gap??8,s=a.margin??8,o=a.prefer??"above",l=Math.min(a.minHeight??120,Math.max(0,r-2*s)),c=Math.max(0,e-i-s),d=Math.max(0,r-t-i-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=n||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(n,h?u:p))}}function d7(e,t,r){return Math.min(e*t,r)}function d9(e,t,r){let{viewportFraction:n,cap:i,gap:s,margin:o,minHeight:l,prefer:c}=r,[d,u]=(0,a.useState)({side:c??"above",maxHeight:i}),p=(0,a.useCallback)(()=>{let t=e.current;if(!t)return;let r=window.visualViewport?.height??window.innerHeight,a=t.getBoundingClientRect(),d=d3(a.top,a.bottom,r,d7(r,n,i),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,i,s,o,l,c,n]);return(0,a.useEffect)(()=>{if(!t)return;p();let r=e.current,n=r?new ResizeObserver(p):null;return r&&n&&n.observe(r),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{n?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var ue=r(14755);let ut="omp-web:model-roles-expanded";async function ur(e,t,r,n,a,i,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...ug,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(i&&(!c||"builtin"===c.source))return a(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await r?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&n(d.prompt),!0}if(c&&"builtin"!==c.source)return n(e),!0;return a(`/${o} is not available in this web session.`),!1}catch(e){return a(e instanceof Error?e.message:String(e)),!1}}function un(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t||"fallback"===t}let ua=["off","default","full"],ui={off:"none",default:"default",full:"full"},us=ue.IN.join(" \xb7 "),uo=ue.C1.filter(e=>!ue.IN.includes(e)).join(" \xb7 ");function ul(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let uc=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),ud=0,uu={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function up(e,t){return uc.compare(e.name||e.modelId,t.name||t.modelId)||uc.compare(e.provider,t.provider)||uc.compare(e.modelId,t.modelId)}let uh=["auto","off","minimal","low","medium","high","xhigh","max"],um=["low","medium","high","xhigh"],uf={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},ug=[{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"}],ux=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uv={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},ub={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function uy(e,t,r){let n=e.name.toLowerCase(),a=uw(e,r).toLowerCase();return n===t?0:n.startsWith(t)?1:n.includes(t)?2:a.includes(t)?3:4}function uw(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uk(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uj(e){return{data:e.data,mimeType:e.mimeType}}function uS(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uC(e){return(e??[]).filter(rW).slice(0,10).map(uS)}let uN=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uT="\n\nTranscript of the audio ";function uI(e){return ll(e).map(e=>{let t=lf(e),r="audio"===t&&e.attachmentId&&!e.text.includes(uT)?uN.exec(e.text):null;return{...e,id:++ud,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...r?{storedInfo:{path:r[1],mimeType:r[2],size:Number(r[3])}}:{}}})}function uM({name:e,mimeType:t,size:r,text:n,attachmentId:a}){return a?{name:e,mimeType:t,size:r,text:n,attachmentId:a}:{name:e,mimeType:t,size:r,text:n}}function uE(e,t){let r=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?r.get(e.attachmentId):void 0;return t?(r.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class u$ extends Error{constructor(e,t,r,n,a=null){super(e),this.code=t,this.completedParts=r,this.parts=n,this.offer=a}}let uR="composer:unkeyed";async function uL(e){let t=await e.json().catch(()=>null),r=t&&"object"==typeof t?{...t}:{};if(e.ok)return r;let n="number"==typeof r.completedParts?r.completedParts:null,a="number"==typeof r.parts?r.parts:null,i="fallback_confirmation_required"===r.code&&"string"==typeof r.fallbackToken&&"string"==typeof r.notice&&null!==n&&null!==a?{token:r.fallbackToken,notice:r.notice,completedParts:n,parts:a}:null;throw new u$("string"==typeof r.error?r.error:`HTTP ${e.status}`,"string"==typeof r.code?r.code:null,n,a,i)}function uA(e,t){fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fallbackToken:t,approve:!1})}).catch(()=>void 0)}function uP(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function uF({tone:e,title:t,body:r}){let a="error"===e?"danger":"warning";return(0,n.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${a}-line)`,borderRadius:"var(--radius-control)",background:`var(--${a}-soft)`,color:`var(--${a})`,fontSize:11,lineHeight:1.45},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,n.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontWeight:600},children:t}),(0,n.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:r})]})]})}function u_({error:e}){return e?(0,n.jsx)(uF,{tone:"error",title:"Model error",body:e}):null}function uz({warnings:e}){return e&&0!==e.length?(0,n.jsx)(uF,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uW=(0,a.forwardRef)(function({onSend:e,onAbort:t,onSteer:r,onFollowUp:i,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:T,effectiveThinkingLevel:I,outputTokensPerSecond:M=null,outputSpeedLive:E=!1,thinkingCeiling:$,onThinkingLevelChange:R,availableThinkingLevels:L,thinkingLevelMap:A,fastMode:P=null,fastModeBusy:F=!1,onFastModeToggle:_,retryInfo:W,deliveryRows:O=[],inputHistory:D=[],onRecallQueue:H,onRemoveQueuedMessage:U,slashCommands:q,slashCommandsLoading:V,onLoadSlashCommands:K,onBuiltinCommand:G,soundEnabled:J,onSoundToggle:Z,onAudioUnlock:Y,onPromptWithStreamingBehavior:X,draftKey:Q,cwd:ee,sessionTitle:et,sessionId:er,onEnsureSession:en,onLiveTranscriptPersisted:ea},ei){let es,eo,el,ec,ed,eu,ep,eh,em,ef,{t:eg}=(0,z.s)();am();let{st:ex}=ag(),ev=O.some(e=>e.removable),eb=B(),[ey,ew]=(0,a.useState)(()=>Q?dL(Q)?.value??"":""),[ek,ej]=(0,a.useState)(!1),[eS,eC]=(0,a.useState)(null),[eN,eT]=(0,a.useState)(""),[eI,eM]=(0,a.useState)({});(0,a.useEffect)(()=>{ek&&eM(d6())},[ek]);let[eE,e$]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(ek)try{e$("1"===window.localStorage.getItem(ut))}catch{}},[ek]);let eR=()=>{e$(e=>{let t=!e;try{window.localStorage.setItem(ut,t?"1":"0")}catch{}return t})},[eL,eA]=(0,a.useState)(!1),[eP,eF]=(0,a.useState)(null),[e_,ez]=(0,a.useState)(!1),[eW,eO]=(0,a.useState)(!1),[eD,eH]=(0,a.useState)(null),[eU,eB]=(0,a.useState)(!1),[eq,eV]=(0,a.useState)(()=>Q?uC(dL(Q)?.images):[]),[eK,eG]=(0,a.useState)(()=>Q?uI(dL(Q)?.documents):[]),[eJ,eZ]=(0,a.useState)(null),eY=(0,a.useMemo)(()=>eK.filter(e=>"ready"===e.status),[eK]),eX=eK.some(e=>"ready"!==e.status||un(e)),eQ=eK.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uT))),e0=ey.trimStart(),e1=0===eq.length&&0===eK.length&&e0.startsWith("!"),e2=e1&&e0.startsWith("!!"),[e8,e4]=(0,a.useState)(!1),[e5,e6]=(0,a.useState)(0),[e3,e7]=(0,a.useState)(null),e9=e3?.value===ey&&e3.draftKey===Q?e3.token:null,[te,tt]=(0,a.useState)(!1),[tr,tn]=(0,a.useState)(!1),ta=(0,a.useRef)(null),[ti,ts]=(0,a.useState)(null),[to,tl]=(0,a.useState)(!1),[tc,td]=(0,a.useState)(0),[tu,tp]=(0,a.useState)(!1),[th,tm]=(0,a.useState)(0),[tf,tg]=(0,a.useState)(null),[tx,tv]=(0,a.useState)(!1),[tb,ty]=(0,a.useState)(null),[tw,tk]=(0,a.useState)(null),tj=ee&&tw?.cwd===ee?tw.values:{},tS=(0,a.useRef)(null),tC=(0,a.useRef)(null),tN=(0,a.useRef)(null),tT=(0,a.useRef)(null),tI=(0,a.useRef)(null),tM=(0,a.useRef)(null),tE=(0,a.useRef)(null),t$=(0,a.useRef)(null),tR=(0,a.useRef)(null),tL=(0,a.useRef)(null),tA=(0,a.useRef)(null),tP=(0,a.useRef)(!1),tF=(0,a.useRef)(0),t_=(0,a.useRef)(!1),tz=(0,a.useRef)([]),tW=(0,a.useRef)([]),tO=(0,a.useRef)([]),tD=(0,a.useRef)(null),tH=(0,a.useRef)(null),tU=(0,a.useRef)(Q),tB=(0,a.useRef)(ey),tq=(0,a.useRef)(eq),tV=(0,a.useRef)(0),tK=(0,a.useRef)(eK);tB.current=ey,tq.current=eq,tK.current=eK,(0,a.useImperativeHandle)(ei,()=>({insertIfEmpty(e){let t=tS.current;(t?t.value:ey).trim()||(tB.current=e,ew(e),ts(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,r,n=tS.current;if(!function(e,t,r,n=0){return!e.trim()&&0===t&&0===r&&0===n}(n?n.value:ey,tq.current.length,tV.current,tK.current.length))return;let a=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lu(t)?.message??t),i=uC("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,r=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof r)return[];let n={data:t,mimeType:r};return rW(n)?[n]:[]})),s=uI((r="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lu(r)?.documents??[]));tB.current=a,tq.current=i,tK.current=s,ew(a),ts(null),tp(!1),eV(e=>(e.forEach(uP),i)),eG(s),requestAnimationFrame(()=>{n&&(n.focus(),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tU.current!==e)return void d_(e,t);let r={value:tB.current,images:tq.current.map(uj),documents:tK.current.filter(e=>"ready"===e.status).map(uM)},n=d_(e,t,r)??{value:"",images:[],documents:[]},a=n.value===r.value&&n.images.length===r.images.length&&n.images.every((e,t)=>e.data===r.images[t]?.data&&e.mimeType===r.images[t]?.mimeType)&&n.documents.length===r.documents.length&&n.documents.every((e,t)=>e.name===r.documents[t]?.name&&e.mimeType===r.documents[t]?.mimeType&&e.size===r.documents[t]?.size&&e.text===r.documents[t]?.text&&e.attachmentId===r.documents[t]?.attachmentId);if(tU.current=t,a)return;let i=uC(n.images),s=uE(uI(n.documents),tK.current),o=n.value;tB.current=o,tq.current=i,tK.current=s,ew(o),eV(e=>(e.forEach(uP),i)),eG(s),ts(null),tp(!1)},restoreSubmission(e,t,r,n){if(!e.trim()&&!t?.length&&!r?.length)return;let a=tU.current,i=n??a,s=i===a,o=!s&&i?dL(i):null,l=dF(e,t,s?tB.current:o?.value??"",s?tq.current.map(uj):o?.images??[],r,s?tK.current.filter(e=>"ready"===e.status).map(uM):o?.documents??[]);if(i&&dA(i,l),!s)return;let c=t?.length?[...uC(t).slice(0,Math.max(0,10-tq.current.length)),...tq.current].slice(0,10):tq.current,d=uE(uI(l.documents),tK.current);tB.current=l.value,tq.current=c,tK.current=d,ew(l.value),ts(null),tp(!1),t?.length&&eV(e=>{let r=Math.max(0,10-e.length),n=uC(t).slice(0,r),a=n.length>0?[...n,...e]:e;return tq.current=a,a}),eG(d),requestAnimationFrame(()=>{let e=tS.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=tS.current;if(!t)return void ew(t=>t+(t?" ":"")+e);let r=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length,a=t.value.slice(0,r),i=t.value.slice(n),s=a.length>0&&!a.endsWith(" ")?" ":"",o=a+s+e+i;tB.current=o,ew(o),ts(null),requestAnimationFrame(()=>{if(!t)return;let n=r+s.length+e.length;t.setSelectionRange(n,n),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){t9(e)}}));let tG=(0,a.useCallback)(async e=>{let t=Math.max(0,10-tq.current.length-tV.current),r=e.filter(e=>e.size>0xa00000);r.length>0&&eZ(eg("chat.attachImageTooLarge",{name:r.map(e=>e.name).join(", "),limit:lp(0xa00000)}));let n=e.filter(e=>e.size<=0xa00000),a=n.slice(0,t);if(a.length<n.length&&eZ(eg("chat.attachImageLimit",{count:10})),a.length){tV.current+=a.length;try{let e=await Promise.all(a.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result.split(",")[1];t({data:r,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},n.onerror=r,n.readAsDataURL(e)})));eV(t=>{let r=e.slice(0,Math.max(0,10-t.length));e.slice(r.length).forEach(uP);let n=[...t,...r];return tq.current=n,n})}finally{tV.current-=a.length}}},[eg]),tJ=(0,a.useCallback)(async e=>{for(let t of e){let e=la(t);if(!e)continue;if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eZ(eg("chat.attachTooLarge",{name:t.name,limit:lp(8388608)}));continue}if(tK.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eZ(eg("chat.attachTotalTooLarge",{limit:lp(0x1000000)}));continue}let r={id:++ud,name:t.name,mimeType:lt[e],size:t.size,text:"",status:"extracting"},n=[...tK.current,r];tK.current=n,eG(n);try{let e=await lc(t);if(tK.current.reduce((e,t)=>e+(t.id===r.id?0:t.text.length),0)+e.text.length>24e4)throw new le("text_too_large","Total extracted text exceeds 240000 characters");let n=tK.current.map(t=>t.id===r.id?{...e,id:t.id,status:"ready"}:t);tK.current=n,eG(n)}catch(a){let e=tK.current.some(e=>e.id===r.id),n=tK.current.filter(e=>e.id!==r.id);if(tK.current=n,eG(n),!e)continue;a instanceof le?"text_too_large"===a.code?eZ(eg("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===a.code?eZ(eg("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===a.code?eZ(eg("chat.attachNoPdfText",{name:t.name})):"password_protected"===a.code?eZ(eg("chat.attachPasswordProtected",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name}))}}},[eg]),tZ=(0,a.useCallback)((e,t)=>{if(!tK.current.some(t=>t.id===e))return!1;let r=t?tK.current.map(r=>r.id===e?t:r):tK.current.filter(t=>t.id!==e);return tK.current=r,eG(r),!0},[]),tY=(0,a.useCallback)((e,t)=>{if(!tK.current.some(t=>t.attachmentId===e))return!1;let r=tK.current.map(r=>r.attachmentId===e?t(r):r);return tK.current=r,eG(r),!0},[]),tX=(0,a.useCallback)((e,t,r)=>{if(!e||e===tU.current)return;let n=dL(e);n?.documents.some(e=>e.attachmentId===t)&&dA(e,{...n,documents:uI(n.documents).map(e=>e.attachmentId===t?r(e):e).map(uM)})},[]),tQ=(0,a.useRef)(new Map),t0=(0,a.useRef)(new Map),t1=(0,a.useRef)(new Set),t2=(0,a.useCallback)((e,t,r)=>{if(!e.storedInfo)return null;let n=Math.min(12e4,24e4-r.reduce((t,r)=>t+(r.attachmentId===e.attachmentId?0:r.text.length),0)),a=lg({...e.storedInfo,transcript:t},n);return a.length>n?null:{...e,text:a,size:new TextEncoder().encode(a).byteLength,transcription:void 0}},[]),t8=(0,a.useCallback)(e=>e instanceof u$&&"media_tool_unavailable"===e.code?eg("chat.transcribeToolMissing"):e instanceof u$&&"fallback_confirmation_expired"===e.code?eg("chat.transcribeFallbackExpired"):e instanceof u$&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eg("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eg]),t4=(0,a.useCallback)(async(e,t)=>{let r=tU.current,n=tK.current.find(t=>t.attachmentId===e);if(!n?.storedInfo)return;let a=n.transcription?.state==="confirm"?n.transcription.plan:null;t0.current.get(e)?.abort();let i=new AbortController;t0.current.set(e,i),tY(e,e=>({...e,transcription:{state:"running",plan:a}}));try{let n=await uL(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:i.signal}));if("string"!=typeof n.transcript)throw new u$("Invalid transcription result",null,null,null);let a=n.transcript;tY(e,e=>t2(e,a,tK.current)??{...e,transcription:{state:"failed",error:eg("chat.transcribeTooLong")}})||tX(r,e,e=>t2(e,a,[])??e)}catch(n){if(i.signal.aborted)return void tY(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof u$&&"confirmation_required"===n.code)return void t5.current?.(e);let t=n instanceof u$?n.offer:null;if(t){let r={state:"fallback",reason:n instanceof Error?n.message:"",...t};tY(e,e=>({...e,transcription:r}))||uA(e,t.token);return}let r=t8(n);tY(e,e=>({...e,transcription:{state:"failed",error:r}}))}finally{t0.current.get(e)===i&&t0.current.delete(e)}},[eg,t8,tY,tX,t2]),t5=(0,a.useRef)(null),t6=(0,a.useCallback)(async e=>{let t;t0.current.get(e)?.abort();let r=new AbortController;t0.current.set(e,r),tY(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 u$("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await uL(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:r.signal})))}catch(t){if(r.signal.aborted)tY(e,e=>({...e,transcription:{state:"skipped"}}));else{let r=t8(t);tY(e,e=>({...e,transcription:{state:"failed",error:r}}))}return}finally{t0.current.get(e)===r&&t0.current.delete(e)}t.requiresConfirmation?tY(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await t4(e,{})},[t4,t8,tY]);t5.current=t6;let t3=(0,a.useCallback)(e=>{let t=t0.current.get(e);if(t)return void t.abort();let r=tK.current.find(t=>t.attachmentId===e)?.transcription;r?.state==="fallback"&&uA(e,r.token),tY(e,e=>({...e,transcription:{state:"skipped"}}))},[tY]),t7=(0,a.useCallback)(async(e,t)=>{let r=null;for(let n of e){if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}let e="file"===t&&n.size<=8388608,a={id:++ud,name:n.name,mimeType:"text/plain",size:e?n.size:0,text:"",status:e?"extracting":"uploading",sourceSize:n.size},i=[...tK.current,a];tK.current=i,eG(i);let s=(e,t)=>{let r=tK.current.filter(e=>e.id!==a.id);return e<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&r.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?lo("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?lo("utf-16be",t.subarray(2)):t.includes(0)?null:lo("utf-8",t)??lo("euc-kr",t)},()=>null);if(null!==e&&s(e.length,n.size)){tZ(a.id,{...a,text:e,status:"ready"});continue}}if(null===r&&(r=1048576*(await dX().catch(()=>dJ)).uploadLimitMb),n.size>r){tZ(a.id,null)&&eZ(eg("chat.attachStoredTooLarge",{name:n.name,limit:lp(r)}));continue}let o={...a,stored:t,status:"uploading",size:0};if(!tZ(a.id,o))continue;let l=tU.current??uR,c=await dD(l),d=null,u=new AbortController;tQ.current.set(a.id,u);try{if(t1.current.has(a.id))continue;let e=await lx(n,{sessionId:er,draftId:c.draftId,signal:u.signal}),r=tK.current.filter(e=>e.id!==a.id).reduce((e,t)=>e+t.text.length,0),i=lg({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-r)),p=new TextEncoder().encode(i).byteLength;if(!s(i.length,p)){tZ(a.id,null)&&eZ(eg("chat.attachTotalTooLarge",{limit:lp(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:i,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tZ(a.id,h))d=e.id;else if(!t1.current.has(a.id)&&l!==tU.current){let t=dL(l)??{value:"",images:[],documents:[]};dA(l,{...t,documents:[...t.documents,uM(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tZ(a.id,null)&&eZ(eg("chat.attachUploadFailed",{name:n.name,error:e instanceof Error?e.message:String(e)}))}finally{tQ.current.delete(a.id),c.end(d)}d&&"audio"===t&&tK.current.some(e=>e.attachmentId===d)&&t6(d)}},[tZ,t6,er,eg]),t9=(0,a.useCallback)(async e=>{eZ(null);let{images:t,documents:r,audio:n,files:a}=function(e){let t=[],r=[],n=[],a=[];for(let i of e)i.type.startsWith("image/")?t.push(i):null!==la(i)?r.push(i):ls(i)?n.push(i):a.push(i);return{images:t,documents:r,audio:n,files:a}}(e),i=r.filter(e=>e.size>8388608);await Promise.all([tG(t),tJ(r.filter(e=>e.size<=8388608)),t7(n,"audio"),t7([...a,...i],"file")])},[tJ,t7,tG]),re=(0,a.useCallback)(e=>{eV(t=>{let r=[...t],[n]=r.splice(e,1);return n&&uP(n),tq.current=r,r})},[]),rt=(0,a.useCallback)(e=>{let t=tK.current.find(t=>t.id===e);if(t1.current.add(e),tQ.current.get(e)?.abort(),t?.attachmentId){t0.current.get(t.attachmentId)?.abort(),t.transcription?.state==="fallback"&&uA(t.attachmentId,t.transcription.token);var r=t.attachmentId;for(let[e,t]of dk)t.delete(r)&&(0===t.size&&dk.delete(e),dK())}let n=tK.current.filter(t=>t.id!==e);tK.current=n,eG(n)},[]),rr=(0,a.useCallback)(()=>{tq.current=[],eV(e=>(e.forEach(uP),[]))},[]),rn=(0,a.useCallback)(()=>{tK.current=[],eG([])},[]),ra=(0,a.useCallback)(()=>{tB.current="",ew(""),ts(null),e7(null),tt(!1),tp(!1),Q&&dP(Q),tU.current&&tU.current!==Q&&dP(tU.current),rr(),rn(),eZ(null),tS.current&&(tS.current.style.height="auto")},[rn,rr,Q]);(0,a.useEffect)(()=>{Q&&tU.current===Q&&dA(Q,{value:ey,images:eq.map(uj),documents:eY.map(uM)})},[eq,Q,eY,ey]),(0,a.useEffect)(()=>{let e=tU.current;if(e===Q)return;e&&dA(e,{value:tB.current,images:tq.current.map(uj),documents:tK.current.filter(e=>"ready"===e.status).map(uM)});let t=Q?dL(Q):null;tU.current=Q;let r=t?.value??"",n=uC(t?.images),a=uI(t?.documents);tB.current=r,tq.current=n,tK.current=a,ew(r),ts(null),tp(!1),eV(e=>(e.forEach(uP),n)),eG(a)},[Q]),(0,a.useEffect)(()=>{let e=tS.current;e&&(e.style.height="auto",ey&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ey]),(0,a.useEffect)(()=>()=>{tq.current.forEach(uP)},[]);let ri=(0,a.useCallback)((e,t)=>{let r=function(e,t){let r=dz(t);if(0===r.length)return()=>{};let n=++dy;return db.set(n,{draftId:dW(e),ids:r}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=db.get(n);if(t){if(db.delete(n),"accepted"===e){let e=dj.get(t.draftId)??new Set;for(let r of t.ids)e.add(r);dj.set(t.draftId,e)}dK()}}}(tU.current??uR,e);Promise.resolve(t()).then(e=>r("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),rs=(0,a.useCallback)(async()=>{let t=ey.trim(),r=e0.trim(),n=r.startsWith("/")||r.startsWith("!")?r:t;if(!n&&!eq.length&&!eY.length||o||eX)return;Y?.();let a=eq.length?eq:void 0,i=eY.length?eY:void 0;if(n.startsWith("/")){await ur(n,q,G,t=>ri(i,()=>e(t,a,i)),eZ,!!(a||i),K)&&ra();return}ra(),ri(i,()=>e(n,a,i))},[ey,e0,eq,eY,eX,o,G,q,K,e,ra,Y,ri]),ro=!e0.startsWith("/")||e0.startsWith("//")||/\s/.test(e0.slice(1))?null:e0.slice(1).toLowerCase(),rl=(()=>{if(null===ro)return[];let e=[...o?[]:ug,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),r=uw(e,eg).toLowerCase();return t.includes(ro)||r.includes(ro)}).sort((e,t)=>{let r=uy(e,ro,eg)-uy(t,ro,eg);return 0!==r?r:ub[e.source]-ub[t.source]||uc.compare(e.name,t.name)}).filter(e=>{let r=e.name.toLowerCase();return!t.has(r)&&(t.add(r),!0)})})(),{commands:rc,groups:rd}=(es=0,{commands:(eo=ux.map(e=>{let t=rl.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!uk(e,tj)),...t.filter(e=>uk(e,tj))]:t;return{source:e,items:r.map(e=>({command:e,index:es++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:eo}),ru=1===rl.length?eg(ro?"chat.match":"chat.command"):eg(ro?"chat.matches":"chat.commands",{count:rl.length}),rp=!!ey.trim(),rh=!eX&&(rp||eq.length>0||eY.length>0),rm=(0,a.useCallback)((e,t)=>{let r=function(e,t){let r=Math.max(0,Math.min(e.length,t)),n=/(?:^|\s)(\/\/[^\s]*)$/.exec(e.slice(0,r));if(!n)return null;let a=r-n[1].length,i=/^\S*/.exec(e.slice(r))[0];return{start:a,end:r+i.length,query:e.slice(a+2,r)}}(e,t??e.length);if(e7(r?{value:e,draftKey:Q,token:r}:null),tn(!1),!ee)return void ts(null);let n=t??e.length;ts(d0(e.slice(0,n)))},[ee,Q]),rf=ti?.query??null,rg=a.useMemo(()=>null!==rf&&tf&&tf.cwd===ee?function(e,t,r=20){let n=t.toLowerCase();if(!n)return e.slice(0,r);let a=[];for(let t of e){let e=function(e,t){let r=e.path.toLowerCase(),n=0;if(t.includes("/"))r===t?n=100:r.startsWith(t)?n=80:r.includes(t)?n=50:d2(t,r)&&(n=10);else{let e=r.lastIndexOf("/"),a=-1===e?r:r.slice(e+1);a===t?n=100:a.startsWith(t)?n=80:a.includes(t)?n=50:r.includes(t)?n=30:d2(t,r)&&(n=10)}return e.isDir&&n>0&&(n+=10),n}(t,n);e>0&&a.push({entry:t,score:e})}return a.sort((e,t)=>t.score-e.score||d1(e.entry.path)-d1(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),a.slice(0,r).map(e=>e.entry)}(tf.entries,rf):[],[rf,tf,ee]),rx=!!(rf&&tf?.truncated&&tf.cwd===ee);(0,a.useEffect)(()=>{if(!rx||!ee||!rf)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(rf)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ty({cwd:ee,query:rf,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[rx,rf,ee]);let rv=rx&&null!==tb&&tb.cwd===ee&&tb.query===rf,rb=rv?tb.matches:rg,ry=null===ti?null:`${ti.start}:${+!!ti.quoted}:${ti.query}`;(0,a.useEffect)(()=>{if(null===ry){tl(!1),td(0);return}tl(!0),td(0)},[ry]);let rw=null!==ti,rk=d9(tL,tu,{viewportFraction:.44,cap:360}),rj=d9(tL,e8,{viewportFraction:.56,cap:460}),rS=d9(tL,to,{viewportFraction:.48,cap:400}),rC=d9(tL,te,{viewportFraction:.48,cap:400}),rN=e9?`${e9.start}:${e9.end}:${e9.query}`:null;(0,a.useEffect)(()=>{tt(null!==rN)},[rN]);let rT=(0,a.useCallback)((e,t,r,n=!1)=>{tB.current===e&&tU.current===Q&&(tB.current=t,ew(t),e7(null),tt(!1),tn(n),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(r,r),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[Q]);(0,a.useEffect)(()=>{if(!rw||!ee)return;let e=tD.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tH.current===ee||(tH.current=ee,tv(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tg({cwd:ee,entries:function(e){let t=new Set;for(let r of e){let e=r.indexOf("/");for(;-1!==e;)t.add(r.slice(0,e)),e=r.indexOf("/",e+1)}let r=[];for(let e of t)r.push({path:e,isDir:!0});for(let t of e)t&&r.push({path:t,isDir:!1});return r.sort((e,t)=>d1(e.path)-d1(t.path)||e.path.localeCompare(t.path)),r}(e.files??[]),truncated:!!e.truncated}),tD.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tD.current=null}).finally(()=>{tH.current=null,tv(!1)}))},[rw,ee]);let rI=(0,a.useCallback)(e=>{if(!ti)return;let t=tS.current,r=t?.selectionStart??ey.length,n=ey.slice(0,ti.start),a=ey.slice(r);ti.quoted&&a.startsWith('"')&&(a=a.slice(1));let i=function(e,t,r=!1){let n=t?`${e}/`:e,a=r||n.includes(" ");if(t){let e=a?`@"${n}"`:`@${n}`;return{text:e,cursorOffset:a?e.length-1:e.length}}let i=a?`@"${n}" `:`@${n} `;return{text:i,cursorOffset:i.length}}(e.path,e.isDir,ti.quoted),s=n+i.text+a,o=n.length+i.cursorOffset;ew(s),ts(d0(s.slice(0,o))),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[ti,ey]);(0,a.useEffect)(()=>{tc>=rb.length&&td(Math.max(0,rb.length-1))},[rb.length,tc]),(0,a.useEffect)(()=>{tW.current.length=rb.length},[rb.length]),(0,a.useEffect)(()=>{to&&tW.current[tc]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tc,to]),(0,a.useEffect)(()=>{th>=D.length&&tm(Math.max(0,D.length-1))},[D.length,th]),(0,a.useEffect)(()=>{tO.current.length=D.length},[D.length]),(0,a.useEffect)(()=>{tu&&tO.current[th]?.scrollIntoView({block:"nearest",inline:"nearest"})},[th,tu]);let rM=(0,a.useCallback)(e=>{tB.current=e,ew(e),tp(!1),tm(0),ts(null),requestAnimationFrame(()=>{let t=tS.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),rE=(0,a.useCallback)(e=>{let t=`/${e.name} `;tB.current=t,ew(t),e4(!1),e6(0),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),r$=(0,a.useCallback)(async e=>{let t=ey.trim(),n=e0.trim(),a=n.startsWith("/")||n.startsWith("!")?n:t,s=eX||!a&&0===eq.length&&0===eY.length?null:{message:a,images:eq.length?eq:void 0,documents:eY.length?eY:void 0};if(!s)return;Y?.();let o="steer"===e?"steer":"followUp";if(a.startsWith("/")){await ur(a,q,G,e=>{if(!X)throw Error("Cannot queue this command while the session is busy.");ri(s.documents,()=>X(e,o,s.images,s.documents))},eZ,!!(s.images?.length||s.documents?.length),K)&&ra();return}ra(),"steer"===e&&r?ri(s.documents,()=>r(s.message,s.images,s.documents)):"followup"===e&&i&&ri(s.documents,()=>i(s.message,s.images,s.documents))},[ey,e0,eq,eY,eX,q,K,G,X,r,i,ra,Y,ri]),rR=(0,a.useCallback)(e=>{let t=rc.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e5-1);if("right"===e)return Math.min(t,e5+1);let r=tz.current[e5];if(!r)return"down"===e?Math.min(t,e5+1):Math.max(0,e5-1);let n=r.getBoundingClientRect(),a=n.left+n.width/2,i=n.top+n.height/2,s=-1,o=1/0;for(let r=0;r<=t;r+=1){if(r===e5)continue;let t=tz.current[r];if(!t)continue;let n=t.getBoundingClientRect(),l=n.top+n.height/2-i;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(n.left+n.width/2-a);c<o&&(s=r,o=c)}return s>=0?s:"down"===e?Math.min(t,e5+1):Math.max(0,e5-1)},[rc.length,e5]),rL=(0,a.useCallback)(e=>{let n=e.nativeEvent,a=Date.now()-tF.current<100,s=tP.current||n.isComposing||229===n.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||a)){a&&e.preventDefault();return}if(tu&&!s){if("ArrowDown"===e.key){e.preventDefault(),tm(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tm(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tp(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[th]){e.preventDefault(),rM(D[th]);return}}if(!(te&&e9&&!s&&ta.current?.handleKeyDown(e))){if(e8&&null!==ro){if("ArrowDown"===e.key){e.preventDefault(),e6(rR("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e6(rR("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e6(rR("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e6(rR("left"));return}if("Escape"===e.key){e.preventDefault(),e4(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rc[e5]){e.preventDefault(),rE(rc[e5]);return}}if(to&&null!==ti&&!s){if("ArrowDown"===e.key){e.preventDefault(),td(e=>Math.min(Math.max(0,rb.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),td(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tl(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rb[tc]){e.preventDefault(),rI(rb[tc]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===ey.trim().length){e.preventDefault(),e4(!1),tl(!1),tm(D.length-1),tp(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(r||i)?r$(r?"steer":"followup"):rs())}},[o,r,i,t,e8,ro,rc,e5,rE,r$,rs,rR,to,ti,rb,tc,rI,tu,D,th,rM,ey,te,e9]),rA=(0,a.useCallback)(()=>{let e=tS.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),rP=(0,a.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let r=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&r.push(e)}return r}(e.clipboardData);t.length&&(e.preventDefault(),t9(t))},[t9]);(0,a.useEffect)(()=>{if(null===ro){e4(!1),e6(0),t_.current=!1;return}e4(!0),e6(0),!t_.current&&K&&(t_.current=!0,Promise.resolve(K()).catch(()=>{t_.current=!1}))},[ro,K]),(0,a.useEffect)(()=>{if(!e8||!ee)return;let e=!1;return tk({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let r={};for(let e of t.skills??[])r[e.name]=e.disableModelInvocation;tk({cwd:ee,values:r})}).catch(()=>{e||tk({cwd:ee,values:{}})}),()=>{e=!0}},[e8,ee]),(0,a.useEffect)(()=>{e5>=rc.length&&e6(Math.max(0,rc.length-1))},[rc.length,e5]),(0,a.useEffect)(()=>{tz.current.length=rc.length},[rc.length]),(0,a.useEffect)(()=>{e8&&tz.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e8]);let rF=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(up):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(up),r_=g??null,rz=nh.find(e=>e.alias===r_)?.provider??null,rO=rz?rF.filter(e=>e.provider===rz):rF,rD=(el=eN.trim().toLocaleLowerCase())?rO.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(el)):rO,rH=rO.length>8,rB=[];for(let e of rD){let t=rB.find(t=>t.provider===e.provider);t?t.options.push(e):rB.push({provider:e.provider,options:[e]})}let rq=rz?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),rV=l?rq.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,rK=eN.trim()?[]:rO.map((e,t)=>{var r,n;return{option:e,order:t,count:eI[r=e.provider,n=e.modelId,`${r}/${n}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),rG=(e,t,r)=>{let a=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,n.jsxs)("button",{onClick:()=>{if(ej(!1),eT(""),!a||c){var t,r;let n=function(e,t){let r={...e,[t]:(e[t]??0)+1},n=Object.keys(r);if(n.length<=30)return r;for(let e of(n.sort((e,t)=>r[e]-r[t]),n)){if(Object.keys(r).length<=30)break;e!==t&&delete r[e]}return r}(d6(),(t=e.provider,r=e.modelId,`${t}/${r}`));try{window.localStorage.setItem(d5,JSON.stringify(n))}catch{}eM(n),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:a?"var(--bg-selected)":"none",border:"none",color:a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:a?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:[a?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==r&&r>=2&&(0,n.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eg("chat.modelPickCount",{count:r})})]},`${t}:${e.provider}:${e.modelId}`)},rJ=l?rF.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,rZ=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,rY=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eg("chat.compacted")} ${rU(S.tokensBefore)} -> ${rU(S.estimatedTokensAfter)} tokens (${eg("chat.tokensSaved",{saved:rU(rZ)})})`:null,rX=e=>{let t=A?.[e];return null!=t&&t!==e?t:null},rQ="auto"===(ec=T??"auto")?$?`auto ≤ ${rX($)??$}`:"auto":A?A[ec]??ec:ec,r0=(T??"auto")==="auto"&&I&&"auto"!==I?A?.[I]??I:null,r1=R&&r0?eg("chat.currentReasoning",{level:r0}):null,r2=e=>!L||L.includes(e),r8=[{level:"auto",ceiling:null},...um.filter(r2).map(e=>({level:"auto",ceiling:e})),...uh.filter(e=>"auto"!==e&&r2(e)).map(e=>({level:e,ceiling:null}))],r4=Object.entries(ui).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,a.useEffect)(()=>{let e=e=>{tC.current&&!tC.current.contains(e.target)&&tN.current&&!tN.current.contains(e.target)&&(ej(!1),eT("")),tT.current&&!tT.current.contains(e.target)&&tI.current&&!tI.current.contains(e.target)&&eA(!1),tM.current&&!tM.current.contains(e.target)&&ez(!1),tE.current&&!tE.current.contains(e.target)&&eO(!1),t$.current&&!t$.current.contains(e.target)&&eB(!1),!tR.current||tR.current.contains(e.target)||tS.current?.contains(e.target)||tp(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,a.useEffect)(()=>{eb||eB(!1)},[eb]);let r5=(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eq.length||eK.length?" is-active":""}`,onClick:()=>tA.current?.click(),title:eg("chat.attachFile"),"aria-label":eg("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:eq.length||eK.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=eq.length||eK.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eq.length||eK.length?"var(--accent)":"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,n.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,n.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),r6=f&&nh.length>0?(0,n.jsxs)("div",{ref:tT,style:{position:"relative",flexShrink:+!!eb,minWidth:0},children:[(0,n.jsxs)("button",{className:`${eb?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eF({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eg("chat.mainPreset"),"aria-label":eg("chat.mainPreset"),children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eb?null:(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eg("chat.mainPreset")})]}),eL&&eP&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eP.top,eP.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eP.top+6}:{top:eP.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eP.left,width:"max-content",minWidth:eP.width};return(0,n.jsx)("div",{ref:tI,role:"menu","aria-label":eg("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tT.current?.querySelector("button")?.focus())},style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:(0,n.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:nh.map(e=>{let t=e.alias===r_;return(0,n.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eA(!1),f({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,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("img",{className:"account-avatar",src:nU(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,n.jsx)("span",{children:nL(e.alias)}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,r3=R?(0,n.jsxs)("div",{ref:tE,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,n.jsxs)("button",{type:"button",className:`${eb?"composer-icon-button":"composer-chip"}${eW?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eH({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(!1),eO(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eW,onKeyDown:e=>{"Escape"===e.key&&eW&&(e.stopPropagation(),eO(!1))},title:eg("chat.changeReasoning",{level:rQ}),"aria-label":eg("chat.changeReasoning",{level:rQ}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eb?0:"8px 12px",height:32,background:eW?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eW?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,n.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eb?null:(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:rQ})]}),eW&&eD&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eD.top,eD.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eD.top+6}:{top:eD.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eD.left,width:"max-content",minWidth:Math.max(180,eD.width)};return(0,n.jsx)("div",{role:"menu","aria-label":eg("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eO(!1),tE.current?.querySelector("button")?.focus())},style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:r},children:r8.map(({level:e,ceiling:t})=>{let r=(T??"auto")===e&&("auto"!==e||($??null)===t),a=t??e,i="auto"===e&&null===t?null:rX(a),s=t?`auto ≤ ${i??t}`:i??e,o=t?eg("chat.thinkingAutoCapped",{level:i??t}):eg(uf[e]);return(0,n.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":r,onClick:()=>{eO(!1),R(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsxs)("span",{style:{flex:1},children:[s,null!==i&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",a,")"]})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,r7=_?(ed=F?eg("chat.fastModeBusy"):null===P?eg("chat.fastModeUnknown"):P.active?eg("chat.fastModeActive"):P.enabled?eg("chat.fastModeInactive"):eg("chat.fastModeOff"),eu=F||o||b,ep=P?.enabled===!0,(0,n.jsx)("button",{type:"button",className:`composer-icon-button${P?.active?" is-active":""}`,onClick:_,disabled:eu,"aria-pressed":null===P?void 0:P.enabled,"aria-busy":F||void 0,title:ed,"aria-label":ed,style:{flexShrink:0,opacity:o?.5:1},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:P?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===P?"3 2":void 0,style:{opacity:ep&&!P?.active?.6:1},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,r9=(0,n.jsxs)(n.Fragment,{children:[r&&(0,n.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>r$("steer"),disabled:!rh,title:eX?eg("chat.attachExtractingWait"):eg("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rh?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:rh?"var(--warning)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eg("chat.steer")]}),i&&(0,n.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>r$("followup"),disabled:!rh,title:eX?eg("chat.attachExtractingWait"):eg("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rh?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:rh?"var(--accent-hover)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,n.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,n.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eg("chat.followUp")]})]}),ne=void 0!==Z?(0,n.jsx)(de,{soundEnabled:J??!0,onToggle:Z}):null;return(0,n.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,n.jsx)("input",{ref:tA,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t9(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(u_,{error:p}),(0,n.jsx)(uz,{warnings:h}),O.length>0&&(0,n.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,n.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ex("delivery.title",{count:O.length})}),H&&ev&&(0,n.jsxs)("button",{onClick:H,title:eg("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,n.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eg("chat.recall")]})]}),(0,n.jsx)(c5,{rows:O,removeLabel:eg("chat.queueRemove"),onRemove:U?(e,t)=>U("steer"===e?"steering":"followUp",t):void 0})]}),W&&(0,n.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]}),eg("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,n.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),rY&&(0,n.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),rY]}),j&&(0,n.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eJ&&(0,n.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eJ}),(0,n.jsx)("button",{type:"button",onClick:()=>eZ(null),"aria-label":eg("i18n.close"),title:eg("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,n.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eq.length>0||eK.length>0)&&(0,n.jsxs)("div",{role:"list","aria-label":eg("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eq.map((e,t)=>(0,n.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,n.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,n.jsx)("button",{type:"button","aria-label":eg("chat.removeImage",{index:t+1}),onClick:()=>re(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,n.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eK.map(e=>(0,n.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||un(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,n.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):aT(e.name,14),(0,n.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,n.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,n.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eg("chat.attachKindAudio"):"file"===e.stored?eg("chat.attachKindFile"):uu[e.mimeType]," \xb7 ",lp(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eg("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eg("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eg("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"||e.transcription?.state==="fallback"?` \xb7 ${eg("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eg("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,n.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eg("chat.attachTranscribeFailed")}`})]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>rt(e.id),"aria-label":eg("chat.removeAttachment",{name:e.name}),title:eg("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,n.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eQ.length>0&&(0,n.jsx)("div",{role:"group","aria-label":eg("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eQ.map(e=>{let t,r,a,i,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?eg("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eg("chat.transcribeDurationUnknown"):(r=Math.floor((t=Math.round(c.durationSeconds))/3600),a=Math.floor(t%3600/60),i=String(t%60).padStart(2,"0"),r>0?`${r}:${String(a).padStart(2,"0")}:${i}`:`${a}:${i}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?eg("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="fallback"?eg("chat.transcribeFallbackTitle",{name:e.name}):l?.state==="running"?eg("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${eg("chat.transcribeChecking")}`:l?.state==="failed"?eg("chat.transcribeFailedRow",{name:e.name,error:l.error}):eg("chat.transcribeSkipped",{name:e.name});return(0,n.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,n.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,n.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[l.plan.notice&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeUsageNotice")})]}),l?.state==="fallback"&&(0,n.jsxs)(n.Fragment,{children:[l.reason&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.reason}),l.completedParts>0&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:eg("chat.transcribeFallbackProgress",{done:l.completedParts,total:l.parts})}),(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeFallbackUsageNotice")})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{confirmed:!0}),children:eg("chat.transcribeStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),l?.state==="fallback"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{fallbackToken:l.token,approve:!0}),children:eg("chat.transcribeFallbackStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void t6(o),children:eg(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,n.jsxs)("div",{ref:tL,style:{position:"relative",minWidth:0},children:[tu&&D.length>0&&(0,n.jsxs)("div",{ref:tR,style:{position:"absolute",left:0,right:0,...ul(rk.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rk.maxHeight},children:[(0,n.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,n.jsx)("path",{d:"M3 4v5h5"}),(0,n.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rk.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let r=t===th;return(0,n.jsxs)("button",{ref:e=>{tO.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rM(e)},onMouseEnter:()=>tm(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,n.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,n.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),tr&&(0,n.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:eg("savedPrompts.saved")}),te&&e9&&(0,n.jsx)(c3,{ref:ta,value:ey,token:e9,cwd:ee,sessionTitle:et,style:ul(rC.side),maxHeight:rC.maxHeight,onReplace:rT,onClose:()=>tt(!1)}),e8&&null!==ro&&(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ul(rj.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rj.maxHeight},children:[(0,n.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,n.jsx)("span",{children:V?eg("chat.loadingCommands"):eg("chat.slashCommands",{label:ru})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rj.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==rl.length?rd.map(e=>(0,n.jsxs)("section",{style:{marginBottom:12},children:[(0,n.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,n.jsx)("span",{children:eg(uv[e.source])}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let r=t===e5,a=uk(e,tj);return(0,n.jsxs)("button",{ref:e=>{tz.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rE(e)},onMouseEnter:()=>e6(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${r?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:r?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,n.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:a?"var(--text-dim)":void 0},children:["/",e.name,a&&(0,n.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eg("chat.dormant")})]}),uw(e,eg)&&(0,n.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uw(e,eg)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,n.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eg("chat.noCommands")})})]}),to&&null!==ti&&(eh=tx&&(!tf||tf.cwd!==ee),em=1===rb.length?eg("chat.match"):eg("chat.matches",{count:rb.length}),ef=tf?.truncated&&!rv?ti.query?eg("chat.searchingAll"):eg("chat.indexTruncated"):"",(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ul(rS.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rS.maxHeight},children:[(0,n.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,n.jsx)("span",{children:eh?eg("chat.loadingFiles"):eg("chat.files",{label:em,hint:ef})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rS.maxHeight-34),overflowY:"auto",padding:4},children:eh||0!==rb.length?rb.map((e,t)=>{let r=t===tc,a=e.path.split("/").pop()??e.path,i=e.path.slice(0,e.path.length-a.length);return(0,n.jsxs)("button",{ref:e=>{tW.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rI(e)},onMouseEnter:()=>td(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,n.jsx)(aS,{size:14}):aT(a,14)}),(0,n.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[i&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:i}),a,e.isDir&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,n.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:rx&&!rv?eg("chat.searching"):eg("chat.noMatchingFiles")})})]})),(0,n.jsxs)("div",{className:`chat-composer-field${e1?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${e1?"var(--tool-bg)":o&&(r||i)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,n.jsx)("textarea",{className:"chat-composer-textarea",ref:tS,"aria-controls":te?"saved-prompt-menu":void 0,value:ey,onChange:e=>{tB.current=e.target.value,ew(e.target.value),tp(!1),rm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;rm(t.value,t.selectionStart)},onKeyDown:rL,onCompositionStart:()=>{tP.current=!0},onCompositionEnd:e=>{tP.current=!1,tF.current=Date.now();let t=e.currentTarget;rm(t.value,t.selectionStart)},onInput:rA,onPaste:rP,placeholder:o&&(r||i)?eg("chat.steerPlaceholder"):o?eg("chat.agentPlaceholder"):eg("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?eb?null:(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:r9}):(0,n.jsxs)("button",{className:"chat-composer-send",onClick:rs,disabled:!rh,"aria-busy":eX||void 0,"aria-label":eb?eg("chat.send"):void 0,title:eX?eg("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eb?44:void 0,padding:eb?0:"7px 14px",background:rh?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:rh?"var(--accent-hover)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,n.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eb?null:eg("chat.send")]})]})]}),e1&&(0,n.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e2?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eg("chat.shell")," \xb7 ",e2?eg("chat.outputLocal"):eg("chat.outputModel")]}),(0,n.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("div",{style:{flex:eb?"1 1 0%":"0 0 auto",minWidth:eb?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eb||!o)&&r5,!eb&&r6,!(eb&&o)&&(rF.length>0||rJ||p)&&m&&(0,n.jsxs)("div",{ref:tC,style:{position:"relative",flex:eb?"1 1 0%":void 0,width:eb?0:void 0,minWidth:44*!!eb},children:[(0,n.jsxs)("button",{className:`composer-chip${ek?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eC({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(e=>(e&&eT(""),!e))},disabled:o||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eb?"flex-start":void 0,padding:eb?"8px 10px":"8px 12px",height:32,width:eb?"100%":void 0,maxWidth:eb?"100%":220,overflow:"hidden",background:ek?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ek?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":rF.length>0?"Change model":"No available models",children:[b?(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rJ??(rF.length>0?"Select model":"No models")})]}),ek&&eS&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eS.top,eS.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eS.top+6}:{top:eS.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eS.left,width:"max-content",minWidth:eS.width};return(0,n.jsxs)("div",{ref:tN,style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:[rH&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsx)("input",{value:eN,onChange:e=>eT(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eT(""),ej(!1))},placeholder:eg("chat.filterModels"),"aria-label":eg("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eb,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,n.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[rK.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eg("chat.frequentModels")}),rK.map(({option:e,count:t})=>rG(e,"frequent",t))]}),rq.length>0&&!eN.trim()&&v&&(0,n.jsxs)("div",{style:{borderTop:rK.length>0?"1px solid var(--border)":"none"},children:[(0,n.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eE,"aria-controls":"model-role-rows",onClick:eR,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,n.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:eE?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,n.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,n.jsx)("span",{style:{textTransform:"uppercase"},children:eg("chat.modelRoles")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:rq.length}),rV&&(0,n.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:rV.tag??rV.role.toUpperCase()}),rV.name]})]}),(0,n.jsx)("div",{id:"model-role-rows",hidden:!eE,children:rq.map(e=>{let t=rV?.role===e.role,r=e.resolved?.name??e.resolved?.modelId??"";return(0,n.jsxs)("button",{onClick:()=>{ej(!1),eT(""),v(e.role)},title:e.selector??r,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,n.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[r,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eg("chat.allModels")})]}),0===rB.length?(0,n.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eN.trim()?eg("chat.noMatchingModels"):"No available models"}):rB.map((e,t)=>(0,n.jsxs)("div",{children:[rB.length>1&&(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>rG(e,"all"))]},e.provider))]})]})})()]}),eb&&o&&(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:r9}),!eb&&r3,!eb&&r7,!eb&&r1&&(0,n.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:r1}),!eb&&null!==M&&(0,n.jsx)("span",{title:eg(E?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:eg(E?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,n.jsx)(dp,{sessionId:er})]}),(0,n.jsxs)("div",{ref:t$,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eb?4:2},children:[eb?(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eU?" is-active":""}`,title:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,n.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eU?void 0:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:eg("chat.moreControls")}),(0,n.jsxs)("div",{role:"group","aria-label":eg("chat.moreControls"),style:{display:eU?"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:eb?"flex-start":"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:[eb&&(0,n.jsxs)(n.Fragment,{children:[o&&r5,r6,r3,r7]}),!o&&N&&(0,n.jsxs)("div",{ref:tM,style:{position:"relative"},children:[(0,n.jsxs)("button",{className:`composer-chip${e_?" is-active":""}`,onClick:()=>!o&&ez(e=>!e),disabled:o,title:eg("chat.changeToolPreset")+`: ${r4}`,"aria-label":eg("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:e_?"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=e_?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:r4})]}),e_&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:ua.map(e=>{let t=ui[e],r=(C??"default")===t,a="off"===e?eg("chat.noTools"):"default"===e?eg("chat.builtInTools",{tools:us}):eg("chat.allBuiltInTools",{tools:`${us} + ${uo}`});return(0,n.jsxs)("button",{onClick:()=>{ez(!1),r||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1},children:e}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:a})]},e)})})]}),!o&&y&&(0,n.jsx)("div",{children:(0,n.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eg("chat.stopCompaction"):eg("chat.compactContext"),"aria-label":k?eg("chat.stopCompaction"):eg("chat.compactContext"),children:k?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compacting")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compact")})]})})}),eb&&ne,eU&&(0,n.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eg("chat.collapseControls"),"aria-label":eg("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ez(!1),eO(!1),eB(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,n.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eg("chat.stopAgent"),"aria-label":eb?eg("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eb?44:void 0,padding:eb?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eb?null:eg("chat.stop")]}),(0,n.jsx)(dd,{sessionId:er,onEnsureSession:en,onTranscriptPersisted:ea}),!eb&&ne]})]})]})]})});function uO({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),r=e$(t);return(0,n.jsx)("div",{role:"status","aria-label":r,title:r,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eF(t).map((e,t)=>(0,n.jsx)("span",{style:e.style,children:e.text},t))})})}function uD({phases:e,flow:t,busy:r}){let{t:i}=(0,z.s)(),{st:s}=ag(),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(!1),h=(0,a.useId)(),m=e??[],{currentPhase:f,activeTask:g,remaining:x,completed:v,total:b,percent:y}=tL(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,r){if(!t||!e.current)return null;let n=r("flow.strip.running",{stage:r(`flow.stage.${e.current}`)});return e.attempt>1?`${n} \xb7 ${r("flow.attempt",{attempt:e.attempt})}`:n}(t,r,s);if(0===b&&null===j)return null;let S=b>0&&0===x;return(0,n.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,n.jsxs)("div",{className:"todo-strip-row",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,n.jsx)("span",{className:"todo-strip-lead",role:r?"status":void 0,children:j}),b>0&&(0,n.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!j&&f&&(0,n.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,n.jsx)("span",{className:"todo-strip-task",children:S?i("todo.allDone",{count:v}):g?.content??""}),(0,n.jsx)("span",{className:"todo-strip-count",children:S?i("todo.progressDone",{percent:y??0,completed:v,total:b}):i("todo.progress",{percent:y??0,completed:v,total:b,remaining:x})})]}),k&&(0,n.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,n.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,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,n.jsx)(oy,{flow:t,live:r,st:s,id:h}),o&&b>0&&(0,n.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let r=e.tasks.filter(e=>u||"completed"!==e.status);return 0===r.length?null:(0,n.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),r.map((e,t)=>(0,n.jsx)(aw,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,n.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:i(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function uH(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uU(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function uB(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let r={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let n=await t.getServiceWorkerRegistration();if(n)return await n.showNotification(e.title,{...r,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let n=t.createWindowNotification(e.title,r);return n.onclick=()=>{n.close(),e.onClick()},"window"}catch{return null}}class uq extends Error{constructor(e,t,r,n){super(e),this.status=t,this.code=r,this.accepted=n,this.name="AgentCommandError"}}async function uV(e,t){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok||n.error)throw new uq(n.error??`HTTP ${r.status}`,r.status,n.code,n.accepted);return n.data}let uK="ompweb-update-client-id",uG="ompweb-update-resume-intent-v2",uJ="ompweb-update-return-v1",uZ="cuelo-restart-return-v1",uY="ompweb-update-failure-return-v1",uX="ompweb:update-wake";function uQ(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function u0(){let e=sessionStorage.getItem(uK);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(uK,t),t}function u1(){sessionStorage.removeItem(uG)}function u2(){let e=sessionStorage.getItem(uJ);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 u8(e){let t=u2();if(!t||t.requestId!==e)return t;let r={...t,dismissed:!0};try{sessionStorage.setItem(uJ,JSON.stringify(r))}catch{}return r}async function u4(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:u0(),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 u5(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let r=await t.json().catch(()=>null);!function(e){let t=u2();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let r={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(uJ,JSON.stringify(r))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u1();let n=r?.wake;e.sessionId&&(n?.wake===!0||n?.reason==="already-claimed"||n?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(uX,{detail:{sessionId:e.sessionId}}))}async function u6(e){let t=function(e){let t=sessionStorage.getItem(uY);if(!t)return null;sessionStorage.removeItem(uY);try{let r=JSON.parse(t);if(1!==r.schemaVersion||r.requestId!==e.requestId||r.stageHash!==e.stageHash||r.clientId!==e.clientId)return null;return{wake:!0===r.wake}}catch{return null}}(e);return t?(u1(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(uX,{detail:{sessionId:e.sessionId}})),"failed"):(await u5(e),"resumed")}function u3(e,t){let r=new Map(e.map(e=>[e.id,e]));for(let e of t)r.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(r.get(e.id),e));let n=[...r.values()];return[...n.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...n.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function u7(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 u9(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function pe(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function pt(e){return t=>{let r=e?.isCompacting?e.compaction:null;if(!r)return t;let n=Date.now()-r.elapsedMs;return{startedAt:t?Math.min(t.startedAt,n):n,reason:t?.reason??r.reason}}}function pr(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],a=t[r];if(!n||!a||n.name!==a.name||n.tasks.length!==a.tasks.length)return!1;for(let e=0;e<n.tasks.length;e+=1){let t=n.tasks[e],r=a.tasks[e];if(!t||!r||t.content!==r.content||t.status!==r.status||t.blocker!==r.blocker||(t.dependsOn?.length??0)!==(r.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==r.dependsOn?.[t]))return!1}}return!0}function pn(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function pa(e,t){for(let r=e.length-1;r>=0;r--){let n=t[r]??null;if(!tn(n??void 0))return{message:e[r],entryId:n}}return null}let pi=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class ps 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 po(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pl(e){return new Promise(t=>setTimeout(t,e))}function pc(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,r)=>r===t?{...e,exiting:!0}:e)}function pd(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:pc(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:pc(e.visible)};case"remove":return function(e,t){let r=e,n=t;for(;n.length>0&&r.length<5;){let[e,...t]=n;r=[...r,e],n=t}return n.length>0&&!r.some(e=>e.exiting)&&(r=pc(r)),{visible:r,pending:n}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function pu(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 pp(e){let t,r=e.content;return"string"==typeof r?JSON.stringify({text:r,images:[]}):Array.isArray(r)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:r.map(pu).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function ph(e){return"user"===e.role?`user:${pp(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 pm(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 pf(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function pg(e){rN(e),e.clear()}function px(e,t,r){for(let n of r??[]){let r=rC(t,n);r&&e.add(r)}}function pv(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let pb=!1,py={width:0,height:0},pw=new Set,pk=null;function pj(){let e=window.visualViewport,t=pv();py.width!==window.innerWidth?py={width:window.innerWidth,height:window.innerHeight}:t||(py.height=Math.max(py.height,window.innerHeight));let r=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:r,viewportScale:n,baselineHeight:a}){return!(!e||Math.abs(n-1)>=.01)&&(t-r>120||a-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:py.height});if(r!==pb)for(let e of(pb=r,pw))e()}function pS(e){if(pw.add(e),!pk){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,pj()})},r=window.visualViewport;r?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),pj(),pk=()=>{r?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{pw.delete(e),0===pw.size&&pk&&(pk(),pk=null)}}function pC(){return(0,a.useSyncExternalStore)(pS,()=>pb,()=>!1)}let pN={count:50,end:null};function pT(e,t){let r=Math.max(e,0),n=null===t.end?r:Math.min(Math.max(t.end,0),r),a=Math.min(Math.max(t.count,0),n),i=n-a;return{startIndex:i,endIndex:n,hasMore:i>0,hasLater:n<r}}function pI(e,t,r){let{startIndex:n,endIndex:a}=pT(e,r);if(t>=n&&t<a)return r;let i=Math.max(0,t-10),s=Math.max(t+1,i+50);return s>=e?{count:e-i,end:null}:{count:s-i,end:s}}function pM({sticker:e,text:t,tag:r,followRef:i}){let s=(0,a.useRef)(null);return((0,a.useEffect)(()=>{(!i||i.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,n.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,n.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:r8[r]}),t&&(0,n.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,n.jsx)(cm(),{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 pE(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),r=(lu(t)?.message??t).trim();return r.length>0?r:null}function p$(e){return`omp-cues:${e}`}function pR(e,t){let r=[];for(let n of t)n.sessionId===e&&null!==n.anchorEntryId&&r.push({id:n.id,anchorEntryId:n.anchorEntryId,sticker:n.sticker,text:n.text,tag:n.tag});try{window.localStorage.setItem(p$(e),JSON.stringify(r.slice(-200)))}catch{}}let pL=[];function pA(e){return`omp-web:interrupted-dismissed:${e}`}let pP=(0,a.memo)(function({messages:e,entryIds:t,toolResultsMap:r,modelNames:i,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,main:g,process:x,dispatchSlots:v,compactedDispatch:b,openRequest:y,startIndex:w,endIndex:k,sentinelRef:j,laterSentinelRef:S,flashItem:C,t:N,onProcessLogChange:T,cues:I,cueFollowRef:M}){(0,a.useEffect)(()=>{T({groups:x,messages:e,entryIds:t,toolResults:r,modelNames:i,cwd:s,sessionId:f})},[T,x,e,t,r,i,s,f]);let E=(0,a.useMemo)(()=>(function(e){let t=new Map;for(let r=0;r<e.length;r++){let n=tt(e,r);n>=0&&t.set(n,function(e){let t="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");if(!t.startsWith("[interpreter] "))return t;let r=t.indexOf("\n\n");return r<0?t:t.slice(r+2)}(e[r]))}return t})(e),[e]),$=(0,a.useMemo)(()=>{let t=new Map;for(let[n,a]of function(e,t,r,n){let a=new Map;e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.idx,t)});let i=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=r[o.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(o.blocks?a.get(o.idx):void 0)??o.afterMainIndex??-1),l=t;!function(e,t,r){for(let n of e){if("toolCall"!==n.type||"learn"!==n.toolName&&"manage_skill"!==n.toolName)continue;let e=t?.get(n.toolCallId);if(!e||e.isError)continue;let a=n.input??{};if("manage_skill"===n.toolName){let e=to(a.action);if(!0===ts[e]){let t={kind:"skill",action:e,name:to(a.name)};r(JSON.stringify(t),t)}continue}let i=to(a.memory),s=a.skill,o=s?{action:to(s.action),name:to(s.name)}:void 0;r(JSON.stringify({kind:"lesson",memory:i,skill:o}),{kind:"lesson",memory:i.length>160?`${i.slice(0,160)}…`:i,...o?{skill:o}:{}})}}(o.blocks??e.content??[],n,(e,t)=>{if(l.has(e))return;l.add(e);let r=i.get(s);r?r.push(t):i.set(s,[t])})}}return i}(g,x,e,r)){let e=a.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(n,{role:"custom",customType:e9,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,r,N]),R=(0,a.useMemo)(()=>{let n=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(n=t.idx);return function(e,t,r,n,a,i,s=[]){let o=function(e,t,r){let n=new Map,a=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&sD(t,e.idx)===e.idx).map(e=>e.idx),i=null===r?null:sD(t,r),s=new Map;for(let[r,o]of(e.forEach((e,r)=>{"answer"===e.kind&&s.set(sD(t,e.anchorIdx),r)}),s)){if(r===i)continue;let e=a.find(e=>e>r);n.set(o,{from:r+1,to:e??t.length})}return n}(e,t,r),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,r]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(sU(t,n,r.from,u,d),u=Math.max(u,r.from),0===r.from&&i){let a=r.to-1;for(;a>=r.from&&tn(s[a]);)a-=1;if(s[a]!==i.throughEntryId)continue;let o=sW(t,r.from,r.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sH(t,n,r.from,r.to);c.set(e,{...i.summary,...p?{remaining:s_(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...i.ciHeads),u=r.to;continue}c.set(e,{...function(e,t,r,n,a,i=[]){let s=sW(e,r,n),o=sH(e,t,r,n);return{...sz(s,t,a),remaining:o?s_(o):null,span:sB(e,r,n),flow:sP(s,t,!1,i,a,sO(e,r,n))}}(t,n,r.from,r.to,a,d),latest:e===l})}return c}(g,e,n,r,s,y,t)},[g,e,r,s,l,y,t]),L=w>0,A=k<g.length,P=(a,g={})=>{let x=g.messageOverride??e[a],v=a-1;for(;v>=0&&tn(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=a+1;t<e.length;t++){let r=e[t].role;if("user"===r)break;if("assistant"===r){w=!1;break}}w&&d&&a===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,n.jsx)(lL,{message:x,toolResults:r,modelNames:i,cwd:s,onOpenFile:o,entryId:t[a],onFork:l||c||0===a&&"user"===x.role?void 0:u,forking:p===t[a],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:a>0?e[a-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary,inputTranslation:"user"===x.role?E.get(a):void 0,recoveredError:eK(e,a)},`${y}-view-${a}`)},F=(t,r)=>{let a=g[t],i="message"===a.kind&&e[a.idx]?.role==="user";return(0,n.jsx)("div",{"data-chat-item":t,"data-chat-question":i?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:r})};return(0,n.jsxs)(n.Fragment,{children:[L&&(0,n.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((i,l)=>{let c=w+l,d=b?.position===c?(0,n.jsx)(o_,{calls:b.calls}):null,u="message"===i.kind?i.anchorIdx??i.idx:i.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(r=>{let n=null!==r.anchorEntryId?t.indexOf(r.anchorEntryId):Math.min(r.liveIndex??-1,e.length-1);return n>=i.idx&&n<m}).map(e=>(0,n.jsx)(pM,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),y=h!==u,k=$.get(c),j=k?(0,n.jsx)(lL,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=y?(0,n.jsx)(cw,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:o}):null;if("message"===i.kind)return(0,n.jsxs)(a.Fragment,{children:[d,F(c,P(i.idx)),j,S,x]},`message-${i.idx}`);let C=tN(i.precedingBlocks,r,s);return(0,n.jsxs)(a.Fragment,{children:[d,F(c,P(i.idx,{keyPrefix:`answer-${i.runIndex}`,messageOverride:function(e,t){let r=eB(e,t);if(!e.replyTranslation)return r;let n=e.content.find(e=>"text"===e.type);return n&&t.includes(n)||(r.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(r.content=t.filter(e=>"text"!==e.type))),r}(e[i.idx],i.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:R.get(c)})),j,S,x]},`answer-${i.idx}-${i.runIndex}`)}),b?.position===g.length&&k===g.length&&(0,n.jsx)(o_,{calls:b.calls}),A&&(0,n.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function pF({session:e,newSessionCwd:t,initialSessionData:i,transitioning:s=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onLabWidgetsChange:y,onOpenWorkspaceView:w,onOpenSessionList:k,onOpenMaker:j,selectedMaker:S,onProcessLogChange:C,onOpenFile:N,transcriptReplacement:T,onComposerFocusChange:I,onSessionBusyChange:M,onWaitingChange:E,onAttentionChange:$,soundEnabled:R=!0,onSoundToggle:L,playCueSound:A=async()=>({sticker:null,text:null}),preloadCueSound:P,unlockAudio:F,jumpRequest:_=null,onJumpHandled:W}){var O,D;let H,U,V,{t:K}=(0,z.s)(),G=pC(),J=B(),Z=(0,a.useRef)(A);Z.current=A;let Y=(0,a.useRef)(null),X=(0,a.useRef)(P);X.current=P;let[Q,et]=(0,a.useState)([]),er=(0,a.useRef)(Q);er.current=Q;let en=(0,a.useRef)(0),ea=(0,a.useRef)([]),ei=(0,a.useRef)([]),es=(0,a.useRef)(null),eo=(0,a.useRef)(0),el=(0,a.useRef)(-1),ec=(0,a.useRef)(-1),ed=(0,a.useCallback)(()=>{let e=es.current?.current;return e?{sessionId:e,turn:eo.current}:null},[]),eu=(0,a.useCallback)(e=>es.current?.current===e.sessionId&&eo.current===e.turn,[]),ep=(0,a.useCallback)((e,t,r,n)=>{if(!e.sticker&&!e.text)return;en.current=Math.max(en.current+1,Date.now());let a={id:en.current,sticker:e.sticker,text:e.text,tag:t,sessionId:r.sessionId},i="entry"===n.kind?{...a,anchorEntryId:n.entryId}:{...a,anchorEntryId:null,liveIndex:n.liveIndex,intent:n.intent};et(e=>{let t=[...e,i];return null!==i.anchorEntryId&&pR(r.sessionId,t),t})},[]),eh=(0,a.useCallback)((e,t,r,n)=>{let a=()=>eu(r)&&("working"!==t||ec.current!==r.turn);a()&&Z.current(e,t,a).then(e=>{null!==t&&null!==n&&a()&&ep(e,t,r,n)}).catch(()=>{})},[eu,ep]),em=(0,a.useCallback)(async(e,t,r,n)=>{let a=(await ap(e,t,r,n))?.alias??null;return a&&X.current?.(a),a},[]),ef=(0,a.useCallback)((e,t,r,n,a)=>{let i=function(e,t){let r=e.length-1;if(r<0)return null;let n=Math.min(e.length,t.length);if(r<n)return{kind:"entry",entryId:t[r]};let a=ni(e[r]),i=0;for(let t=n;t<=r;t++)ni(e[t])===a&&(i+=1);return{kind:"pending",liveIndex:r,intent:{baseEntryId:n>0?t[n-1]:null,identity:a,occurrence:i}}}(ea.current,ei.current);em(t.sessionId,r,n,a).then(r=>{eh(r,e,t,i)})},[eh,em]),[eg,ex]=(0,a.useState)(0),ev=(0,a.useRef)([]),eb=(0,a.useCallback)(e=>{if(eo.current+=1,null!==r3(e.outcome)){let t=e.sessionId;ev.current.push({completion:e,trigger:t?{sessionId:t,turn:eo.current}:null}),ex(e=>e+1)}o?.(e)},[o]);(0,a.useEffect)(()=>{for(let{completion:e,trigger:t}of ev.current.splice(0)){let r=r3(e.outcome),n="neutral"===r?null:r;t?ef(n,t,e.provider,e.credentialId,e.model):Z.current(null,n).catch(()=>{})}},[eg,ef]);let ey=(0,a.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ew,error:ek,messages:ej,entryIds:eS,streamState:eC,agentRunning:eN,bashRunning:eT,pendingBash:eI,modelNames:eM,modelList:eE,modelError:eR,modelScopeWarnings:eL,modelThinkingLevels:eA,modelThinkingLevelMaps:eP,modelRoles:eF,toolPreset:e_,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eO,fastMode:eD,fastModeBusy:eH,handleFastModeToggle:eU,retryInfo:eq,contextUsage:eZ,forkingEntryId:eY,isCompacting:e0,compaction:e1,compactError:e8,compactResult:e4,displayModel:e9,modelSwitching:ts,sessionStats:to,runStateKnown:tc,compactedWork:td,slashCommands:tu,slashCommandsLoading:tp,deliveryRows:th,subagents:tm,todoPhases:tf,notices:tg,extensionDialog:tx,extensionResponse:tv,extensionCustomUi:tb,extensionStatuses:ty,extensionWidgets:tw,respondToExtensionUi:tk,sendExtensionCustomInput:tj,isAutoModelSelection:tS,agentPhase:tC,isNew:tN,autoFollowPaused:tT,resumeAutoFollow:tI,pauseAutoFollow:tM,goalStatus:tE,sessionIdRef:tR,messagesEndRef:tL,scrollContainerRef:tA,handleSend:tP,handleAbort:t_,handleFork:tz,handleNavigate:tW,handleModelChange:tO,handleRoleModelChange:tD,handleMainPresetChange:tH,newSessionAccount:tU,handleCompact:tB,handleSteer:tq,handleFollowUp:tV,handlePromptWithStreamingBehavior:tK,handleAbortCompaction:tG,handleRecallQueue:tJ,handleRemoveQueuedMessage:tZ,handleBuiltinSlashCommand:tY,handleToolPresetChange:tX,handleThinkingLevelChange:tQ,loadSlashCommands:t0,ensureNewSession:t1,refreshLiveTranscript:t2}=function(e){let{session:t,newSessionCwd:n,initialData:i,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==n,f=i&&i.sessionId===t?.id?i:null,[g,x]=(0,a.useState)(f),[v,b]=(0,a.useState)(!m&&!f),[y,w]=(0,a.useState)(null),[k,j]=(0,a.useState)(f?.leafId??null),[S,C]=(0,a.useState)(f?.context.messages??[]),[N,T]=(0,a.useState)(f?.context.entryIds??[]),[I,M]=(0,a.useState)(f?.context.compactedWork??null),[E,$]=(0,a.useReducer)(u7,{isStreaming:!1,streamingMessage:null}),[R,L]=(0,a.useState)(!1),[A,P]=(0,a.useState)(!1),[F,_]=(0,a.useState)(null),[z,W]=(0,a.useState)({}),[O,D]=(0,a.useState)([]),[H,U]=(0,a.useState)(null),[B,q]=(0,a.useState)([]),[V,K]=(0,a.useState)({}),[G,J]=(0,a.useState)({}),[Z,Y]=(0,a.useState)([]),[X,Q]=(0,a.useState)(null),[ee,et]=(0,a.useState)(null),[er,en]=(0,a.useState)(null),[ea,ei]=(0,a.useState)("default"),[es,eo]=(0,a.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[el,ec]=(0,a.useState)(),[ed,eu]=(0,a.useState)(null),[ep,eh]=(0,a.useState)(null),[em,ef]=(0,a.useState)(!1),eg=(0,a.useRef)(0),ex=(0,a.useRef)(0),ev=(0,a.useRef)(""),[eb,ey]=(0,a.useState)(null),[ew,ek]=(0,a.useState)(f?.contextUsage??null),[ej,eS]=(0,a.useState)(null),[eC,eN]=(0,a.useState)(null),[eT,eI]=(0,a.useState)(null),[eM,eE]=(0,a.useState)(null),[eR,eL]=(0,a.useState)(!1),[eA,eP]=(0,a.useState)(!1),[eF,e_]=(0,a.useState)(null),[ez,eW]=(0,a.useState)(null),[eO,eD]=(0,a.useState)(null),eH=(0,a.useRef)(null),[eU,eB]=(0,a.useState)(!1),[eq,eV]=(0,a.useState)(null),[eK,eG]=(0,a.useState)([]),[eJ,eZ]=(0,a.useState)(!1),[eY,eX]=(0,a.useReducer)(pd,{visible:[],pending:[]}),[eQ,e0]=(0,a.useState)(null),[e1,e2]=(0,a.useState)(null),[e8,e4]=(0,a.useState)(null),e5=(0,a.useRef)(null),[e6,e3]=(0,a.useState)(null),[e9,te]=(0,a.useState)([]),[tt,ti]=(0,a.useState)([]),[ts,to]=(0,a.useState)({steering:[],followUp:[]}),[tl,tc]=(0,a.useState)([]),[td,tu]=(0,a.useReducer)(ia,[]),tp=(0,a.useRef)(0);(0,a.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,a.useEffect)(()=>{R||tu({type:"idle"})},[R]),(0,a.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,a.useMemo)(()=>(function(e,t){let r=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${it(t)}`;r.set(e,(r.get(e)??0)+1)}let n=[],a=(e,t)=>{t.forEach((t,a)=>{let i=`${e}\u0000${ie(t)}`,s=r.get(i)??0;s>0?r.set(i,s-1):n.push({key:`queue-${e}-${a}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let r of(a("steer",t?.steering??[]),a("followUp",t?.followUp??[]),e))n.push({key:`sent-${r.id}`,kind:r.kind,text:r.text,images:r.images,stage:r.stage,removable:r.inQueue});return n})(td,ts),[td,ts]),[tm,tf]=(0,a.useState)(null),tg=(0,a.useRef)(null),tx=(0,a.useRef)(null),tv=(0,a.useRef)(null),tb=(0,a.useRef)(null),ty=(0,a.useRef)(null),tw=(0,a.useRef)(0),tk=(0,a.useRef)(!1),tj=(0,a.useRef)(t?.id??null),tS=(0,a.useRef)(f?.leafId??null),tC=(0,a.useRef)(S),tN=(0,a.useRef)(N);tC.current=S,tN.current=N;let tT=(0,a.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tI=(0,a.useRef)(!1),tM=(0,a.useRef)(new Set);(0,a.useEffect)(()=>()=>pg(tM.current),[]);let tE=(0,a.useRef)(!1),t$=(0,a.useRef)(!1),tR=(0,a.useRef)(-1),tL=(0,a.useRef)("unknown"),tA=(0,a.useRef)(null),tP=(0,a.useRef)(null),tF=(0,a.useRef)(0),t_=(0,a.useRef)(!1),tz=(0,a.useRef)(0),tW=(0,a.useRef)(null),tO=(0,a.useRef)(null),tD=(0,a.useRef)(null),tH=(0,a.useRef)(!1),tU=(0,a.useRef)(!0),[tB,tq]=(0,a.useState)(!1),[tV,tK]=(0,a.useState)(null),tG=(0,a.useRef)(void 0),tJ=(0,a.useRef)(0),tZ=(0,a.useRef)(null),tY=(0,a.useRef)(0),tX=(0,a.useRef)(()=>{}),tQ=(0,a.useRef)(null),t0=(0,a.useRef)(null),t1=(0,a.useRef)(null),t2=(0,a.useRef)(null),t8=(0,a.useRef)(!1),t4=(0,a.useRef)(null),t5=(0,a.useRef)(null),t6=(0,a.useRef)(null),t3=(0,a.useRef)(null),t7=(0,a.useRef)(0),t9=(0,a.useRef)(null),re=(0,a.useRef)(null),rt=(0,a.useRef)(!1);rt.current=e.transitioning??!1;let rr=(0,a.useRef)(Date.now()),rn=(0,a.useRef)(0),ra=(0,a.useRef)(0),ri=(0,a.useRef)(null),rs=(0,a.useRef)(!1),ro=(0,a.useRef)(Promise.resolve()),rl=e.setToolPreset??ei,rc=eT??g?.context.model??eM??null,rd=m?X??er:rc,ru=(0,a.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},r=0,n=0,a=0,i=0,s=0;for(let t of S){if("user"===t.role&&(n+=1),"toolResult"===t.role&&(i+=1),"assistant"!==t.role)continue;a+=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,r+=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:n,assistantMessages:a,toolCalls:s,toolResults:i,totalMessages:S.length,tokens:e,cost:r,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),rp=(0,a.useRef)(0),rh=(0,a.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(rp.current+=1,tf(r=>r?.sid===e&&pr(r.phases,t)?r:{sid:e,phases:t}))},[]),rm=(0,a.useCallback)((e,t,r)=>{tj.current===e&&rp.current===r&&Array.isArray(t)&&tf(r=>r?.sid===e&&pr(r.phases,t)?r:{sid:e,phases:t})},[]),rf=(0,a.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),rg=(0,a.useCallback)(e=>{tN.current=e,T(e)},[]),rx=(0,a.useCallback)(async(e,t=!1,r=!1,n)=>{let a=!1;try{t&&b(!0);let i=n??null;if(!i){let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),n=await fetch(`/api/sessions/${encodeURIComponent(e)}?${r}`);if(404===n.status)return t&&(x(null),j(null),rf([]),M(null),w(null)),null;if(!n.ok)throw Error(`HTTP ${n.status}`);i=await n.json()}if(tj.current!==e)return null;x(i),j(i.leafId),tS.current=i.leafId??null;let s=ta(i.context.messages,i.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);rf(s.messages),rg(s.entryIds),M(i.context.compactedWork??null),ek(i.contextUsage??null),eI(e=>rs.current?e:null),w(null);let o=!r&&t3.current===e;if(o||(eo(i.context.configuredThinkingLevel??i.context.thinkingLevel??"off"),ec(i.context.thinkingLevel)),eu(i.context.thinkingCeiling??null),a=!0,t&&b(!1),!r){if(o)try{let t=t7.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(r.ok&&tj.current===e){let n=await r.json();tj.current===e&&t7.current===t&&(n.state?.thinkingLevel!==void 0?(eo(n.state.configuredThinkingLevel??n.state.thinkingLevel),ec(n.state.thinkingLevel)):n.running||(t3.current=null,eo(i.context.configuredThinkingLevel??i.context.thinkingLevel??"off"),ec(i.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=rp.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();if(tj.current!==e)return null;let a=n.state;return a?(void 0!==a.contextUsage&&ek(a.contextUsage??null),void 0!==a.systemPrompt&&eS(a.systemPrompt??null),void 0!==a.thinkingLevel&&(t3.current=e,eo(a.configuredThinkingLevel??a.thinkingLevel),ec(a.thinkingLevel)),void 0!==a.thinkingCeiling&&eu(a.thinkingCeiling??null),void 0!==a.extensionStatuses&&te(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ti(a.extensionWidgets??[]),void 0!==a.queuedMessages&&to(u9(a.queuedMessages)),void 0!==a.subagents&&tc(e=>u3(e,a.subagents??[])),rm(e,a.todoPhases,t)):n.running||to({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!a&&b(!1)}},[rm,rg,rf]),rv=(0,a.useCallback)(e=>{let t=ro.current.then(async()=>{tj.current===e&&await rx(e)});return ro.current=t.catch(()=>{}),t},[rx]),rb=(0,a.useCallback)(async(e,t)=>{let r=++ex.current;try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let a=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,i=await fetch(a);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(ex.current!==r||tj.current!==e)return;tS.current=t;let o=ta(s.context.messages,s.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);rf(o.messages),rg(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[rg,rf]),ry=(0,a.useCallback)(async e=>{try{let t=await uV(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(r.bind(r,14755));rl(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[rl]),rk=(0,a.useCallback)((e=0,t="(no messages)")=>{let r=tj.current;m&&n&&r&&!t8.current&&(t8.current=!0,l?.({id:r,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,n,l]),rS=(0,a.useCallback)(async()=>{if(t1.current)return t1.current;let e=tj.current;if(e&&re.current!==e||!e&&(!m||!n))return e;let t=(async()=>{let t=e;if(!t){let e=t4.current,r=t6.current,a=t5.current;e&&eE(e);let i={cwd:n,type:"ensure_session",toolNames:(0,ue.xG)(ea),...e?{provider:e.provider,modelId:e.modelId}:{},...r?{thinkingLevel:r}:{},...e&&null!==a?{oauthPosition:a}:{}},s=JSON.stringify(i),o=t2.current,l=o?.body===s?o.createRequestId:po();t2.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,createRequestId:l})});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();t2.current=null,t=d.sessionId,tj.current=t,null!==t9.current&&(re.current=t),d.model&&t4.current===e&&(eE(d.model),e||en(d.model)),d.thinkingLevel&&t6.current===r&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;re.current===t;){let e=t9.current;await uV(t,{type:"set_thinking_ceiling",ceiling:e}),t9.current===e&&re.current===t&&(re.current=null)}return t})();t1.current=t;try{return await t}finally{t1.current=null}},[m,n,ea]),rT=(0,a.useCallback)(async()=>{let e=tj.current??await rS();if(!e)return eG([]),[];eZ(!0);try{let t=await uV(e,{type:"get_commands"}),r=t?.commands??[];return eG(r),r}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[rS]),rI=(0,a.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),rM=(0,a.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),rE=(0,a.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),r$=(0,a.useCallback)(e=>{rE();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let r=JSON.parse(t.data);"session_snapshot"===r.type?tW.current?.(r):"agent_start"===r.type&&tO.current?.(e)}catch{}}},[rE]),rR=(0,a.useCallback)(e=>{rM();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let r=new Promise(r=>{let n=!1,a=e=>{n||(n=!0,clearTimeout(i),tv.current?.source===t&&(tv.current.pending=!1),r({status:e,source:t}))},i=setTimeout(()=>a("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&&a("connected"),tW.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(a("closed"),tg.current===t&&(tI.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tI.current||tk.current)&&rR(e)},1e3)}}});return tv.current={source:t,promise:r,pending:!0},r},[rM]),rL=(0,a.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let r=await rR(e);if("connected"!==r.status&&r.source.readyState!==EventSource.OPEN)throw tg.current===r.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===r.source&&(tv.current=null),r.source.close(),new ps(r.status)},[rR]),rA=(0,a.useCallback)(async(e,t)=>{let r=e5.current;if(r?.id===e.id&&"sending"===r.status)return;let n=tj.current,a=e=>{e5.current=e,e4(e)};if(!n)return void a({id:e.id,status:"failed",error:"no session"});a({id:e.id,status:"sending"});try{await uV(n,{type:"extension_ui_response",id:e.id,...t})}catch(t){a({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}a(null),e2(t=>t?.id===e.id?null:t)},[]),rP=(0,a.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{await uV(r,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rF=(0,a.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??po(),message:t,type:e.type??"info"}})},[]),r_=(0,a.useCallback)(e=>{let t={role:"custom",customType:e7,content:e$(e).trim(),display:!0,timestamp:Date.now()},r=tT.current,n=tj.current;r.sessionId!==n&&(r.sessionId=n,r.outputs=[]);let a=tN.current.slice(0,tC.current.length),i=null;for(let e=a.length-1;e>=0;e--)if(!tn(a[e])){i=a[e];break}r.seq+=1,r.outputs.push({entryId:`${tr}${r.seq}`,baseEntryId:i,message:t});let s=ta(tC.current,tN.current,r.outputs);rf(s.messages),rg(s.entryIds)},[rf,rg]),rz=(0,a.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e2(e=>e?.id===t.id?null:e),e5.current?.id===t.id&&(e5.current=null,e4(null));return}switch(uU(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":e2(t);break;case"notify":rF({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(e=>{let r=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...r,{key:t.statusKey,text:t.statusText}]:r});break;case"setWidget":ti(e=>{let r=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...r,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:r});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e3(e=>t.closed?e?.id===t.id?null:e:t)}},[rF,o,e.chatInputRef]),rW=(0,a.useCallback)(()=>{let e=tI.current;return tI.current=!1,L(!1),eV(null),pg(tM.current),ey(null),$({type:"end"}),e},[]),rO=(0,a.useCallback)(()=>{tL.current="unknown",tA.current=null;let e=pa(tC.current,tN.current);tP.current=e?{entryId:e.entryId,key:ph(e.message)}:null,tF.current+=1},[]),rD=(0,a.useCallback)(()=>{let e=tL.current,t=tA.current;if("unknown"===e){let r=pa(tC.current,tN.current),n=r?.message,a=tP.current;null!==r&&(null===a||(null!==r.entryId&&null!==a.entryId?r.entryId!==a.entryId:ph(r.message)!==a.key))&&n?.role==="assistant"&&n.stopReason&&(e=pn(n),t??={provider:n.provider,...n.model?{model:n.model}:{},...void 0!==n.credentialId?{credentialId:n.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),rH=(0,a.useCallback)(e=>{let t=rD();if("unknown"!==t.outcome||!e)return void s?.(t);let r=tF.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tF.current===r;s?.(e?rD():t)})},[s,rD]),rU=(0,a.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,rH(t),!0),[rH]),rB=(0,a.useCallback)(e=>{rI(),tk.current=!0;let t=tw.current,r=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let n=rp.current,a=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!a.ok)throw Error(`HTTP ${a.status}`);let i=await a.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=i.state;if(tc(e=>u3(e,s?.subagents??[])),rm(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tE.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tI.current=!0,L(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&s?.isCompacting){eP(!0),eD(pt(s)),ty.current=setTimeout(()=>void r(),600);return}if(i.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void r(),1e3);return}tk.current=!1,ty.current=null,rM()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void r(),600)}};ty.current=setTimeout(()=>void r(),3e4)},[rm,rI,rM]),rq=(0,a.useCallback)(async(e=tj.current,t=rn.current)=>{if(rn.current===t)try{e&&await rx(e)}finally{if(rn.current!==t)return;let r=t$.current,n=tE.current;t$.current=!1,tE.current=!1,ri.current=null;let a=rW();r?rU(t):n&&a&&rH(),e&&rB(e)}},[rx,rH,rU,rB,rW]),rV=(0,a.useCallback)(async(e,t)=>{await pl(800);let r=Date.now();for(;tI.current&&Date.now()-r<2e4;){if(void 0!==t&&rn.current!==t)return;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(r.ok){let n=await r.json(),a=n.state;if(!n.running||!a||!a.isStreaming&&!a.isPromptRunning)return void await rq(e,t)}}catch{}await pl(600)}},[rq]),rK=(0,a.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;t_.current&&tz.current===t&&tj.current===e;){await pl(1e3);try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)continue;let n=await r.json();if(n.state?.isBashRunning)continue;if(await rx(e),tz.current!==t||tj.current!==e)return;t_.current=!1,P(!1),_(null);return}catch{}}},[rx]),rG=(0,a.useCallback)(async e=>{if(!tI.current)return;let t=rn.current;try{let r=rp.current,n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let a=await n.json();if(rn.current!==t)return;let i=a.state;if(eP(i?.isCompacting??!1),eD(pt(i)),to(u9(i?.queuedMessages)),i?.contextUsage!==void 0&&ek(i.contextUsage??null),tc(e=>u3(e,i?.subagents??[])),rm(e,i?.todoPhases,r),a.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting||i.isHandoffRunning)||!tI.current)return;i&&(void 0!==i.systemPrompt&&eS(i.systemPrompt??null),void 0!==i.extensionStatuses&&te(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ti(i.extensionWidgets??[])),await rq(e,t)}catch{}},[rm,rq]),rJ=(0,a.useCallback)(async e=>{let t=await rx(e,!1,!0),r=t?.state;return!!t?.running&&!!r&&tj.current===e&&!tI.current&&!!(r.isStreaming||r.isPromptRunning||r.isHandoffRunning)&&(tE.current=!!r.isStreaming,t$.current=!!r.isPromptRunning,tI.current=!0,L(!0),eV(r.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),px(tM.current,e,r.pendingToolCalls),rR(e),!r.isStreaming&&r.isPromptRunning&&rV(e),!0)},[rR,rx,rV]),rZ=(0,a.useCallback)(async(e,t=rn.current)=>{let r=ra.current+1;ra.current=r;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let a=await n.json();if(r!==ra.current||tj.current!==e||rn.current!==t)return;a.state?.contextUsage!==void 0&&ek(a.state.contextUsage??null)}catch{}},[]);(0,a.useEffect)(()=>{if(!eA){eH.current=null,eD(null);return}eD(e=>e??{startedAt:Date.now(),reason:eH.current})},[eA]),(0,a.useEffect)(()=>{if(!R&&!eA)return;let e=()=>{let e=tj.current;e&&rZ(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[R,eA,rZ]),(0,a.useEffect)(()=>{if(!R)return;let e=()=>{let e=tj.current;e&&rG(e)},t=()=>{"visible"===document.visibilityState&&e()},r=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(r),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[R,rG]),(0,a.useEffect)(()=>{if(R)return;let e=()=>{let e=tj.current;e&&!tI.current&&rJ(e)},t=()=>{"visible"===document.visibilityState&&e()},r=e=>{let t=tj.current,r=e.detail?.sessionId;t&&r===t&&!tI.current&&rJ(t).then(e=>{e||tj.current!==t||tI.current||rx(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(uX,r),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(uX,r)}},[R,rJ,rx]),tO.current=e=>{if(tj.current!==e||tI.current||tg.current||tD.current)return;let t=rJ(e).then(async t=>{t||tj.current!==e||tI.current||await rx(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,a.useEffect)(()=>{tI.current=R},[R]),tW.current=(0,a.useCallback)(e=>{var t;switch(e.type){case"session_snapshot":{let t=function(e,t,r,n,a){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===r||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let i=e.context.messages,s=new Map;for(let e of i){let t=ph(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(n.length,a.length);for(let e of n.slice(0,o)){let t=ph(e),r=s.get(t)??0;r>0&&s.set(t,r-1)}let l=n.slice(o).filter(e=>{let t=ph(e),r=s.get(t)??0;return 0===r||(s.set(t,r-1),!1)});return{entryId:e.entryId,messages:[...i,...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 r=ta(t.messages,t.entryIds,tT.current.sessionId===tj.current?tT.current.outputs:[]);rf(r.messages),rg(r.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tI.current;rI(),e&&rO(),tE.current=!0,tI.current=!0,L(!0),eV({kind:"waiting_model"}),$({type:"start"});break}case"agent_end":if(!tI.current)break;if(eV(null),pg(tM.current),ey(null),$({type:"end"}),tj.current){rx(tj.current);let e=rp.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&&te(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ti(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>u3(e,t.state?.subagents??[])),tj.current&&rm(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),to(u9(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tE.current;if(tE.current=!1,!e||t$.current)break;let t=tj.current,r=rW();eP(!1);let n=t?rx(t):void 0;t&&rB(t),r&&rH(n);break}case"prompt_done":{let e=rn.current,t=t$.current;t$.current=!1,ri.current=null;let r=tR.current!==e;if(!t&&!r)break;let n=tj.current;rU(e,n?rx(n):void 0),!tE.current&&(rW(),n&&rB(n))}break;case"prompt_error":tL.current="failed",rF({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tL.current="failed",rF({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tI.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&$({type:"update",message:s2(t)}),eV(null);break}case"message_end":{if(!tI.current)break;let t=e.message;if(t?.role==="assistant"&&(tA.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tL.current=pn(t)),t&&"user"===t.role){let e=s2(t),r=pp(e),n=ri.current;ri.current=null,rf(t=>{let a=t[t.length-1];return n&&a?.role==="user"&&pp(a)===n?n===r?t:[...t.slice(0,-1),e]:[...t,e]}),n||tu({type:"user-message",kind:is(e),text:ii(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&rf(e=>[...e,s2(t)]);let r=tj.current;r&&rZ(r),$({type:"reset"}),eV(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,r=e.thinkingLevel;t&&void 0!==r&&(t3.current=t,t7.current+=1,eo(e.configured??r),ec(r));break}case"todo_changed":rh(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,r=e.toolName,n=e.args,a=rC(tj.current,t);a&&tM.current.add(a),eV(e=>{let a=e?.kind==="running_tools"?[...e.tools]:[];return a.some(e=>e.id===t)||a.push({id:t,name:r,args:n}),{kind:"running_tools",tools:a}});break}case"tool_execution_update":{let r=rC(tj.current,"string"==typeof e.toolCallId?e.toolCallId:null);r&&tM.current.has(r)&&"string"==typeof e.text&&(t=e.text,rw.get(r)!==t&&(rw.set(r,t),rj()));break}case"tool_execution_end":{let t=e.toolCallId,r=rC(tj.current,t);r&&tM.current.delete(r)&&rN([r]),eV(e=>{if(e?.kind!=="running_tools")return e;let r=e.tools.filter(e=>e.id!==t);return 0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";tc(r=>{let n=r.find(e=>e.id===t.id);return u3(r,[{id:t.id,index:t.index??n?.index??0,agent:t.agent??n?.agent??t.id,agentSource:t.agentSource??n?.agentSource??"bundled",description:t.description??n?.description,status:e,task:n?.task,assignment:n?.assignment,sessionFile:t.sessionFile??n?.sessionFile,parentToolCallId:t.parentToolCallId??n?.parentToolCallId,lastUpdate:Date.now(),progress:n?.progress?{...n.progress,status:e}:void 0}])});break}let r={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};tc(e=>u3(e,[r]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let r=t.progress,n={id:r.id,index:t.index??r.index,agent:t.agent??r.agent,agentSource:t.agentSource??"bundled",description:r.description,status:r.status,task:t.task??r.task,assignment:t.assignment??r.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:r};tc(e=>u3(e,[n]));break}case"queue_update":to({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eH.current=e.reason;let t=e.reason;eD(e=>e?{...e,reason:t}:e)}eP(!0),e_(null),eW(null);break;case"auto_compaction_end":case"compaction_end":if(eP(!1),e.errorMessage)e_(e.errorMessage),eW(null);else if(!e.aborted){eW(pm(e.result,e.reason??"auto"));let t=tj.current;t&&(rx(t),rZ(t))}break;case"extension_ui_request":rz(e)}},[rF,rh,rm,rI,rz,rx,rH,rU,rZ,rO,rB,rW,rg,rf]);let rY=(0,a.useCallback)(async(r,a,i)=>{let s=r.trim();if(!s&&!a?.length&&!i?.length)return"returned";if(tI.current||t_.current||rs.current)return"unknown";let o=ld(r,i??[]),l=!a?.length&&!i?.length&&s.startsWith("/");if(!a?.length&&!i?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tG.current?.(t,e),"accepted"):"unknown"}rO();let c=rn.current+1;rI(),t$.current=!0;let d=a?.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()};rf(e=>[...e,u]),ri.current=pp(u),rn.current=c,tI.current=!0,L(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),$({type:"start"}),tX.current(!0);let p=a?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1,g="unknown";try{if(m&&n){let e=tj.current??await t1.current,t=await rS();t&&(h=t,X&&(eE(X),e&&await uV(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await rL(t),f=!0,await uV(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),rk(1,r),g="accepted")}else t&&(h=t.id,await rL(t.id),f=!0,await uV(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&rV(h,c),g}catch(o){console.error("Failed to send message:",o);let n=o instanceof uq&&"update_draining"===o.code&&!1===o.accepted;if(!(!f||o instanceof uq&&"prompt_rejected"===o.code&&!1===o.accepted||n)&&h)return rV(h,c),"unknown";t$.current=!1,tI.current=!1,rM();let s=ri.current;return s&&rf(e=>{let t=e[e.length-1];return t?.role==="user"&&pp(t)===s?e.slice(0,-1):e}),rF({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(r,pf(a),i,t?.id??h??void 0),ri.current=null,L(!1),eV(null),$({type:"end"}),"returned"}},[m,n,X,t,rS,rL,rk,rV,rF,rI,rM,e.chatInputRef,rO,rf]);tG.current=(0,a.useCallback)(async(r,n)=>{if(tI.current||t_.current)return;let a=`${n?"!!":"!"}${r}`;t_.current=!0,tX.current(!0),_({command:r,excludeFromContext:n}),P(!0);try{let e=tj.current??t?.id??await rS();if(!e)throw Error("Unable to create a session for the shell command");await uV(e,{type:"bash",command:r,excludeFromContext:n}),await rx(e),rk(1,a)}catch(t){console.error("Failed to execute shell command:",t),rF({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(a)}finally{t_.current=!1,_(null),P(!1)}},[rF,rS,rx,e.chatInputRef,rk,t]);let rX=(0,a.useCallback)(async()=>{let e=tj.current;if(e){if(t_.current){try{await uV(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uV(e,{type:"abort"}),tL.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),rQ=(0,a.useCallback)(async e=>{if(t_.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:r,newSessionId:n}=await uV(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!r&&n)return c?.(n),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eN(null)}},[c]),r0=(0,a.useCallback)(async e=>{if(t_.current)return;let t=tj.current;t&&(uV(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await rb(t,e))},[rb]),r1=(0,a.useCallback)(async e=>{if(t_.current)return;j(e);let t=tj.current;t&&(await rb(t,e),e&&uV(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[rb]),r2=(0,a.useCallback)(async(e,t)=>{if(m){let r={provider:e,modelId:t},n=t4.current?.provider===e;t4.current=r,n||(t5.current=null,et(null)),Q(r),eE(r);let a=tj.current??await t1.current;if(!a)return;try{await uV(a,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let r=tj.current;if(r&&!rs.current){rs.current=!0,eI({provider:e,modelId:t}),eL(!0);try{await uV(r,{type:"set_model",provider:e,modelId:t}),rs.current=!1,await rx(r)}catch(e){console.error("Failed to set model:",e),rs.current=!1,eI(eT),rF({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await rx(r)}finally{rs.current=!1,eL(!1)}}},[rF,eT,m,rx,Q]),r8=(0,a.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},r=e.oauthPosition,n={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==r?{oauthPosition:r}:{}},a=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(rs.current)return!1;rs.current=!0,eL(!0);let e=t4.current,i=t5.current,s=t6.current;try{t4.current=t,t5.current=r??null,t6.current="auto";let e=tj.current??await t1.current;return e&&await uV(e,n),Q(t),et(r??null),eE(t),eo("auto"),ec(void 0),e&&await rx(e),!0}catch(r){console.error("Failed to apply Main preset:",r),t4.current=e,t5.current=i,t6.current=s,rF({type:"error",message:a(r)});let t=tj.current;return t&&await rx(t),!1}finally{rs.current=!1,eL(!1)}}let i=tj.current;if(!i||rs.current)return!1;rs.current=!0,eI(t),eL(!0);try{return await uV(i,n),await rx(i),!0}catch(e){return console.error("Failed to apply Main preset:",e),eI(eT),rF({type:"error",message:a(e)}),await rx(i),!1}finally{rs.current=!1,eL(!1)}},[rF,eT,el,m,rx,Q,es]),r4=(0,a.useCallback)(async e=>{let t=Z.find(t=>t.role===e),r=t?.resolved;if(!r)return;if(m){let e={provider:r.provider,modelId:r.modelId},t=r.thinkingLevel;t6.current=t??null,eo(t??"auto"),ec(void 0),t4.current=e,t5.current=null,et(null),Q(e),eE(e)}let n=tj.current??(m?await t1.current:null);if(n)try{await uV(n,{type:"set_role_model",role:e}),m||eI({provider:r.provider,modelId:r.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,Q]),r5=(0,a.useCallback)(async()=>{let e=tj.current;if(e&&!eA){eH.current="manual",eP(!0),e_(null),eW(null);try{let t=await uV(e,{type:"compact"});eW(pm(t,"manual")),await rx(e,!0)}catch(e){e_(e instanceof Error?e.message:String(e)),eW(null)}finally{eP(!1)}}},[eA,rx]),r6=(0,a.useCallback)(async e=>{let r=n??t?.cwd??"",a=r?`/api/models?cwd=${encodeURIComponent(r)}`:"/api/models",i=await fetch(a,e?{signal:e}:void 0);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();W(s.models),U(s.modelError??null),q(s.modelScopeWarnings??[]),K(s.thinkingLevels??{}),J(s.thinkingLevelMaps??{}),Y(s.roles??[]);let o=s.modelList??[];if(D(o),m&&!tj.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];en(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t6.current&&eo(t??"auto")}},[m,n,t?.cwd]),r3=(0,a.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,r,n=""]=t,a=n.trim(),i=await rS(),s=e=>(e.handled&&(e.error?rF({type:"error",message:e.error}):"openSessionStats"!==e.action&&rF({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":{if(!i||eA)return s({handled:!0,error:"No active session to compact"});eH.current="manual",eP(!0),e_(null),eW(null);let e=await uV(i,{type:"compact",...a?{customInstructions:a}:{}});return eW(pm(e,"manual")),await rx(i,!0)&&rk(),s({handled:!0,message:"Compacted context"})}case"reload":if(!i)return s({handled:!0,error:"No active session to reload"});return await uV(i,{type:"reload"}),await Promise.all([rx(i,!1,!0),ry(i),rT(),r6()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!i)return s({handled:!0,error:"No active session to name"});if(!a)return s({handled:!0,error:"Usage: /name <name>"});return await uV(i,{type:"set_session_name",name:a}),await rx(i)&&rk(),s({handled:!0,message:`Session renamed to ${a}`});case"session":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"get_session_stats"});return e&&e0(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{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(!i)return s({handled:!0,error:"No active session to fork"});let e=await rQ();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"goal",args:a});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(r_(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&rF({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!i)return s({handled:!0,error:"No active session"});if(tI.current||t_.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tI.current=!0,L(!0),eV({kind:"running_command"});try{await rL(i);let e=await uV(i,{type:"handoff",...a?{customInstructions:a}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await rx(i,!0)&&rk(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tI.current=!1,L(!1),eV(null),tj.current===i&&rB(i)}default:{if(!i)return s({handled:!0,error:"No active session"});let t=await uV(i,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let r=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(r&&r_(r),t.prompt)return{handled:!0,prompt:t.prompt};if(r)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&eP(!1)}},[rF,r_,rL,rS,rQ,eA,r6,rx,rT,ry,rk,h,rB]),r7=(0,a.useCallback)(async(t,r,n)=>{let a=tj.current;if(!a)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n),"returned";let i=ld(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:i,images:s?.length??0});try{return await uV(a,{type:"steer",message:i,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(i){return tu({type:"fail",id:o}),console.error("Failed to steer:",i),rF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n,a),"returned"}},[rF,e.chatInputRef]),r9=(0,a.useCallback)(async(t,r,n,a)=>{let i=tj.current;if(!i)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(n),a),"returned";let s=ld(t,a??[]),o=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:r,text:s,images:o?.length??0});try{return await uV(i,{type:"prompt",message:s,streamingBehavior:r,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(r){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",r),rF({type:"error",message:r instanceof Error?r.message:String(r)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(n),a,i),"returned"}},[rF,e.chatInputRef]),ne=(0,a.useCallback)(async(t,r,n)=>{let a=tj.current;if(!a)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n),"returned";let i=ld(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:i,images:s?.length??0});try{return await uV(a,{type:"follow_up",message:i,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(i){return tu({type:"fail",id:o}),console.error("Failed to follow up:",i),rF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n,a),"returned"}},[rF,e.chatInputRef]),nt=(0,a.useCallback)(async()=>{let e=tj.current;if(e)try{await uV(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nr=(0,a.useCallback)(async()=>{let t=tj.current;if(t)try{var r;let n=await uV(t,{type:"clear_queue"});tu({type:"withdraw"}),to({steering:[],followUp:[]});let a={text:(r=[...n?.steering??[],...n?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:r.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(a.text,a.images.length?a.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),rF({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,rF]),nn=(0,a.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{let n=await uV(r,{type:"remove_queued_message",message:t,queue:e});if(!n?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(r=>{let n=r[e].indexOf(t);return(n<0&&""===t.trim()&&(n=r[e].indexOf("[Image]")),n<0)?r:{...r,[e]:r[e].filter((e,t)=>t!==n)}})}catch(e){console.error("Failed to remove queued message:",e),rF({type:"error",message:"Failed to remove queued message"})}},[rF]),na=(0,a.useCallback)(async(e,t=null)=>{let r="auto"===e?t:null,n=r!==ed;eo(e),eu(r),m&&(!tj.current||re.current===tj.current)&&(t6.current=e,t9.current=r),ec(void 0);let a=tj.current??await t1.current;if(a)try{re.current===a?await rS():n&&await uV(a,{type:"set_thinking_ceiling",ceiling:r}),await uV(a,{type:"set_thinking_level",level:e}),await rx(a)}catch(e){console.error("Failed to set thinking level:",e),rF({type:"error",message:"Failed to set thinking level"}),await rx(a)}},[m,rx,rF,ed,rS]);ev.current=rd?`${rd.provider}/${rd.modelId}`:"";let ni=e=>e?`${e}|${ev.current}`:null,ns=t?.id??tj.current,no=ni(ns),nl=ep&&ep.key===no?ep.value:null;(0,a.useEffect)(()=>{let e=++eg.current;no&&ns&&!R&&!eR&&fetch(`/api/agent/${encodeURIComponent(ns)}`).then(e=>e.json()).then(t=>{eg.current===e&&ni(tj.current)===no&&eh({key:no,value:(t.running?pe(t.state):void 0)??null})}).catch(()=>{})},[no,R,eR]);let nc=(0,a.useCallback)(async()=>{let e=tj.current??await rS(),t=ni(tj.current);if(!e||!t)return;let r=++eg.current,n=()=>eg.current===r&&ni(tj.current)===t,a=e=>{n()&&eh({key:t,value:e})};ef(!0);try{let r=ep?.key===t?ep.value?.enabled:void 0;if(void 0===r){let t=pe(await uV(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");r=t.enabled}if(!n())return;let i=await uV(e,{type:"set_fast_mode",enabled:!r});a({enabled:i?.enabled===!0,active:i?.active===!0})}catch(t){if(!n())return;rF({type:"error",message:t instanceof Error?t.message:String(t)});try{a(pe(await uV(e,{type:"get_state"}))??null)}catch{a(null)}}finally{ef(!1)}},[rS,ep,rF]),nd=(0,a.useCallback)(async e=>{let t=(0,ue.xG)(e);rl(e);let r=tj.current??await t1.current;if(r)try{await uV(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[rl]),nu=(0,a.useCallback)(e=>{tU.current=e,tq(t=>!e===t?t:!e)},[]);tX.current=e=>{tZ.current=null,nu(e)};let np=(0,a.useCallback)((e="smooth")=>{tY.current=Date.now()+700,tQ.current?.scrollIntoView({behavior:e})},[]),nh=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,nu(!0),np("smooth")},[np,nu]),nm=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,nu(!1)},[nu]),nf=(0,a.useCallback)(()=>{if(!tZ.current)return;tZ.current=null;let e=t0.current;e&&nu(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[nu]),ng=(0,a.useCallback)(e=>{if(e instanceof PointerEvent&&"mouse"===e.pointerType&&1===e.button&&!(e.target instanceof Element&&e.target.closest("a[href], input, textarea"))&&!(e.target instanceof HTMLElement&&e.target.isContentEditable)){if(tZ.current)return void nf();nm();let e=t0.current;return void(tZ.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}nf(),e instanceof KeyboardEvent&&(!pi.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[nf,nm]),nx=(0,a.useCallback)(()=>{let e=t0.current;if(!e)return;let t=tZ.current;if(null!==t){let r=t.top;t.moved||=e.scrollTop!==r,t.top=e.scrollTop;return}if(!tI.current&&!t_.current)return;let r=e.scrollHeight-e.scrollTop-e.clientHeight,n=Date.now()<=tJ.current;if(!(!n&&Date.now()<tY.current)){if(r<=72)return void nu(!0);n&&nu(!1)}},[nu]);return(0,a.useEffect)(()=>(tj.current=t?.id??null,tT.current.sessionId!==tj.current&&(tT.current={sessionId:tj.current,outputs:[],seq:0}),t&&rx(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;r$(t.id),e?.running&&(ry(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tE.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tI.current=!0,L(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),px(tM.current,t.id,e.state.pendingToolCalls),rR(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&rV(t.id)),e.state?.isBashRunning&&(t_.current=!0,P(!0),rK(t.id)),(e.state?.subagents?.length??0)>0&&rR(t.id));let r=e?.state;r&&(void 0!==r.isCompacting&&eP(r.isCompacting),eD(pt(r)),void 0!==r.contextUsage&&ek(r.contextUsage??null),void 0!==r.systemPrompt&&eS(r.systemPrompt??null),void 0!==r.thinkingLevel&&(t3.current=t.id,eo(r.configuredThinkingLevel??r.thinkingLevel),ec(r.thinkingLevel)),void 0!==r.thinkingCeiling&&eu(r.thinkingCeiling??null),void 0!==r.extensionStatuses&&te(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&ti(r.extensionWidgets??[]),void 0!==r.queuedMessages&&to(u9(r.queuedMessages)),void 0!==r.subagents&&tc(e=>u3(e,r.subagents??[])),void 0!==r.goal&&tK(r.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,rI(),rM(),rE()}),[t?.id]),(0,a.useEffect)(()=>{p?.(ej)},[ej,p]),(0,a.useEffect)(()=>{u&&u(g?.tree??[],k,r1)},[g?.tree,k,r1,u]),(0,a.useEffect)(()=>{let e=e=>{let t=tZ.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t0.current?.contains(e.target))?nf():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",ng),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",ng)}},[nf,ng]),(0,a.useEffect)(()=>{let e=t0.current;if(!e)return;let t=()=>{tZ.current?.moved&&nf()};return e.addEventListener("pointerdown",ng,{passive:!0}),e.addEventListener("wheel",ng,{passive:!0}),e.addEventListener("touchstart",ng,{passive:!0}),e.addEventListener("scroll",nx,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",ng),e.removeEventListener("wheel",ng),e.removeEventListener("touchstart",ng),e.removeEventListener("scroll",nx),e.removeEventListener("scrollend",t)}},[S.length,v,nf,nx,ng]),(0,a.useEffect)(()=>{if(rt.current||!R&&!A||!tU.current)return;let e=t0.current;if(!e)return;let t=requestAnimationFrame(()=>{tU.current&&(tY.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[R,A,S.length,E.streamingMessage,eq,F,e.transitioning]),(0,a.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,np("instant");return}if(!rt.current&&tU.current){let e=Date.now()-rr.current<1500;np(tI.current||t_.current||e?"instant":"smooth")}}},[S.length,R,A,np,e.transitioning]),(0,a.useEffect)(()=>{let e=new AbortController;return r6(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[r6,d]),(0,a.useEffect)(()=>{if(!ez)return;let e=setTimeout(()=>eW(null),6e3);return()=>clearTimeout(e)},[ez]),(0,a.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,a.useEffect)(()=>{e0(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:E,agentRunning:R,modelNames:z,modelList:O,modelError:H,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ea,thinkingLevel:es,effectiveThinkingLevel:el,thinkingCeiling:ed,retryInfo:eb,contextUsage:ew,systemPrompt:ej,forkingEntryId:eC,isCompacting:eA,compaction:eO,compactError:eF,compactResult:ez,currentModel:rc,displayModel:rd,modelSwitching:eR,sessionStats:ru,runStateKnown:eU,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:ts,deliveryRows:th,subagents:tl,todoPhases:tm&&tm.sid===tj.current?tm.phases:null,compactedWork:I,notices:eY.visible,extensionDialog:e1,extensionResponse:e8,extensionCustomUi:e6,extensionStatuses:e9,extensionWidgets:tt,respondToExtensionUi:rA,sendExtensionCustomInput:rP,isAutoModelSelection:m&&null===X,agentPhase:eq,isNew:m,autoFollowPaused:tB,resumeAutoFollow:nh,pauseAutoFollow:nm,goalStatus:tV,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tQ,scrollContainerRef:t0,handleSend:rY,handleAbort:rX,handleFork:rQ,handleNavigate:r0,handleModelChange:r2,handleRoleModelChange:r4,handleMainPresetChange:r8,newSessionAccount:ee,handleCompact:r5,handleSteer:r7,handleFollowUp:ne,handlePromptWithStreamingBehavior:r9,handleAbortCompaction:nt,handleRecallQueue:nr,handleRemoveQueuedMessage:nn,handleBuiltinSlashCommand:r3,handleToolPresetChange:nd,handleThinkingLevelChange:na,fastMode:nl,fastModeBusy:em,handleFastModeToggle:nc,loadTools:ry,loadSlashCommands:rT,ensureNewSession:rS,refreshLiveTranscript:rv,setActiveLeafId:j,setData:x,setMessages:C,dispatch:$,setAgentRunning:L,setForkingEntryId:eN,bashRunning:A,pendingBash:F,handleAgentEventRef:tW}}({session:e,newSessionCwd:t,initialData:i,transitioning:s,onAgentEnd:eb,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),t8=(0,a.useMemo)(()=>(function(e){let t=null,r=new Map;for(let n=0;n<e.length;n++){let a=e[n],i=e3(a);if(!i||"custom"!==a.role)continue;t??=[...e];let s=[];for(let t=0;t<n;t++){let n=e[t];if("assistant"!==n.role)continue;if(void 0===i.sourceHash){n.timestamp===i.sourceTimestamp&&s.push(t);continue}let a=r.get(t);void 0===a&&(a=function(e){let t=e6(e),r=5381;for(let e=0;e<t.length;e++)r=(r<<5)+r+t.charCodeAt(e)|0;return`${t.length}:${r}`}(n.content??[]),r.set(t,a)),a===i.sourceHash&&s.push(t)}s.length>1&&void 0!==i.sourceHash&&void 0!==i.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===i.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[n]={...a,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let r="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return r.startsWith(e5)?{kind:"translated",text:r.slice(e5.length),original:t}:r.startsWith("[번역 생략]")?{kind:"skipped",text:r,original:t}:{kind:"failed",text:r,original:t}}(a,e6(o.content??[]))}}return t??e})(ej),[ej]),t4=ah(e?.id,e9?.provider,void 0,e9?.modelId),t5=t4?.alias;(0,a.useEffect)(()=>{t5&&X.current?.(t5)},[t5]);let t6=(0,a.useMemo)(()=>{if(!e9)return null;let e=tN?tU:nh.find(e=>e.alias===t4?.alias)?.oauthPosition;return nh.find(t=>t.provider===e9.provider&&(void 0===t.oauthPosition?null===t4||t4.seed===t.seed:t.oauthPosition===e))?.alias??null},[e9,tN,tU,t4]),t3=eN||eT,t7=e?.id;ea.current=t8,ei.current=eS,es.current=tR;let t9=(0,a.useRef)(!0);t9.current=!tT;let re=(0,a.useRef)(!1);(0,a.useEffect)(()=>{eN&&!re.current&&(eo.current+=1),re.current=eN},[eN]),(0,a.useEffect)(()=>()=>{eo.current+=1},[]),(0,a.useEffect)(()=>{et(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(p$(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[]}}(t7),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t7)])},[t7]),(0,a.useEffect)(()=>{let e=tR.current;e&&er.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let r=!1,n=[];for(let a of t){if(null!==a.anchorEntryId||!a.intent||a.sessionId!==e){n.push(a);continue}let i=function(e,t,r){let n=Math.min(t.length,r.length),a=0;if(null!==e.baseEntryId){let t=r.indexOf(e.baseEntryId);if(-1===t||t>=n)return{kind:"drop"};a=t+1}let i=0;for(let s=a;s<n;s++)if(ni(t[s])===e.identity&&(i+=1)===e.occurrence)return{kind:"entry",entryId:r[s]};return null}(a.intent,t8,eS);if(null===i){n.push(a);continue}r=!0,"drop"!==i.kind&&("working"===a.tag&&[...t,...n].some(e=>"working"===e.tag&&e.anchorEntryId===i.entryId)||n.push({id:a.id,anchorEntryId:i.entryId,sticker:a.sticker,text:a.text,tag:a.tag,sessionId:a.sessionId}))}return r?(pR(e,n),n):t})},[t8,eS,tR]);let rt=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=tR.current,t=rt.current;if(rt.current=e?{sessionId:e,entryIds:eS}:null,!e||!t||t.sessionId!==e)return;let r=function(e,t,r){if(0===e.length||t.length<=e.length)return[];for(let r=0;r<e.length;r++)if(e[r]!==t[r])return[];let n=[],a=Math.min(r.length,t.length);for(let i=e.length;i<a;i++){let e=r[i];"assistant"===e.role&&"web6"===e.provider&&e.model===no&&n.push(t[i])}return n}(t.entryIds,eS,t8),n=ed();if(0===r.length||!n)return;let a=au(e,"web6",void 0)?.alias??null;for(let e of r)er.current.some(t=>t.anchorEntryId===e)||eh(a,"done",n,{kind:"entry",entryId:e})},[eS,t8,tR,ed,eh]);let rr=eN&&tC?.kind==="running_tools"&&tC.tools.length>0&&tC.tools.every(e=>"wait"===e.name),rn=ew||s,{hideThinkingBlock:ra}=(O=t??e?.cwd??null,H=rX(),(0,a.useEffect)(()=>{rY(O).catch(()=>{})},[O]),H),ri=(0,a.useMemo)(()=>({hideThinking:ra}),[ra]);(0,a.useEffect)(()=>{var e;if(!tx||Y.current===tx.id)return;Y.current=tx.id;let t=ed();if(!t)return;ec.current=t.turn;let r=eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,n=ns(ea.current,r,e9?.provider,e9?.modelId);ef("select"===(e=tx.method)||"ask"===e||"form"===e?"choice":"approval",t,n.provider,n.credentialId,n.model)},[tx,eC.streamingMessage,e9?.provider,e9?.modelId,ed,ef]),(0,a.useEffect)(()=>(v=t3?t_:null,()=>void(v=null)),[t3,t_]),(0,a.useEffect)(()=>{M?.(t3)},[M,t3]),(0,a.useEffect)(()=>()=>M?.(!1),[M]),(0,a.useEffect)(()=>{E?.(rr)},[rr,E]),(0,a.useEffect)(()=>()=>E?.(!1),[E]),(0,a.useEffect)(()=>{$?.(null!==tx)},[$,tx]),(0,a.useEffect)(()=>()=>$?.(!1),[$]);let{main:rs,process:ro}=(0,a.useMemo)(()=>(function(e,t,r={}){let n=[],a=[],i=-1,s=null,o=(e,t,r)=>{if(0===t.length)return;let i=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},a.push(s)),s),o=n.length-1;for(let e of t)i.entries.push({...e,afterMainIndex:o});i.messageCount+=t.length,i.toolCallCount+=r},l=e2(e),c=new Map,d=(e,t)=>{let r=c.get(e)??0;c.set(e,r+1),n.push({kind:"answer",anchorIdx:i,idx:e,runIndex:r,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let a of t){if("answer"===a.kind){n.push(a);continue}if("process"===a.kind){o(a.anchorIdx,a.entries,a.toolCallCount);continue}let t=e[a.idx];if(!t)continue;if("user"===t.role){u(),i=a.idx,n.push(a);continue}if(te(t)){n.push(void 0!==a.anchorIdx||i<0?a:{...a,anchorIdx:i});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===e3(t)&&0>tt(e,a.idx)&&o(i,[{idx:a.idx}],0);continue}let s=eG(t,r);if(eV(t,r)&&eK(e,a.idx)){let e=s.flatMap(e=>e.blocks);o(i,[{idx:a.idx}],eJ(e)),l.collect(a.idx,e);continue}let c=!1;for(let e of s){if("answer"===e.kind){d(a.idx,e.blocks),c=!0;continue}o(i,[{idx:a.idx,blocks:e.blocks}],eJ(e.blocks)),l.collect(a.idx,e.blocks)}!c&&eV(t,r)&&d(a.idx,[])}return u(),{main:n,process:a}})(t8,function(e,t={}){let r=-1;for(let t=e.length-1;t>=0;t--)if(ti(e[t])){r=t;break}let n=[];for(let a=0;a<e.length;){if(!ti(e[a])){n.push({kind:"message",idx:a}),a+=1;continue}let i=a,s=i+1;for(;s<e.length&&!ti(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&i===r||!function(e,t,r){for(let n=t;n<r;n++)if(e[n]?.role==="assistant")return!0;return!1}(e,i+1,s)){for(let e=i;e<s;e++)n.push({kind:"message",idx:e});a=s;continue}for(let r of(n.push({kind:"message",idx:i}),function(e,t,r,n){let a=[],i=[],s=0,o=[],l=0,c=0,d=e2(e.slice(t+1,r)),u=()=>{0!==i.length&&(a.push({kind:"process",anchorIdx:t,idx:i[0].idx,groupIndex:c++,entries:i,messageCount:i.length,toolCallCount:s,turnHasAnswer:!1}),i=[],s=0)},p=(e,r)=>{u(),a.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(r),precedingBlocks:o}),o=[]};for(let l=t+1;l<r;l++){let r=e[l];if("assistant"!==r.role){if(null!==e3(r)||tt(e,l)>=0)continue;if(te(r)){u(),a.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==r.role&&i.push({idx:l});continue}let c=eG(r,n);if(eV(r,n)&&eK(e,l)){let e=c.flatMap(e=>e.blocks);for(let t of(i.push({idx:l}),s+=eJ(e),d.collect(l,e),c))"process"===t.kind&&o.push(...t.blocks);continue}let 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(i.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eJ(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eV(r,n)&&p(l,[])}u();let h=d.takeRemaining();h&&a.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let m=a.some(e=>"answer"===e.kind);for(let e of a)"process"===e.kind&&(e.turnHasAnswer=m);return a}(e,i,s,{hideThinking:t.hideThinking})))n.push(r);a=s}return n}(t8,{sessionBusy:t3,isStreaming:eC.isStreaming,hideThinking:ri.hideThinking}),ri),[t8,t3,eC.isStreaming,ri]),rl=(0,a.useMemo)(()=>(function(e,t,r=[]){let n=new Map,a=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===a.length)return n;let i=-1,s=-1;t.forEach((e,t)=>{let r=a2(e);if(r.length>0){let e=a.filter(e=>e.item.anchorIdx===i||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=n.get(l.position);e?e.calls.push(...r):n.set(l.position,{calls:[...r],placement:o?"after":"before"})}}"user"===e.role&&(i=t),ti(e)&&(s=t)});let{continuing:o}=a8(e,t,r);if(o){let e=n.get(o.position);e?e.calls.unshift(...o.calls):n.set(o.position,{calls:o.calls,placement:"before"})}return n})(rs,t8,td?.messages),[rs,t8,td]),rc=(0,a.useMemo)(()=>(function(e,t,r=[]){let{atCompaction:n}=a8(e,t,r);if(0===n.length)return null;let a=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(a=t)});let i=e.findIndex(e=>e.idx>a);return{position:-1===i?e.length:i,calls:n}})(rs,t8,td?.messages),[rs,t8,td]),[rd,ru]=(0,a.useState)(pN),{startIndex:rp,endIndex:rh,hasLater:rm}=pT(rs.length,rd),rf=null!==rd.end&&rm,rg=(0,a.useRef)(rs.length);rg.current=rs.length;let rx=(0,a.useRef)(null),rv=(0,a.useRef)(null),rb=(0,a.useRef)(null);(0,a.useEffect)(()=>{null!==rd.end&&rd.end>=rs.length&&ru(e=>({count:e.count,end:null}))},[rd.end,rs.length]),(0,a.useEffect)(()=>{let e=rx.current,t=tA.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(rb.current=t.scrollHeight-t.scrollTop,ru(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rd,rs.length,tA]),(0,a.useEffect)(()=>{if(null==rb.current)return;let e=tA.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-rb.current),rb.current=null}},[rd.count,tA]),(0,a.useEffect)(()=>{let e=rv.current,t=tA.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ru(e=>(function(e,t,r=50){if(null===t.end)return t;let{startIndex:n,endIndex:a}=pT(e,t),i=a+r;return i>=e?{count:e-n,end:null}:{count:i-n,end:i}})(rg.current,e))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rd,rs.length,tA]);let[ry,rk]=(0,a.useState)(null),[rS,rT]=(0,a.useState)(0),rI=(0,a.useRef)(null),rM=(0,a.useCallback)(e=>{tM(),rI.current=e,rk(null),ru(t=>pI(rg.current,e,t)),rT(e=>e+1)},[tM]);(0,a.useLayoutEffect)(()=>{let e=rI.current,t=tA.current;if(null===e||!t)return;let r=t.querySelector(`[data-chat-item="${e}"]`);if(!r)return;rI.current=null;let n=document.createRange();n.selectNodeContents(r),t.scrollTop+=n.getBoundingClientRect().top-t.getBoundingClientRect().top-24,rk(e)},[rS,rd,rs,tA]),(0,a.useEffect)(()=>{if(null===ry)return;let e=setTimeout(()=>rk(null),1800);return()=>clearTimeout(e)},[ry]);let rE=(0,a.useCallback)(()=>{(0,q.flushSync)(()=>ru(pN));let e=tA.current;e&&(e.scrollTop=e.scrollHeight)},[tA]),r$=(0,a.useCallback)(()=>{rf&&rE(),tI()},[rf,rE,tI]),rR=(0,a.useRef)(null),[rL,rA]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(!_||rR.current===_.id||_.sessionId!==e?.id||ew||0===t8.length)return;rR.current=_.id,W?.(_.id);let t=eS.indexOf(_.entryId);if(t<0)return void rA(!0);let r=0;for(let e=0;e<rs.length;e++){let n=rs[e].idx;if(n>t||(r=e,n===t))break}rM(r)},[_,e?.id,ew,t8.length,eS,rs,rM,W]),(0,a.useEffect)(()=>{if(!rL)return;let e=setTimeout(()=>rA(!1),6e3);return()=>clearTimeout(e)},[rL]);let[rP,rF]=(0,a.useState)(!1),[r_,rz]=(0,a.useState)(0),rW=(0,a.useMemo)(()=>rP?rs.map(e=>(function(e,t){if("answer"===e.kind)return tl(e.blocks);let r=t[e.idx];return r&&"content"in r?tl(r.content):""})(e,t8).toLowerCase()):pL,[rP,rs,t8]),rO=(0,a.useCallback)(e=>{tM(),ru(t=>pI(rg.current,e,t))},[tM]),rD=(0,a.useCallback)(()=>rF(!1),[]);(0,a.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tA.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let r=e.target instanceof Element?e.target:null;if(r?.closest("[data-capture-keys], [role='dialog']"))return;let n=r?.closest("input, textarea, select, [contenteditable='true']");(!n||n.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),rF(!0),rz(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tA]);let rH=(0,a.useMemo)(()=>{let e=[];return rs.forEach((t,r)=>{if("message"!==t.kind)return;let n=pE(t8[t.idx]);null!==n&&e.push({item:r,text:n})}),e},[rs,t8]),rU=`${rp}:${rh}`,rB=eS.length>0?eS[eS.length-1]:null,[rq,rV]=(0,a.useState)(null),rK=(0,a.useRef)(!1);(0,a.useEffect)(()=>{rK.current||!tc||ew||!e?.id||(rK.current=!0,t3||!rB||!function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role||"toolResult"===r.role)return!0;if("assistant"===r.role){if(!r.stopReason)return!0;if("aborted"===r.stopReason||"error"===r.stopReason||"length"===r.stopReason)break;return r.content.some(e=>"toolCall"===e.type)}}return!1}(t8)||function(e){try{return window.localStorage.getItem(pA(e))}catch{return null}}(e.id)!==rB&&rV(rB))},[tc,ew,e?.id,t3,rB,t8]);let rG=(0,a.useCallback)(()=>{e?.id&&rq&&function(e,t){try{window.localStorage.setItem(pA(e),t)}catch{}}(e.id,rq),rV(null)},[e?.id,rq]),rJ=null!==rq&&rq===rB&&!t3&&!rf,rZ=to?[to.sessionId,to.sessionFile??"",to.sessionName??"",to.userMessages,to.assistantMessages,to.toolCalls,to.toolResults,to.totalMessages,to.tokens.input,to.tokens.output,to.tokens.cacheRead,to.tokens.cacheWrite,to.tokens.total,to.cost??0,to.totalActiveMs??0].join("|"):null,rQ=(0,a.useRef)(to);rQ.current=to,(0,a.useEffect)(()=>{f?.(rQ.current)},[rZ,f]),(0,a.useEffect)(()=>()=>{f?.(null)},[f]);let r0=eZ?`${eZ.percent??"null"}|${eZ.contextWindow}|${eZ.tokens??"null"}`:null,r1=(0,a.useRef)(eZ);r1.current=eZ,(0,a.useEffect)(()=>{x?.(r1.current)},[r0,x]),(0,a.useEffect)(()=>()=>{x?.(null)},[x]),(0,a.useEffect)(()=>{b?.(tm)},[b,tm]),(0,a.useEffect)(()=>()=>{b?.([])},[b]);let{regular:r2,lab:r8}=(0,a.useMemo)(()=>(function(e){let t=[],r=[];for(let a of e){var n;((n=a.key).startsWith(cF)&&null!==c_(n)?r:t).push(a)}return{regular:t,lab:r}})(tw),[tw]),r4=e?.id??null;(0,a.useEffect)(()=>{y?.(r4,r8)},[y,r4,r8]),(0,a.useEffect)(()=>()=>{y?.(null,[])},[y]);let{isDragOver:r5,handleDragEnter:r6,handleDragOver:r7,handleDragLeave:r9,handleDrop:ne}=function(e){let[t,r]=(0,a.useState)(!1),n=(0,a.useRef)(0),i=(0,a.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),n.current+=1,r(!0))},[]),s=(0,a.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:i,handleDragOver:s,handleDragLeave:(0,a.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,r(!1))},[]),handleDrop:(0,a.useCallback)(t=>{t.preventDefault(),n.current=0,r(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,a.useCallback)(e=>{t3||p?.current?.addAttachments(e)},[t3,p])),nt=(0,a.useMemo)(()=>{var e;return e=td?.messages,e&&e.length>0?[...e,...t8]:t8},[td,t8]),nr=(0,a.useMemo)(()=>{let e=new Map;for(let t of nt)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[nt]),nn=(0,a.useMemo)(()=>{let e,t,r,n,a,i,s,o,l,c,d;return e=new Map,t=new Map,r=new Map,n=new Map,a=new Map,i=new Map,s=new Map,o=(e,n,a)=>{let i=r.get(e);i&&n&&t.set(i,{status:n,order:a})},l=new Set,c=(e,t)=>{let n=t?r.get(t):void 0,i=aK(e.status);if(!n||l.has(n)||"completed"!==i&&"failed"!==i&&"aborted"!==i)return;l.add(n);let s=aV(e);null!==s&&a.set(n,s)},d=(e,t,n)=>{let a=t?r.get(t):void 0,i=aV(e);a&&"number"==typeof n&&null!==i&&"running"===aK(e.status)&&s.set(a,Math.max(s.get(a)??-1/0,n-i))},nt.forEach((t,a)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=nr.get(e.toolCallId);if(t)for(let a of aJ(e,t)??[])r.set(a.agentId,a.key),"number"==typeof t.timestamp&&n.set(a.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let r=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let r=JSON.parse(aG(e.content));t=r?.ok===!0?r.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let r=t.verdict;if("accepted"!==r&&"rework"!==r&&"held"!==r)return null;let n=aq(t.assignmentId),a=n?.split("#")??[];if(a.length<3)return null;let i=a[a.length-1],s=a.slice(1,-1).join("#");return/^\d+$/.test(i)&&s?{key:`${s}#${i}`,record:{verdict:r,attempt:"number"==typeof t.attempt?t.attempt:null,reason:aq(t.reason)}}:null}(t);if(!r)return;let n=e.get(r.key)??[];n.push({...r.record,order:a,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(r.key,n);return}if("wait"===t.toolName){let e=new Set;for(let n of aB(t.details?.jobs)){if("task"!==n.type)continue;let i=aq(n.id);if(i&&o(i,aK(n.status),a),c(n,i),d(n,i,t.timestamp),i&&"running"===aK(n.status)){let t=r.get(i);t&&e.add(t)}}for(let t of e)for(let r of e){if(t===r)continue;let e=i.get(t);e||i.set(t,e=new Set),e.add(r)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of aG(t.content).matchAll(aZ)){let t=Object.fromEntries([...e[1].matchAll(aY)].map(e=>[e[1],e[2]]));t.id&&o(t.id,aK(t.status),a)}for(let e of aB(t.details?.jobs))"task"===e.type&&c(e,aq(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:r,spawnedAt:n,durations:a,parallelWith:i,runStartedAt:s}},[nt,nr]),na=(0,a.useMemo)(()=>({ledger:nn,subagents:tm,toolResults:nr,onOpenPanel:w,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:j,selectedMaker:S}),[nn,tm,nr,w,e?.id,e?.cwd,t,j,S]),nl=(0,a.useMemo)(()=>{let e=new Set,t=[];for(let r=t8.length-1;r>=0;r-=1){let n=pE(t8[r]);if(!(!n||e.has(n))&&(e.add(n),t.push(n),t.length>=50))break}return t.reverse()},[t8]),nc=(0,a.useMemo)(()=>t$(t8,nr,tf,td?.todoPhases??null),[t8,nr,tf,td]),nd=(0,a.useMemo)(()=>cN(eC.streamingMessage).join("|"),[eC.streamingMessage]),nu=(0,a.useMemo)(()=>JSON.stringify(cC(eC.streamingMessage)),[eC.streamingMessage]),np=(0,a.useMemo)(()=>JSON.stringify(cI(eC.streamingMessage)),[eC.streamingMessage]),nm=(0,a.useMemo)(()=>(function(e,t,r=[],n=[],a=[]){let i=function(e){let t=new Map;for(let r of e){if("toolResult"!==r.role||"write"!==r.toolName)continue;let e=r.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let n=e.message;if(!n||"object"!=typeof n||Array.isArray(n)||"send"!==n.op)continue;let a=Array.isArray(n.receipts)?n.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(r.toolCallId,{from:"string"==typeof n.from?n.from:void 0,receipts:a})}return t}(e),s=[],o=new Map,l=-1;for(let r=0;r<e.length;r+=1){let n=e[r];if("user"===n.role){l=r;continue}let a=cN(n),c=cI(n,i);if(0===a.length&&0===c.length||l<0)continue;let d=cC(n),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,...a],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(r.length>0||a.length>0){let i=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){i=t;break}if(i>=0){let e=o.get(i);e||(e={index:i,entryId:t[i],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(i,e),s.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...r.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...n.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...a.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(t8,eS,nd.length>0?nd.split("|"):[],JSON.parse(nu),JSON.parse(np)),[t8,eS,nd,nu,np]),nf=e?.id??tR.current??void 0,ng=(U=c$(D=(0,a.useMemo)(()=>({sessionId:nf,sessionProvider:e9?.provider,turns:nm,messages:t8,subagents:tm}),[nf,e9?.provider,nm,t8,tm])),V=cP(D),(0,a.useMemo)(()=>(function(e){let t=new Map;for(let r of e){let e=t.get(r.turnIndex);e?e.push(r):t.set(r.turnIndex,[r])}return t})(function(e){let t=[];for(let r of e){let e=t[t.length-1];if(e&&e.speakerId===r.speakerId&&e.turnIndex===r.turnIndex&&e.text===r.text){t[t.length-1]=r;continue}t.push(r)}return t}([...U,...V])),[U,V])),nx=tN&&0===t8.length&&!eC.isStreaming&&!t3,nv=(0,a.useMemo)(()=>t8.filter(e=>"assistant"===e.role).length,[t8]),nb=function(e,t){let r=(0,a.useRef)(new Map),n=(0,a.useMemo)(()=>{if(!e)return r.current=new Map,0;let t=new Map,n=0;return(e.content??[]).forEach((e,a)=>{let i=eX(e);if(null===i)return;let s=eQ(r.current.get(a),i);t.set(a,{text:i,tokens:s}),n+=s}),r.current=t,n},[e]),i=(0,a.useRef)(n);i.current=n;let s=null!==e,o=e?.timestamp,[l,c]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(!s)return void c(null);let e=o??Date.now(),t=()=>{let t=(Date.now()-e)/1e3;c(t>=.5?i.current/t:0)};t();let r=setInterval(t,1e3);return()=>clearInterval(r)},[s,o,t]),s?l??0:null}(eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,nv),ny=(0,a.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("assistant"!==r.role)continue;let{usage:n,timestamp:a,completedAt:i}=r,s=n?.output??0;if(!(s<=0)&&a&&i&&!(i<=a))return s/((i-a)/1e3)}return null})(t8),[t8]),nw=e?.cwd??t??void 0,nk=e9?eA[`${e9.provider}:${e9.modelId}`]??null:null,nj=e9?eP[`${e9.provider}:${e9.modelId}`]??null:null,nS=(0,a.useRef)(null),nC=(0,a.useRef)(null),nN=(0,a.useCallback)(()=>{let e=nS.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,a.useEffect)(()=>(I?.(nN),()=>I?.(null)),[nN,I]),(0,a.useLayoutEffect)(()=>{let e=nC.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let r=tA.current?.clientHeight??0,n=()=>{let n=Math.ceil(e.getBoundingClientRect().height);n>0&&t.style.setProperty("--omp-dock-h",`${n}px`);let a=tA.current;if(!a)return;let i=r-a.clientHeight;r=a.clientHeight,i<=0||a.scrollHeight-a.scrollTop-a.clientHeight-i<=1&&(a.scrollTop+=i)};n();let a=new ResizeObserver(n);return a.observe(e),()=>a.disconnect()},[ew,tA]);let nT=(0,a.useCallback)((...e)=>(null!==rd.end&&rE(),tP(...e)),[tP,rd.end,rE]),nI=(0,n.jsx)("div",{ref:nS,"data-chat-composer":"",style:{display:"contents"},children:(0,n.jsx)(uW,{ref:p,sessionId:e?.id??tR.current??void 0,onEnsureSession:tN&&t?t1:void 0,onLiveTranscriptPersisted:t2,onSend:nT,onAbort:t_,onSteer:eN?tq:void 0,onFollowUp:eN?tV:void 0,onPromptWithStreamingBehavior:eN?tK:void 0,isStreaming:t3,model:e9,isAutoModelSelection:tS,modelNames:eM,modelList:eE,modelError:eR,modelScopeWarnings:eL,onModelChange:tO,onMainPresetChange:e||tN?tH:void 0,mainPresetActiveAlias:t6,modelRoles:eF,onRoleModelChange:tD,modelSwitching:ts,onCompact:e||tN?tB:void 0,onAbortCompaction:tG,isCompacting:e0,compactError:e8,compactResult:e4,toolPreset:e_,onToolPresetChange:e||tN?tX:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,outputTokensPerSecond:nb??ny,outputSpeedLive:null!==nb,thinkingCeiling:eO,onThinkingLevelChange:e||tN?tQ:void 0,fastMode:eD,fastModeBusy:eH,onFastModeToggle:e||tN?eU:void 0,availableThinkingLevels:nk,thinkingLevelMap:nj,retryInfo:eq,deliveryRows:th,inputHistory:nl,onRecallQueue:tJ,onRemoveQueuedMessage:tZ,slashCommands:tu,slashCommandsLoading:tp,onLoadSlashCommands:t0,onBuiltinCommand:tY,soundEnabled:R,onSoundToggle:L,onAudioUnlock:F,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name})}),nM=eC.streamingMessage,nE=(0,a.useMemo)(()=>nM?eG(nM,{isStreaming:!0}):[],[nM]),n$=(0,a.useMemo)(()=>nE.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[nE]),nR=(0,a.useMemo)(()=>nE.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[nE]),nL=nM?.role==="assistant"?nM:null,nA=(0,a.useMemo)(()=>{let e=-1;for(let t=t8.length-1;t>=0;t-=1)if("user"===t8[t].role){e=t;break}let t=e<0?-1:sD(t8,e);return{start:t,blocks:sW(t8,t+1,t8.length),priorCiHeads:sU(t8,nr,t+1),jobNotices:sO(t8,t+1,t8.length)}},[t8,nr]),nP=(0,a.useMemo)(()=>sP(nL?[...nA.blocks,...nL.content??[]]:nA.blocks,nr,t3,nA.priorCiHeads,nw,nA.jobNotices),[nA,nL,nr,t3,nw]),nF=(0,a.useMemo)(()=>t3?{...sz(nA.blocks,nr,nw),span:sB(t8,nA.start+1,t8.length)}:null,[t3,nA,nr,nw,t8]),n_=(0,a.useMemo)(()=>nF?{...nF,flow:nP,latest:!0}:null,[nF,nP]),nz=eN&&(tC?.kind==="running_tools"||(nL?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),nW=ns(t8,nL,e9?.provider,e9?.modelId),nO=nW.provider,nD=nW.model,nH=nW.credentialId;(0,a.useEffect)(()=>{if(!nz)return;let e=ed();e&&el.current!==e.turn&&ec.current!==e.turn&&(el.current=e.turn,ef("working",e,nO,nH,nD))},[nz,nO,nD,nH,ed,ef]);let[nU,nB]=(0,a.useState)(null),nq=(0,a.useCallback)(e=>{nB(e)},[]),nV=(0,a.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),nK=(0,a.useMemo)(()=>{let e=[eN&&!nM&&tC?function(e,t){if(e?.kind==="running_tools"){let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tC,K):null,eT&&!eI?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eN,nM,tC,eT,eI,K]);(0,a.useEffect)(()=>{if(!nU)return void C?.(null);let e=[],t=[],r=0;if(nM&&nR.length>0){let n=nU.messages.length+e.length;for(let a of(e.push(nM),nR))t.push({idx:n,blocks:a}),r+=eJ(a)}if(nV&&(t.push({idx:nU.messages.length+e.length}),e.push(nV)),0===t.length)return void C?.(nK?{...nU,status:nK}:nU);let n=-1;for(let e=nU.messages.length-1;e>=0;e--)if(ti(nU.messages[e])){n=e;break}let a=nU.groups.slice(),i=a.length>0?a[a.length-1]:void 0;i&&i.anchorIdx===n?a[a.length-1]={...i,entries:[...i.entries,...t],messageCount:i.messageCount+t.length,toolCallCount:i.toolCallCount+r}:a.push({anchorIdx:n,entries:t,messageCount:t.length,toolCallCount:r}),C?.({...nU,groups:a,messages:[...nU.messages,...e],status:nK})},[nU,nR,nM,nV,nK,C]),(0,a.useEffect)(()=>()=>C?.(null),[C]);let nG=r2.filter(e=>"belowEditor"!==e.placement),nJ=r2.filter(e=>"belowEditor"===e.placement);return ek?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ek}):(0,n.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":rn,"data-empty-start":nx&&!T?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:r6,onDragOver:r7,onDragLeave:r9,onDrop:ne,children:[rn?(0,n.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,n.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,r5&&!t3&&(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,n.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),tb&&(0,n.jsx)(pH,{request:tb,onInput:tj}),nx&&!T?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,n.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[860px] py-8",children:[(0,n.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,n.jsx)(ee,{})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.231"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.19.0"]})]})]})]}),nw&&(0,n.jsxs)("section",{className:"empty-workspace-context","aria-label":K("chat.emptyProjectLabel"),children:[(0,n.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,n.jsx)("span",{className:"empty-workspace-context-kicker",children:K("chat.emptyProjectLabel")}),(0,n.jsx)("strong",{children:tF(nw)||nw}),(0,n.jsx)("code",{title:nw,children:nw}),(0,n.jsx)("p",{children:K("chat.emptyProjectHint")})]}),k&&(0,n.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:k,children:K("chat.openSessionList")})]}),(0,n.jsx)(pW,{notices:tg,align:"right"})]})}):(0,n.jsxs)(n.Fragment,{children:[T&&(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:T}),(0,n.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!T,style:{display:T?"none":"flex"},children:[(0,n.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,n.jsx)(cs,{open:rP,onClose:rD,containerRef:tA,index:rW,renderedStart:rp,renderedEnd:rh,contentKey:t8,onReveal:rO,onProgrammaticScroll:tM,focusRequest:r_,t:K}),rL&&(0,n.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,n.jsx)(pW,{notices:tg,floating:!0,align:"right"})]})}),(0,n.jsx)("div",{ref:tA,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,n.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(pz,{widgets:nG}),(0,n.jsxs)(s7.Provider,{value:na,children:[(0,n.jsx)(cy,{utterances:ng,children:(0,n.jsx)(pP,{messages:t8,entryIds:eS,toolResultsMap:nr,modelNames:eM,messageCwd:nw,onOpenFile:N,sessionBusy:t3,isNew:tN,isStreaming:eC.isStreaming,handleFork:tz,forkingEntryId:eY,handleNavigate:tW,handleEditContent:ey,sessionId:e?.id??tR.current??void 0,main:rs,dispatchSlots:rl,compactedDispatch:rc,openRequest:td?.openRequest??null,process:ro,startIndex:rp,endIndex:rh,sentinelRef:rx,laterSentinelRef:rv,flashItem:ry,t:K,cues:Q,cueFollowRef:t9,onProcessLogChange:nq})}),!rf&&eC.isStreaming&&eC.streamingMessage&&n$.length>0&&(0,n.jsx)(lL,{message:eB(eC.streamingMessage,n$),sessionId:e?.id??tR.current??void 0,isStreaming:!0,modelNames:eM,cwd:nw,onOpenFile:N}),!rf&&n_&&(0,n.jsx)(o5,{summary:n_,live:!0,onOpenFile:N})]}),rJ&&(0,n.jsx)(cp,{onDismiss:rG,t:K}),(0,n.jsx)("div",{ref:tL})]})})}),(0,n.jsx)(co,{questions:rH,containerRef:tA,layoutKey:rU,onJump:rM,label:K("chat.questionRail")}),(t3&&tT||rf)&&(0,n.jsxs)("button",{type:"button",onClick:r$,"aria-label":K("chat.jumpToBottom"),title:K("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:J?44:void 0,borderRadius:"var(--seed-radius-full)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 5v14"}),(0,n.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,n.jsxs)("div",{ref:nC,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tx&&(0,n.jsx)("div",{style:{padding:"0 16px"},children:(0,n.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,n.jsx)(pD,{request:tx,onRespond:tk,onActivity:(e,t)=>void tj(e,t??"activity"),delivery:tv})})}),(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(cu,{compaction:e1,t:K}),(0,n.jsx)(p_,{goal:tE,t:K}),(0,n.jsx)(pz,{widgets:nJ}),(nc||nP.steps.length>0)&&!(G&&J)&&(0,n.jsx)(uD,{phases:nc,flow:nP,busy:t3})]})}),nI,(0,n.jsx)(uO,{statuses:ty})]})]})}function p_({goal:e,t}){if(!e)return null;let r=!e.enabled,a=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:rU(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:rU(e.tokensUsed)});return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:r?.7:1},children:[(0,n.jsx)("span",{style:{color:r?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,n.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:r?t("chat.goalPaused"):e.status}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:a})]})}function pz({widgets:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,n.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function pW({notices:e,floating:t=!1,align:r="left"}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===r?"flex-end":"stretch",marginBottom:10*!t},children:e.map((r,a)=>{let i="error"===r.type?"var(--danger)":"warning"===r.type?"var(--warning)":"success"===r.type?"var(--success)":"var(--accent)";return(0,n.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(a!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:r.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:i,flexShrink:0}}),(0,n.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.message})]},r.id)})})}function pO({focusKey:e,label:t,labelledBy:r,maxBlockSize:i="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,z.s)(),d=(0,a.useRef)(null),u=(0,a.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,a.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 r=document.activeElement;(null===r||r===document.body||e?.contains(r))&&t.focus()}},[e]),(0,n.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":r,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:i},children:[o?(0,n.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 pD({request:e,onRespond:t,onActivity:r,delivery:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,a.useState)({selected:{},custom:{}}),[u,p]=(0,a.useState)(""),h=(0,a.useRef)(0),m=(0,a.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!r)return;let t=Date.now();t-h.current<1e3||(h.current=t,r(e))},[e,r]);(0,a.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let r of e)t[r.id]=void 0!==r.recommended&&void 0!==r.options[r.recommended]?[r.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("form"===e.method)return(0,n.jsx)(pO,{focusKey:e.id,label:s("chat.agentQuestion"),delivery:i,children:(0,n.jsx)(c2,{request:e,onRespond:t,onActivity:r,delivery:i},e.id)});if("ask"===e.method){var g;let r=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),a=()=>{if(r){var n;t(e,{value:(n=e.questions,JSON.stringify({kind:"submit",results:n.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,n.jsx)(pO,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,n.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,r)=>{let i=c.selected[t.id]??[];return(0,n.jsxs)("section",{style:{paddingTop:20*(0!==r),borderTop:0===r?"none":"1px solid var(--hairline)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,n.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[r+1,"/",e.questions.length]})]}),(0,n.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,n.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,r)=>{let a=i.includes(r),o=t.recommended===r;return(0,n.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":a,onClick:()=>{m(),d(e=>(function(e,t,r){let n=e.selected[t.id]??[];if(t.multi){let a=n.includes(r)?n.filter(e=>e!==r):[...n,r];return{...e,selected:{...e.selected,[t.id]:a}}}return{selected:{...e.selected,[t.id]:[r]},custom:{...e.custom,[t.id]:""}}})(e,t,r))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${a?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:a?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,n.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${a?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:a?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:a&&(t.multi?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,n.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,n.jsxs)("span",{style:{minWidth:0},children:[(0,n.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:a?600:500},children:e.label}),e.description&&(0,n.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),a&&e.preview&&(0,n.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${r}`)})}),(0,n.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let r=e.target.value;d(e=>{let n;return n={...e.custom,[t.id]:r},t.multi||0===r.trim().length?{...e,custom:n}:{selected:{...e.selected,[t.id]:[]},custom:n}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&a()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,n.jsx)("button",{type:"button",disabled:!r||i?.status==="sending",onClick:a,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:r&&i?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:r&&i?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:r&&i?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:i?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,n.jsx)(pO,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,n.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,n.jsx)(rb,{children:e.planContent})}),(0,n.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.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,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback: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,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,n.jsx)(pO,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,n.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,n.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(r=>(0,n.jsx)("button",{onClick:()=>t(e,{value:r}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:r},r))}),"input"===e.method&&(0,n.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,n.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&f()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,n.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,n.jsx)("button",{onClick:f,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 pH({request:e,onInput:t}){let{t:r}=(0,z.s)(),i=(0,a.useRef)(null),s=(0,a.useRef)(!1),o=eP(e.lines);return(0,a.useEffect)(()=>{i.current?.focus()},[e.id]),(0,n.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||i.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,n.jsx)("textarea",{ref:i,"aria-label":r("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=ez[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":" ":e_[e.key]??null}(r);n&&(r.preventDefault(),r.stopPropagation(),t(e,n))},onInput:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=r.currentTarget.value;r.currentTarget.value="",n&&t(e,n)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:r=>{s.current=!1;let n=r.currentTarget;queueMicrotask(()=>{let r=n.value;n.value="",r&&t(e,r)})},onPaste:r=>{r.preventDefault();let n=r.clipboardData.getData("text");n&&t(e,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:r("chat.extensionPanel")}),(0,n.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:r("chat.close")})]}),(0,n.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,r)=>{var i;return(0,n.jsxs)(a.Fragment,{children:[(i=`line-${t}`,eF(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},`${i}-${t}`):e.text)),t<r.length-1?"\n":null]},t)})})]})})}var pU=r(40960),pB=r.n(pU);function pq({sessionId:e,refreshKey:t,compact:r}){let{t:i}=(0,z.s)(),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(null),h=(0,a.useRef)(e);h.current=e;let m=(0,a.useRef)(0);(0,a.useEffect)(()=>{if(!e)return;let t=!1,r=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(n=>{if(t||r!==m.current)return;let a=n.running?n.state?.computerTakeover:null;l(a?{sessionId:e,state:{enabled:!0===a.enabled,available:!0===a.available}}:null),p(null)}).catch(()=>{}),()=>{t=!0}},[e,t]);let f=(0,a.useCallback)(async e=>{let t=h.current;if(t){d(!0),p(null);try{let r=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),n=await r.json();if(!r.ok)throw Error("shared_settings"===n.code?i("computerTakeover.shared"):n.error??r.statusText);h.current===t&&(m.current+=1,l({sessionId:t,state:{enabled:!0===n.enabled,available:!0!==n.enabled}}))}catch(e){h.current===t&&p(i("computerTakeover.failed",{error:e instanceof Error?e.message:String(e)}))}finally{d(!1)}}},[i]),g=o&&o.sessionId===e?o.state:null;if(!g||!g.enabled&&!g.available)return null;let x=g.enabled,v=x?i("computerTakeover.active"):i("computerTakeover.allow"),b=u??(x?i("computerTakeover.activeHint"):i("computerTakeover.allowHint"));return(0,n.jsxs)(s.r,{className:`workspace-header-action workspace-takeover${x?` ${pB().active}`:""}`,variant:x?"neutralWeak":"ghost",size:"small",type:"button",disabled:c,"aria-pressed":x,"aria-label":v,title:b,onClick:()=>void f(!x),children:[(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!r)&&(0,n.jsx)("span",{children:v})]})}function pV({onPick:e,t}){let[r,i]=(0,a.useState)(""),[s,o]=(0,a.useState)({kind:"idle"}),l=(0,a.useRef)(null),c=r.trim();(0,a.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,n.jsxs)("div",{className:"palette-search",children:[(0,n.jsx)("input",{type:"search",value:r,onChange:e=>i(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 r=u.hits[0],n=u.sessions[r.sessionId];n&&e(n,r,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,n.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,n.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,n.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((r,a)=>{let i=u.sessions[r.sessionId],s=r.matchStart+u.query.length;return(0,n.jsxs)("button",{type:"button",disabled:!i,onClick:()=>i&&e(i,r,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(a+("ArrowDown"===e.key?1:-1)))},children:[(0,n.jsxs)("span",{className:"palette-search-title",children:[(0,n.jsx)("span",{children:i?i.name?.trim()||i.firstMessage?.trim()||i.id:""}),(0,n.jsx)("small",{children:"user"===r.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,n.jsxs)("span",{className:"palette-search-snippet",children:[r.snippet.slice(0,r.matchStart),(0,n.jsx)("mark",{children:r.snippet.slice(r.matchStart,s)}),r.snippet.slice(s)]})]},`${r.sessionId}:${r.entryId}`)})})]})]})}var pK=r(50640),pG=r(73620);let pJ=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pZ(e){return function e(t,r){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(r.has(t))return"[Circular]";r.add(t);try{return t.map(t=>e(t,r)).filter(Boolean).join(", ")}finally{r.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let pY=["tags","categories","keywords","tag","category"];function pX({data:e}){var t;if(!e)return null;let r=Object.entries(e);if(0===r.length)return null;let a="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,i=pY.find(t=>Array.isArray(e[t])),s=i?e[i].map(pZ).filter(Boolean):[],o=r.filter(([e])=>e!==i&&("title"!==e||!a));return(0,n.jsxs)("div",{className:"markdown-frontmatter",children:[a&&(0,n.jsx)("div",{className:"markdown-frontmatter-title",children:a}),s.length>0&&(0,n.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,n.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,n.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,n.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,n.jsx)("dt",{children:e}),(0,n.jsx)("dd",{children:function(e){let t=pZ(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,n.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var pQ=r(8745);let p0=(0,a.createContext)(null),p1=(0,n.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,n.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),p2=(0,n.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,n.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),p8=(0,n.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,n.jsx)("path",{d:"m10 3-5 5 5 5"})}),p4=(0,n.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,n.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),p5=(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,n.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,n.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function p6({back:e,title:t,titleTooltip:r,titleRef:a,titleAdornment:i,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:m}){let{t:f}=(0,z.s)();return(0,n.jsxs)("header",{className:"panel-header",children:[e&&(0,n.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,n.jsx)(o.In,{size:"16px",svg:p8})}),(0,n.jsxs)("div",{className:"panel-header-heading",children:[(0,n.jsx)("h2",{className:"panel-header-title",title:r,ref:a,tabIndex:a?-1:void 0,children:t}),i,l&&("path"===d?(0,n.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,n.jsx)("bdi",{dir:"ltr",children:l})}):(0,n.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,n.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,n.jsxs)(pQ.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,n.jsxs)(pQ.A.Item,{value:e.value,title:e.title,children:[(0,n.jsx)(pQ.A.ItemHiddenInput,{}),e.label]},e.value)),(0,n.jsx)(pQ.A.Indicator,{})]}),h.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,n.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,n.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,n.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,n.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,n.jsx)(c.k.Trigger,{asChild:!0,children:(0,n.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,n.jsx)(o.In,{size:"16px",svg:p5})})}),(0,n.jsx)(c.k.Positioner,{children:(0,n.jsx)(c.k.Content,{"aria-label":f("panel.more"),children:(0,n.jsx)(c.k.ScrollArea,{children:(0,n.jsx)(c.k.Group,{children:h.map(e=>(0,n.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,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,n.jsx)(p3,{}),m&&(0,n.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:m.onClick,"aria-label":m.label,title:m.label,children:(0,n.jsx)(o.In,{size:"16px",svg:p4})})]})}function p3({className:e="panel-header-button"}){let{t}=(0,z.s)(),r=(0,a.useContext)(p0);if(!r)return null;let i=t(r.expanded?"panel.restore":"panel.expand");return(0,n.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":r.expanded,"aria-label":i,title:i,onClick:r.onToggle,children:(0,n.jsx)(o.In,{size:"16px",svg:r.expanded?p2:p1})})}let p7="cuelo-html-pick",p9="cuelo-html-pick-exit";function he(e,t){return"string"==typeof e&&e.length<=t}function ht(e){return"number"==typeof e&&Number.isFinite(e)}function hr({content:e,title:t,picking:r,onExitPick:i,onRequestEdit:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null),d=(0,a.useMemo)(()=>{if(!r)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var r;let n=`<script>${(r=t,`(function(){
|
|
21
|
+
var NONCE=${JSON.stringify(r)},TYPE=${JSON.stringify(p7)},EXIT=${JSON.stringify(p9)};
|
|
22
|
+
var host=window.parent;
|
|
23
|
+
if(document.currentScript)document.currentScript.remove();
|
|
24
|
+
var box=document.createElement("div");
|
|
25
|
+
box.setAttribute("aria-hidden","true");
|
|
26
|
+
box.style.cssText="position:fixed;pointer-events:none;z-index:2147483647;border:2px solid #e5484d;outline:1px solid #fff;border-radius:2px;display:none;box-sizing:border-box";
|
|
27
|
+
document.documentElement.appendChild(box);
|
|
28
|
+
function pickable(t){return t&&t.nodeType===1&&t!==box&&t!==document.documentElement&&t!==document.body;}
|
|
29
|
+
function esc(v){return window.CSS&&CSS.escape?CSS.escape(v):String(v).replace(/[^a-zA-Z0-9_-]/g,"\\\\$&");}
|
|
30
|
+
function uniqueId(el){return el.id&&esc(el.id).length<=200&&document.querySelectorAll("#"+esc(el.id)).length===1;}
|
|
31
|
+
function cssPath(el){
|
|
32
|
+
if(uniqueId(el))return "#"+esc(el.id);
|
|
33
|
+
var parts=[],node=el;
|
|
34
|
+
while(node&&node.nodeType===1&&node!==document.body&&node!==document.documentElement){
|
|
35
|
+
if(node!==el&&uniqueId(node)){parts.unshift("#"+esc(node.id));break;}
|
|
36
|
+
var tag=node.tagName.toLowerCase(),part=tag,parent=node.parentElement;
|
|
37
|
+
if(parent){var same=0,index=0;for(var c=parent.firstElementChild;c;c=c.nextElementSibling){if(c.tagName===node.tagName){same++;if(c===node)index=same;}}if(same>1)part+=":nth-of-type("+index+")";}
|
|
38
|
+
parts.unshift(part);node=parent;
|
|
39
|
+
if(node===document.body){parts.unshift("body");break;}
|
|
40
|
+
}
|
|
41
|
+
// 부모 검사가 받는 길이 안에 들도록, 너무 길면 앞쪽 조상부터 떼어 낸다(끝 요소에 가까운 경로는 남는다).
|
|
42
|
+
while(parts.length>1&&parts.join(" > ").length>1000)parts.shift();
|
|
43
|
+
var sel=parts.join(" > ");
|
|
44
|
+
return sel.length>1000?sel.slice(-1000):sel;
|
|
45
|
+
}
|
|
46
|
+
function startTag(el){var s=el.cloneNode(false).outerHTML,end="</"+el.tagName.toLowerCase()+">";if(s.slice(-end.length).toLowerCase()===end)s=s.slice(0,-end.length);return s.slice(0,300);}
|
|
47
|
+
function show(el){var r=el.getBoundingClientRect();box.style.display="block";box.style.left=r.left+"px";box.style.top=r.top+"px";box.style.width=r.width+"px";box.style.height=r.height+"px";}
|
|
48
|
+
function block(e){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();}
|
|
49
|
+
window.addEventListener("pointermove",function(e){if(pickable(e.target))show(e.target);else box.style.display="none";},true);
|
|
50
|
+
window.addEventListener("pointerleave",function(){box.style.display="none";},true);
|
|
51
|
+
["pointerdown","mousedown","mouseup","pointerup","auxclick","dblclick"].forEach(function(n){window.addEventListener(n,function(e){if(pickable(e.target))block(e);},true);});
|
|
52
|
+
window.addEventListener("submit",block,true);
|
|
53
|
+
window.addEventListener("click",function(e){
|
|
54
|
+
block(e);
|
|
55
|
+
// 누르기 기본 동작을 막아 이 문서가 초점을 받지 못하므로, Escape가 이 문서로 오도록 직접 초점을 가져온다.
|
|
56
|
+
try{window.focus();}catch(err){}
|
|
57
|
+
var el=e.target;if(!pickable(el))return;
|
|
58
|
+
show(el);
|
|
59
|
+
var r=el.getBoundingClientRect();
|
|
60
|
+
var text=(el.textContent||"").replace(/\\s+/g," ").trim().slice(0,160);
|
|
61
|
+
host.postMessage({type:TYPE,nonce:NONCE,selector:cssPath(el),tag:el.tagName.toLowerCase(),id:String(el.id||"").slice(0,256),
|
|
62
|
+
classes:Array.prototype.slice.call(el.classList,0,32).map(function(c){return c.slice(0,128);}),text:text,startTag:startTag(el),
|
|
63
|
+
rect:{x:r.left,y:r.top,w:r.width,h:r.height},viewport:{w:window.innerWidth,h:window.innerHeight}},"*");
|
|
64
|
+
},true);
|
|
65
|
+
window.addEventListener("keydown",function(e){if(e.key==="Escape"){block(e);host.postMessage({type:EXIT,nonce:NONCE},"*");}},true);
|
|
66
|
+
})();`)}</script>`,a=-1;for(let t of e.matchAll(/<\/body>/gi))a=t.index;return a<0?e+n:e.slice(0,a)+n+e.slice(a)}(e,t)}},[r,e]),u=d.nonce,[p,h]=(0,a.useState)(null),[m,f]=(0,a.useState)(""),g=r&&m===u?p:null;return(0,a.useEffect)(()=>{if(!r)return;let e=e=>{let t=function(e,t,r,n){var a;if(!r||e!==r||!n||!t||"object"!=typeof t||t.nonce!==n)return null;if(t.type===p9)return{kind:"exit"};if(t.type!==p7)return null;let{selector:i,tag:s,id:o,classes:l,text:c,startTag:d}=t;if(!he(i,1e3)||0===i.length||!he(s,64)||!/^[a-z][a-z0-9-]*$/.test(s)||!he(o,256)||!he(c,160)||!he(d,300)||!Array.isArray(l)||l.length>32||!l.every(e=>he(e,128)))return null;let u=(a=t.rect)&&"object"==typeof a&&ht(a.x)&&ht(a.y)&&ht(a.w)&&ht(a.h)&&!(a.w<0)&&!(a.h<0)?{x:a.x,y:a.y,w:a.w,h:a.h}:null,p=t.viewport;return u&&p&&"object"==typeof p&&ht(p.w)&&ht(p.h)&&!(p.w<=0)&&!(p.h<=0)?{kind:"pick",element:{selector:i,tag:s,id:o,classes:[...l],text:c,startTag:d,rect:u,viewport:{w:p.w,h:p.h}}}:null}(e.source,e.data,c.current?.contentWindow,u);if(t){if("exit"===t.kind)return void i();h(t.element),f(u)}};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)},[u,i,r]),(0,n.jsxs)("div",{className:"html-pick-shell",children:[r&&(0,n.jsxs)("div",{className:"html-pick-bar","aria-label":l("files.pickedElement"),role:"group",children:[g?(0,n.jsxs)("p",{className:"html-pick-summary",title:`${g.selector}${g.text?`
|
|
67
|
+
${g.text}`:""}`,children:[(0,n.jsxs)("span",{className:"html-pick-tag",children:["<",g.tag,">"]}),g.text&&(0,n.jsxs)("span",{className:"html-pick-text",children:[' \xb7 "',g.text,'"']}),(0,n.jsx)("span",{className:"html-pick-selector",children:g.selector})]}):(0,n.jsx)("p",{className:"html-pick-summary html-pick-hint",children:l("files.pickElementHint")}),(0,n.jsxs)("div",{className:"html-pick-actions",children:[(0,n.jsx)(s.r,{variant:"neutralSolid",size:"small",disabled:!g,onClick:()=>g&&o(g),children:l("files.requestElementEdit")}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"small",disabled:!g,onClick:()=>h(null),children:l("files.clearPick")})]})]}),(0,n.jsx)("iframe",{ref:c,className:"html-pick-frame",srcDoc:d.srcDoc,sandbox:"allow-scripts",title:t},u||"plain")]})}let hn={source:"Source",preview:"Preview",diff:"Diff"},ha={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},hi={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function hs(){return(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,n.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function ho(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function hl(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let r=t.getRangeAt(0);if(!e.contains(r.startContainer)||!e.contains(r.endContainer))return null;let n=ho(r.startContainer),a=ho(r.endContainer);if(!n||!a||!e.contains(n)||!e.contains(a))return null;let i=Number(n.dataset.lineNumber),s=Number(a.dataset.lineNumber);if(!Number.isInteger(i)||!Number.isInteger(s))return null;if(i<s){let e=n.querySelector(".file-source-line-content");if(e?.contains(r.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(r.startContainer,r.startOffset),0===t.toString().length){let e=n.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(i=Number((n=e).dataset.lineNumber))}}let t=a.querySelector(".file-source-line-content");if(t?.contains(r.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(r.endContainer,r.endOffset),0===e.toString().length){let e=a.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((a=e).dataset.lineNumber))}}}return i>s?null:{startLine:i,endLine:s}}function hc({rows:e,stylesheet:t,useInlineStyles:r,wrapLines:a}){return e.map((e,i)=>{let s=e.children??[],o=s[0]?.properties?.className,l=Array.isArray(o)&&o.includes("react-syntax-highlighter-line-number"),c=l?s[0]:null,d=l?s.slice(1):s;return(0,n.jsxs)("span",{className:"file-source-line","data-line-number":i+1,style:{display:"flex",minWidth:"100%"},children:[c&&(0,pK.Ay)({node:c,stylesheet:t,useInlineStyles:r,key:`source-line-number-${i}`}),(0,n.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:a?"anywhere":"normal",whiteSpace:a?"pre-wrap":"pre"},children:d.map((e,n)=>(0,pK.Ay)({node:e,stylesheet:t,useInlineStyles:r,key:`source-token-${i}-${n}`}))})]},`source-line-${i}`)})}let hd=(0,a.memo)(function({content:e,language:t,isDark:r,wrapLines:a}){return(0,n.jsx)(tz.A,{className:a?"file-source-view is-wrapped":"file-source-view",language:"text"===t?"plaintext":t,style:r?tW.xJ:tW.vs,showLineNumbers:!0,lineNumberStyle:{...hi},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...ha,width:a?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:a?"anywhere":"normal"}},renderer:e=>(0,n.jsx)(hc,{...e,wrapLines:a}),wrapLongLines:a,children:e})});function hu(e,t,r,n={}){let a=tP(e),i=new URLSearchParams({type:t});for(let[e,t]of(r&&i.set("sessionId",r),Object.entries(n)))void 0!==t&&i.set(e,String(t));return`/api/files/${a}?${i.toString()}`}let hp=(0,n.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,n.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,n.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,n.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),hh=(0,n.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,n.jsx)("path",{d:"M3 6h18"}),(0,n.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,n.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,n.jsx)("path",{d:"M3 18h7"})]}),hm=(0,n.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,n.jsx)("path",{d:"M4 4h6M4 4v6M20 4h-6M20 4v6M4 20h6M4 20v-6"}),(0,n.jsx)("path",{d:"m13 13 7 3-3 1-1 3z"})]});function hf({filePath:e,cwd:t,sourceSessionId:r,meta:a,watching:i,viewSwitch:s,actions:o=[],downloadable:l=!0}){let{t:c}=(0,z.s)(),d=tF(e),u=t_(e,t),p=u.endsWith(d)?u.slice(0,u.length-d.length).replace(/[\\/]+$/,""):"",h=c(i?"panel.liveSync":"i18n.notWatching");return(0,n.jsx)(p6,{title:d,titleTooltip:`${u}
|
|
68
|
+
${a}`,titleAdornment:null===i?void 0:(0,n.jsx)("span",{className:"panel-header-live",role:"img","aria-label":h,"data-live":i?"true":"false",title:h}),subtitle:p||void 0,subtitleKind:"path",viewSwitch:s,actions:l?[...o,{id:"download",label:c("i18n.downloadFile"),icon:hp,href:hu(e,"download",r),download:d}]:o})}function hg(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function hx({patch:e}){let t,{t:r}=(0,z.s)(),a=(t=ab(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!a.some(e=>"unchanged"!==e.type))return(0,n.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:r("i18n.noChanges")});let i=new Set(a.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of i)for(let t=Math.max(0,e-3);t<=Math.min(a.length-1,e+3);t++)s.add(t);let o=[],l=0;for(;l<a.length;)if(s.has(l)){let e=[];for(;l<a.length&&s.has(l);)e.push(a[l]),l++;o.push({hidden:!1,lines:e})}else{let e=0;for(;l<a.length&&!s.has(l);)e++,l++;o.push({hidden:!0,count:e})}return(0,n.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...ha},children:o.map((e,t)=>{if(e.hidden)return(0,n.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let r=e.lines.map((e,t)=>{let r="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",a="added"===e.type?"+":"removed"===e.type?"-":" ",i="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,n.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:r,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,n.jsx)("span",{style:hi,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,n.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:i,userSelect:"none",flexShrink:0,fontWeight:600},children:a}),(0,n.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,n.jsx)("div",{children:r},t)})})}function hv({filePath:e,cwd:t,sourceSessionId:r}){let[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),f=(0,a.useRef)(null),g=tF(e).toLowerCase().split(".").pop()??"";(0,a.useEffect)(()=>{l(0),d(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(hu(e,"watch",r));return f.current=t,t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}l(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{t.close(),f.current=null}},[e,r]);let x=hu(e,"read",r,o?{v:o}:void 0),v=null!=c?hg(c):null;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(hf,{filePath:e,cwd:t,sourceSessionId:r,watching:i,meta:[g||"image",u?`${u.w} \xd7 ${u.h}`:null,v].filter(Boolean).join(" \xb7 ")}),(0,n.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:h?(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13},children:h}):(0,n.jsx)("img",{src:x,alt:e,onLoad:e=>{let t=e.currentTarget;p({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>m("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function hb({filePath:e,cwd:t,sourceSessionId:r}){let[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),f=(0,a.useRef)(null),g=tF(e).toLowerCase().split(".").pop()??"";(0,a.useEffect)(()=>{l(0),d(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(hu(e,"watch",r));return f.current=t,t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}p(null),m(null),l(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{t.close(),f.current=null}},[e,r]);let x=hu(e,"read",r,o?{v:o}:void 0);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(hf,{filePath:e,cwd:t,sourceSessionId:r,watching:i,meta:[g||"audio",null!=u?function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),r=Math.floor(t/60);return`${r}:${String(t%60).padStart(2,"0")}`}(u):null,null!=c?hg(c):null].filter(Boolean).join(" \xb7 ")}),(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,n.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[h&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:h}),(0,n.jsx)("audio",{controls:!0,preload:"metadata",src:x,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>m("Failed to load audio"),style:{width:"100%"}},x)]})})]})}function hy({filePath:e,cwd:t,sourceSessionId:r}){let{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(!1),[l,c]=(0,a.useState)(0),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)(null),m=(0,a.useRef)(null),f=eD(e),g="pdf"===f,x=g?hu(e,"read",r,l?{v:l}:void 0):hu(e,"preview",r,l?{v:l}:void 0);return(0,a.useEffect)(()=>{c(0),u(null),h(null),o(!1),m.current&&(m.current.close(),m.current=null),fetch(hu(e,"meta",r)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(hu(e,"watch",r));return m.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!g&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),c(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),m.current=null}},[e,g,r]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(hf,{filePath:e,cwd:t,sourceSessionId:r,watching:s,meta:["docx"===f?"docx preview":"pdf",null!=d?hg(d):null].filter(Boolean).join(" \xb7 ")}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,n.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:i("i18n.previewFile",{file:tF(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function hw({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:a,onMentionLines:i,onAtMention:s,onInsertText:o,gitRefreshKey:l,initialDisplayMode:c,viewStateStore:d,viewStateKey:u}){return eH(e)?(0,n.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:r}):null!==(eO[eD(e)]??null)?(0,n.jsx)(hb,{filePath:e,cwd:t,sourceSessionId:r}):eU(e)?(0,n.jsx)(hy,{filePath:e,cwd:t,sourceSessionId:r}):(0,n.jsx)(hk,{filePath:e,cwd:t,sourceSessionId:r,onOpenFile:a,onMentionLines:i,onAtMention:s,onInsertText:o,gitRefreshKey:l,initialDisplayMode:c,viewStateStore:d,viewStateKey:u})}function hk({filePath:e,cwd:t,sourceSessionId:r,onOpenFile:i,onMentionLines:s,onAtMention:o,onInsertText:l,gitRefreshKey:c,initialDisplayMode:d,viewStateStore:u,viewStateKey:p}){let h,m,{isDark:f}=rh(),{t:g}=(0,z.s)(),x=p?u?.get(p):void 0,v=(0,a.useCallback)(e=>{u&&p&&u.set(p,{...u.get(p),...e})},[p,u]),b=x?.mode,[y,w]=(0,a.useState)(null),[k,j]=(0,a.useState)(null),[S,C]=(0,a.useState)(!1),[N,T]=(0,a.useState)(!0),[I,M]=(0,a.useState)(null),[E,$]=(0,a.useState)("source"),[R,L]=(0,a.useState)(!1),[A,P]=(0,a.useState)(!1),F=(0,a.useCallback)(()=>P(!1),[]),[_,W]=(0,a.useState)(!1),O=(0,a.useRef)(null),D=(0,a.useRef)(0),H=(0,a.useRef)(null),[U,B]=(0,a.useState)(null),q=(0,a.useCallback)(e=>fetch(hu(e,"read",r)).then(e=>e.json()).then(e=>e.error?(M(e.error),null):(M(null),w(e),e)).catch(e=>(M(String(e)),null)),[r]),V=(0,a.useCallback)(async e=>{let r=++D.current;if(C(!0),!t){j(null),C(!1);return}try{let n=new URLSearchParams({cwd:t,path:e}),a=await fetch(`/api/git/diff?${n.toString()}`),i=await a.json();if(r!==D.current)return;j(a.ok&&i.supported&&"string"==typeof i.patch?i:null)}catch{r===D.current&&j(null)}finally{r===D.current&&C(!1)}},[t]);(0,a.useEffect)(()=>{T(!0),M(null),w(null),j(null),$("source"),L(!1),W(!1),O.current&&(O.current.close(),O.current=null),q(e).finally(()=>T(!1));let t=new EventSource(hu(e,"watch",r));return O.current=t,t.addEventListener("connected",()=>{W(!0)}),t.addEventListener("change",()=>{q(e),V(e)}),t.addEventListener("error",()=>{W(!1)}),t.onerror=()=>{W(!1)},()=>{t.close(),O.current=null}},[e,q,V,r]),(0,a.useEffect)(()=>{V(e)},[V,e,c]),(0,a.useEffect)(()=>{let e=y?.language==="markdown"||y?.language==="html";if(b){"preview"===b&&e&&$("preview");return}e&&"diff"!==d&&$("preview")},[y?.language,d,b]);let K=k?.supported===!0&&"string"==typeof k.patch,G=K&&"deleted"===k.status;(0,a.useEffect)(()=>{K||"diff"!==E||$("source")},[E,K]),(0,a.useEffect)(()=>{G&&O.current&&(O.current.close(),O.current=null,W(!1))},[G]);let J=(0,a.useRef)(!1);(0,a.useEffect)(()=>{J.current=!1},[e]),(0,a.useEffect)(()=>{(b?"diff"===b:"diff"===d)&&K&&!J.current&&(J.current=!0,$("diff"))},[d,K,b]);let Z=(0,a.useRef)(!1);(0,a.useEffect)(()=>{Z.current=!1},[p]);let Y=x?.scrollTop;(0,a.useEffect)(()=>{if(Z.current||!y)return;if(!Y){Z.current=!0;return}if(b&&E!==b)return;let e=requestAnimationFrame(()=>{let e=H.current;e&&(e.scrollTop=Y,Z.current=!0)});return()=>cancelAnimationFrame(e)},[y,E,b,Y]);let X=(0,a.useMemo)(()=>y?.language==="markdown"?tJ(y.content):"",[y]),Q=(0,a.useMemo)(()=>y?.language==="markdown"?function(e){let t=function(e){let t=pJ.exec(e);if(!t)return null;let r=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;r.lastIndex=t[0].length;let n=r.exec(e);return n?{yaml:e.slice(t[0].length,n.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(n.index+n[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,pG.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(y.content):null,[y]);(0,a.useEffect)(()=>{let e=()=>{let e=H.current,t=s&&"source"===E&&e?hl(e,window.getSelection()):null;B(e=>e?.startLine===t?.startLine&&e?.endLine===t?.endLine?e:t)};if(e(),s&&"source"===E)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[y?.content,E,s]);let ee=(0,a.useCallback)(r=>{s&&r&&s(t_(e,t),r.startLine,r.endLine)},[t,e,s]);if((0,a.useEffect)(()=>{if(!s||"source"!==E)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let r=H.current,n=r?hl(r,window.getSelection()):null;n&&(e.preventDefault(),ee(n))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[E,ee,s]),N||"diff"===d&&S&&!y)return(0,n.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(hf,{filePath:e,cwd:t,sourceSessionId:r,meta:g("i18n.loading"),watching:null,downloadable:!1}),(0,n.jsx)("div",{role:"status",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:g("i18n.loading")})]});if(I&&!G)return(0,n.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(hf,{filePath:e,cwd:t,sourceSessionId:r,meta:I,watching:null,downloadable:!1}),(0,n.jsx)("div",{role:"alert",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--danger)",fontSize:13},children:I})]});if(!y&&!G)return null;let et=y?.language??"text",er=y?.content??"",en="html"===et,ea="markdown"===et,ei=(m=(h=tA(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===m?"/":2===m&&/^[a-zA-Z]:\//.test(h)?h.slice(0,3):h.slice(0,m),es=er.split("\n"),eo=G?"diff":E,el=G?["diff"]:["source",...en||ea?["preview"]:[],...K?["diff"]:[]],ec=G?g("files.deleted"):`${et} \xb7 ${es.length} lines \xb7 ${hg(y.size)}`,ed=en&&"preview"===eo&&!!l,eu=ed&&A;return(0,n.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(hf,{filePath:e,cwd:t,sourceSessionId:r,meta:ec,watching:G?null:_,downloadable:!G,viewSwitch:{label:g("i18n.fileViewMode"),value:eo,options:el.map(e=>({value:e,label:hn[e],title:"diff"===e?g("i18n.compareHead"):void 0})),onChange:e=>{$(e),P(!1),v({mode:e})}},actions:[...o||s?[{id:"mention",label:g("files.mention"),icon:(0,n.jsx)(hs,{}),onPointerDown:e=>e.preventDefault(),onClick:()=>{U&&s?ee(U):o?.(t_(e,t),!1)},title:U&&s?`${g("i18n.mentionSelectedLines")} (L${U.startLine}${U.startLine!==U.endLine?`-L${U.endLine}`:""})`:g("files.insertPath")}]:[],..."source"===eo?[{id:"wrap",label:R?g("i18n.disableWrap"):g("i18n.enableWrap"),icon:hh,pressed:R,onClick:()=>L(e=>!e)}]:[],...ed?[{id:"pick-element",label:g("files.pickElement"),icon:hm,pressed:A,onClick:()=>P(e=>!e)}]:[]]}),(0,n.jsx)("div",{ref:H,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},onScroll:e=>v({scrollTop:e.currentTarget.scrollTop}),children:"diff"===eo&&K?(0,n.jsx)(hx,{patch:k.patch}):en&&"preview"===eo?(0,n.jsx)(hr,{content:er,title:g("i18n.htmlPreview"),picking:eu,onExitPick:F,onRequestEdit:r=>{var n,a;let i;if(!l)return;let s=t_(e,t),o=function(e,t){if(!t)return null;let r=e.indexOf(t);if(r<0||e.indexOf(t,r+1)>=0)return null;let n=1;for(let t=e.indexOf("\n");t>=0&&t<r;t=e.indexOf("\n",t+1))n+=1;return n}(er,r.startTag);l((n=null===o?d8(s,!1):d4(s,o,o),a={element:e=>g("files.pickLocatorElement",{selector:e}),text:e=>g("files.pickLocatorText",{text:e}),position:e=>g("files.pickLocatorPosition",e)},i=[n.trimEnd(),a.element(r.selector)],r.text&&i.push(a.text(r.text)),i.push(a.position({x:Math.round(r.rect.x),y:Math.round(r.rect.y),w:Math.round(r.rect.w),h:Math.round(r.rect.h),vw:Math.round(r.viewport.w),vh:Math.round(r.viewport.h)})),`${i.join("\n")}
|
|
69
|
+
`))}}):ea&&"preview"===eo?(0,n.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[Q?.data&&(0,n.jsx)(pX,{data:Q.data}),(0,n.jsx)(tO.oz,{remarkPlugins:t0,rehypePlugins:t2,components:{code({className:e,children:t,...r}){let a=e?.replace("language-","").toLowerCase()??"",i=String(t);return e?.includes("language-")||i.includes("\n")?"mermaid"===a?(0,n.jsx)(rg,{code:i.replace(/\n$/,"")}):(0,n.jsx)(rv,{code:i.replace(/\n$/,""),lang:a}):(0,n.jsx)("code",{className:e,...r,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:r,...a}){delete a.node;let s=i?th(e,ei,t??ei):null;return s&&i?(0,n.jsx)("a",{href:e,...a,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),i(s))},children:r}):(0,n.jsx)("a",{href:e,...a,children:r})},img({src:e,alt:a,...i}){delete i.node;let s="string"==typeof e?th(e,ei,t??ei):null,o=s?hu(s,"read",r):e;return(0,n.jsx)("img",{src:o,alt:a??"",loading:"lazy",...i})},table:({children:e})=>(0,n.jsx)("div",{className:"markdown-table-wrap",children:(0,n.jsx)("table",{children:e})})},children:X})]}):(0,n.jsx)(hd,{content:er,language:et,isDark:f,wrapLines:R})})]})}function hj({tabs:e,activeTabId:t,onSelectTab:r,onCloseTab:i}){let{t:s,locale:o}=(0,z.s)(),[l,c]=(0,a.useState)(null);return(0,n.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===o?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let a=e.id===t;return(0,n.jsxs)("div",{className:`file-tab${a?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),i(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,n.jsxs)("button",{type:"button",role:"tab","aria-selected":a,onClick:()=>r(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,n.jsx)("span",{style:{flexShrink:0,opacity:a?1:.7,display:"flex",alignItems:"center"},children:aT(e.label,13)}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:a?500:400},children:e.label})]}),(0,n.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),i(e.id)},onMouseEnter:()=>c(e.id),onMouseLeave:()=>c(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:l===e.id?"var(--bg-hover)":"transparent",border:"none",color:l===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("i18n.close"),"aria-label":`${s("i18n.close")} ${e.label}`,children:(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,n.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let hS=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],hC=new Set(hS);function hN(e){return void 0!==e&&hC.has(e)}function hT(e){if(!e)return[...hS];let t=new Set(e);return hS.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function hI(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),r=t>=0?e.slice(t+1):void 0;return hN(r)?r:"inherit"}function hM(e,t){let r=e.lastIndexOf(":"),n=hN(r>=0?e.slice(r+1):void 0)?e.slice(0,r):e;return"inherit"===t?n:`${n}:${t}`}var hE=r(98795),h$=r.n(hE);function hR(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function hL({value:e,options:t,onChange:r,disabled:i=!1,placeholder:s="Select…",searchPlaceholder:o="Search options…",noResultsLabel:l="No matching options",ariaLabel:c,className:d,style:u}){let p=(0,a.useRef)(null),h=(0,a.useRef)(null),m=(0,a.useRef)(null),f=(0,a.useRef)([]),[g,x]=(0,a.useState)(!1),[v,b]=(0,a.useState)(""),[y,w]=(0,a.useState)(0),k=(0,a.useId)(),j=t.find(t=>t.value===e),S=(0,a.useMemo)(()=>{let e=hR(v.trim());return e?t.filter(t=>hR(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,a.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,a.useEffect)(()=>{g?requestAnimationFrame(()=>m.current?.focus()):b("")},[g]),(0,a.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,a.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,a.useEffect)(()=>{g&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=d9(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),T=e=>{e.disabled||(r(e.value),x(!1))},I=e=>{if(!S.length)return;let t=y;for(let r=0;r<S.length;r+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,n.jsxs)("div",{ref:p,className:`${h$().root}${d?` ${d}`:""}`,style:u,children:[(0,n.jsxs)("button",{ref:h,type:"button",className:h$().trigger,disabled:i,"aria-label":c,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,n.jsx)("span",{className:j?h$().value:h$().placeholder,children:j?.label??(e||s)}),(0,n.jsx)("svg",{className:h$().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,n.jsxs)("div",{className:h$().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,n.jsxs)("div",{className:h$().searchWrap,children:[(0,n.jsxs)("svg",{className:h$().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,n.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,n.jsx)("input",{ref:m,className:h$().search,value:v,placeholder:o,"aria-label":o,role:"combobox","aria-expanded":"true","aria-controls":k,"aria-activedescendant":S[y]?`${k}-${y}`:void 0,autoComplete:"off",spellCheck:!1,onChange:e=>{b(e.target.value),w(0)},onKeyDown:e=>{if("ArrowDown"===e.key)e.preventDefault(),I(1);else if("ArrowUp"===e.key)e.preventDefault(),I(-1);else if("Enter"===e.key){e.preventDefault();let t=S[y];t&&T(t)}else"Tab"===e.key&&x(!1)}})]}),(0,n.jsx)("div",{id:k,className:h$().options,role:"listbox","aria-label":c,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,r)=>(0,n.jsxs)("button",{ref:e=>{f.current[r]=e},id:`${k}-${r}`,type:"button",role:"option","aria-selected":t.value===e,className:h$().option,"data-active":r===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(r),onClick:()=>T(t),children:[(0,n.jsxs)("span",{className:h$().optionCopy,children:[(0,n.jsx)("span",{className:h$().optionLabel,children:t.label}),t.description&&(0,n.jsx)("span",{className:h$().optionDescription,children:t.description})]}),t.value===e&&(0,n.jsx)("svg",{className:h$().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,n.jsx)("div",{className:h$().empty,children:l})})]})]})}let hA=["global","project"],hP=["implSol","implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet","crossReviewOpenAI","crossReviewAnthropic","crossReviewAdvisory","preflightAnthropic","skim","draft","ocr","interpreter"];function hF(e){return`${e.provider}/${e.id}`}function h_({cwd:e,onRolesChanged:t}){let{t:r}=(0,z.s)(),[i,s]=(0,a.useState)([]),[o,l]=(0,a.useState)([]),[c,d]=(0,a.useState)({}),[u,p]=(0,a.useState)("global"),[h,m]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),b=(0,a.useCallback)(async t=>{if(!e){s([]),l([]),d({}),m(!1);return}m(!0),g(null);try{let r=`?cwd=${encodeURIComponent(e)}`,[n,a]=await Promise.all([fetch(`/api/model-roles${r}`,t?{signal:t}:void 0),fetch(`/api/models${r}`,t?{signal:t}:void 0)]);if(!n.ok)throw Error(`HTTP ${n.status}`);let i=await n.json();if(i.error)throw Error(i.error);if(!a.ok)throw Error(`HTTP ${a.status}`);let o=await a.json();s(i.roles??[]),l(o.modelList??[]),d(o.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[e]);(0,a.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,a.useCallback)(async(r,n)=>{if(e){v(r),g(null);try{let a=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:r,selector:n,scope:u})}),i=await a.json();if(!a.ok||i.error)throw Error(i.error??`HTTP ${a.status}`);s(i.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,a.useMemo)(()=>i.filter(e=>!e.hidden),[i]),k=w.some(e=>hP.includes(e.role)&&!e.selector);return e?(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:r("roles.title")}),(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r("roles.description")}),!h&&k&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:r("roles.harnessNote")})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:r("roles.scope")}),(0,n.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",overflow:"hidden"},children:hA.map(e=>(0,n.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?r("roles.scopeGlobal"):r("roles.scopeProject")},e))}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:r("i18n.loading")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:hM(e.selector??"","inherit"),a=hI(e.selector),i=hT(c[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=hP.includes(e.role);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,n.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,n.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),s&&(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:r(`roles.harness.${e.role}`)}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:s&&!e.selector?r("roles.harnessUnset"):r(`roles.source.${e.source}`)})]}),(0,n.jsx)(hL,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let r=o.find(e=>hF(e)===t),n=r?c[`${r.provider}:${r.id}`]:void 0,a=hI(e.selector),i=hT(n).includes(a)?a:"inherit";y(e.role,hM(t,i))},options:[{value:"",label:r("roles.unset")},...o.map(e=>({value:hF(e),label:`${e.name} — ${e.provider}`,searchText:hF(e)})),...t&&!o.some(e=>hF(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,n.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:r("roles.thinking")}),(0,n.jsx)("div",{role:"group","aria-label":`${e.name} ${r("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:i.map(i=>{let s=a===i;return(0,n.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===i?r("roles.thinkingInherit"):i,onClick:()=>{s||y(e.role,hM(t,i))},style:{padding:"3px 7px",border:`1px solid ${s?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:s?"var(--bg-selected)":"transparent",color:s?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:s?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:i},i)})})]})]},e.role)})})]}):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:r("roles.needsProject")})}function hz(e){window.open(e,"_blank","noopener,noreferrer")}var hW=r(67381),hO=r(64433),hD=r(70350),hH=r(88195),hU=r(9312),hB=r(87275),hq=r(22008),hV=r(95476),hK=r(35029),hG=r(14489),hJ=r(78728),hZ=r(19872),hY=r(7751),hX=r(92526),hQ=r(48238),h0=r(57794),h1=r(41098),h2=r(84604),h8=r(15315),h4=r(74278),h5=r(55457),h6=r(71437),h3=r(29167),h7=r(97283),h9=r(34166),me=r(33889),mt=r(85486),mr=r(74068),mn=r(83546),ma=r(83709);let mi={anthropic:{Icon:hW.A,hasColor:!1},openai:{Icon:hO.A,hasColor:!1},"openai-codex":{Icon:hO.A,hasColor:!1},google:{Icon:hD.A,hasColor:!0},"google-vertex":{Icon:hD.A,hasColor:!0},"ant-ling":{Icon:me.A,hasColor:!0},deepseek:{Icon:hH.A,hasColor:!0},groq:{Icon:hU.A,hasColor:!1},mistral:{Icon:hB.A,hasColor:!0},moonshotai:{Icon:hq.A,hasColor:!1},"moonshotai-cn":{Icon:hq.A,hasColor:!1},moonshot:{Icon:hq.A,hasColor:!1},minimax:{Icon:hV.A,hasColor:!0},"minimax-cn":{Icon:hV.A,hasColor:!0},fireworks:{Icon:hK.A,hasColor:!0},huggingface:{Icon:hG.A,hasColor:!0},cerebras:{Icon:hJ.A,hasColor:!0},openrouter:{Icon:hZ.A,hasColor:!1},xai:{Icon:hY.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:hX.A,hasColor:!0},"cloudflare-workers-ai":{Icon:hX.A,hasColor:!0},"vercel-ai-gateway":{Icon:hQ.A,hasColor:!1},"github-copilot":{Icon:h0.A,hasColor:!1},"amazon-bedrock":{Icon:h1.A,hasColor:!0},"azure-openai-responses":{Icon:h2.A,hasColor:!0},"kimi-coding":{Icon:h8.A,hasColor:!0},nvidia:{Icon:mt.A,hasColor:!0},opencode:{Icon:mr.A,hasColor:!1},"opencode-go":{Icon:mr.A,hasColor:!1},qwen:{Icon:h4.A,hasColor:!0},xiaomi:{Icon:mn.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:mn.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:mn.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:mn.A,hasColor:!1},zai:{Icon:ma.A,hasColor:!1},"zai-coding-cn":{Icon:ma.A,hasColor:!1},zhipu:{Icon:h5.A,hasColor:!0},cohere:{Icon:h6.A,hasColor:!0},perplexity:{Icon:h3.A,hasColor:!0},together:{Icon:h7.A,hasColor:!0},grok:{Icon:h9.A,hasColor:!1}},ms=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function mo({label:e,children:t}){return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let ml={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function mc({value:e,onChange:t,placeholder:r,mono:a}){return(0,n.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:r,style:{...ml,fontFamily:a?"var(--font-mono)":"inherit"}})}function md({value:e,onChange:t,placeholder:r,mono:i,onKeyDown:s,autoComplete:o="off",spellCheck:l=!1,style:c}){let[d,u]=(0,a.useState)(!1),{t:p}=(0,z.s)();return(0,a.useEffect)(()=>{e||u(!1)},[e]),(0,n.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,n.jsx)("input",{type:d?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:r,style:{...ml,paddingRight:34,fontFamily:i?"var(--font-mono)":"inherit"},autoComplete:o,spellCheck:l}),(0,n.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(d?"i18n.hideDetails":"i18n.showDetails"),title:p(d?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:d?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,n.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,n.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,n.jsx)("path",{d:"M1 1l22 22"})]}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function mu({value:e,onChange:t,placeholder:r}){return(0,n.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:r,style:ml})}function mp({value:e,onChange:t,options:r,required:a}){let{t:i}=(0,z.s)();return(0,n.jsx)(hL,{value:e,onChange:t,options:[...a?[]:[{value:"",label:`— ${i("i18n.default")} / none —`}],...r.map(e=>({value:e,label:e}))]})}function mh({label:e,checked:t,onChange:r}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:t,onChange:e=>r(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function mm({children:e}){return(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function mf({name:e,provider:t,onChange:r,onRename:i,onDelete:s,onAddModels:o}){let{t:l}=(0,z.s)(),[c,d]=(0,a.useState)(e),[u,p]=(0,a.useState)({phase:"idle"}),[h,m]=(0,a.useState)(""),[f,g]=(0,a.useState)([]),x=(0,a.useRef)(0),v=(0,a.useRef)(null);(0,a.useEffect)(()=>d(e),[e]);let b=(e,n)=>r({...t,[e]:n});(0,a.useEffect)(()=>{t.api||r({...t,api:"openai-completions"})},[t.api]),(0,a.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,a.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let r=++x.current;p({phase:"loading"}),g([]);try{let n=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),a=await n.json();if(r!==x.current)return;if(!n.ok||a.error||!a.models)return void p({phase:"error",message:a.error??`HTTP ${n.status}`});p({phase:"success",models:a.models,endpoint:a.endpoint??t.baseUrl})}catch(e){if(r!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),T=f.filter(e=>!w.has(e)).length,I=N.length>0&&N.every(e=>f.includes(e)),M=!I&&N.some(e=>f.includes(e));return(0,a.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(mm,{children:l("i18n.provider")}),(0,n.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11},children:l("i18n.delete")})]}),(0,n.jsxs)(mo,{label:l("i18n.providerName"),children:[(0,n.jsx)(mc,{value:c,onChange:d,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,n.jsx)("button",{onClick:()=>i(c.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"var(--radius-control)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:l("i18n.rename")})]}),(0,n.jsx)(mo,{label:"Base URL",children:(0,n.jsx)(mc,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,n.jsxs)(mo,{label:"API Key",children:[(0,n.jsx)(md,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,n.jsx)(mo,{label:"API",children:(0,n.jsx)(mp,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:ms,required:!0})}),(0,n.jsxs)(mo,{label:"Headers",children:[(0,n.jsx)(my,{headers:t.headers,onChange:e=>b("headers",e)}),(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,n.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?l("models.discoveryFetching"):l("models.discoveryFetch")}),"error"===u.phase&&(0,n.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-surface)",color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:l("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":l("models.discoveryFilter"),style:{...ml,width:"100%",minWidth:0}}),(0,n.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,n.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,n.jsx)("input",{ref:v,type:"checkbox",checked:I,disabled:0===N.length,onChange:()=>{let e=new Set(N);g(t=>I?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...N])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),l("models.discoverySelectShown")]}),0===C.length?(0,n.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("models.discoveryNoMatches")}):C.map((e,t)=>{let r=w.has(e.id),a=f.includes(e.id);return(0,n.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:r?"default":"pointer",opacity:r?.65:1},children:[(0,n.jsx)("input",{type:"checkbox",checked:a||r,disabled:r,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,n.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,n.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),r&&(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:l("models.discoveryAdded")})]},e.id)})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,n.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?l("models.discoveryShowing",{shown:C.length,total:S.length}):l("models.discoveryFetched",{count:u.models.length})}),(0,n.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(o(t),g([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:"var(--radius-control)",background:T?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:T?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?l("models.discoveryAddSelectedCount",{count:T}):l("models.discoveryAddSelected")})]})]})]})]})}let mg=["off","minimal","low","medium","high","xhigh","max"],mx={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function mv({value:e,onChange:t}){let r=e??{},a=(e,n)=>{let a={...r};"omit"===n?delete a[e]:a[e]=n,t(Object.keys(a).length?a:void 0)};return(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:mg.map(e=>{let t=r[e],i=e in r?null===t?"null":"string":"omit",s="string"==typeof t?t:"",o=mx[e],l={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:"var(--radius-control)",background:"transparent",border:"1px solid transparent"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0,opacity:"null"===i?.3:1}}),(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===i?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===i?"line-through":"none"},children:e})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,n.jsx)("button",{onClick:()=>a(e,"omit"),style:{...l,..."omit"===i?c:{}},children:"Default"}),(0,n.jsx)("button",{onClick:()=>a(e,null),style:{...l,borderLeft:"1px solid var(--border)",..."null"===i?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:`1px solid ${"string"===i?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,n.jsx)("button",{onClick:()=>a(e,s||e),style:{...l,..."string"===i?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,n.jsx)("input",{value:s,onChange:t=>a(e,t.target.value),onFocus:()=>{"string"!==i&&a(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===i?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===i?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let mb={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function my({headers:e,onChange:t}){let[r,i]=(0,a.useState)(()=>Object.entries(e??{}).map(([e,t],r)=>({id:r,name:e,value:t}))),s=(0,a.useRef)(r.length),o=e=>{i(e),t(function(e){let t={};for(let r of e){let e=r.name.trim();e&&(t[e]=r.value)}return Object.keys(t).length?t:void 0}(e))},l=(e,t)=>{o(r.map(r=>r.id===e?{...r,...t}:r))},c={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[r.map(e=>(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{value:e.name,onChange:t=>l(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...ml,fontFamily:"var(--font-mono)",flex:1}}),(0,n.jsx)("input",{value:e.value,onChange:t=>l(e.id,{value:t.target.value}),placeholder:"value",style:{...ml,fontFamily:"var(--font-mono)",flex:1}}),(0,n.jsx)("button",{onClick:()=>{var t;return t=e.id,void o(r.filter(e=>e.id!==t))},style:c,children:"✕"})]},e.id)),(0,n.jsx)("button",{onClick:()=>i(e=>[...e,{id:s.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function mw({providerName:e,provider:t,model:r,onChange:i,onDelete:s}){let[o,l]=(0,a.useState)({phase:"idle"}),{t:c}=(0,z.s)(),[d,u]=(0,a.useState)({phase:"idle"}),p=(0,a.useRef)(0),h=(0,a.useRef)(null),m=(e,t)=>i({...r,[e]:t}),f=(()=>{if("idle"===o.phase)return null;if("testing"===o.phase)return c("i18n.testingModel");let e=[void 0!==o.latencyMs?`${o.latencyMs}ms`:null,void 0!==o.status?`HTTP ${o.status}`:null].filter(Boolean);return"success"===o.phase?[c("i18n.connected"),...e,o.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,o.message].filter(Boolean).join(" \xb7 ")})();(0,a.useEffect)(()=>{l({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,r.id,r.api]),(0,a.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,r.id]);let g=(0,a.useCallback)(async()=>{if(r.id.trim()&&"testing"!==o.phase){l({phase:"testing"});try{let n=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:r})}),a=await n.json();if(!n.ok||!a.ok)return void l({phase:"error",message:a.error??`HTTP ${n.status}`,latencyMs:a.latencyMs,status:a.status});l({phase:"success",latencyMs:a.latencyMs,status:a.status,responseText:a.responseText})}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[r,t,e,o.phase]),x=(0,a.useCallback)(async()=>{let n=r.id.trim();if(!n||"loading"===d.phase)return;let a=++p.current;u({phase:"loading"});try{let s=new URLSearchParams({q:n,provider:e,limit:"50"});t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let o=await fetch(`/api/models-config/catalog?${s}`),l=await o.json();if(a!==p.current)return;if(!o.ok||l.error||!l.recommendation)return void u({phase:"error",message:l.error??`HTTP ${o.status}`});let c=function(e,t){let r={...e},n=0;if(!e.name?.trim()&&t.name&&(r.name=t.name,n+=1),void 0===e.reasoning&&!0===t.reasoning&&(r.reasoning=!0,n+=1),!e.input?.length&&t.input?.length&&(r.input=[...t.input],n+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(r.contextWindow=t.contextWindow,n+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(r.maxTokens=t.maxTokens,n+=1),t.cost){let a={...e.cost??{}},i=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===a[e]&&void 0!==t.cost[e]&&(a[e]=t.cost[e],i=!0,n+=1);i&&(r.cost=a)}return{model:r,appliedCount:n}}(r,l.recommendation.preset);c.appliedCount>0&&(h.current=r,i(c.model)),u({phase:"success",recommendation:l.recommendation,appliedCount:c.appliedCount})}catch(e){if(a!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[d.phase,r,i,t.baseUrl,e]),v=(()=>{if("success"!==d.phase)return null;let{recommendation:t,appliedCount:r}=d,n=r>0?c("models.catalogFilled",{count:r}):c("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${n} \xb7 ${e}`}let a="provider"===t.price.method?c("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?c("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):c("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${n} \xb7 ${a}`})(),b="error"===d.phase?d.message:v,y="error"===d.phase?"#ef4444":"success"===d.phase&&"unreliable"===d.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(mm,{children:c("i18n.model")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,n.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===o.phase?"#fecaca":"success"===o.phase?"#bbf7d0":"var(--border)"}`,borderRadius:"var(--radius-control)",background:"error"===o.phase?"#fee2e2":"success"===o.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,n.jsxs)("button",{onClick:g,disabled:!r.id.trim()||"testing"===o.phase,title:c("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===o.phase?"#16a34a":"none",border:`1px solid ${"success"===o.phase?"#16a34a":"var(--border)"}`,borderRadius:"var(--radius-control)",color:"success"===o.phase?"#fff":r.id.trim()&&"testing"!==o.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"testing"!==o.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===o.phase&&(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===o.phase?c("i18n.checking"):"success"===o.phase?c("common.ok"):c("i18n.test")]}),(0,n.jsx)("button",{onClick:s,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:c("i18n.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(mo,{label:"ID *",children:(0,n.jsx)(mc,{value:r.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,n.jsx)(mo,{label:"Name",children:(0,n.jsx)(mc,{value:r.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,n.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>void x(),disabled:!r.id.trim()||"loading"===d.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:r.id.trim()&&"loading"!==d.phase?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"loading"!==d.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===d.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,n.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),(0,n.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,n.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,n.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,i(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,n.jsx)(mo,{label:"API override",children:(0,n.jsx)(mp,{value:r.api??"",onChange:e=>m("api",e||void 0),options:ms})}),(0,n.jsxs)(mo,{label:"Headers",children:[(0,n.jsx)(my,{headers:r.headers,onChange:e=>m("headers",e)}),(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,n.jsx)(mh,{label:"Reasoning / thinking",checked:r.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,n.jsx)(mh,{label:"Image input",checked:r.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),r.reasoning&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(mh,{label:"DeepSeek thinking compat",checked:r.compat?.thinkingFormat==="deepseek",onChange:e=>i(function(e,t){if(t)return{...e,compat:{...e.compat??{},...mb}};if(!e.compat)return e;let r={...e.compat};return delete r.thinkingFormat,delete r.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(r).length?r:void 0}}(r,e))}),(0,n.jsx)(mh,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...r.compat??{}}).supportsDeveloperRole,onChange:e=>i({...r,compat:{...r.compat??{},supportsDeveloperRole:e}})}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,n.jsx)(mm,{children:"Thinking level map"}),r.thinkingLevelMap&&(0,n.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,n.jsx)(mv,{value:r.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(mo,{label:"Context window (tokens)",children:(0,n.jsx)(mu,{value:void 0!==r.contextWindow?String(r.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,n.jsx)(mo,{label:"Max output tokens",children:(0,n.jsx)(mu,{value:void 0!==r.maxTokens?String(r.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(mm,{children:"Cost (per million tokens)"}),(0,n.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,n.jsx)(mo,{label:e,children:(0,n.jsx)(mu,{value:r.cost?.[e]!==void 0?String(r.cost[e]):"",onChange:t=>{let n;return n=parseFloat(t),void i({...r,cost:{...r.cost??{},[e]:isNaN(n)?void 0:n}})},placeholder:"0"})},e))})]})]})}let mk={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function mj({provider:e,onRefresh:t,relogin:r}){let i=r?.onLoginSucceeded,[s,o]=(0,a.useState)({phase:"idle"}),{t:l}=(0,z.s)(),[c,d]=(0,a.useState)(""),u=(0,a.useRef)(null),p=(0,a.useRef)(!1),h=(0,a.useRef)(null),m=(0,a.useRef)(null),f=void 0!==r;(0,a.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,a.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,a.useEffect)(()=>{o({phase:"idle"}),d(""),u.current?.close(),u.current=null},[e.id]),(0,a.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,a.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,d(""),o({phase:"success"}),t(),i?.())},[t,i]),x=(0,a.useCallback)(t=>{u.current?.close(),p.current=!1,o({phase:"connecting"}),d("");let r=void 0!==t,n=r?`?login=${encodeURIComponent(t)}`:"",a=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}${n}`);u.current=a,a.onmessage=e=>{let t=JSON.parse(e.data);if("auth"===t.type)o({phase:"auth",url:t.url,instructions:t.instructions??null,token:t.token,device:r,progress:null}),hz(t.url);else if("device_code"===t.type)o({phase:"device_code",userCode:t.userCode,verificationUri:t.verificationUri,intervalSeconds:t.intervalSeconds??null,expiresInSeconds:t.expiresInSeconds??null}),hz(t.verificationUri);else if("prompt_request"===t.type)o({phase:"prompt",message:t.message,placeholder:t.placeholder??null,token:t.token});else if("select_request"===t.type)o({phase:"select",message:t.message,options:t.options??[],token:t.token});else if("progress"===t.type){let e=t.message;o(t=>"auth"===t.phase&&t.device?{...t,progress:e}:{phase:"progress",message:e})}else"success"===t.type?g():"error"===t.type?(a.close(),o({phase:"error",message:t.message})):"cancelled"===t.type&&(a.close(),o({phase:"idle"}))},a.onerror=()=>{a.close(),o(e=>"success"===e.phase||"auth"===e.phase||"prompt"===e.phase||"select"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,g]),v=(0,a.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),o({phase:"idle"}),t()},[e.id,t]),b=(0,a.useCallback)(async(t,r,n)=>{o({phase:"progress",message:n});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:r})}),a=await n.json().catch(()=>({}));if(!n.ok)return void o({phase:"error",message:a.error??`Server error ${n.status}`});if(d(""),"success"===a.state)return void g();u.current?.readyState===EventSource.CLOSED&&o({phase:"error",message:"Connection lost. Start the login again."})}catch(e){o({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id,g]),y=(0,a.useCallback)(async(e,t)=>{t.trim()&&await b(e,t.trim(),"Verifying…")},[b]),w=(0,a.useCallback)(async(e,t)=>{await b(e,t,"Continuing…")},[b]),k="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(mm,{children:l("i18n.subscription")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:l(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),r&&(0,n.jsxs)("div",{role:"note","aria-label":l("relogin.title"),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,n.jsx)(ax,{seed:r.target.seed,size:32,provider:r.target.provider}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:l("relogin.title")}),(0,n.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[r.target.alias,r.target.masked&&(0,n.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:r.target.masked})]}),r.target.reason&&(0,n.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:r.target.reason})]})]}),(0,n.jsxs)("div",{style:{minHeight:48},children:["idle"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r?l("relogin.guide",{action:l(e.loggedIn?"i18n.relogin":"i18n.login")}):e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("i18n.openingBrowser")}),"select"===s.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,n.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),"auth"===s.phase&&s.device&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:l("i18n.deviceLoginGuide")}),s.instructions&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0,overflowWrap:"anywhere"},children:s.instructions}),(0,n.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{fontSize:12,color:"var(--accent)",wordBreak:"break-all"},children:s.url}),s.progress&&(0,n.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:s.progress})]}),("auth"===s.phase&&!s.device||"prompt"===s.phase)&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===s.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":s.message}),"auth"===s.phase&&(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,n.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{ref:h,value:c,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&y(s.token,c)},placeholder:"auth"===s.phase?"Paste the redirect URL or code":s.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,n.jsx)("button",{onClick:()=>y(s.token,c),disabled:!c.trim(),style:{padding:"6px 12px",background:c.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:"var(--radius-control)",color:c.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:c.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:l("i18n.submit")})]})]}),"device_code"===s.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,n.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,n.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(r?(0,n.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("relogin.done")}),r.outcome&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===r.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===r.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:l(mk[r.outcome],{account:r.target.alias})})]}):(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:l("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,n.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,n.jsx)("button",{onClick:()=>{u.current?.close(),o({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:l("i18n.cancel")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{ref:m,onClick:()=>x(),style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"var(--radius-control)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:12,fontWeight:600},children:l(e.loggedIn?"i18n.relogin":"i18n.login")}),e.deviceLoginId&&(0,n.jsx)("button",{onClick:()=>x(e.deviceLoginId),style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",cursor:"pointer",fontSize:12},children:l("i18n.deviceLogin")}),e.loggedIn&&!r&&(0,n.jsx)("button",{onClick:v,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:12},children:l("i18n.disconnect")})]})})]})}function mS({provider:e,onRefresh:t}){let[r,i]=(0,a.useState)(""),[s,o]=(0,a.useState)(!1),[l,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)(!1),{t:m}=(0,z.s)();(0,a.useEffect)(()=>{i(""),u(null),h(!1)},[e.id]);let f=(0,a.useCallback)(async()=>{if(r.trim()){o(!0),u(null),h(!1);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:r.trim()})}),a=await n.json();!n.ok||a.error?u(a.error??`HTTP ${n.status}`):(i(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{o(!1)}}},[r,e.id,t]),g=(0,a.useCallback)(async()=>{c(!0),u(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),n=await r.json();!r.ok||n.error?u(n.error??`HTTP ${r.status}`):t()}catch(e){u(String(e))}finally{c(!1)}},[e.id,t]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(mm,{children:"API Key"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,n.jsx)(mo,{label:"API Key",children:(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)(md,{value:r,onChange:i,onKeyDown:e=>{"Enter"===e.key&&r.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,n.jsxs)("button",{onClick:f,disabled:s||!r.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":r.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:"var(--radius-control)",color:p?"#fff":r.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:s||!r.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":s?"i18n.saving":"i18n.save")]})]})}),d&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:d}),e.configured&&(0,n.jsx)("button",{onClick:g,disabled:l,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:l?"not-allowed":"pointer",fontSize:12},children:m(l?"i18n.removing":"i18n.disconnect")})]})}function mC({id:e,size:t}){let r=mi[e];if(!r){let r=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,n.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:700,lineHeight:1},children:r})}return r.hasColor?(0,n.jsx)(r.Icon,{size:t}):(0,n.jsx)(r.Icon,{size:t,style:{color:"var(--text-muted)"}})}let mN={display:"flex",alignItems:"center",width:"100%",borderRadius:"var(--radius-control)",border:"none",cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},mT={padding:"6px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.04em"};function mI({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:r,onSelectApiKey:i,onAddCustom:s,onClose:o}){let[l,c]=(0,a.useState)(""),{t:d}=(0,z.s)(),u=(0,a.useRef)(null);(0,a.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=l.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+m.length+ +!!f,x={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&o()},children:(0,n.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,n.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,n.jsx)("input",{ref:u,value:l,onChange:e=>c(e.target.value),onKeyDown:e=>{"Escape"===e.key&&o()},placeholder:d("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,n.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:d("i18n.noProviders")}):(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.custom")}),f&&(0,n.jsxs)("button",{onClick:()=>{s(),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("i18n.customEndpoint")})]}),(0,n.jsx)("span",{style:{width:26,height:26,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.subscriptions")}),h.map(e=>(0,n.jsxs)("button",{onClick:()=>{r(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,n.jsx)(mC,{id:e.id,size:28})]},e.id)),m.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,n.jsxs)("button",{onClick:()=>{i(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,n.jsx)(mC,{id:e.id,size:28})]},e.id))]})})]})})}function mM({cwd:e,onClose:t,embedded:r=!1,onModelsChanged:i,relogin:s}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,a.useState)({providers:{}}),[u,p]=(0,a.useState)(!0),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[j,S]=(0,a.useState)([]),[C,N]=(0,a.useState)([]),[T,I]=(0,a.useState)(!1),M=(0,a.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),E=(0,a.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>N(e.providers)).catch(()=>{})},[]),$=(0,a.useCallback)(()=>{M(),E()},[M,E]);(0,a.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok||!t||t.error)throw Error(t?.error??`HTTP ${e.status}`);d(t.providers?t:{...t,providers:{}})}).catch(e=>v(e instanceof Error?e.message:String(e))).finally(()=>p(!1)),$()},[$]);let R=(0,a.useCallback)(()=>{let e="new-provider",t=1;for(;c.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),k({type:"provider",name:e})},[c.providers]),L=(0,a.useCallback)((e,t)=>{d(r=>({...r,providers:{...r.providers??{},[e]:t}}))},[]),A=(0,a.useCallback)((e,t)=>{d(r=>{let n=Object.entries(r.providers??{}),a=n.findIndex(([t])=>t===e);return -1===a?r:(n[a]=[t,n[a][1]],{...r,providers:Object.fromEntries(n)})}),k(r=>r?"provider"===r.type&&r.name===e?{type:"provider",name:t}:"model"===r.type&&r.providerName===e?{...r,providerName:t}:r:r)},[]),P=(0,a.useCallback)(e=>{d(t=>{let r={...t.providers??{}};return delete r[e],{...t,providers:r}}),d(e=>{let t=Object.keys(e.providers??{});return k(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),F=(0,a.useCallback)(e=>{d(t=>{let r=t.providers?.[e]??{},n=[...r.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...r,models:n}}}}),d(t=>{let r=(t.providers?.[e]?.models?.length??1)-1;return k({type:"model",providerName:e,index:r}),t})},[]),_=(0,a.useCallback)((e,t)=>{d(r=>{let n=r.providers?.[e]??{},a=[...n.models??[]],i=new Set(a.map(e=>e.id));for(let e of t)i.has(e.id)||(i.add(e.id),a.push({id:e.id,name:e.name}));return{...r,providers:{...r.providers??{},[e]:{...n,models:a}}}})},[]),W=(0,a.useCallback)((e,t,r)=>{d(n=>{let a=n.providers?.[e]??{},i=[...a.models??[]];return i[t]=r,{...n,providers:{...n.providers??{},[e]:{...a,models:i}}}})},[]),O=(0,a.useCallback)((e,t)=>{d(r=>{let n=r.providers?.[e]??{},a=[...n.models??[]];return a.splice(t,1),{...r,providers:{...r.providers??{},[e]:{...n,models:a.length?a:void 0}}}}),k({type:"provider",name:e})},[]),D=(0,a.useCallback)(async()=>{m(!0),g(null),y(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),t=await e.json();!e.ok||t.error?g(t.error??`HTTP ${e.status}`):(y(!0),i?.(),setTimeout(()=>y(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[c,i]),H=Object.entries(c.providers??{}),U=j.filter(e=>e.loggedIn),q=C.filter(e=>e.configured),V=u||null!==x,K=(()=>{if(!w)return null;if("roles"===w.type)return(0,n.jsx)(h_,{cwd:e??null,onRolesChanged:i});if("oauth"===w.type){let e=j.find(e=>e.id===w.providerId);return e?(0,n.jsx)(mj,{provider:e,onRefresh:$,relogin:s?.target.provider===e.id?s:void 0},e.id):null}if("apikey"===w.type){let e=C.find(e=>e.id===w.providerId);return e?(0,n.jsx)(mS,{provider:e,onRefresh:$},e.id):null}if("provider"===w.type){let e=c.providers?.[w.name];return e?(0,n.jsx)(mf,{name:w.name,provider:e,onChange:e=>L(w.name,e),onRename:e=>A(w.name,e),onDelete:()=>P(w.name),onAddModels:e=>_(w.name,e)},w.name):null}let t=c.providers?.[w.providerName],r=t?.models?.[w.index];return r?(0,n.jsx)(mw,{providerName:w.providerName,provider:t,model:r,onChange:e=>W(w.providerName,w.index,e),onDelete:()=>O(w.providerName,w.index)},`${w.providerName}-${w.index}`):null})();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{position:r?"relative":"fixed",inset:r?void 0:0,width:"100%",height:"100%",zIndex:r?void 0:1e3,background:r?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{r||e.target!==e.currentTarget||t()},...r?{}:{role:"dialog","aria-modal":!0,"aria-label":l("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,n.jsxs)("div",{style:{width:r?"100%":o?"calc(100vw - 16px)":860,maxWidth:r?"none":"calc(100vw - 16px)",height:r?"100%":o?"calc(100dvh - 16px)":"78vh",maxHeight:r?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:r?"none":"1px solid var(--border)",borderRadius:10*!r,display:"flex",flexDirection:"column",boxShadow:r?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.models")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,n.jsx)("button",{onClick:t,"aria-label":l("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:o?"100%":210,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,n.jsxs)("div",{role:"group","aria-labelledby":"models-nav-roles",children:[(0,n.jsx)("div",{id:"models-nav-roles",style:mT,children:l("models.navGroupRoles")}),(0,n.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":w?.type==="roles"?"true":void 0,onClick:()=>k({type:"roles"}),style:{...mN,gap:7,padding:"5px 8px",background:w?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{w?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{w?.type!=="roles"&&(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:l("roles.title")})]})]}),(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),(U.length>0||q.length>0)&&(0,n.jsx)("div",{id:"models-nav-accounts",style:mT,children:l("models.navGroupAccounts")}),U.map(e=>{let t=w?.type==="oauth"&&w.providerId===e.id;return(0,n.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"oauth",providerId:e.id}),style:{...mN,gap:7,padding:"5px 8px",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(mC,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),q.map(e=>{let t=w?.type==="apikey"&&w.providerId===e.id;return(0,n.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"apikey",providerId:e.id}),style:{...mN,gap:7,padding:"5px 8px",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(mC,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(U.length>0||q.length>0)&&H.length>0&&(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),!u&&H.length>0&&(0,n.jsx)("div",{style:mT,children:l("models.navGroupCustom")}),u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):H.map(([e,t])=>{let r=w?.type==="provider"&&w.name===e,a=t.models??[];return(0,n.jsxs)("div",{style:{marginBottom:2},children:[(0,n.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":r?"true":void 0,onClick:()=>k({type:"provider",name:e}),style:{...mN,gap:6,padding:"7px 8px",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:r?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),a.map((t,r)=>{let a=w?.type==="model"&&w.providerName===e&&w.index===r;return(0,n.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":a?"true":void 0,onClick:()=>k({type:"model",providerName:e,index:r}),style:{...mN,gap:6,padding:"5px 8px 5px 26px",background:a?"var(--bg-selected)":"none"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||l("i18n.newModel")}),t.reasoning&&(0,n.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:"var(--radius-control)",flexShrink:0},children:"T"})]},r)}),(0,n.jsx)("div",{onClick:t=>{t.stopPropagation(),F(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:"var(--radius-control)",cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("span",{style:{fontSize:11},children:["+ ",l("i18n.model")]})})]},e)})]}),(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,n.jsxs)("button",{onClick:()=>I(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:["+ ",l("i18n.addProvider")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:K??(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectProviderModel")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(x??f)&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:x??f}),(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:l("i18n.cancel")}),(0,n.jsxs)("button",{onClick:D,disabled:h||b||V,style:{position:"relative",padding:"6px 16px",minWidth:92,background:b?"#16a34a":h||V?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"var(--radius-control)",color:b?"#fff":h||V?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:V?"not-allowed":h||b?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:b?"saved-pop 0.45s ease":void 0},children:[b&&(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,n.jsx)("span",{children:b?l("i18n.saved"):h?l("i18n.saving"):l("i18n.save")})]})]})]})}),T&&(0,n.jsx)(mI,{oauthProviders:j,apiKeyProviders:C,onSelectOAuth:e=>k({type:"oauth",providerId:e}),onSelectApiKey:e=>k({type:"apikey",providerId:e}),onAddCustom:R,onClose:()=>I(!1)})]})}function mE(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function m$(e){let t=e.sourceInfo?.source,r=e.sourceInfo?.scope;return"user"===r||"user"===t?"global":"project"===r||"project"===t?"project":"path"}function mR(e){let t=m$(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function mL(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function mA(e){return e?e.slice(0,8):"unknown"}function mP({enabled:e,loading:t,onToggle:r}){let{t:a}=(0,z.s)();return(0,n.jsx)("button",{onClick:r,disabled:t,title:a(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:"var(--seed-radius-full)",border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mF({skill:e,cwd:t,onToggle:r,toggling:a,saveError:i,updateStatus:s,checkingUpdate:o,updating:l,updateError:c,onCheckUpdate:d,onUpdate:u}){let{t:p}=(0,z.s)(),h=m$(e),m=!e.disableModelInvocation;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:h}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let r=e.slice(t.length).replace(/^[/\\]/,"");return`./${r}`}return mE(e)}(e.filePath)}),(0,n.jsx)(mP,{enabled:m,loading:a,onToggle:()=>r(e)})]}),(0,n.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),i&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:i})]})]}),e.install?.skillsShUrl&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,n.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,n.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:mA(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,n.jsx)("button",{onClick:d,disabled:o||l,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11},children:p("i18n.check")}),s?.state==="update-available"&&(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:mA(s.latestVersion)}),(o||s&&"update-available"!==s.state)&&(0,n.jsx)("span",{style:{fontSize:12,color:o?"var(--accent)":s?.state==="up-to-date"?"#16a34a":s?.state==="error"?"#ef4444":"var(--text-dim)"},children:o?p("i18n.checking"):s?.state==="up-to-date"?p("i18n.upToDate"):s?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):s?.message||p("i18n.checkFailed")}),s?.state==="update-available"&&(0,n.jsx)("button",{onClick:u,disabled:l||o,style:{padding:"4px 10px",border:"none",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11,fontWeight:600},children:p(l?"i18n.updating":"i18n.update")})]}),c&&(0,n.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:c})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,n.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function m_({cwd:e,installedPackages:t,projectResourcesLoaded:r,onInstalled:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(""),[c,d]=(0,a.useState)([]),[u,p]=(0,a.useState)(!1),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(new Set),[w,k]=(0,a.useState)("global"),j=(0,a.useRef)(null);(0,a.useEffect)(()=>{j.current?.focus()},[]);let S=(0,a.useCallback)(async e=>{if(e.trim()){p(!0),m(null),d([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),r=await t.json();if(r.error)return void m(r.error);d(r.results??[]),0===(r.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,a.useCallback)(async t=>{g(t),v(null);try{let r=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),n=await r.json();if(!r.ok||n.error)return void v(n.error??`HTTP ${r.status}`);y(e=>new Set(e).add(`${w}:${t}`)),i()}catch(e){v(String(e))}finally{g(null)}},[i,w,e]),N="global"===w?"~/.claude/skills/":`${mE(e)}/.claude/skills/`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:s("i18n.addSkill")}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsx)("input",{ref:j,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(o)},placeholder:s("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",outline:"none"}}),(0,n.jsx)("button",{onClick:()=>S(o),disabled:u||!o.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:"var(--radius-control)",border:"none",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:u||!o.trim()?"not-allowed":"pointer",opacity:u||!o.trim()?.5:1,flexShrink:0},children:u?s("i18n.searching"):s("i18n.search")})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,n.jsx)("button",{onClick:()=>{("global"===e||r)&&k(e)},disabled:"project"===e&&!r,title:"project"!==e||r?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||r?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||r?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),c.length>0?(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let r=t[w].has(e.package)||b.has(`${w}:${e.package}`),a=f===e.package,i=e.package.indexOf("@"),o=i>-1?e.package.slice(0,i):e.package,l=i>-1?e.package.slice(i+1):null;return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,n.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,n.jsx)("button",{onClick:()=>!r&&!a&&C(e.package),disabled:r||a||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",cursor:r||a||null!==f?"not-allowed":"pointer",background:r?"rgba(34,197,94,0.1)":"none",color:r?"#16a34a":a?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:r?`✓ ${s("i18n.installed")}`:a?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!h&&!u&&(0,n.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,n.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function mz({cwd:e,onClose:t,embedded:r=!1}){let i=B(),{t:s}=(0,z.s)(),[o,l]=(0,a.useState)([]),[c,d]=(0,a.useState)(!0),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(new Set),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)({}),[j,S]=(0,a.useState)(new Set),[C,N]=(0,a.useState)(!1),[T,I]=(0,a.useState)(null),[M,E]=(0,a.useState)(null),[$,R]=(0,a.useState)(!0),[L,A]=(0,a.useState)({}),P=(0,a.useCallback)(async()=>{d(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let n=r.skills??[];if(l(n),R(r.projectResourcesLoaded??!0),n.length>0&&!h){let e=n.find(e=>!e.disableModelInvocation)??n[0];m(e.filePath),e.disableModelInvocation&&A(t=>({...t,[mR(e)]:!0}))}return n}catch(e){return p(String(e)),[]}finally{d(!1)}},[e,h]);(0,a.useEffect)(()=>{k({}),E(null),P()},[e]);let F=(0,a.useCallback)(async t=>{let r=(t?[t]:o.filter(e=>!!e.install)).map(mL).filter(e=>!!e);if(0!==r.length){E(null),S(e=>new Set([...e,...r])),t||N(!0);try{let r=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);k(e=>{let t={...e};for(let e of n.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){E(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),t||N(!1)}}},[e,o]),_=(0,a.useCallback)(async t=>{if(!t.install)return;let r=mL(t);I(r),E(null);try{let n=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),a=await n.json();if(!n.ok||a.error||!a.success)throw Error(a.error??`HTTP ${n.status}`);await P();let i=a.skill?.install?.versionHash;k(e=>({...e,[r]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:i,latestVersion:i}}))}catch(e){E(e instanceof Error?e.message:String(e))}finally{I(null)}},[e,P]),W=(0,a.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),n=await r.json();if(!r.ok||n.error)return void v(n.error??`HTTP ${r.status}`);l(r=>r.map(r=>r.filePath===e.filePath?{...r,disableModelInvocation:t}:r)),t&&A(t=>({...t,[mR(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let r=new Set(t);return r.delete(e.filePath),r})}},[]),O=o.find(e=>e.filePath===h)??null;return(0,n.jsx)("div",{style:{position:r?"relative":"fixed",inset:r?void 0:0,width:"100%",height:"100%",zIndex:r?void 0:1e3,background:r?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{r||e.target!==e.currentTarget||t()},children:(0,n.jsxs)("div",{style:{width:r?"100%":i?"calc(100vw - 16px)":860,maxWidth:r?"none":"calc(100vw - 16px)",height:r?"100%":i?"calc(100dvh - 16px)":"78vh",maxHeight:r?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:r?"none":"1px solid var(--border)",borderRadius:10*!r,display:"flex",flexDirection:"column",boxShadow:r?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common.skills")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mE(e)})]}),(0,n.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!$&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("trust.skillsNotLoaded")}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:i?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:i?"100%":210,maxHeight:i?"40vh":void 0,borderRight:i?"none":"1px solid var(--border)",borderBottom:i?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===o.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:r}of[{label:"project / skills.sh",matches:e=>"project"===m$(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===m$(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===m$(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===m$(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===m$(e)}]){let n=o.filter(r);n.length>0&&e.push({label:t,skills:n})}let t=e=>{let t,r,a=!b&&h===e.filePath,i=e.disableModelInvocation;return(0,n.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:a?"var(--bg-selected)":"none"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:i?"var(--border)":"var(--accent)",boxShadow:i?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:a?600:400,color:i?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(r=(t=mL(e))?w[t]:void 0,r?.state!=="update-available"?null:(0,n.jsx)("span",{title:s("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:r})=>{let a=r.filter(e=>!e.disableModelInvocation),i=r.filter(e=>e.disableModelInvocation),o=L[e]??!1;return(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),a.map(t),i.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{onClick:()=>A(t=>({...t,[e]:!o})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,n.jsx)("span",{style:{fontSize:8},children:o?"▾":"▸"}),s("i18n.dormant")," (",i.length,")"]}),o&&i.map(t)]})]},e)})})()}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s("i18n.addSkill")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,n.jsx)(m_,{cwd:e,projectResourcesLoaded:$,installedPackages:{global:new Set(o.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(o.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{P()}}):c?null:O?(0,n.jsx)(mF,{skill:O,cwd:e,onToggle:W,toggling:f.has(O.filePath),saveError:x,updateStatus:mL(O)?w[mL(O)]:void 0,checkingUpdate:!!mL(O)&&j.has(mL(O)),updating:T===mL(O),updateError:M,onCheckUpdate:()=>void F(O),onUpdate:()=>void _(O)},O.filePath):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("i18n.selectSkill")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.some(e=>!!e.install)&&(0,n.jsx)("button",{onClick:()=>void F(),disabled:C||null!==T,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:C||null!==T?"not-allowed":"pointer",opacity:C||null!==T?.5:1,fontSize:12},children:C?s("i18n.checking"):s("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,n.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?s("i18n.update"):s("i18n.updates")]})]}),(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("i18n.close")})]})]})})}let mW="global";function mO(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function mD(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function mH(e){return`${e.scope}\0${e.source}`}function mU(e,t){if(e.disabled)return t("i18n.disabled");let r=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return r.length?r.join(" \xb7 "):t("i18n.noResources")}function mB(e,t){let r=[];return e.version&&r.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&r.push(t("i18n.configuredVersion",{version:e.configuredVersion})),r.length?r.join(" \xb7 "):t("i18n.unknown")}function mq(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function mV({pkg:e}){let{t}=(0,z.s)(),r=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,r])=>({kind:t,label:r,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===r.length?(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:r.map((e,t)=>(0,n.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,n.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function mK({scope:e}){return(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function mG(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function mJ({enabled:e,loading:t,onToggle:r,label:a}){return(0,n.jsx)("button",{type:"button",onClick:r,disabled:t,title:a,"aria-label":a,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:"var(--seed-radius-full)",border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mZ({installDir:e,source:t,busy:r,actionError:i,onSourceChange:s,onInstall:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null);return(0,a.useEffect)(()=>{c.current?.focus()},[]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:l("i18n.addPlugin")}),(0,n.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,n.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,n.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,n.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mO(e)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,n.jsx)("input",{id:"plugin-source",ref:c,value:t,onChange:e=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),r=mD(t);r!==t&&(e.preventDefault(),s(r))},onBlur:e=>s(mD(e.currentTarget.value)),placeholder:"@scope/package or github:user/repo",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!r&&o()}})]}),(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,n.jsx)("button",{type:"button",onClick:o,disabled:r||!t.trim(),style:{...mG(r||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:l(r?"i18n.installing":"i18n.install")})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),i&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function mY({pkg:e,cwd:t,busyKey:r,actionError:a,actionMessage:i,sessionId:s,onAction:o,onReloadSession:l}){let{t:c}=(0,z.s)(),d=mH(e),u=r?.endsWith(d)??!1,p="reload"===r,h=!e.disabled;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,n.jsx)(mJ,{enabled:h,loading:u||p,onToggle:()=>o(e.disabled?"enable":"disable",e),label:c(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,n.jsx)(mK,{scope:e.scope}),e.disabled?(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:c("i18n.disabled")}):e.filtered&&(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",background:"rgba(245,158,11,0.12)",color:"#d97706"},children:c("i18n.filtered")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,n.jsx)("button",{onClick:()=>o("update",e),disabled:u||p,style:mG(u||p),children:c(r===`update:${d}`?"i18n.updating":"i18n.update")}),(0,n.jsx)("button",{onClick:l,disabled:!s||p||u,style:mG(!s||p||u),title:c(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:c(p?"i18n.reloading":"i18n.reloadSession")}),(0,n.jsx)("button",{onClick:()=>o("remove",e),disabled:u||p,style:mG(u||p,!0),children:c(r===`remove:${d}`?"i18n.removing":"i18n.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.status")}),(0,n.jsx)("div",{style:{color:mq(e.status),textTransform:"capitalize"},children:e.status}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.version")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:mB(e,c)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.package")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??c("i18n.unknown")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.resources")}),(0,n.jsx)("div",{style:{color:"var(--text-muted)"},children:mU(e,c)}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.installedPath")}),(0,n.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?mO(e.installedPath):c("i18n.notFound")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.cwd")}),(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mO(t)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:c("i18n.resolvedResources")}),(0,n.jsx)(mV,{pkg:e})]}),i&&(0,n.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:i}),a&&(0,n.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function mX({cwd:e,sessionId:t,onClose:r,onReloaded:i,embedded:s=!1}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!0),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(!1),[b,y]=(0,a.useState)(""),[w,k]=(0,a.useState)(null),[j,S]=(0,a.useState)(null),[C,N]=(0,a.useState)(null),T=(0,a.useMemo)(()=>c?.packages??[],[c?.packages]),I=T.find(e=>mH(e)===f)??null,M=c?.projectResourcesLoaded??!0,E=(0,a.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:T.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[T]),$=(0,a.useCallback)(async()=>{p(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),r=await t.json();if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);d(r),v(e=>0===r.packages.length||e),g(e=>e&&r.packages.some(t=>mH(t)===e)?e:r.packages[0]?mH(r.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,a.useEffect)(()=>{$()},[$]);let R=(0,a.useCallback)(async(t,r)=>{let n=mH(r);k(`${t}:${n}`),S(null),N(null);try{let n=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:r.source,scope:r.scope,cwd:e})}),a=await n.json();if(!n.ok||a.error)throw Error(a.error??`HTTP ${n.status}`);if(d(a),"remove"===t)g(a.packages[0]?mH(a.packages[0]):null),0===a.packages.length&&v(!0),N(l("i18n.packageRemoved"));else{let e={install:l("i18n.packageInstalled"),update:l("i18n.packageUpdated"),disable:l("i18n.packageDisabledRestartRequired"),enable:l("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,l]),L=(0,a.useCallback)(async()=>{let t=mD(b).trim();if(!t)return;y(t);let r=`${mW}\0${t}`;k(`install:${r}`),S(null),N(null);try{var n;let a,i,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:mW,cwd:e})}),o=await s.json();if(!s.ok||o.error)throw Error(o.error??`HTTP ${s.status}`);d(o);let c=(n=o.packages,i=(a=t.trim()).startsWith("npm:")?a.slice(4):a,n.find(e=>e.scope===mW&&e.source===a)??n.find(e=>e.scope===mW&&e.source===`npm:${i}`)??n.find(e=>e.scope===mW&&e.source.endsWith(a)));g(c?mH(c):r),v(!1),y(""),N(l("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,l]),A=(0,a.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await uV(t,{type:"reload"}),i?.(),await $(),N(l("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[$,i,t,l]),P=w?.startsWith("install:")??!1;return(0,n.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||r()},children:(0,n.jsxs)("div",{style:{width:s?"100%":o?"calc(100vw - 16px)":860,maxWidth:s?"none":"calc(100vw - 16px)",height:s?"100%":o?"calc(100dvh - 16px)":"76vh",maxHeight:s?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:s?"none":"1px solid var(--border)",borderRadius:8*!s,display:"flex",flexDirection:"column",boxShadow:s?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.plugins")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mO(e)})]}),(0,n.jsx)("button",{onClick:r,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,n.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:l("trust.pluginsNotLoaded")}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:o?"100%":245,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===T.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):E.map(e=>(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=mH(e),r=!x&&f===t;return(0,n.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:r?"var(--bg-selected)":"none"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:mq(e.status)}}),(0,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:r?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mU(e,l)}),(e.version||e.configuredVersion)&&(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mB(e,l)})]})]},t)})]},e.scope))}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("button",{type:"button",onClick:()=>{v(!0),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:"var(--radius-control)",border:"none",width:"100%",cursor:"pointer",background:x?"var(--bg-selected)":"none",color:x?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{x||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{x||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),l("i18n.addPlugin")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,n.jsx)(mZ,{installDir:c?.installDir,source:b,busy:P,actionError:j,onSourceChange:y,onInstall:L}):u?null:I?(0,n.jsx)(mY,{pkg:I,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:R,onReloadSession:A},mH(I)):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectPackage")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:c?.diagnostics.length?(0,n.jsxs)("span",{title:c.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:c.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[c.diagnostics.length," diagnostic",1===c.diagnostics.length?"":"s"]}):(0,n.jsx)("span",{children:c?`${c.totals.extensions} ext \xb7 ${c.totals.skills} skills \xb7 ${c.totals.prompts} prompts \xb7 ${c.totals.themes} themes`:""})}),(0,n.jsx)("button",{onClick:()=>void $(),disabled:u||null!==w,style:mG(u||null!==w),children:l("i18n.refresh")}),(0,n.jsx)("button",{onClick:r,style:mG(!1),children:l("i18n.close")})]})]})})}var mQ=r(13004),m0=r.n(mQ);function m1(){let[e,t]=(0,a.useState)(null),[r,i]=(0,a.useState)(null),[s,o]=(0,a.useState)(null),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1),[p,h]=(0,a.useState)(""),[m,f]=(0,a.useState)(""),g=(0,a.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),r=await e.json();if(!e.ok||r.error)throw Error(r.error??`HTTP ${e.status}`);t(r),i(null)}catch(e){i(e instanceof Error?e.message:String(e))}},[]);(0,a.useEffect)(()=>{g()},[g]);let x=(0,a.useCallback)(async(e,r={})=>{u(!0),o(null),c(null);try{let n=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...r})}),a=await n.json();if(!n.ok||a.error)throw Error(a.error??`HTTP ${n.status}`);return t(a),a}catch(e){return o(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,a.useCallback)(async()=>{if(p!==m)return void o("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),f(""),c(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[m,p,x]),b=(0,a.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&c(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,a.useCallback)(async()=>{await x("clear")&&c("The stored password was removed and password access is off.")},[x]);if(!e)return(0,n.jsx)("div",{className:m0().empty,children:r??"Loading password access…"});let w=e.managedByEnvironment,k=!d&&!w&&p.length>=8&&p===m;return(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:"Access"}),(0,n.jsxs)("p",{className:m0().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,n.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,n.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,n.jsxs)("div",{className:m0().readOnlyNotice,children:["Read-only \xb7 ",(0,n.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),l&&(0,n.jsx)("div",{className:m0().reloadNotice,children:(0,n.jsx)("span",{children:l})})]}),(0,n.jsxs)("div",{className:m0().settingsBody,children:[(0,n.jsxs)("section",{className:m0().group,children:[(0,n.jsx)("h3",{className:m0().groupTitle,children:"Password access"}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:m0().settingLabel,children:"Require a password"}),(0,n.jsx)("div",{className:m0().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!e.configured&&!w&&(0,n.jsx)("div",{className:m0().settingDescription,children:"Set a password below before turning this on."}),s&&(0,n.jsx)("div",{className:m0().error,children:s})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("button",{type:"button",className:m0().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:d||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,n.jsxs)("section",{className:m0().group,children:[(0,n.jsx)("h3",{className:m0().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:m0().settingLabel,children:"New password"}),(0,n.jsxs)("div",{className:m0().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("input",{className:m0().textInput,type:"password",autoComplete:"new-password",value:p,disabled:d||w,onChange:e=>h(e.target.value)})})]}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:m0().settingLabel,children:"Confirm password"}),(0,n.jsx)("div",{className:m0().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("input",{className:m0().textInput,type:"password",autoComplete:"new-password",value:m,disabled:d||w,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,n.jsxs)("div",{className:m0().editorActions,children:[(0,n.jsx)("div",{children:(0,n.jsx)("div",{className:m0().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,n.jsx)("button",{type:"button",className:m0().dangerButton,disabled:d,onClick:()=>void y(),children:"Remove password"}),(0,n.jsx)("button",{type:"button",className:m0().primaryButton,disabled:!k,onClick:()=>void v(),children:d?"Saving…":"Save password"})]})]})]}),(0,n.jsxs)("section",{className:m0().group,children:[(0,n.jsx)("h3",{className:m0().groupTitle,children:"If you forget it"}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:m0().settingLabel,children:"Recovery"}),(0,n.jsxs)("div",{className:m0().settingDescription,children:["Run ",(0,n.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,n.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("a",{className:m0().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:m0().settingLabel,children:"Basic Auth is not encryption"}),(0,n.jsx)("div",{className:m0().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,n.jsx)("div",{className:m0().settingControl})]})]})]})]})}let m2="/api/live/voices";function m8(){let{t:e}=(0,z.s)(),[t,r]=(0,a.useState)(null),[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(null),c=(0,a.useCallback)(async()=>{try{let e=await fetch(m2,{cache:"no-store"}),t=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(t.voices)||"string"!=typeof t.defaultVoice)throw Error(`HTTP ${e.status}`);let n=dr.includes(t.pace)?t.pace:"normal";r({voices:t.voices,defaultVoice:t.defaultVoice,pace:n})}catch(e){l(e instanceof Error?e.message:String(e))}},[]);(0,a.useEffect)(()=>{c()},[c]);let d=async e=>{s(!0),l(null);try{let t=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"live.voice",value:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let a="string"==typeof n.value?n.value:e;r(e=>e?{...e,defaultVoice:a}:e)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(!1)}},u=async e=>{s(!0),l(null);try{let t=await fetch(m2,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pace:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);r(t=>t?{...t,pace:n.pace??e}:t)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(!1)}};return t?(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,n.jsx)("p",{className:m0().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,n.jsx)("div",{className:m0().settingsBody,children:(0,n.jsxs)("section",{className:m0().group,children:[(0,n.jsx)("h3",{className:m0().groupTitle,children:e("chat.liveVoiceSpeakerGroup")}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{className:m0().settingLabel,children:e("chat.liveVoiceCodexLabel")}),(0,n.jsx)("div",{className:m0().settingDescription,children:e("chat.liveVoiceCodexHelp")}),o&&(0,n.jsx)("div",{className:m0().error,role:"alert",style:{overflowWrap:"anywhere"},children:o})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)(hL,{value:t.defaultVoice,disabled:i,ariaLabel:e("chat.liveVoiceCodexLabel"),options:t.voices,onChange:e=>{e!==t.defaultVoice&&d(e)}})})]}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{className:m0().settingLabel,children:e("chat.livePaceLabel")}),(0,n.jsx)("div",{className:m0().settingDescription,children:e("chat.livePaceHelp")})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)(hL,{value:t.pace,disabled:i,ariaLabel:e("chat.livePaceLabel"),options:[{value:"normal",label:e("chat.livePaceNormal")},{value:"slow",label:e("chat.livePaceSlow")}],onChange:e=>{e!==t.pace&&dr.includes(e)&&u(e)}})})]})]})})]}):(0,n.jsx)("div",{className:m0().empty,children:o?`${e("chat.liveVoiceLoadFailed")}: ${o}`:"…"})}function m4(){let{t:e}=(0,z.s)(),t=(0,a.useId)(),r=(0,a.useId)(),[i,s]=(0,a.useState)(null),[o,l]=(0,a.useState)(""),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1),[h,m]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=new AbortController;return dX({signal:e.signal}).then(e=>{s(e),l(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||d(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let f=(0,a.useCallback)(async e=>{p(!0),d(null),m(!1);try{let t=await dQ(e);s(t),l(String(t.uploadLimitMb)),m(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return i?(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,n.jsx)("p",{className:m0().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,n.jsx)("div",{className:m0().settingsBody,children:(0,n.jsxs)("section",{className:m0().group,children:[(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:t,className:m0().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,n.jsx)("div",{className:m0().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("input",{id:t,className:m0().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:o,disabled:u,onChange:e=>l(e.target.value),onBlur:()=>{let t=o.trim();if(t===String(i.uploadLimitMb))return;let r=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(r)||r<1){m(!1),d(e("chat.attachmentUploadLimitInvalid"));return}f({uploadLimitMb:r})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{id:r,className:m0().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,n.jsx)("div",{className:m0().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:i.orphanGraceDays})})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("button",{type:"button",className:m0().switch,"data-on":i.autoCleanupEnabled,"aria-pressed":i.autoCleanupEnabled,"aria-labelledby":r,disabled:u,onClick:()=>void f({autoCleanupEnabled:!i.autoCleanupEnabled})})})]}),c&&(0,n.jsx)("div",{className:m0().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),h&&!c&&(0,n.jsx)("div",{className:m0().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,n.jsx)("div",{className:m0().empty,children:c?`${e("chat.attachmentSettingsLoadFailed")}: ${c}`:"…"})}function m5(){let{t:e}=(0,z.s)(),t=(0,a.useId)(),r=am(),[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1);(0,a.useEffect)(()=>{nM().then(()=>s(!0))},[]);let h=(0,a.useCallback)(async e=>{l(!0),d(null),p(!1);try{let t=await fetch("/api/character-mode",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:e})}),r=await t.json().catch(()=>null);if(!t.ok)throw Error("object"==typeof r&&null!==r&&"error"in r?String(r.error):`HTTP ${t.status}`);nN(r),p(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(!1)}},[]);if(!i)return(0,n.jsx)("div",{className:m0().empty,children:"…"});let m=[{mode:"default",label:e("characterMode.default")},{mode:"office",label:e("characterMode.office")}];return(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:e("characterMode.title")}),(0,n.jsx)("p",{className:m0().contentDescription,children:e("characterMode.description")})]}),(0,n.jsx)("div",{className:m0().settingsBody,children:(0,n.jsxs)("section",{className:m0().group,children:[(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{id:t,className:m0().settingLabel,children:e("characterMode.label")}),(0,n.jsx)("div",{className:m0().settingDescription,children:e("characterMode.help")})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("div",{className:m0().multiSelect,role:"radiogroup","aria-labelledby":t,children:m.map(e=>(0,n.jsx)("span",{className:m0().choice,"data-selected":r.mode===e.mode,children:(0,n.jsx)("button",{type:"button",role:"radio","aria-checked":r.mode===e.mode,className:m0().choiceToggle,disabled:o,onClick:()=>{r.mode!==e.mode&&h(e.mode)},children:e.label})},e.mode))})})]}),"office"===r.mode&&!r.rosterAvailable&&(0,n.jsx)("div",{className:m0().settingDescription,role:"status",children:e("characterMode.noRoster")}),c&&(0,n.jsx)("div",{className:m0().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),u&&!c&&(0,n.jsx)("div",{className:m0().saveState,role:"status",children:e("characterMode.saved")})]})})]})}function m6({cwd:e}){let{t}=(0,z.s)(),[r,i]=(0,a.useState)(null),[s,o]=(0,a.useState)(null),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)({}),[m,f]=(0,a.useState)(null),[g,x]=(0,a.useState)(null),v=(0,a.useRef)(new Map);(0,a.useEffect)(()=>{g&&d!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[d,r,g]);let b=(0,a.useRef)(0),y=(0,a.useRef)(null),w=(0,a.useRef)(null),k=(0,a.useRef)(!1),j=(0,a.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let r=++b.current;y.current?.abort();let n=new AbortController;y.current=n;try{let a=e?`?include=${encodeURIComponent(e)}`:"",s=await fetch(`/api/project-trust${a}`,{cache:"no-store",signal:n.signal}),l=await s.json();if(r!==b.current||n.signal.aborted)return;if(!s.ok||!l.projects)throw Error(l.error??`HTTP ${s.status}`);let c=l.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=l.projects,i(l.projects),o(null),c&&f({cwd:c.cwd,text:t("trust.doneApplied")})}catch(e){if(r!==b.current||n.signal.aborted)return;o(e instanceof Error?e.message:String(e))}finally{y.current===n&&(y.current=null)}},[e,t]);(0,a.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=r?.some(e=>null!==e.pending)??!1;(0,a.useEffect)(()=>{let e;if(!S||null!==d||null!==l)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},r=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",r),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",r)}},[d,l,r,S,j]);let C=(0,a.useCallback)(async(e,r)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),c(null),x(e),f(null),h(t=>{let r={...t};return delete r[e],r});try{let n=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:r})}),a=await n.json();if(!n.ok)throw Error(a.error??`HTTP ${n.status}`);let s=w.current?.map(t=>t.cwd===e?{...a,cwd:e}:t)??null;w.current=s,i(s),"cancel"===r?f({cwd:e,text:t("trust.doneCancelled")}):a.error||null!==a.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(r=>({...r,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!r)return(0,n.jsxs)("div",{className:m0().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,n.jsx)("button",{type:"button",className:m0().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==d;return(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:t("trust.settingsNav")}),(0,n.jsx)("p",{className:m0().contentDescription,children:t("trust.settingsDescription")}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,n.jsx)("button",{type:"button",className:m0().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,n.jsx)("div",{className:m0().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,n.jsx)("div",{className:m0().settingsBody,children:(0,n.jsxs)("section",{className:m0().group,children:[0===r.length&&(0,n.jsx)("div",{className:m0().settingDescription,children:t("trust.settingsEmpty")}),r.map(e=>{var r;let a=d===e.cwd,i=l?.cwd===e.cwd?l:null,s=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),o=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsxs)("div",{className:m0().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{className:m0().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,n.jsx)("span",{children:(r=e.cwd).split(/[\\/]/).filter(Boolean).pop()??r}),(0,n.jsx)("span",{className:m0().settingDescription,style:{fontWeight:600},children:s})]}),(0,n.jsx)("code",{className:m0().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,n.jsx)("div",{className:m0().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,n.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,n.jsx)("div",{className:m0().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,n.jsx)("div",{className:m0().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),i&&(0,n.jsx)("div",{className:m0().settingDescription,style:{color:"var(--text)"},children:"revoke"===i.action?t("trust.confirmRevoke"):i.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,n.jsx)("div",{className:m0().saveState,children:m.text})]}),o&&(0,n.jsx)("div",{className:m0().error,role:"alert",children:o})]}),(0,n.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:m0().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:m0().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{c(null),x(e.cwd)},children:t("trust.cancel")}),(0,n.jsx)("button",{type:"button",className:"revoke"===i.action?m0().dangerButton:m0().primaryButton,disabled:N,onClick:()=>void C(e.cwd,i.action),children:"revoke"===i.action?t("trust.revoke"):t("trust.confirm")})]}):a?(0,n.jsx)("button",{type:"button",className:m0().primaryButton,disabled:!0,children:t("trust.working")}):(0,n.jsxs)(n.Fragment,{children:["grant"===e.pending&&(0,n.jsx)("button",{type:"button",className:m0().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,n.jsx)("button",{type:"button",className:m0().primaryButton,disabled:N,onClick:()=>c({cwd:e.cwd,action:"grant",again:"revoke"===e.pending}),children:"revoke"===e.pending?t("trust.trustAgain"):t("trust.trustProject")}),e.trusted&&(0,n.jsx)("button",{type:"button",className:m0().dangerButton,disabled:N,onClick:()=>c({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let m3="cuelo-look",m7="cuelo-look-wallpaper",m9="data-cuelo-look",fe="data-cuelo-wallpaper";function ft(e){try{return localStorage.getItem(e)}catch{return null}}function fr(e,t){try{return null===t?localStorage.removeItem(e):localStorage.setItem(e,t),!0}catch{return!1}}function fn(e,t){let r=document.documentElement;e?r.setAttribute(m9,"graphite"):r.removeAttribute(m9),e&&t?r.setAttribute(fe,t):r.removeAttribute(fe)}let fa=new Set,fi=null,fs=null;function fo(){return fi??"graphite"===ft(m3)}function fl(e){let t;fi=fr(m3,e?"graphite":null)?null:e,fn(e,fs??("default"===(t=ft(m7))||"office"===t?t:null)),fa.forEach(e=>e())}function fc(e){let t="office"===e?"office":"default";fs=fr(m7,t)?null:t,fn(fo(),t)}function fd(e){return fa.add(e),()=>{fa.delete(e)}}let fu=JSON.parse('{"tabs":{"appearance":"외관","model":"모델 동작","interaction":"상호작용","context":"컨텍스트","memory":"메모리","files":"파일","shell":"셸","tools":"도구","tasks":"작업","providers":"제공자"},"groups":{"Theme":"테마","Status Line":"상태 표시줄","Display":"표시","Images":"이미지","Thinking":"사고","Sampling":"샘플링","Prompt":"프롬프트","Retry & Fallback":"재시도 및 폴백","Advisor":"어드바이저","Prewalk":"Prewalk","Vision":"비전","Input":"입력","Approvals":"승인","Notifications":"알림","Speech":"음성","Collab":"협업","Magic Keywords":"매직 키워드","Startup & Updates":"시작 및 업데이트","Power (macOS)":"전원 (macOS)","Agent":"에이전트","Git":"Git","General":"일반","Compaction":"압축","Rules (TTSR)":"규칙 (TTSR)","Experimental":"실험적 기능","Auto-Learn":"자동 학습","Mnemopi":"Mnemopi","Hindsight":"Hindsight","Editing":"편집","Reading":"읽기","Read Summaries":"읽기 요약","LSP":"LSP","Bash":"Bash","Eval & Runtimes":"평가 및 런타임","Available Tools":"사용 가능한 도구","Todos":"할 일","Grep & Browser":"Grep 및 브라우저","Computer":"컴퓨터","GitHub":"GitHub","Output Limits":"출력 제한","Execution":"실행","Discovery & MCP":"탐색 및 MCP","Developer":"개발자","Modes":"모드","Subagents":"서브에이전트","Isolation":"격리","Commands & Skills":"명령 및 스킬","Services":"서비스","Fireworks":"Fireworks","Tiny Model":"Tiny Model","Protocol":"프로토콜","Timeouts":"타임아웃","Privacy":"개인정보"},"shell":{"Loading omp settings…":"omp 설정을 불러오는 중…","Settings unavailable":"설정을 사용할 수 없음","Matching canonical /settings entries across every category.":"모든 카테고리에서 표준 /settings 항목을 일치시킨다.","Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.":"표준 omp /settings 값이다. 변경 사항은 공유 에이전트 설정에 즉시 저장된다.","Saved. Reload the active session to apply runtime settings.":"저장됨. 런타임 설정을 적용하려면 활성 세션을 다시 불러온다.","Reloading…":"다시 불러오는 중…","Reload session":"세션 다시 불러오기","No settings match this search.":"이 검색과 일치하는 설정이 없다.","Search /settings":"/settings 검색","Configuration":"구성","OMP settings":"OMP 설정","Close settings":"설정 닫기","Global configuration":"전역 구성","Settings":"설정","Search":"검색","Models & accounts":"모델\xb7계정","Access":"접속 암호","Themes":"테마","Skills":"스킬","Plugins":"플러그인","MCP":"MCP","Loading themes…":"테마를 불러오는 중…","Themes unavailable":"테마를 사용할 수 없음","Active on web":"웹에서 활성","Preview ":"미리보기 ","The web interface uses the same dark and light theme mappings as omp. Changes are persisted to ":"웹 인터페이스는 omp와 동일한 다크 및 라이트 테마 매핑을 사용한다. 변경 사항은 다음에 저장된다: "," and applied here immediately.":" 그리고 여기에 즉시 적용된다."," mapping":" 매핑","requires a project":"프로젝트가 필요하다"},"fields":{"theme.dark":{"label":"다크 테마","description":"터미널 배경이 어두울 때 사용하는 테마이다"},"theme.light":{"label":"라이트 테마","description":"터미널 배경이 밝을 때 사용하는 테마이다"},"symbolPreset":{"label":"심볼 프리셋","description":"아이콘과 기호에 사용하는 글리프 세트이다 (Unicode, Nerd Font, ASCII)"},"colorBlindMode":{"label":"색맹 모드","description":"diff 추가 표시에 초록색 대신 파란색을 사용한다"},"statusLine.preset":{"label":"상태 표시줄 프리셋","description":"미리 구성된 상태 표시줄 설정이다"},"statusLine.separator":{"label":"상태 표시줄 구분자","description":"세그먼트 사이 구분자의 스타일이다"},"statusLine.sessionAccent":{"label":"세션 강조색","description":"에디터 테두리와 상태 표시줄 여백에 세션 이름 색상을 사용한다"},"statusLine.transparent":{"label":"투명 상태 표시줄","description":"상태 표시줄에 테마의 `statusLineBg` 대신 터미널 기본 배경을 사용한다. Powerline 끝 캡은 주변 터미널로 이어지려면 대비되는 채움색이 필요하므로 제거된다."},"statusLine.compactThinkingLevel":{"label":"간결한 thinking 레벨","description":"thinking 레벨을 별도의 ` \xb7 <level>` 접미사 대신 모델 이름에 아이콘 하나로 표시한다."},"statusLine.showHookStatus":{"label":"hook 상태 표시","description":"상태 표시줄 아래에 hook 상태 메시지를 표시한다"},"terminal.showImages":{"label":"인라인 이미지 표시","description":"터미널에 이미지를 인라인으로 렌더링한다"},"images.autoResize":{"label":"이미지 자동 크기 조정","description":"모델 호환성을 높이기 위해 큰 이미지를 최대 2000x2000으로 축소한다"},"images.blockImages":{"label":"이미지 차단","description":"이미지가 LLM 제공자에게 전송되지 않도록 한다"},"terminal.showProgress":{"label":"네이티브 터미널 진행 표시","description":"에이전트나 컨텍스트 유지 작업이 실행되는 동안 OSC 9;4 부정형 진행 표시를 내보낸다"},"tui.textSizing":{"label":"큰 제목 (Kitty)","description":"Kitty의 OSC 66 text-sizing 프로토콜을 사용해 Markdown H1 제목을 2배 크기로 렌더링한다. Kitty 터미널에서만 적용되며 그 외에서는 무시된다. 기본값은 꺼짐이다."},"tui.renderMermaid":{"label":"Mermaid 다이어그램 렌더링","description":"Mermaid 코드 블록을 ASCII 다이어그램으로 렌더링한다"},"tui.codexResetFireworks":{"label":"Codex 리셋 불꽃놀이","description":"예정에 없던 Codex 주간 사용량 리셋과 새로 적립된 저장 리셋을 화면 상단 1/3의 불꽃놀이 오버레이로 축하하며, Escape를 누를 때까지 유지된다"},"tui.titleState":{"label":"터미널 제목 실행 상태","description":"터미널 제목의 구분자에 에이전트 실행 상태를 표시한다 — 작업 중에는 애니메이션 스피너(Windows에서는 고정된 \':\'), 사용자 차례일 때는 \'>\', 에이전트가 사용자를 기다릴 때는 \'!\'이다"},"tui.hyperlinks":{"label":"터미널 하이퍼링크","description":"터미널 자체의 클릭 열기를 위해 경로와 URL을 OSC 8 하이퍼링크로 감싼다 (auto: 지원 여부 감지, off: 사용 안 함, always: 무조건 사용)"},"tui.tight":{"label":"조밀한 레이아웃","description":"터미널 출력 좌우의 1문자 가로 여백을 제거한다"},"tui.scrollbackRebuild":{"label":"스크롤백 다시 쓰기","description":"블록의 최종 형태가 실시간 미리보기를 대체할 때 터미널 스크롤백을 지우고 다시 출력한다. 꺼짐(기본값)일 때는 오래된 미리보기 사본이 기록에 남고 최종 내용이 그 아래에 추가된다."},"display.shimmer":{"label":"셔머","description":"작업/로딩 메시지의 애니메이션 스타일이다"},"display.smoothStreaming":{"label":"부드러운 스트리밍","description":"청크가 도착하는 동안 어시스턴트 텍스트와 스트리밍되는 도구 입력을 부드럽게 표시한다"},"display.hideToolActivity":{"label":"도구 활동 숨김","description":"모델이 시작한 도구 호출과 결과를 대화 기록에서 숨긴다"},"display.showTokenUsage":{"label":"토큰 사용량 표시","description":"어시스턴트 메시지에 턴별 토큰 사용량을 표시한다"},"display.cacheMissMarker":{"label":"캐시 미스 표시","description":"요청이 프롬프트 캐시를 놓친(miss) 어시스턴트 턴 위에 구분선을 표시한다"},"display.collapseCompacted":{"label":"압축 히스토리 접기","description":"라이브 트랜스크립트에서 compaction 이전 히스토리를 요약 구분선 뒤로 접는다. 비활성화하면 각 compaction 지점에 구분선을 둔 채 전체 트랜스크립트를 인라인으로 유지한다"},"showHardwareCursor":{"label":"하드웨어 커서 표시","description":"IME 지원을 위해 터미널 커서를 표시한다"},"tui.imeSafeCursor":{"label":"IME 안전 프롬프트 레이아웃","description":"macOS IME preedit가 프롬프트 하단 테두리를 밀어내지 못하도록 테두리를 별도 행으로 옮긴다"},"task.showResolvedModelBadge":{"label":"확정 모델 배지 표시","description":"task 위젯 상태줄에 각 subagent가 실제로 사용한 모델 ID를 표시한다"},"advisor.enabled":{"label":"Advisor 활성화","description":"\'advisor\' 역할에 배정된 두 번째 모델을 함께 두어 각 턴을 수동적으로 검토하고 메모를 주입한다."},"prewalk.enabled":{"label":"Prewalk 활성화","description":"활성 모델로 시작한 뒤, plan nudge의 todo 목록이 생성된 이후 첫 edit/write 시점에 빠르고 저렴한 모델(기본값은 \'smol\' 역할)로 전환한다 — 강한 모델이 계획하고 todo를 확정하며 구현을 시작한 후 인계한다. 세션별로 --prewalk / --no-prewalk로 재정의할 수 있다."},"advisor.syncBacklog":{"label":"Advisor 동기화 백로그","description":"advisor가 이 턴 수만큼 뒤처지면 메인 에이전트를 최대 30초 동안 멈춘다. Off로 두면 따라잡기 지연을 비활성화한다."},"advisor.immuneTurns":{"label":"Advisor 면역 턴","description":"advisor의 concern 또는 blocker가 한 번 인터럽트한 뒤에는, 이 primary 턴 수 동안 이후 concern/blocker를 인터럽트 없이 전달한다."},"modelRoleStorage":{"label":"모델 역할 저장소","description":"모델 선택기의 역할 배정이 저장되는 위치이다"},"images.describeForTextModels":{"label":"텍스트 모델용 이미지 설명","description":"vision을 지원하지 않는 모델에 이미지가 첨부되면, 이미지를 버리지 않고 local:// 아래에 저장한 뒤 vision 지원 모델이 만든 설명을 주입한다"},"defaultThinkingLevel":{"label":"Thinking 레벨","description":"thinking을 지원하는 모델의 추론 깊이이다"},"hideThinkingBlock":{"label":"Thinking 블록 숨김","description":"어시스턴트 응답에서 thinking 블록을 숨긴다"},"proseOnlyThinking":{"label":"산문 전용 Thinking","description":"thinking 요약에서 코드 블록을 제외하고 생략 부호로 대체한다"},"omitThinking":{"label":"Thinking 요약 생략","description":"응답에서 thinking 요약을 완전히 생략하도록 업스트림 provider에 지시한다(지원되는 경우)"},"externalThinking":{"label":"외부 Thinking","description":"사용자에게 표시되지 않는 비공개 스크래치패드이다. 지원되는 GPT, Claude, Gemini의 reasoning을 비활성화한다"},"model.loopGuard.enabled":{"label":"Loop Guard","description":"모델 reasoning과 산문에 대한 자동 스트림 루프 감지를 활성화한다"},"model.loopGuard.checkAssistantContent":{"label":"Loop Guard 산문 검사","description":"thinking 로그 외에 어시스턴트 산문 메시지에도 loop guard를 적용한다"},"model.loopGuard.toolCallReminder":{"label":"Loop Guard 도구 호출 알림","description":"Gemini reasoning 스트림이 도구를 호출하지 않고 계획 헤더를 연속으로 다수 출력하면 중단하고 도구 호출을 요구하는 알림을 주입한다(Loop Guard 필요)"},"model.toolCallLoopGuard.enabled":{"label":"도구 호출 Loop Guard","description":"여러 턴에 걸친 동일한 연속 도구 호출을 감지하고 교정용 steer를 주입한다"},"inlineToolDescriptors":{"label":"인라인 도구 디스크립터","description":"시스템 프롬프트에 전체 도구 디스크립터를 렌더링하고 provider 도구 스키마에서 최상위/중첩 description을 제거해 디스크립터 텍스트를 한 번만 전송한다. Auto는 Gemini 모델에서 이를 활성화하고 그 외에는 비활성화한다"},"includeModelInPrompt":{"label":"프롬프트에 모델 포함","description":"에이전트가 자신이 어떤 모델인지 알 수 있도록 시스템 프롬프트에 활성 모델 식별자를 노출한다"},"includeWorkspaceTree":{"label":"워크스페이스 트리 포함","description":"시스템 프롬프트에 워크스페이스 디렉터리 트리를 렌더링한다. 경고: 파일이 수정되면 세션 간 프롬프트 캐싱이 깨질 수 있다."},"personality":{"label":"성격","description":"시스템 프롬프트의 personality 블록에 렌더링되는 의사소통 스타일이다"},"temperature":{"label":"Temperature","description":"샘플링 temperature이다(0 = 결정적, 1 = 창의적, -1 = provider 기본값)"},"topP":{"label":"Top P","description":"Nucleus 샘플링 컷오프이다(0-1, -1 = provider 기본값)"},"topK":{"label":"Top K","description":"상위 K개 토큰에서 샘플링한다(-1 = provider 기본값)"},"minP":{"label":"Min P","description":"최소 확률 임계값 (0-1, -1 = provider 기본값)"},"presencePenalty":{"label":"Presence Penalty","description":"이미 등장한 토큰을 도입하는 데 대한 페널티 (-1 = provider 기본값)"},"repetitionPenalty":{"label":"Repetition Penalty","description":"반복된 토큰에 대한 페널티 (-1 = provider 기본값)"},"textVerbosity":{"label":"텍스트 상세도","description":"OpenAI Responses 및 Codex 응답의 상세도 (low, medium, high)"},"tier.openai":{"label":"서비스 티어 — OpenAI","description":"OpenAI / OpenAI-Codex 요청 및 OpenRouter를 경유하는 OpenAI 계열 모델의 처리 티어 (none = 생략). `service_tier`로 전송한다."},"tier.anthropic":{"label":"서비스 티어 — Anthropic","description":"Claude 요청의 처리 티어. `priority`는 지원되는 직접 Anthropic 모델에서 fast 모드(`speed: \\"fast\\"`)를 활성화하며, Bedrock/Vertex Claude 및 OpenRouter 경유에서는 무시된다."},"tier.google":{"label":"서비스 티어 — Google","description":"Gemini(Google AI Studio + Vertex) 요청 및 OpenRouter를 경유하는 Google 계열 모델의 처리 티어 (none = 생략). 최상위 `serviceTier` 필드로 전송한다."},"tier.subagent":{"label":"서비스 티어 — 서브에이전트","description":"생성된 task/eval 서브에이전트의 서비스 티어. Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다(/fast를 추적한다). 값을 지정하면 서브에이전트 모델이 속한 계열에 그 값을 적용한다."},"tier.advisor":{"label":"서비스 티어 — Advisor","description":"advisor 모델의 서비스 티어. None = 표준 처리, Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다. 값을 지정하면 advisor 모델의 계열에 그 값을 적용한다."},"retry.maxRetries":{"label":"재시도 횟수","description":"API 오류 시 최대 재시도 횟수"},"retry.modelFallback":{"label":"재시도 모델 폴백","description":"재시도 복구 시 설정된 폴백 모델로 전환하도록 허용한다"},"retry.usageAwareFallback":{"label":"사용량 인식 폴백","description":"신뢰할 수 있는 coding-plan 할당량 보고를 활용해, 하드 사용량 한도에 도달하기 전에 동일 provider 계정을 먼저 사용하고 그다음 설정된 폴백 모델을 사용한다. 일반 설정 API 키는 제외한다."},"retry.usageReservePct":{"label":"예비 마진","description":"남은 비율이 이 값 미만이면 coding-plan 모델이 한도에 근접한 것으로 간주한다. 사용량을 알 수 없거나 매핑되지 않은 경우 주 모델을 유지한다."},"retry.usageReservePolicy":{"label":"예비 정책","description":"동일 provider의 모든 coding-plan 계정이 예비 마진 안에 들어왔을 때의 동작이다."},"retry.fallbackChains":{"label":"재시도 폴백 체인","description":"모델 역할, 모델 선택자(\\"provider/model-id\\"), 또는 provider 와일드카드(\\"provider/*\\")를 순서가 있는 폴백 선택자에 매핑하는 JSON 객체이다. 예: {\\"default\\":[\\"openai/gpt-4o-mini\\"],\\"google-antigravity/*\\":[\\"google/*\\",\\"google-vertex/*\\"]}. 모델 지향 키는 역할과 무관하게 해당 모델/provider가 활성일 때마다 적용되며, \\"provider/*\\" 항목은 실패한 모델의 id를 유지한 채 provider만 교체한다. id 접두사 와일드카드(\\"openrouter/google/*\\")는 실패한 모델의 순수 id에 접두사를 다시 붙이고(google-antigravity/gemini-x -> openrouter/google/gemini-x), 키로 사용될 때는 해당 접두사 아래의 그 provider id에만 매칭된다."},"retry.fallbackRevertPolicy":{"label":"폴백 복귀 정책","description":"폴백 이후 주 모델로 되돌아가는 시점이다"},"providers.anthropic.serverSideFallback":{"label":"Anthropic 서버 사이드 폴백 (Fable 5)","description":"Claude Fable 5 / Mythos 5 요청이 Anthropic의 안전 분류기에 의해 차단되면 서버 사이드에서 Claude Opus 4.8로 재시도한다(Anthropic `server-side-fallback-2026-06-01` 베타). 옵트인 방식이며, 끄면 모든 요청에 대해 폴백 이전 동작이 유지된다."},"providers.autoThinkingModel":{"label":"Auto Thinking 모델","description":"`auto` thinking 레벨의 난이도 분류기이다. 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 사용할 수 있다"},"providers.autoThinkingMaxEffort":{"label":"Auto Thinking 상한","description":"`auto` 분류기가 도달할 수 있는 최고 effort이다. `xhigh`는 분류기를 최상위보다 한 단계 아래로 유지해 명시적인 `ultrathink`만 `max`에 도달하게 하며, `max`는 분류기가 예외적이라고 판단한 턴이 이를 노출하는 모델에서 최상위 티어로 과금되도록 허용한다."},"autoResume":{"label":"자동 재개","description":"현재 디렉터리의 가장 최근 세션을 자동으로 재개한다"},"power.sleepPrevention":{"label":"절전 방지","description":"활성 세션 동안 macOS 절전을 방지한다. 각 레벨은 누적되며, 하위 레벨의 플래그를 모두 포함한다."},"git.enabled":{"label":"Git 통합 활성화","description":"TUI에 git 브랜치, 상태, PR 정보를 표시하고 저장소 메타데이터를 감시한다."},"steeringMode":{"label":"Steering 모드","description":"에이전트가 작업하는 동안 대기 중인 메시지를 처리하는 방식이다"},"followUpMode":{"label":"후속 메시지 모드","description":"턴이 완료된 후 후속 메시지를 처리하는 방식이다"},"interruptMode":{"label":"인터럽트 모드","description":"steering 메시지가 도구 실행을 중단하는 시점이다"},"loop.mode":{"label":"Loop 모드","description":"/loop 반복 사이에 프롬프트를 다시 제출하기 전에 일어나는 동작이다"},"doubleEscapeAction":{"label":"이중 Escape 동작","description":"편집기가 비어 있는 상태에서 Escape를 두 번 누를 때의 동작이다"},"treeFilterMode":{"label":"세션 트리 필터","description":"세션 트리를 열 때의 기본 필터 모드이다"},"autocompleteMaxVisible":{"label":"자동완성 항목 수","description":"자동완성 드롭다운에 표시되는 최대 항목 수이다 (3-20)"},"emojiAutocomplete":{"label":"이모지 자동완성","description":"`:name:` 숏코드로 이모지를 제안하고 `:D` 또는 `:-)` 같은 텍스트 이모티콘을 확장한다"},"paste.largeMenuThreshold":{"label":"대용량 붙여넣기 메뉴","description":"붙여넣기가 이 줄 수에 도달하면 코드 블록으로 감싸기, XML 태그로 감싸기, 파일로 저장하기 메뉴를 제공한다. 0은 메뉴를 비활성화한다(대용량 붙여넣기는 여전히 [Paste] 마커로 축약된다)."},"startup.quiet":{"label":"조용한 시작","description":"환영 화면과 시작 상태 메시지를 건너뛴다"},"startup.showSplash":{"label":"시작 스플래시 표시","description":"설정을 다시 실행하지 않고 일반 대화형 시작 시 전체 애니메이션 설정 스플래시를 표시한다. 조용한 시작은 여전히 이를 억제한다."},"startup.setupWizard":{"label":"설정 위저드","description":"새로 추가된 온보딩 단계를 설정 버전마다 한 번 표시한다"},"startup.checkUpdate":{"label":"업데이트 확인","description":"시작 시 omp 업데이트를 확인한다"},"marketplace.autoUpdate":{"label":"마켓플레이스 자동 업데이트","description":"시작 시 플러그인 업데이트를 확인한다"},"startup.changelogMode":{"label":"시작 변경 내역","description":"업데이트 노트를 요약으로 시작할지, 전체 상세로 시작할지, 숨긴 상태로 둘지 선택한다"},"magicKeywords.enabled":{"label":"매직 키워드","description":"단독으로 쓰인 ultrathink, orchestrate, workflowz 키워드에 대한 숨겨진 공지를 활성화한다"},"magicKeywords.ultrathink":{"label":"Ultrathink 키워드","description":"단독으로 쓰인 ultrathink가 최대 자동 사고를 요청하고 숨겨진 공지를 덧붙이도록 한다"},"magicKeywords.orchestrate":{"label":"Orchestrate 키워드","description":"단독으로 쓰인 orchestrate가 숨겨진 멀티 에이전트 오케스트레이션 공지를 덧붙이도록 한다"},"magicKeywords.workflow":{"label":"Workflow 키워드","description":"단독으로 쓰인 workflowz가 숨겨진 eval 워크플로 공지를 덧붙이도록 한다"},"completion.notify":{"label":"완료 알림","description":"에이전트가 턴을 마쳤을 때 알린다"},"error.notify":{"label":"오류 알림","description":"에이전트가 오류로 중단되었을 때 알린다"},"ask.timeout":{"label":"Ask 타임아웃","description":"이 초가 지나면 권장 ask 옵션을 자동 선택한다 (0은 비활성화)"},"ask.notify":{"label":"Ask 알림","description":"ask 도구가 입력을 기다릴 때 알린다"},"recap.enabled":{"label":"유휴 요약","description":"터미널이 유휴 상태가 된 후 현재 상황에 대한 간단한 LLM 요약을 생성한다"},"recap.idleSeconds":{"label":"유휴 요약 지연","description":"요약을 표시하기 전 유휴 상태로 대기하는 초이다"},"collab.relayUrl":{"label":"Relay URL","description":"/collab에서 사용하는 relay이다 (wss://host[:port])"},"collab.webUrl":{"label":"웹 UI URL","description":"/collab 링크에 사용되는 브라우저 UI이다. 비어 있으면 collab.relayUrl에서 파생되며, 명시적인 http://는 localhost에서만 사용된다"},"collab.displayName":{"label":"표시 이름","description":"다른 collab 참가자에게 표시되는 이름이다 (기본값: OS 사용자 이름)"},"share.serverUrl":{"label":"Share 서버","description":"/share에서 사용하는 공유 뷰어/업로드 기준 주소이다 (암호화된 blob 업로드 + 뷰어, 링크는 <base>/<id>#<key> 형식이다)"},"share.store":{"label":"Share 저장소","description":"/share가 암호화된 세션 blob을 업로드하는 위치이다"},"share.redactSecrets":{"label":"공유 시 비밀정보 삭제","description":"업로드 전에 /share 스냅샷에 대해 secret obfuscator를 실행한다(secrets.* 설정을 사용한다)"},"stt.enabled":{"label":"음성 인식","description":"마이크를 통한 speech-to-text 입력을 활성화한다"},"stt.modelName":{"label":"음성 모델","description":"로컬 온디바이스 음성 모델이다. Parakeet TDT v3(sherpa-onnx)가 SoTA 기본값이며, Whisper base/small/large-v3-turbo 등급(transformers.js)은 크기를 다국어 지원과 맞바꾼다. 첫 사용 시 다운로드된다."},"stt.submitTrigger":{"label":"음성 입력 전송 트리거","description":"음성 받아쓰기가 자동으로 전송되는 시점을 선택한다: Never, Release(2단어 이상), 완전한 문장으로 Release, 또는 When I Say Submit."},"tools.approval":{"label":"도구 승인 정책","description":"도구별 승인 정책이다. \'allow\'는 자동 승인, \'prompt\'는 확인 요구, \'deny\'는 차단으로 설정한다. 재정의는 모든 승인 모드에서 적용된다."},"tools.approvalMode":{"label":"도구 승인","description":"도구 호출의 기본 승인 동작이다. \'Always ask\'는 읽기 전용 도구만 자동 승인한다. \'Write\'는 읽기 및 workspace-write 도구를 자동 승인한다. \'Yolo\'는 모든 등급을 자동 승인하지만, 사용자 정책에 따라 확인이나 차단이 발생할 수 있다."},"features.unexpectedStopDetection":{"label":"예상치 못한 중단","description":"어시스턴트가 예상치 못하게 멈추면 자동으로 복구한다. \'기계적\'(기본값)은 표시할 답변 없이 끝난 경우를 재시도하고 도구 호출이 있었던 중단은 제외한다. \'스마트\'는 기계적 감지에 더해 작은 모델로 텍스트만 남긴 중단도 판별하며, \'사용 안 함\'은 감지를 끈다."},"contextPromotion.enabled":{"label":"컨텍스트 자동 승격","description":"컨텍스트 초과 시 compaction 대신 더 큰 컨텍스트 모델로 승격한다"},"compaction.enabled":{"label":"자동 Compact","description":"컨텍스트가 너무 커지면 자동으로 compact한다"},"compaction.midTurnEnabled":{"label":"턴 중간 Compaction","description":"다음 provider 요청 전에 안전한 턴 중간 tool-loop 경계에서 임계값을 확인한다"},"compaction.strategy":{"label":"Compaction 전략","description":"제자리 context-full 유지, auto-handoff, surgical shake(무거운 콘텐츠 제거), snapcompact(히스토리를 밀집 이미지로 보관) 중에서 선택하거나 자동 유지를 비활성화(off)한다"},"compaction.thresholdPercent":{"label":"Compaction 임계값","description":"컨텍스트 유지의 퍼센트 임계값이다. Default로 설정하면 기존 reserve 기반 동작을 사용한다"},"compaction.thresholdTokens":{"label":"Compaction 토큰 한도","description":"컨텍스트 유지의 고정 토큰 한도이다. 설정하면 퍼센트 값을 재정의한다"},"compaction.handoffSaveToDisk":{"label":"Handoff 문서 저장","description":"auto-handoff 흐름에서 생성된 handoff 문서를 markdown 파일로 저장한다"},"compaction.remoteEnabled":{"label":"원격 Compaction","description":"가능한 경우 로컬 요약 대신 원격 compaction 엔드포인트를 사용한다"},"compaction.remoteStreamingV2Enabled":{"label":"원격 Compaction V2","description":"호환되는 원격 compaction 모델에 대해 Responses 스트리밍 compaction을 사용한다"},"compaction.idleEnabled":{"label":"유휴 Compaction","description":"토큰 수가 임계값을 넘으면 유휴 상태에서 컨텍스트를 compact한다"},"compaction.idleThresholdTokens":{"label":"유휴 Compaction 임계값","description":"유휴 compaction이 트리거되는 토큰 수 기준이다"},"compaction.idleTimeoutSeconds":{"label":"유휴 Compaction 지연","description":"compact하기 전 유휴 상태로 대기하는 초이다"},"compaction.supersedeReads":{"label":"오래된 읽기 대체","description":"같은 파일을 다시 읽으면 이전 읽기 결과를 정리한다(캐시 인식, 매 턴 실행)"},"compaction.dropUseless":{"label":"무의미한 결과 제거","description":"컨텍스트상 무용하다고 표시된 도구 결과(일치 없음, 시간 초과된 대기)를 소비된 후 정리한다(캐시 인식)"},"snapcompact.systemPrompt":{"label":"Snapcompact 시스템 프롬프트","description":"실험적 기능이다: 선택한 시스템 프롬프트 텍스트를 밀집 PNG 이미지로 렌더링해 첫 사용자 메시지에 첨부한다(비전 모델 전용). 토큰을 절약하지만 이미지화된 텍스트의 prompt caching을 잃는다."},"snapcompact.toolResults":{"label":"Snapcompact 도구 결과","description":"실험적 기능이다: 큰 과거 도구 결과를 텍스트 대신 밀집 PNG 이미지로 렌더링한다(비전 모델 전용). 누적된 읽기/검색 출력의 토큰을 절약한다."},"tools.format":{"label":"도구 호출 모드","description":"도구가 모델에 노출되는 방식을 제어한다. Auto는 provider-native 도구 호출을 사용하지만, 선택된 모델이 이를 지원하지 않는다고 표시된 경우 GLM owned dialect로 대체한다. Native는 provider-native 도구를 강제하고, 나머지 값은 지정된 owned dialect를 강제한다. 세션 시작 시 적용된다."},"snapcompact.shape":{"label":"Snapcompact 형태","description":"snapcompact가 텍스트를 출력하는 프레임 형태이다(compaction 보관 및 인라인 이미지화). Auto는 현재 모델에 맞게 조정된 형태를 선택한다."},"branchSummary.enabled":{"label":"브랜치 요약","description":"브랜치를 떠날 때 요약을 요청한다"},"ttsr.enabled":{"label":"TTSR","description":"출력이 규칙 패턴과 일치하면 스트리밍 도중에 에이전트를 중단한다(Time-Traveling Stream Rules)"},"ttsr.contextMode":{"label":"TTSR 컨텍스트 모드","description":"TTSR이 발동할 때 부분 출력을 어떻게 처리할지 정한다"},"ttsr.interruptMode":{"label":"TTSR 인터럽트 모드","description":"스트리밍 도중에 중단할지, 완료 후 경고를 주입할지 정한다"},"ttsr.repeatMode":{"label":"TTSR 반복 모드","description":"규칙이 반복되는 방식을 정한다: 세션당 한 번 또는 메시지 간격 이후"},"ttsr.repeatGap":{"label":"TTSR 반복 간격","description":"규칙이 다시 발동할 수 있기까지의 메시지 수이다"},"ttsr.builtinRules":{"label":"기본 제공 규칙","description":"에이전트에 기본 포함된 규칙을 로드한다(ttsr.disabledRules로 개별 해제 가능)"},"memory.backend":{"label":"메모리 백엔드","description":"끄기, 로컬 요약 파이프라인, Mnemopi SQLite, 또는 Hindsight 원격 메모리 중에서 선택한다"},"autolearn.enabled":{"label":"자동 학습 (실험적)","description":"에이전트가 멈춘 뒤 교훈을 메모리에 기록하고 격리된 관리형 skill을 생성/보강하도록 유도한다"},"autolearn.autoContinue":{"label":"중지 시 캡처 자동 실행","description":"켜면 중지 시 비공개 캡처 턴을 한 번 자동 실행한다(추가 토큰을 사용한다). 끄면 상시 자동 학습 안내만 남는다."},"mnemopi.dbPath":{"label":"Mnemopi DB 경로","description":"선택적 SQLite DB 경로이다. 기본값은 에이전트 memories 디렉터리이다."},"mnemopi.bank":{"label":"Mnemopi 뱅크","description":"선택적 공유 뱅크 기본 이름이다. per-project 모드는 이를 기반으로 프로젝트 로컬 뱅크를 파생한다."},"mnemopi.scoping":{"label":"Mnemopi 스코핑","description":"global = 공유 뱅크 하나, per-project = cwd별 격리 뱅크, per-project-tagged = 프로젝트 로컬 쓰기에 global recall 가시성을 더한 방식이다"},"mnemopi.embeddingVariant":{"label":"임베딩 variant","description":"로컬 임베딩 모델 계열이다. en = 더 강력한 영어 모델, multilingual = 교차 언어 모델이다. 이를 변경하면 다음 시작 시 기존 메모리 임베딩을 다시 생성한다."},"mnemopi.autoRecall":{"label":"Mnemopi 자동 recall","description":"각 세션의 첫 턴에 로컬 메모리를 recall한다"},"mnemopi.autoRetain":{"label":"Mnemopi 자동 retain","description":"완료된 대화 턴을 로컬 Mnemopi 메모리에 retain한다"},"mnemopi.polyphonicRecall":{"label":"Mnemopi 폴리포닉 recall","description":"reciprocal rank fusion으로 융합한 4-voice recall(vector, graph, fact, temporal)을 활성화한다"},"mnemopi.enhancedRecall":{"label":"Mnemopi 향상된 recall","description":"반복되거나 유사한 recall 쿼리를 위한 계층형 쿼리 결과 캐시를 활성화한다"},"mnemopi.proactiveLinking":{"label":"Mnemopi 선제적 링킹","description":"새 메모리를 저장하는 즉시 episodic 그래프에 수집해 관련 엔터티 및 메모리와 연결한다"},"mnemopi.noEmbeddings":{"label":"Mnemopi 임베딩 비활성화","description":"vector 임베딩 대신 결정적인 FTS 전용 recall을 강제한다"},"mnemopi.embeddingModel":{"label":"Mnemopi 임베딩 모델","description":"고급: variant를 재정의하는 명시적 임베딩 모델 id이다. 비워 두면 mnemopi.embeddingVariant를 사용한다."},"mnemopi.embeddingApiUrl":{"label":"Mnemopi 임베딩 API URL","description":"Mnemopi에 전달하는 선택적 OpenAI 호환 임베딩 엔드포인트이다"},"mnemopi.embeddingApiKey":{"label":"Mnemopi 임베딩 API 키","description":"Mnemopi에 전달하는 선택적 임베딩 API 키이다"},"mnemopi.llmMode":{"label":"Mnemopi LLM 모드","description":"LLM 미사용, 온라인 tiny 모델(/models의 TINY 역할, 없으면 @smol), 또는 원격 OpenAI 호환 엔드포인트를 사용한다"},"mnemopi.llmBaseUrl":{"label":"Mnemopi LLM Base URL","description":"Mnemopi 원격 모드를 위한 선택적 OpenAI 호환 LLM 엔드포인트이다"},"mnemopi.llmApiKey":{"label":"Mnemopi LLM API 키","description":"Mnemopi 원격 모드를 위한 선택적 LLM API 키이다"},"mnemopi.llmModel":{"label":"Mnemopi LLM 모델","description":"Mnemopi 원격 모드를 위한 선택적 LLM 모델 이름이다"},"hindsight.apiUrl":{"label":"Hindsight API URL","description":"Hindsight 서버 URL(Cloud 또는 self-hosted)이다"},"hindsight.apiToken":{"label":"Hindsight API 토큰","description":"인증이 필요한 Hindsight 서버용 Bearer 토큰이다"},"hindsight.bankId":{"label":"Hindsight Bank ID","description":"메모리 뱅크 식별자다(기본값: 프로젝트 이름)"},"hindsight.scoping":{"label":"Hindsight 범위","description":"global = 하나의 공유 뱅크, per-project = cwd별로 격리된 뱅크, per-project-tagged = 프로젝트 태그가 붙은 공유 뱅크로 recall 시 global 메모리와 프로젝트 메모리가 병합된다"},"hindsight.autoRecall":{"label":"Hindsight 자동 recall","description":"각 세션의 첫 턴에 메모리를 recall한다"},"hindsight.autoRetain":{"label":"Hindsight 자동 retain","description":"N턴마다 그리고 세션 경계에서 대화 기록을 retain한다"},"hindsight.retainMode":{"label":"Hindsight retain 모드","description":"full-session = 세션당 문서 하나를 upsert하고, last-turn = 청크 단위로 저장한다"},"hindsight.mentalModelsEnabled":{"label":"Hindsight 멘탈 모델","description":"부팅 시 정리된 reflect 요약(멘탈 모델)을 developer instructions로 읽어들인다. 뱅크에 있는 기존 모델을 로드하며 쓰기는 하지 않는다. 내장 seed 세트를 자동 생성하려면 hindsight.mentalModelAutoSeed와 함께 사용한다."},"hindsight.mentalModelAutoSeed":{"label":"Hindsight 멘탈 모델 자동 seed","description":"세션 시작 시 뱅크에 아직 없는 내장 멘탈 모델(project-conventions, project-decisions, user-preferences)을 생성한다."},"providers.memoryModel":{"label":"메모리 모델","description":"사실 추출 및 통합에 사용하는 Mnemopi LLM이다: 기본값은 online(/models의 TINY 역할, 없으면 smol/remote)이며, 로컬 on-device 모델도 사용할 수 있다"},"edit.mode":{"label":"편집 모드","description":"edit 도구 변형을 선택한다(replace, patch, hashline, apply_patch)"},"edit.fuzzyMatch":{"label":"퍼지 매치","description":"공백 차이에 대해 신뢰도가 높은 퍼지 매치를 허용한다"},"edit.fuzzyThreshold":{"label":"퍼지 매치 임계값","description":"퍼지 매치를 허용하는 유사도 임계값(0-1)이다"},"edit.streamingAbort":{"label":"프리뷰 실패 시 중단","description":"패치 프리뷰가 실패하면 스트리밍 edit 도구 호출을 중단한다"},"edit.blockAutoGenerated":{"label":"자동 생성 파일 차단","description":"자동 생성된 것으로 보이는 파일(protoc, sqlc, swagger 등)의 편집을 막는다"},"edit.enforceSeenLines":{"label":"확인된 줄 가드 적용","description":"이전 read/search가 전체를 표시하지 않은 줄을 기준으로 하는 편집을 거부한다"},"readLineNumbers":{"label":"줄 번호","description":"기본적으로 read 도구 출력에 줄 번호를 앞에 붙인다"},"read.defaultLimit":{"label":"기본 read 제한","description":"에이전트가 limit 없이 read를 호출할 때 반환하는 기본 줄 수다"},"read.renderMarkdown":{"label":"Markdown 프리뷰","description":"Markdown read 결과를 원본 소스가 아니라 서식이 적용된 터미널 Markdown 프리뷰로 렌더링한다"},"read.summarize.enabled":{"label":"read 요약","description":"명시적 selector 없이 read가 호출되면 구조적 코드 요약을 반환한다"},"read.summarize.prose":{"label":"산문 요약","description":"Markdown 및 일반 텍스트 read에 대해 구조적 요약을 반환한다"},"read.toolResultPreview":{"label":"인라인 read 프리뷰","description":"read 도구 결과를 요약 행이 아니라 대화 기록에 인라인으로 렌더링한다"},"lsp.enabled":{"label":"LSP","description":"코드 인텔리전스(정의, 참조, 진단, 이름 변경)를 위한 lsp 도구를 활성화한다"},"lsp.lazy":{"label":"LSP 지연 시작","description":"세션 시작 시점이 아니라 처음 사용할 때(lsp 도구 호출 또는 해당 파일 타입 편집) language server를 시작한다"},"lsp.shared":{"label":"공유 language server","description":"daemon broker를 통해 프로젝트당 하나의 language server를 omp 인스턴스 간에 공유한다(사용할 수 없으면 개별 서버로 대체된다)"},"lsp.formatOnWrite":{"label":"쓰기 시 포맷","description":"파일을 쓴 후 LSP로 코드 파일을 자동 포맷한다"},"lsp.diagnosticsOnWrite":{"label":"쓰기 시 진단","description":"코드 파일을 쓴 후 LSP 진단을 반환한다"},"lsp.diagnosticsOnEdit":{"label":"편집 시 진단","description":"코드 파일을 편집한 후 LSP 진단을 반환한다"},"lsp.diagnosticsDeduplicate":{"label":"진단 중복 제거","description":"파일에 대해 이미 표시된 편집 후 LSP 진단을 억제하고, 새롭거나 변경된 것만 표시한다"},"bash.enabled":{"label":"Bash","description":"셸 명령 실행을 위한 bash 도구를 활성화한다"},"bash.autoBackground.enabled":{"label":"Bash 자동 백그라운드","description":"오래 실행되는 bash 명령을 자동으로 백그라운드로 보내고 결과를 나중에 전달한다"},"bashInterceptor.enabled":{"label":"Bash 인터셉터","description":"전용 도구가 있는 셸 명령을 차단한다"},"bash.direnv":{"label":"direnv 자동 로드","description":"저장소의 direnv/devenv `.envrc`를 bash 세션에 자동으로 로드해 수동 `direnv exec` 없이 devenv 도구와 환경 변수를 사용할 수 있게 한다. direnv의 허용 목록을 따르며, `direnv allow`하지 않은 `.envrc`는 절대 실행되지 않는다"},"shellMinimizer.enabled":{"label":"셸 출력 축소","description":"장황한 셸 출력(git, npm, cargo 등)을 에이전트에 반환하기 전에 압축한다"},"shellMinimizer.sourceOutlineLevel":{"label":"셸 축소 소스 아웃라인","description":"소스 파일의 cat/read에 대한 소스 아웃라인 모드: default 또는 aggressive"},"eval.py":{"label":"Python Eval 백엔드","description":"eval 도구가 Python 셀을 IPython 커널로 보내도록 허용한다"},"eval.js":{"label":"JavaScript Eval 백엔드","description":"eval 도구가 JavaScript 셀을 인프로세스 런타임으로 보내도록 허용한다"},"eval.rb":{"label":"Ruby Eval 백엔드","description":"eval 도구가 Ruby 셀을 상시 유지되는 Ruby 커널로 보내도록 허용한다"},"eval.jl":{"label":"Julia Eval 백엔드","description":"eval 도구가 Julia 셀을 상시 유지되는 Julia 커널로 보내도록 허용한다"},"python.kernelMode":{"label":"Python 커널 모드","description":"eval 호출 간에 IPython 커널을 유지할지 매번 새로 시작할지 정한다"},"python.interpreter":{"label":"Python 인터프리터","description":"정확한 Python 실행 파일의 선택적 경로이다. 설정하면 자동 Python 런타임 탐색을 건너뛴다."},"ruby.interpreter":{"label":"Ruby 인터프리터","description":"정확한 Ruby 실행 파일의 선택적 경로이다. 설정하면 자동 Ruby 런타임 탐색을 건너뛴다."},"julia.interpreter":{"label":"Julia 인터프리터","description":"정확한 Julia 실행 파일의 선택적 경로이다. 설정하면 자동 Julia 런타임 탐색을 건너뛴다."},"tools.artifactSpillThreshold":{"label":"아티팩트 분리 임계값(KB)","description":"이 크기를 넘는 도구 출력은 아티팩트로 저장되고, 끝부분은 인라인으로 유지된다"},"tools.artifactTailBytes":{"label":"아티팩트 끝부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 양이다"},"tools.artifactHeadBytes":{"label":"아티팩트 앞부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 끝부분과 함께 인라인으로 유지되는 앞부분 내용의 양이다(중간 생략). 0이면 비활성화되어 끝부분만 유지한다."},"tools.outputMaxColumns":{"label":"출력 열 제한","description":"스트리밍 도구 출력(bash, python, js eval)과 `read`에 대한 줄당 바이트 제한이다. 이보다 긴 줄은 말줄임표로 잘리고, 다음 줄바꿈까지 남은 바이트는 버려진다. 0이면 비활성화된다."},"tools.artifactTailLines":{"label":"아티팩트 끝부분 줄 수","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 최대 줄 수이다"},"todo.enabled":{"label":"할 일 목록","description":"작업 추적을 위한 todo 도구를 활성화한다"},"todo.reminders":{"label":"할 일 알림","description":"중지하기 전에 할 일을 완료하도록 에이전트에 상기시킨다"},"todo.remindersMax":{"label":"할 일 알림 제한","description":"포기하기 전까지의 최대 할 일 알림 횟수이다"},"todo.eager":{"label":"할 일 자동 생성","description":"첫 메시지 이후 자동 할 일 목록 생성을 얼마나 강하게 유도할지 정한다"},"glob.enabled":{"label":"Glob","description":"glob 기반 파일 조회를 위한 glob 도구를 활성화한다"},"grep.enabled":{"label":"Grep","description":"정규식 내용 검색을 위한 grep 도구를 활성화한다"},"grep.contextBefore":{"label":"Grep 앞 컨텍스트","description":"각 grep 일치 항목 앞에 표시할 컨텍스트 줄 수이다"},"grep.contextAfter":{"label":"Grep 뒤 컨텍스트","description":"각 grep 일치 항목 뒤에 표시할 컨텍스트 줄 수이다"},"astGrep.enabled":{"label":"AST Grep","description":"구조적 AST 검색을 위한 ast_grep 도구를 활성화한다"},"astEdit.enabled":{"label":"AST Edit","description":"구조적 AST 재작성을 위한 ast_edit 도구를 활성화한다"},"debug.enabled":{"label":"디버그","description":"DAP 기반 디버깅을 위한 debug 도구를 활성화한다"},"launch.enabled":{"label":"Launch","description":"공유되는 장기 실행 프로젝트 프로세스를 감독하는 launch 도구를 활성화한다"},"speechgen.enabled":{"label":"음성 생성","description":"온디바이스(Kokoro) 또는 xAI Grok Voice 음성 파일 합성을 위한 tts 도구를 활성화한다"},"generate_image.enabled":{"label":"이미지 생성","description":"generate_image 도구(텍스트-이미지 생성 및 편집)를 활성화한다. tools.xdev가 켜져 있으면 xd:// 장치로 노출된다."},"inspect_image.mode":{"label":"이미지 분석","description":"이미지 이해를 비전 지원 모델에 위임하는 inspect_image 도구를 제어한다. \'auto\'는 활성 모델이 네이티브 이미지 입력을 지원하지 않을 때만 노출하고, \'on\'은 항상 노출하며, \'off\'는 노출하지 않는다."},"computer.enabled":{"label":"컴퓨터","description":"스크립트 가능한 호스트 데스크톱 제어 도구(스크린샷, 입력, 접근성)를 활성화한다"},"computer.display":{"label":"컴퓨터 디스플레이","description":"모든 디스플레이를 합성하거나 네이티브 display id를 선택한다"},"inspect_image.timeoutMs":{"label":"이미지 분석 타임아웃","description":"inspect_image 비전 모델 호출의 요청당 타임아웃이며 단위는 milliseconds이다. 응답이 멈춘 제공자는 수동 중단까지 차단되지 않고 타임아웃 오류로 빠르게 실패한다. 0으로 설정하면 타임아웃을 비활성화한다."},"checkpoint.enabled":{"label":"체크포인트/되돌리기","description":"컨텍스트 체크포인팅을 위한 checkpoint 및 rewind 도구를 활성화한다"},"fetch.enabled":{"label":"URL 읽기","description":"read 도구가 URL을 가져와 처리하도록 허용한다"},"vault.enabled":{"label":"Obsidian Vault","description":"Obsidian CLI를 통해 Obsidian vault 내용을 읽고 편집하는 vault:// 내부 URL을 활성화한다. 비활성화하면 vault:// 해석이 거부되고 시스템 프롬프트에서 vault:// 항목이 생략된다."},"github.enabled":{"label":"GitHub CLI","description":"github 도구(리포지터리, 이슈, pull request, diff, 검색, checkout, push, Actions watch 워크플로에 대한 op 기반 디스패치)를 활성화한다"},"github.cache.enabled":{"label":"GitHub 뷰 캐시","description":"렌더링된 이슈/PR 뷰 출력을 ~/.omp/cache/github-cache.db에 캐시해 반복 읽기 비용을 없앤다"},"web_search.enabled":{"label":"웹 검색","description":"실시간 웹 결과를 위한 web_search 도구를 활성화한다"},"security.enabled":{"label":"보안","description":"OMP 네이티브 보안 스캔 계획과 실행, 그리고 읽기 전용 security:// 리소스 네임스페이스를 활성화한다"},"ask.enabled":{"label":"Ask","description":"대화형 사용자 질문을 위한 ask 도구를 활성화한다"},"browser.enabled":{"label":"브라우저","description":"스크립트 기반 Chromium 자동화(puppeteer)를 위한 browser 도구를 활성화한다"},"browser.cdpUrl":{"label":"브라우저 CDP URL","description":"브라우저를 실행하는 대신 연결할 기본 HTTP CDP 디스커버리 엔드포인트이다(예: http://127.0.0.1:9222). 도구 호출에 명시된 app.cdp_url 또는 app.path가 우선한다."},"browser.relay":{"label":"브라우저 릴레이","description":"omp browser relay를 통해 사용자의 Chrome 탭을 제어한다. 확장 프로그램을 한 번 설치하면(`omp browser-relay install`) browser 도구가 필요할 때 릴레이 서버가 자동으로 시작된다. Browser CDP URL보다 우선하며, PI_BROWSER_RELAY=0 또는 PI_BROWSER_RELAY=1로 재정의한다."},"browser.relayUrl":{"label":"브라우저 릴레이 URL","description":"omp browser relay 엔드포인트이다(기본값 http://127.0.0.1:9224)."},"browser.headless":{"label":"헤드리스 브라우저","description":"브라우저를 headless 모드로 실행한다(비활성화하면 브라우저 UI를 표시한다)"},"browser.cmux":{"label":"cmux 브라우저","description":"cmux 소켓을 사용할 수 있을 때 브라우저 자동화에 cmux WKWebView 서피스를 사용한다. PI_BROWSER_CMUX=0 또는 PI_BROWSER_CMUX=1로 재정의한다."},"browser.screenshotDir":{"label":"스크린샷 디렉터리","description":"스크린샷을 저장할 디렉터리이다. 설정하지 않으면 스크린샷은 임시 파일로 저장된다. ~를 지원한다. 예: ~/Downloads, ~/Desktop, /sdcard/Download (Android)"},"tools.intentTracing":{"label":"인텐트 트레이싱","description":"각 도구 호출을 실행하기 전에 그 의도를 설명하도록 에이전트에 요청한다"},"tools.abortOnFabricatedResult":{"label":"조작된 도구 결과 시 중단","description":"in-band 도구 호출에서 모델이 턴 중간에 도구 결과를 환각하기 시작하면 즉시 중단한다. 비활성화하면 모델이 생성을 끝내도록 두고 조작된 이어쓰기를 폐기한다."},"tools.maxTimeout":{"label":"최대 도구 타임아웃","description":"에이전트가 임의의 도구에 설정할 수 있는 최대 타임아웃(초, 0 = 무제한)"},"async.enabled":{"label":"비동기 실행","description":"비동기 bash 명령과 백그라운드 작업 실행을 활성화한다"},"tools.xdev":{"label":"xd:// 도구","description":"드물게 쓰이는(탐색 가능한) 도구의 스키마를 매 요청마다 보내는 대신 read/write로 구동되는 xd:// 디바이스 URL 아래에 마운트한다. write 도구가 허용되지 않은 세션은 마운트를 건너뛰고 모든 도구를 최상위로 노출한다. 비활성화하면 활성화된 모든 도구를 최상위로 노출한다."},"tools.xdevDocs":{"label":"xd:// 프롬프트 문서","description":"시스템 프롬프트에 인라인으로 포함할 마운트된 디바이스 문서와 스키마를 선택한다. Built-ins는 핵심 도구를 인라인으로 유지하고 MCP 및 확장 도구는 on-demand로 남긴다."},"mcp.selection":{"label":"MCP 연결 선택","description":"all은 시작 시 기존 설정대로 연결한다. per-request는 JEV가 요청에 필요한 서버를 선택해 연결하며, 설치\xb7인증\xb7권한은 자동 승인하지 않는다. 변경 후 새 세션에서 적용된다."},"mcp.enableProjectConfig":{"label":"MCP 프로젝트 설정","description":"프로젝트 루트에서 .mcp.json/mcp.json을 로드한다"},"mcp.renderMarkdownResults":{"label":"MCP Markdown 결과","description":"JSON이 아닌 MCP 텍스트 결과를 트랜스크립트에서 Markdown으로 렌더링한다"},"mcp.notifications":{"label":"MCP 업데이트 주입","description":"MCP 리소스 업데이트를 에이전트 대화에 주입한다"},"tasks.todoClearDelay":{"label":"Todo 자동 정리 지연","description":"완료되거나 중단된 todo가 todo 위젯에서 제거되기까지의 지연 시간이다"},"dev.autoqa":{"label":"Auto QA","description":"자동 도구 이슈 보고(xd://report_issue)이다. 기본적으로 켜져 있으며, 첫 보고 시 동의를 요청하고 거부하면 명시적으로 다시 활성화할 때까지 보고를 비활성화한다"},"dev.autoqaPush.endpoint":{"label":"Auto QA 푸시 엔드포인트","description":"Auto QA JSON 보고를 수신하는 전체 URL이다(기본값 https://qa.omp.sh/v1/grievances)"},"plan.enabled":{"label":"Plan 모드","description":"실행 전 읽기 전용 탐색과 계획 수립을 위한 plan 모드를 활성화한다"},"plan.defaultOnStartup":{"label":"Plan 모드로 시작","description":"모든 새 세션 시작 시 자동으로 plan 모드로 진입한다"},"goal.enabled":{"label":"Goal 모드","description":"세션별 goal 모드와 숨겨진 goal 도구를 활성화한다"},"goal.statusInFooter":{"label":"푸터의 Goal 상태","description":"상태 표시줄에서 goal 표시기와 함께 토큰 예산을 표시한다"},"title.refreshOnReplan":{"label":"재계획 시 제목 갱신","description":"사용자가 제목을 설정한 경우가 아니면 todo init 재계획 이후 생성된 세션 제목을 갱신한다"},"task.isolation.mode":{"label":"격리 모드","description":"서브에이전트의 격리 백엔드이다. \\"auto\\"는 네이티브 PAL이 사용 가능한 최적 백엔드를 선택하게 한다(CoW를 지원하는 파일시스템, 그다음 overlayfs/ProjFS, 그다음 git worktree / 재귀 복사 폴백)."},"task.isolation.apply":{"label":"격리 변경 적용","description":"성공한 격리 작업의 변경을 부모 체크아웃에 자동으로 적용한다. 비활성화하면 patch 또는 branch 아티팩트를 유지한다"},"task.isolation.merge":{"label":"격리 병합 전략","description":"격리 작업의 변경을 통합하는 방식이다(patch apply 또는 branch merge)"},"task.isolation.commits":{"label":"격리 커밋 스타일","description":"중첩 저장소 변경의 커밋 메시지 스타일이다(generic 또는 AI 생성)"},"worktree.base":{"label":"Worktree 기본 디렉터리","description":"에이전트가 관리하는 worktree의 기본 디렉터리로, 작업 격리 사본, `github` PR 체크아웃, `omp worktree` 정리가 모두 여기에 위치한다. 설정하지 않으면 ~/.omp/wt를 사용한다. 절대 경로 또는 ~ 기준 경로여야 하며, 상대 경로는 무시된다. OMP_WORKTREE_DIR 환경 변수가 이 값을 재정의한다."},"task.eager":{"label":"작업 위임 선호도","description":"서브에이전트에 작업을 위임하도록 얼마나 강하게 유도할지를 정한다"},"task.batch":{"label":"작업 호출 배치","description":"task 도구를 배치 형태로 전환한다: 한 번의 호출이 { context, tasks[] }를 전달하며, 항목당 서브에이전트 하나가 실행되고, 항목별 agent(기본값은 세션 spawn-policy 에이전트)와 항목별 격리를 지정할 수 있으며, 공유 context는 모든 assignment 앞에 필수로 붙는다. async.enabled=true인 경우 각 spawn은 일반적인 idle/parked 수명 주기를 갖는 독립 백그라운드 에이전트로 실행되고, 그렇지 않으면 호출은 병합된 결과를 기다리며 블로킹된다. 비활성화하면 평면적인 단일 spawn 스키마로 되돌아간다."},"task.enableEffort":{"label":"작업별 effort","description":"task spawn에서 선택적 effort 파라미터를 노출해, 호출자가 각 서브에이전트의 thinking 레벨을 재정의할 수 있게 한다"},"task.maxConcurrency":{"label":"최대 동시 작업 수","description":"동시에 실행되는 서브에이전트의 최대 개수이다"},"task.enableLsp":{"label":"서브에이전트 LSP","description":"task 도구로 생성된 서브에이전트가 lsp 도구를 사용할 수 있게 한다. 서브에이전트 비용을 낮게 유지하기 위해 기본적으로 꺼져 있으며, LSP를 활용한 위임이 추가 토큰만큼 가치가 있을 때 활성화한다."},"task.maxRecursionDepth":{"label":"최대 작업 재귀 깊이","description":"서브에이전트가 자신의 서브에이전트를 생성할 수 있는 최대 깊이이다"},"task.maxRuntimeMs":{"label":"서브에이전트 최대 실행 시간","description":"서브에이전트당 절대 실행 시간 제한(ms)이다. 0이면 비활성화된다. 추론 계층 워치독을 빠져나가는 프로바이더 측 스트림 정지에 대한 심층 방어 수단이며, \'timed out\' 사유로 일반적인 서브에이전트 중단을 발생시킨다."},"task.softRequestBudget":{"label":"서브에이전트 소프트 요청 예산","description":"서브에이전트당 소프트 요청 예산(실행당 assistant 요청 수)이다. 이를 초과하면 마무리를 유도하는 steering 알림이 주입되며(task.softRequestBudgetNotice 참고), 예산의 1.5배에 도달하면 실행이 강제 중단되고 에이전트는 부분 결과를 내놓아야 한다. 0이면 이 보호 장치가 비활성화된다. 번들된 scout/sonic 에이전트는 더 낮은 내장 예산이 상한이므로, 그 상한보다 낮은 값은 이들에게도 적용된다."},"task.softRequestBudgetNotice":{"label":"소프트 요청 예산 알림","description":"서브에이전트가 소프트 요청 예산을 초과할 때 steering 알림을 한 번 주입해, 1.5배 강제 중단 전에 마무리하도록 요청한다."},"task.maxEffort":{"label":"spawn당 최대 effort","description":"task 도구의 spawn별 effort 힌트에 허용되는 최대 추론 effort이다. 값을 낮추면 호출자가 서브에이전트를 이 상한 이상으로 올릴 수 없으며, 기본값은 모델의 전체 범위를 유지한다."},"task.prewalk":{"label":"일반 작업 prewalk","description":"번들된 일반 `task` 서브에이전트에 prewalk를 적용한다: 해석된 모델로 시작해 계획을 세우고 구현을 시작한 뒤, 첫 편집/쓰기 시점에 \'smol\' 역할로 넘긴다. 에이전트별 재정의(/agents 허브에서 설정하는 task.agentPrewalk)와 사용자 에이전트의 `prewalk` frontmatter는 이 토글과 무관하게 적용된다."},"skills.enableSkillCommands":{"label":"스킬 명령","description":"스킬을 /skill:name 명령으로 등록한다"},"commands.enableClaudeUser":{"label":"Claude 사용자 명령","description":"~/.claude/commands/에서 명령을 로드한다"},"commands.enableClaudeProject":{"label":"Claude 프로젝트 명령","description":".claude/commands/에서 명령을 로드한다"},"commands.enableOpencodeUser":{"label":"OpenCode 사용자 명령","description":"~/.config/opencode/commands/에서 명령을 로드한다"},"commands.enableOpencodeProject":{"label":"OpenCode 프로젝트 명령","description":".opencode/commands/에서 명령을 로드한다"},"providers.maxInFlightRequests":{"label":"최대 동시 요청 수","description":"프로바이더 id별(예: \\"openai\\" 또는 \\"anthropic\\") 최대 동시 LLM 요청 수로, 같은 config root를 쓰는 로컬 OMP 프로세스 간에 공유된다. 명시되지 않은 프로바이더는 제한이 없다."},"secrets.enabled":{"label":"시크릿 숨김","description":"AI 프로바이더로 전송하기 전에 설정된 시크릿을 난독화하고 자격 증명 형태의 토큰을 마스킹한다"},"providers.webSearchOrder":{"label":"웹 검색 프로바이더 순서","description":"web_search 도구에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 그 뒤에 기본 순서를 유지한다"},"providers.webSearchExclude":{"label":"제외할 웹 검색 프로바이더","description":"web_search가 폴백으로도 절대 사용하지 않을 프로바이더이다"},"providers.webSearchTimeoutSeconds":{"label":"웹 검색 타임아웃","description":"web_search가 다음 폴백으로 넘어가기 전 각 프로바이더 검색 전송에 적용되는 절대 타임아웃이며 단위는 초이다(최대 300)"},"providers.webSearchGeminiModel":{"label":"Gemini web_search 모델","description":"Gemini Google Search grounding에 사용할 모델 ID이다. 기본값은 gemini-2.5-flash이다."},"providers.antigravityEndpoint":{"label":"Antigravity 엔드포인트 모드","description":"google-antigravity 프로바이더의 엔드포인트 라우팅 전략이다(chat, search, image, discovery)"},"providers.imageOrder":{"label":"이미지 프로바이더 순서","description":"이미지 생성에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 활성 세션 프로바이더와 내장 순서를 따른다"},"providers.fireworksTier":{"label":"Fireworks 티어","description":"Fireworks 요청의 서빙 경로이다. Priority는 `service_tier: \\"priority\\"`를 전송해 트래픽이 몰릴 때 더 높은 신뢰성을 더 높은 가격에 제공하고, Standard는 이를 생략한다. Fast(`-fast`) 모델은 이 설정을 무시하며, Fast는 별도의 서빙 경로이다."},"live.voice":{"label":"Live 음성","description":"Codex 기반 realtime 음성 세션에서 사용하는 음성이다"},"providers.tts":{"label":"TTS 제공자","description":"tts 도구의 백엔드이다: 로컬 온디바이스 신경망 TTS(Kokoro-82M) 또는 xAI Grok Voice 중 하나이다"},"tts.localModel":{"label":"로컬 TTS 모델","description":"로컬 TTS 백엔드가 사용하는 온디바이스 신경망 TTS 모델(Kokoro-82M)이다"},"tts.localVoice":{"label":"로컬 TTS 음성","description":"로컬 TTS 백엔드가 사용하는 Kokoro 음성이다(미국/영국, 여성/남성)"},"speech.enabled":{"label":"음성 출력","description":"어시스턴트의 출력을 스트리밍되는 대로 스피커로 소리내어 읽는다"},"speech.mode":{"label":"음성 출력 모드","description":"읽을 대상이다: all = 어시스턴트 메시지 + 사고 과정, assistant = 메시지만, yield = 턴 종료 시 마지막 메시지만이다"},"speech.enhanced":{"label":"향상된 음성 재작성","description":"합성 전에 tiny/smol 모델로 어시스턴트 출력을 자연스러운 구어체 산문으로 재작성한다(코드는 설명으로 바꾸고 링크와 markdown은 제거한다). 실패하면 기계적 정리로 대체된다"},"speech.voice":{"label":"음성 출력 목소리","description":"어시스턴트의 출력을 소리내어 읽을 때 사용하는 Kokoro 음성이다"},"providers.tinyModel":{"label":"Tiny 모델","description":"세션 제목 생성 모델이다: 기본값은 온라인(/models의 TINY 역할, 없으면 @smol)이며, 로컬 온디바이스 모델도 가능하다"},"providers.tinyModelDevice":{"label":"Tiny 모델 디바이스","description":"로컬 tiny 모델(제목 + 메모리)에 사용하는 ONNX 실행 제공자이다. 기본값은 CPU 전용 추론을 사용한다. PI_TINY_DEVICE 환경 변수가 이 값을 덮어쓴다."},"providers.tinyModelDtype":{"label":"Tiny 모델 정밀도","description":"로컬 tiny 모델의 ONNX 양자화/정밀도이다. 기본값은 각 모델에 포함된 dtype(q4)을 사용하며, 정밀도가 낮으면 더 빠르고 높으면 원본에 더 충실하다. PI_TINY_DTYPE 환경 변수가 이 값을 덮어쓴다."},"providers.unexpectedStopModel":{"label":"예기치 않은 중단 모델","description":"예기치 않은 중단 감지용 분류기이다: 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 가능하다."},"providers.kimiApiFormat":{"label":"Kimi API 형식","description":"Kimi Code 제공자의 API 형식이다(auto는 라이브 모델 메타데이터를 따른다)"},"providers.openaiWebsockets":{"label":"OpenAI WebSockets","description":"OpenAI Codex 모델의 websocket 정책이다(auto는 모델 기본값을 사용하고, on은 강제하며, off는 비활성화한다)"},"providers.streamFirstEventTimeoutSeconds":{"label":"스트림 첫 이벤트 타임아웃","description":"모델 스트림의 첫 이벤트를 기다리는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.streamIdleTimeoutSeconds":{"label":"스트림 유휴 타임아웃","description":"모델 스트림이 이벤트 사이에 무응답 상태로 있을 수 있는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.openrouterVariant":{"label":"OpenRouter 라우팅","description":"OpenRouter 모델 ID에 덧붙이는 기본 라우팅 variant 접미사이다(선택기에서 이미 variant를 지정한 경우 무시된다)"},"providers.fetch":{"label":"Fetch 제공자","description":"fetch/read URL 도구의 리더 백엔드 우선순위이다"},"codexResets.autoRedeem":{"label":"Codex 리셋 자동 사용","description":"저장된 Codex rate-limit 리셋을 자동으로 사용한다: 턴이 멈추고 다른 계정이 대체할 수 없을 때 5h 또는 weekly 창을 소진해 차단된 계정을 복구하고, 곧 만료될 크레딧을 회수한다. unset은 첫 사용 전에 확인하고, yes는 확인 없이 사용하며, no는 두 검사 모두 비활성화한다."},"provider.appendOnlyContext":{"label":"추가 전용 컨텍스트","description":"시스템 프롬프트 + 도구 명세를 캐시하고 추가 전용 메시지 로그를 유지해 provider prefix 캐시(DeepSeek, Xiaomi/SGLang, Anthropic) 적중률을 최대화한다. auto는 prefix 캐시가 알려진 제공자에 대해 활성화한다."},"exa.enabled":{"label":"Exa","description":"Exa 웹 검색 제공자를 활성화한다"},"searxng.endpoint":{"label":"SearXNG 엔드포인트","description":"웹 검색에 사용하는 자체 호스팅 SearXNG 인스턴스의 기본 URL이다"}}}'),fp=[{id:"models",label:"Models & accounts",icon:"model"},{id:"themes",label:"Themes",icon:"theme"},{id:"skills",label:"Skills",icon:"skill",requiresCwd:!0},{id:"plugins",label:"Plugins",icon:"plugin",requiresCwd:!0},{id:"mcp",label:"MCP",icon:"mcp"},{id:"access",label:"Access",icon:"access"},{id:"trust",label:"Project trust",labelKey:"trust.settingsNav",icon:"trust"},{id:"live-voice",label:"Call voice",labelKey:"chat.liveVoiceSettingsNav",icon:"liveVoice"},{id:"attachments",label:"Attachments",labelKey:"chat.attachmentSettingsNav",icon:"attachments"},{id:"characters",label:"Characters",labelKey:"characterMode.nav",icon:"characters"}],fh={model:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,n.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,n.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,n.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,n.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,n.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,n.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,n.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,n.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),characters:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,n.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}),attachments:(0,n.jsx)("path",{d:"m21 12-8.6 8.6a5 5 0 0 1-7-7l8.5-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9"}),appearance:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,n.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,n.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,n.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,n.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function fm({kind:e}){return(0,n.jsx)("svg",{className:m0().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:fh[e]??fh.tools})}function ff({field:e,busy:t,onSave:r}){let[i,s]=(0,a.useState)("secret"===e.type?"":String(e.value??""));(0,a.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let o="secret"===e.type?"":String(e.value??"");return(0,n.jsx)("input",{className:m0().textInput,type:"secret"===e.type?"password":"text",value:i,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{i!==o&&("secret"!==e.type||i.length>0)&&r(i)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function fg({field:e,busy:t,onSave:r}){let i=JSON.stringify(e.value??{},null,2),[s,o]=(0,a.useState)(i),[l,c]=(0,a.useState)(null);return(0,a.useEffect)(()=>{o(i),c(null)},[i]),(0,n.jsxs)("div",{style:{width:"100%"},children:[(0,n.jsx)("textarea",{className:m0().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>o(e.target.value),onBlur:()=>{if(s!==i)try{r(JSON.parse(s)),c(null)}catch(e){c(e instanceof Error?e.message:String(e))}}}),l&&(0,n.jsx)("div",{className:m0().error,children:l})]})}function fx({field:e,busy:t,onSave:r}){let a=Array.isArray(e.value)?e.value:[],i=(e,t)=>{let n=e+t;if(n<0||n>=a.length)return;let i=[...a];[i[e],i[n]]=[i[n],i[e]],r(i)};return(0,n.jsx)("div",{className:m0().multiSelect,children:e.options?.map(s=>{let o=a.indexOf(s.value);return(0,n.jsxs)("span",{className:m0().choice,"data-selected":o>=0,title:s.description,children:[(0,n.jsx)("button",{type:"button",className:m0().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,r(a.includes(e)?a.filter(t=>t!==e):[...a,e])},children:s.label}),e.ordered&&o>=0&&(0,n.jsxs)("span",{className:m0().reorder,children:[(0,n.jsx)("button",{type:"button",disabled:t||0===o,onClick:()=>i(o,-1),children:"←"}),(0,n.jsx)("button",{type:"button",disabled:t||o===a.length-1,onClick:()=>i(o,1),children:"→"})]})]},s.value)})})}function fv({field:e,busy:t,onSave:r}){return"boolean"===e.type?(0,n.jsx)("button",{type:"button",className:m0().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>r(!0!==e.value)}):"select"===e.type?(0,n.jsx)(hL,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>r("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,n.jsx)(fx,{field:e,busy:t,onSave:r}):"providerLimits"===e.type?(0,n.jsx)(fg,{field:e,busy:t,onSave:r}):(0,n.jsx)(ff,{field:e,busy:t,onSave:r})}function fb({field:e,busy:t,error:r,onSave:a}){return(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:m0().settingLabel,children:e.label}),(0,n.jsx)("div",{className:m0().settingDescription,children:e.description}),r&&(0,n.jsx)("div",{className:m0().error,children:r})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)(fv,{field:e,busy:t,onSave:a})})]})}function fy({mode:e,palette:t}){let r=t.variables["--omp-md-heading"];return(0,n.jsxs)("div",{className:m0().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,n.jsx)("div",{className:m0().themePreviewBar,style:r?{background:r}:void 0}),(0,n.jsxs)("div",{className:m0().themePreviewPanel,children:[(0,n.jsx)("div",{className:m0().themePreviewLine}),(0,n.jsx)("div",{className:m0().themePreviewLine})]})]})}let fw='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',fk=new Set(["hideThinkingBlock"]);function fj({cwd:e,sessionId:t,initialSection:r="models",onClose:i,onModelsChanged:s,onReloaded:o}){let[l,c]=(0,a.useState)(r),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)(!0),[m,f]=(0,a.useState)(null),[g,x]=(0,a.useState)(""),[v,b]=(0,a.useState)(new Set),[y,w]=(0,a.useState)({}),[k,j]=(0,a.useState)(!1),[S,C]=(0,a.useState)(!1),{theme:N,setPreference:T}=rh(),I={enabled:(0,a.useSyncExternalStore)(fd,fo,()=>!1),setEnabled:fl},{locale:M,t:E}=(0,z.s)(),$=(0,a.useRef)(null),R=e=>"ko"===M?fu.shell[e]??e:e,L=(0,a.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/settings${t}`,{cache:"no-store"}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);u(n)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,a.useEffect)(()=>{L()},[L]),(0,a.useEffect)(()=>{let e=$.current;if(!e)return;(Array.from(e.querySelectorAll(fw)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll(fw)).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let a=r[0],i=r[r.length-1];t.shiftKey&&(n===a||!e.contains(n))?(t.preventDefault(),i.focus()):t.shiftKey||n!==i&&e.contains(n)||(t.preventDefault(),a.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let A=(0,a.useCallback)(async(t,r)=>{b(e=>new Set(e).add(t.path)),w(e=>{let r={...e};return delete r[t.path],r});try{let n=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:r})}),a=await n.json();if(!n.ok||a.error)throw Error(a.error??`HTTP ${n.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:a.value??r,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await rp(e),await L()):fk.has(t.path)?await rY(e):j(!0)}catch(e){w(r=>({...r,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let r=new Set(e);return r.delete(t.path),r})}},[e,L]),P=(0,a.useMemo)(()=>new Map(d?.fields.map(e=>[e.path,e.value])??[]),[d?.fields]),F=(0,a.useMemo)(()=>d?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,P))??[],[d?.fields,P]),_=l.startsWith("settings:")?l.slice(9):null,W=(0,a.useMemo)(()=>{let e=g.trim().toLowerCase();return e?F.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):_?F.filter(e=>e.tab===_&&("appearance"!==_||"Theme"!==e.group)):[]},[_,g,F]),O=(0,a.useCallback)(()=>{s?.(),i()},[i,s]),D=(0,a.useCallback)(async()=>{if(t){C(!0);try{await uV(t,{type:"reload"}),j(!1),o?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[o,t]),H=d?.tabs.find(e=>e.id===_),U=g.trim()?`${R("Search")} \xb7 ${W.length}`:H?.label??R("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let r=e.filter(e=>(e.group??"General")===t);return r.length?(0,n.jsxs)("section",{className:m0().group,children:[(0,n.jsx)("h3",{className:m0().groupTitle,children:t}),r.map(e=>(0,n.jsx)(fb,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void A(e,t)},e.path))]},t):null}),q=()=>p?(0,n.jsx)("div",{className:m0().empty,children:R("Loading omp settings…")}):m||!d?(0,n.jsx)("div",{className:m0().empty,children:m??R("Settings unavailable")}):(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:U}),(0,n.jsx)("p",{className:m0().contentDescription,children:R(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,n.jsxs)("div",{className:m0().reloadNotice,children:[(0,n.jsx)("span",{children:R("Saved. Reload the active session to apply runtime settings.")}),(0,n.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:R(S?"Reloading…":"Reload session")})]})]}),(0,n.jsx)("div",{className:m0().settingsBody,children:W.length?B(W,H?.groups??[]):(0,n.jsx)("div",{className:m0().empty,children:R("No settings match this search.")})})]});return(0,n.jsx)("div",{className:m0().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&O()},children:(0,n.jsxs)("div",{ref:$,tabIndex:-1,className:m0().window,role:"dialog","aria-modal":"true","aria-label":R("Settings"),children:[(0,n.jsxs)("aside",{className:m0().sidebar,children:[(0,n.jsxs)("div",{className:m0().brand,children:[(0,n.jsx)("div",{className:m0().eyebrow,children:"omp /settings"}),(0,n.jsx)("h1",{className:m0().title,children:R("Settings")}),(0,n.jsx)("code",{className:m0().context,title:e??R("Global configuration"),children:e??R("Global configuration")})]}),(0,n.jsxs)("div",{className:m0().searchWrap,children:[(0,n.jsxs)("svg",{className:m0().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-4-4"})]}),(0,n.jsx)("input",{className:m0().search,value:g,"aria-label":R("Search /settings"),placeholder:R("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,n.jsxs)("nav",{className:m0().nav,children:[(0,n.jsx)("div",{className:m0().navLabel,children:R("Configuration")}),fp.map(t=>{let r=t.labelKey?E(t.labelKey):R(t.label);return(0,n.jsxs)("button",{type:"button",className:m0().navButton,"data-active":!g&&l===t.id,"aria-current":g||l!==t.id?void 0:"page",disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${r} ${R("requires a project")}`:r,onClick:()=>{x(""),c(t.id)},children:[(0,n.jsx)(fm,{kind:t.icon}),(0,n.jsx)("span",{children:r})]},t.id)}),(0,n.jsx)("div",{className:m0().navLabel,children:R("OMP settings")}),d?.tabs.map(e=>(0,n.jsxs)("button",{type:"button",className:m0().navButton,"data-active":!g&&_===e.id,"aria-current":g||_!==e.id?void 0:"page",onClick:()=>{x(""),c(`settings:${e.id}`)},children:[(0,n.jsx)(fm,{kind:e.id}),(0,n.jsx)("span",{children:e.label})]},e.id))]}),(0,n.jsx)("div",{className:m0().closeRail,children:(0,n.jsxs)("button",{type:"button",className:m0().closeButton,onClick:O,children:[(0,n.jsx)("span",{children:R("Close settings")}),(0,n.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,n.jsx)("main",{className:m0().content,children:g.trim()?q():"models"===l?(0,n.jsx)(mM,{cwd:e,embedded:!0,onClose:O,onModelsChanged:s}):"themes"===l?d?(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:R("Themes")}),(0,n.jsxs)("p",{className:m0().contentDescription,children:[R("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,n.jsx)("code",{children:"~/.omp/agent/config.yml"}),R(" and applied here immediately.")]})]}),(0,n.jsxs)("div",{className:m0().settingsBody,children:[(0,n.jsx)("div",{className:m0().themeGrid,children:["dark","light"].map(e=>{let t=d.fields.find(t=>t.path===`theme.${e}`),r=d.theme.palettes[e];return(0,n.jsxs)("div",{className:m0().themeCard,children:[(0,n.jsx)(fy,{mode:e,palette:r}),(0,n.jsxs)("div",{className:m0().themeCardBody,children:[(0,n.jsxs)("div",{className:m0().themeCardHeader,children:[(0,n.jsxs)("span",{className:m0().themeSlot,children:[e,R(" mapping")]}),N===e&&(0,n.jsx)("span",{className:m0().themeActive,children:R("Active on web")})]}),(0,n.jsx)(hL,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void A(t,e)}),N!==e&&(0,n.jsxs)("button",{type:"button",className:m0().closeButton,style:{marginTop:8},onClick:()=>T(e),children:[R("Preview "),e]})]})]},e)})}),(0,n.jsx)("section",{className:m0().group,children:(0,n.jsxs)("div",{className:m0().settingRow,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{id:"settings-graphite-label",className:m0().settingLabel,children:E("theme.graphite")}),(0,n.jsx)("div",{className:m0().settingDescription,children:E("theme.graphiteHint")})]}),(0,n.jsx)("div",{className:m0().settingControl,children:(0,n.jsx)("button",{type:"button",role:"switch",className:m0().switch,"data-on":I.enabled,"aria-checked":I.enabled,"aria-labelledby":"settings-graphite-label",onClick:()=>I.setEnabled(!I.enabled)})})]})}),B(d.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,n.jsx)("div",{className:m0().empty,children:p?R("Loading themes…"):m??R("Themes unavailable")}):"skills"===l&&e?(0,n.jsx)(mz,{cwd:e,embedded:!0,onClose:O}):"plugins"===l&&e?(0,n.jsx)(mX,{cwd:e,sessionId:t,embedded:!0,onClose:O,onReloaded:o}):"mcp"===l?(0,n.jsx)(fS,{cwd:e,sessionId:t,onReloaded:o}):"access"===l?(0,n.jsx)(m1,{}):"trust"===l?(0,n.jsx)(m6,{cwd:e}):"live-voice"===l?(0,n.jsx)(m8,{}):"attachments"===l?(0,n.jsx)(m4,{}):"characters"===l?(0,n.jsx)(m5,{}):q()})]})})}function fS({cwd:e,sessionId:t,onReloaded:r}){let[i,s]=(0,a.useState)(null),[o,l]=(0,a.useState)("user"),[c,d]=(0,a.useState)(0),[u,p]=(0,a.useState)(""),[h,m]=(0,a.useState)(""),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(!1),[b,y]=(0,a.useState)(null),w=(0,a.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/mcp${t}`,{cache:"no-store"}),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);s(n),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,a.useEffect)(()=>{w()},[w]);let k=i?"user"===o?i.user:i.project:null,j=k?.servers[c]??null;(0,a.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(t=>{if(!t)return t;let r={..."user"===o?t.user:t.project,servers:e};return"user"===o?{...t,user:r}:{...t,project:r}})},C=async()=>{if(k){v(!0),g(null);try{let t,r=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===c?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),n=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,servers:r})}),i=await a.json();if(!a.ok||i.error)throw Error(i.error??`HTTP ${a.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async n=>{y(`${o}:${n.name}`),g(null);try{let a=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${a}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,name:n.name,enabled:!n.enabled})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await w(),t&&(await uV(t,{type:"reload"}),r?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,n.jsxs)("div",{className:m0().scrollContent,children:[(0,n.jsxs)("header",{className:m0().contentHeader,children:[(0,n.jsx)("h2",{className:m0().contentTitle,children:"MCP servers"}),(0,n.jsx)("p",{className:m0().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,n.jsx)("div",{className:m0().settingsBody,children:i?(0,n.jsxs)("div",{className:m0().mcpLayout,children:[(0,n.jsxs)("aside",{className:m0().mcpList,children:[(0,n.jsxs)("div",{className:m0().scopeTabs,children:[(0,n.jsxs)("button",{type:"button",className:m0().scopeButton,"data-active":"user"===o,onClick:()=>{l("user"),d(0)},children:["User \xb7 ",i.user.servers.length]}),(0,n.jsxs)("button",{type:"button",className:m0().scopeButton,"data-active":"project"===o,disabled:!i.project,onClick:()=>{l("project"),d(0)},children:["Project \xb7 ",i.project?.servers.length??0]})]}),k?.error?(0,n.jsx)("div",{className:m0().error,style:{padding:12},children:k.error}):(0,n.jsx)("div",{className:m0().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let r=`${o}:${e.name}`;return(0,n.jsxs)("div",{className:m0().serverRow,"data-active":c===t,children:[(0,n.jsxs)("button",{type:"button",className:m0().serverSelect,title:e.source?.path,onClick:()=>d(t),children:[(0,n.jsx)("span",{className:m0().statusDot,"data-off":!e.enabled}),(0,n.jsx)("span",{className:m0().serverName,children:e.name}),!1===e.editable&&(0,n.jsx)("span",{className:m0().sourceBadge,children:e.source?.provider??"external"})]}),(0,n.jsx)("button",{type:"button",className:m0().serverToggle,"data-on":e.enabled,disabled:b===r,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===r?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,n.jsx)("div",{className:m0().serverListEmpty,children:"No servers in this scope."})}),(0,n.jsx)("button",{type:"button",className:m0().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let r=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(r),d(r.length-1)},children:"+ Add OMP server"})]}),(0,n.jsx)("section",{className:m0().mcpEditor,children:j?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:m0().editorHeader,children:[(0,n.jsx)("input",{className:m0().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,n.jsx)("button",{type:"button",className:m0().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==c)),d(Math.max(0,c-1)))},children:"Delete"})]}),!1===j.editable&&(0,n.jsxs)("div",{className:m0().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,n.jsx)("textarea",{className:m0().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,n.jsxs)("div",{className:m0().editorActions,children:[(0,n.jsxs)("div",{children:[f&&(0,n.jsx)("div",{className:m0().error,children:f}),(0,n.jsx)("div",{className:m0().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,n.jsx)("button",{type:"button",className:m0().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,n.jsx)("div",{className:m0().empty,children:"Add or select an MCP server."})})]}):(0,n.jsx)("div",{className:m0().empty,children:f??"Loading MCP configuration…"})})]})}let fC="cuelo-notification-prompt-dismissed";function fN({variant:e,locale:t,permission:r,dismissed:a,request:i,dismiss:s}){let o="ko"===t;return null===r||"granted"===r?null:"banner"===e?"default"!==r||a?null:(0,n.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":o?"알림 권한 안내":"Notification permission",children:[(0,n.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:o?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:i,children:o?"알림 켜기":"Enable notifications"}),(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":o?"알림 권한 안내 닫기":"Dismiss notification prompt",children:o?"닫기":"Dismiss"})]}):(0,n.jsx)(c.k.Item,{disabled:"denied"===r,onClick:"default"===r?i:void 0,children:(0,n.jsxs)(c.k.ItemBody,{children:[(0,n.jsx)(c.k.ItemLabel,{children:"default"===r?o?"알림 켜기":"Enable notifications":o?"알림 차단됨":"Notifications blocked"}),"denied"===r&&(0,n.jsx)(c.k.ItemDescription,{children:o?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function fT({cwd:e,busy:t,scheduled:r,error:i,onCancel:s,onConfirm:o,onCancelSchedule:l}){let{t:c}=(0,z.s)(),d=(0,a.useRef)(null);(0,a.useEffect)(()=>{d.current?.focus()},[r]);let u={height:32,padding:"0 12px",borderRadius:"var(--radius-control)",cursor:t?"not-allowed":"pointer",fontSize:12};return(0,n.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||s()},children:(0,n.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,n.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,n.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),r?(0,n.jsx)("path",{d:"M12 8v4l2 2"}):(0,n.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:c(r?"trust.scheduledTitle":"trust.dialogTitle")}),(0,n.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:c(r?"trust.scheduledBody":"trust.dialogBody")}),(0,n.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),i&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:i})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[r&&(0,n.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c("trust.cancelSchedule")}),(0,n.jsx)("button",{ref:d,type:"button",onClick:s,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c(r?"trust.close":"trust.cancel")}),!r&&(0,n.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:c(t?"trust.trusting":"trust.trustProject")})]})]})})}var fI=r(55681);let fM={kind:"loading"};function fE(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":s8(e.status)?"var(--accent)":"var(--success)"}function f$(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let fR={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function fL(e){return e.lastUpdate||e.progress?.durationMs||0}let fA=(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})}),fP=[];function fF({state:e,summary:t,reason:r,onOpenFile:a}){let{st:i}=ag(),{t:s}=(0,z.s)(),o="ready-archive"===e.kind||"empty"===e.kind&&"archive"===e.source;if(!t&&!o)return null;let l=t?.files??[],c=t?.checks??[];return(0,n.jsxs)("div",{className:"maker-detail-outcome",children:[r&&(0,n.jsxs)("p",{className:"maker-detail-reason",children:[(0,n.jsx)("span",{children:i("detail.reason")})," ",r]}),(0,n.jsxs)("section",{children:[(0,n.jsx)("h3",{className:"maker-detail-heading",children:i("summary.heading.files")}),o?(0,n.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):l.length>0?(0,n.jsx)(aI,{files:l,onOpenFile:a}):(0,n.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noFiles")})]}),(0,n.jsxs)("section",{children:[(0,n.jsx)("h3",{className:"maker-detail-heading",children:i("summary.heading.checks")}),o?(0,n.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):c.length>0?(0,n.jsx)("ul",{className:"answer-summary-list",children:c.map(e=>(0,n.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,n.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,n.jsxs)("span",{className:"answer-check-result",children:[s(f_[e.state]),null!==e.exitCode?` \xb7 ${i("summary.check.exit",{code:e.exitCode})}`:null]})]},e.toolCallId))}):(0,n.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noChecks")})]})]})}let f_={passed:"makerDetail.checkPassed",unverified:"makerDetail.checkUnverified",failed:"makerDetail.checkFailed",unobserved:"makerDetail.checkUnobserved"};function fz({sessionId:e,sessionCwd:t,record:r,selection:i,client:s,visible:o,onBack:l,onOpenFile:c}){let{st:d}=ag(),{t:u}=(0,z.s)(),p=r?.key,h=r?.live?.id,m=r?.live?.status,f=r?.archive?.name,g=(0,a.useMemo)(()=>p?[{key:p,liveId:h,status:m,archiveName:f}]:[],[p,h,m,f]),x=(0,a.useRef)(null),v=(0,a.useRef)(null),b=s3(g,{sessionId:e,client:s,enabled:o&&g.length>0}),y=(p?b.get(p)?.state:void 0)??fM;(0,a.useEffect)(()=>{o&&v.current?.focus({preventScroll:!0})},[i.key,o]),(0,a.useEffect)(()=>{if(!o||"ready-live"!==y.kind&&"ready-archive"!==y.kind)return;let e=requestAnimationFrame(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[y,o]);let w="ready-live"===y.kind?y.entries:fP,k=(0,a.useMemo)(()=>{let e=new Map;for(let t of w)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[w]),j=(0,a.useMemo)(()=>"ready-live"===y.kind?oL(y.entries,t):null,[y,t]),S=r?.live?.id||r?.archive?.name||"Subagent",C=r?a$(r).title:S,N=i.status;return(0,n.jsxs)("div",{role:"region","aria-label":u("makerDetail.region",{title:S}),style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,n.jsx)(p6,{back:{label:u("subagents.back"),onClick:l},title:C,titleTooltip:r?`${C}
|
|
70
|
+
${S} \xb7 ${f$(r)}`:void 0,titleRef:v,subtitle:r?`${S} \xb7 ${f$(r)}`:void 0,state:N?(0,n.jsx)(oR,{maker:N,st:d}):r?.live&&(0,n.jsx)("span",{style:{color:fE(r.live),fontFamily:"var(--font-mono)",fontSize:11},children:r.live.status})}),!r&&(0,n.jsx)("div",{role:"status",className:"maker-detail-empty",style:{padding:24,textAlign:"center"},children:u("makerDetail.unavailable")}),r&&(0,n.jsx)(fF,{state:y,summary:j,reason:N?.verdict?.reason??null,onOpenFile:c}),r&&(0,n.jsxs)("div",{ref:x,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===y.kind&&(0,n.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===y.kind&&y.entries.flatMap((e,r)=>{if(!("message"in e))return[];let a=y.entries[r-1];return[(0,n.jsx)(lL,{message:e.message,toolResults:k,cwd:t,showTimestamp:!0,prevTimestamp:a&&"message"in a?a.message.timestamp:void 0},e.id)]}),"ready-archive"===y.kind&&(0,n.jsxs)(n.Fragment,{children:[y.note&&(0,n.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:y.note}),y.truncated&&(0,n.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),y.entries.map((e,t)=>(0,n.jsxs)("div",{style:{margin:"0 0 7px",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:11,lineHeight:1.55},children:[(0,n.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===y.kind&&(0,n.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[y.note&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:y.note}),(0,n.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===y.kind&&(0,n.jsx)("div",{role:"status",style:{padding:10,border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:y.message}),"error"===y.kind&&(0,n.jsx)("div",{role:"alert",style:{padding:10,border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5},children:y.message})]})]})}function fW({record:e,view:t,onSelect:r}){let i,s,o,{st:l}=ag(),c=(0,a.useId)(),d=e.live,u=e.archive,p=a$(e),h=!!(d&&s8(d.status)),m=h?p.stage:null,f=h&&t?t:null,g=f?.phase?l("phase.current",{phase:l(`phase.${f.phase}`)}):"",x=f?.todo?oI(l,f.todo):"",v=d?.id||u?.name||"Subagent",b=f$(e),y=(i=e.live,(o=(s=(i?.agent||i?.progress?.agent||"").trim()).toLowerCase().split(/[-_.:/\s]+/).filter(Boolean).join(" "))?{kind:"known",agent:s,source:i?.agentSource??"bundled",label:o}:{kind:"unknown"}),w=aR(e),k=w.modelShort??"모델 미확인",j=w.effort??"추론 미확인",S="known"===y.kind?y.label:"역할 미확인";return(0,n.jsx)("div",{role:"listitem",children:(0,n.jsxs)("button",{type:"button",onClick:r,"data-identity":e.identity,"data-subagent-key":e.key,title:`${v}
|
|
71
|
+
${w.model??"모델 미확인"} \xb7 ${j}
|
|
72
|
+
${p.title}${m?`
|
|
73
|
+
현재 단계: ${m}`:""}${g?`
|
|
74
|
+
${g}`:""}${x?`
|
|
75
|
+
${x}`:""}`,"aria-label":`${S} ${v}, 업무 ${p.title}${m?`, 현재 단계 ${m}`:""}${g?`, ${g}`:""}${x?`, ${x}`:""}, ${d?d.status:u?.status??"미확인"}, 모델 ${w.model??"미확인"}, 추론 ${j}`,"aria-describedby":f&&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,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===y.kind?(0,n.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":y.agent,title:`${y.agent} \xb7 ${fR[y.source]}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"역할 "}),y.label]}):(0,n.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,n.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:p.title})]}),d?(0,n.jsx)("span",{style:{color:fE(d),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:d.status}):u?(0,n.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,n.jsx)("span",{"aria-hidden":"true"}),m&&(0,n.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${m}`,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,n.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",m]}),f?.phase&&(0,n.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,n.jsx)(oS,{phase:f.phase}),x&&(0,n.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle)"},title:x,children:` \xb7 ${x}`})]}),f&&d&&(0,n.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,n.jsx)(oM,{snapshot:d,view:f,id:c})}),(0,n.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,n.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,n.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",j]})]}),(0,n.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,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v}),(0,n.jsx)("span",{children:b})]}),(0,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("span",{children:["도구 ",d.progress.toolCount]}),(0,n.jsxs)("span",{children:[d.progress.tokens.toLocaleString()," Token"]}),(0,n.jsx)("span",{children:function(e=0){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}초`;let r=Math.floor(t/60);return r<60?`${r}분${t%60?` ${t%60}초`:""}`:`${Math.floor(r/60)}시간 ${r%60}분`}(d.progress.durationMs)})]}),u&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:null===u.messages?"메시지 수 미확인":`메시지 ${u.messages}`}),(0,n.jsxs)("span",{children:[(u.bytes/1024).toFixed(+(u.bytes<10240))," KB"]}),(0,n.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 fO({title:e,sessionId:t,sessionPath:r,sessionCwd:i,liveSubagents:s,client:o,visible:l=!0,onClose:c,onReturnFocus:d,selection:u,onSelectionChange:p,onReturnToOrigin:h,onOpenFile:m}){let{t:f}=(0,z.s)(),g=(0,a.useMemo)(()=>o??aW(),[o]),[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)({kind:"loading"}),[w,k]=(0,a.useState)({kind:"loading"}),[j,S]=(0,a.useState)(!1),[C,N]=(0,a.useState)(null),T=p?u??null:C,I=p??N,[M,E]=(0,a.useState)(0),$=(0,a.useRef)(null),R=(0,a.useRef)(null);(0,a.useEffect)(()=>{v([]),y({kind:"loading"}),k({kind:"loading"}),S(!1),N(null)},[t]),(0,a.useEffect)(()=>{if(!l||!t)return;let e=!1,r=!1,n=null,a=async()=>{if(e||r||"visible"!==document.visibilityState)return;r=!0,n=new AbortController;let[a,i]=await Promise.allSettled([g.getLiveSnapshots(t,n.signal),g.getArchive(t,n.signal)]);if(!e&&!n.signal.aborted){if("fulfilled"===a.status)v(a.value.subagents),y(a.value.subagents.length>0?{kind:"ready",data:a.value.subagents}:{kind:"empty",data:[]});else{let e=s6(a.reason);y("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===i.status)S(!0===i.value.listTruncated),k(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=s6(i.reason);k("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}r=!1}};a();let i=setInterval(()=>void a(),3e3),s=()=>{"visible"===document.visibilityState&&a()};return document.addEventListener("visibilitychange",s),()=>{e=!0,n?.abort(),clearInterval(i),document.removeEventListener("visibilitychange",s)}},[M,g,t,l]);let L=(0,a.useMemo)(()=>(function(e,t){let r=new Map,n=[];for(let a of[...e,...t]){let e=r.get(a.id);if(!e){n.push(a.id),r.set(a.id,a);continue}let[t,i]=fL(a)>=fL(e)?[a,e]:[e,a];r.set(a.id,{...t,assignment:t.assignment??i.assignment,description:t.description??i.description})}return n.flatMap(e=>{let t=r.get(e);return t?[t]:[]})})(s,x),[s,x]),A="ready"===w.kind||"empty"===w.kind?w.data:[],P=(0,a.useMemo)(()=>(function(e,t){let r=new Map(t.map(e=>[e.name,e])),n=new Set,a=e.map(e=>{let t=(function(e){let t=[];if(e.sessionFile){let r=e.sessionFile.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"");r&&t.push({name:r,match:"session-file"})}return t.some(t=>t.name===e.id)||t.push({name:e.id,match:"name"}),t})(e).find(e=>r.has(e.name)&&!n.has(e.name)),a=t?r.get(t.name):void 0;return a&&n.add(a.name),{key:`live:${e.id}`,identity:a?"live-archive":"live",live:e,...a&&t?{archive:a,archiveMatch:t.match}:{}}});for(let e of t)n.has(e.name)||a.push({key:`archive:${e.name}`,identity:"archive",archive:e});return a})(L,A),[A,L]),F=T?P.find(e=>e.key===T.key)??null:null,_=F&&T?.toolCallId&&F.live?.parentToolCallId!==T.toolCallId?null:F,W=ow({sessionId:t,snapshots:L,client:g,enabled:l&&!T,cwd:i??void 0});if((0,a.useEffect)(()=>{let e=R.current;if(T||!e)return;R.current=null;let t=[...$.current?.querySelectorAll("[data-subagent-key]")??[]].find(t=>t.dataset.subagentKey===e);t?.focus({preventScroll:!1})}),T&&t)return(0,n.jsx)(fz,{sessionId:t,sessionCwd:i,record:_,selection:T,client:g,visible:l,onOpenFile:m,onBack:()=>{I(null),T.origin&&h?h(T.origin):R.current=T.key}});let O=0===P.length&&"loading"===b.kind&&"loading"===w.kind,D=0===P.length&&("empty"===b.kind||0===s.length)&&"empty"===w.kind;return(0,n.jsxs)("section",{ref:$,"aria-label":"Subagent 기록","data-state":O?"loading":D?"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,n.jsx)(p6,{title:e,titleTooltip:r??void 0,subtitle:O||!t?void 0:f("panel.subagentsCount",{count:P.length}),actions:[{id:"refresh",label:f("panel.refresh"),icon:fA,onClick:()=>E(e=>e+1)}],close:c?{label:f("panel.close"),onClick:()=>{c?.(),d?.()}}:void 0}),(0,n.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?O?(0,n.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):D?(0,n.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,n.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:P.map(e=>(0,n.jsx)(fW,{record:e,view:e.live?W.get(e.live.id):void 0,onSelect:()=>I({key:e.key})},e.key))}):(0,n.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!O&&"loading"===b.kind&&(0,n.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!O&&"loading"===w.kind&&(0,n.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===b.kind&&(0,n.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:b.message}),"error"===b.kind&&(0,n.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:b.message}),"unreachable"===w.kind&&(0,n.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:w.message}),"error"===w.kind&&(0,n.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:w.message}),j&&(0,n.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let fD=new Set(["efficiency","sidechat","resource"]),fH=["process","efficiency","subagents","files","resource","sidechat","plugins","memory"];function fU({activeView:e,onViewChange:t,viewLabels:r,sessionId:a,sessionPath:i,sessionName:l,sessionCwd:c,liveSubagents:d,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:m,resourceSlot:f,efficiencySlot:g,pluginsSlot:x,memorySlot:v,visible:b=!0,onClose:y,onReturnFocus:w,expand:k=null,selectedMaker:j,onSelectMaker:S,onReturnToDispatch:C,onOpenFile:N,fileOpen:T=!1}){return(0,n.jsx)(p0.Provider,{value:k,children:(0,n.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":e,"data-expanded":k?.expanded?"true":void 0,children:(0,n.jsxs)(fI.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:e,onValueChange:e=>t(e),children:[(0,n.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,n.jsxs)(fI.J.List,{"aria-label":"보조 패널 보기",children:[fH.map(e=>{let t="subagents"===e?d.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,n.jsxs)(fI.J.Trigger,{value:e,"aria-label":t>0?`${r[e]} (실행 중 ${t})`:void 0,children:[(0,n.jsx)("span",{className:"auxiliary-deck-tab-label",children:r[e]}),t>0&&(0,n.jsx)(rT.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,n.jsx)(fI.J.Indicator,{})]}),(fD.has(e)||"files"===e&&!T)&&(0,n.jsx)(p3,{className:"auxiliary-deck-expand"}),y&&(0,n.jsx)(s.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{y?.(),w?.()},"aria-label":"보조 패널 닫기",children:(0,n.jsx)(o.In,{size:"16px",svg:(0,n.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,n.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})})]}),(0,n.jsx)(fI.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,n.jsx)(fI.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:g}),(0,n.jsx)(fI.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,n.jsx)(fO,{title:r.subagents,sessionId:a,sessionPath:i,sessionCwd:c,liveSubagents:d,client:u,visible:b&&"subagents"===e,selection:j,onSelectionChange:S,onReturnToOrigin:C,onOpenFile:N})}),(0,n.jsx)(fI.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,n.jsx)(fI.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:m}),(0,n.jsx)(fI.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:f}),(0,n.jsx)(fI.J.Content,{value:"plugins",className:"auxiliary-deck-panel",children:x}),(0,n.jsx)(fI.J.Content,{value:"memory",className:"auxiliary-deck-panel",children:v})]})})})}function fB({title:e,data:t,onOpenFile:r}){let{t:i}=(0,z.s)(),o=t?.groups??[],[l,c]=(0,a.useState)(()=>new Set);return(0,n.jsxs)("section",{className:"process-log","aria-label":e,children:[(0,n.jsx)(p6,{title:`${o.length} ${i(1===o.length?"process.turn":"process.turns")}`}),(0,n.jsxs)("div",{className:"process-log-body",children:[t?.status?(0,n.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,n.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),t.status]}):null,0===o.length?(0,n.jsx)("p",{className:"process-log-empty",children:i("process.empty")}):o.map((e,a)=>{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} ${i(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${i(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,n.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,n.jsxs)(s.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!o,onClick:()=>c(t=>{let r=new Set(t);return r.has(e.anchorIdx)?r.delete(e.anchorIdx):r.add(e.anchorIdx),r}),title:o?i("chat.expandProcess"):i("chat.collapseProcess"),children:[(0,n.jsx)("span",{className:"process-log-turn-title",children:d??i("chat.processDetails")}),(0,n.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!o&&(0,n.jsx)("div",{className:"process-log-entries",children:e.entries.map((a,i)=>{let s=t?.messages[a.idx];return s?(0,n.jsx)(lL,{message:a.blocks?eB(s,a.blocks,{omitUsage:!0}):s,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:r,entryId:t?.entryIds[a.idx],sessionId:t?.sessionId,showTimestamp:!1,recoveredError:eK(t?.messages??[],a.idx)},`process-${e.anchorIdx}-${i}`):null})})]},`turn-${e.anchorIdx}-${a}`)})]})]})}let fq=6,fV="omp-btw-log:",fK="omp-btw-log-index";function fG(e){return e.trim().toLowerCase()}function fJ(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function fZ(e){if(!Array.isArray(e))return[];let t=[],r=0;for(let n of e){if(!n||"object"!=typeof n||"string"!=typeof n.q||"string"!=typeof n.a)continue;let e={q:n.q,a:n.a,at:"number"==typeof n.at&&Number.isFinite(n.at)?n.at:0};t.push(e),r+=e.q.length+e.a.length}for(;t.length>40||r>12e4;){let e=t.shift();if(!e)break;r-=e.q.length+e.a.length}return t}function fY(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function fX(e,t={}){let r=t.now??Date.now,n=new Map,a=new Set,i=!1,s=[],o=t=>{if(e)try{e.removeItem(t)}catch{}},l=e=>{n.delete(e),a.delete(e),o(fV+e)},c=()=>{let e=new Set,t=[];for(let r of(s.sort((e,t)=>t.updatedAt-e.updatedAt),s))!r.id||e.has(r.id)||(e.add(r.id),t.length<20?t.push(r):l(r.id));s=t},d=()=>{if(!i){if(i=!0,e)try{let t=e.getItem(fK),r=t?JSON.parse(t):[];Array.isArray(r)&&(s=r.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:fG(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[r]=s.splice(t,1);return l(r.id),!0}return!1},p=t=>{if(e){try{e.setItem(fK,JSON.stringify(s));return}catch(e){if(!fY(e)||!u(t))return}try{e.setItem(fK,JSON.stringify(s))}catch{}}},h=t=>{let r=fG(t);if(!r)return[];if(a.has(r))return fJ(n.get(r)??[]);if(e)try{let t=e.getItem(fV+r);if(t){let e=JSON.parse(t),a=fZ(e?.entries);return n.set(r,a),fJ(a)}}catch{}return fJ(n.get(r)??[])},m=e=>{let t=fG(e);t&&(d(),s=s.filter(e=>e.id!==t),l(t),p(null))};return{read:h,append:(t,i)=>((t,i)=>{let o=fG(t);if(!o)return[];let l=fZ(i),h=r();if(n.set(o,fJ(l)),d(),(s=s.filter(e=>e.id!==o)).unshift({id:o,updatedAt:h}),c(),p(o),!e)return fJ(l);let m=JSON.stringify({updatedAt:h,entries:l});try{return e.setItem(fV+o,m),a.delete(o),fJ(l)}catch(e){if(!fY(e)||!u(o))return a.add(o),fJ(l)}p(o);try{e.setItem(fV+o,m),a.delete(o)}catch{a.add(o)}return fJ(l)})(t,[...h(t),i]),history:(e,t=fq)=>h(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:m,cleanup:(t,n)=>{if(!t.complete)return;d();let a=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=fG(e.id),r="number"==typeof e.modified?e.modified:Date.parse(e.modified);a.set(t,Number.isFinite(r)?r:0)}let i=n?fG(n):null,l=r();for(let e of[...s])if(e.id!==i){if(!a.has(e.id)){m(e.id);continue}l-Math.max(a.get(e.id)??0,e.updatedAt)>6048e5&&m(e.id)}if(!e||"function"!=typeof e.key||"number"!=typeof e.length)return;let c=[];try{for(let t=0;t<e.length;t+=1){let r=e.key(t);if(!r?.startsWith(fV))continue;let n=fG(r.slice(fV.length));a.has(n)||n===i||c.push(r)}}catch{return}for(let e of c)o(e)}}}function fQ(){let e=new Map,t=new Map,r=new Map,n=e=>{r.get(e)?.forEach(e=>{e()})};return{read(t){let r=e.get(t);return r?{...r.snapshot}:null},begin(t,r){if(e.has(t))return null;let a=new AbortController;return e.set(t,{snapshot:{sessionId:t,question:r,text:"",model:null},controller:a}),n(t),{controller:a}},ingest(t,r){let a=e.get(t);a&&("d"===r.t?a.snapshot.text+=r.v:"done"===r.t?a.snapshot.text=r.v||a.snapshot.text:"m"===r.t&&(a.snapshot.model=r.v),n(t))},abort(t){let r=e.get(t);return!!r&&(r.controller.abort(),!0)},finish(r,a){e.has(r)&&(e.delete(r),t.set(r,a),n(r))},takeOutcome(e){let r=t.get(e)??null;return r&&t.delete(e),r},subscribe(e,t){let n=r.get(e);return n||(n=new Set,r.set(e,n)),n.add(t),()=>{n.delete(t),0===n.size&&r.delete(e)}}}}class f0 extends Error{constructor(e,t,r){super(t),this.kind=e,this.status=r,this.name="SideChatRequestError"}}function f1(e){let t;try{t=JSON.parse(e)}catch{throw new f0("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new f0("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let r=t;if("d"!==r.t&&"done"!==r.t&&"m"!==r.t&&"err"!==r.t||"string"!=typeof r.v)throw new f0("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:r.t,v:r.v}}class f2{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()?[f1(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[f1(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function f8(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 f4(e=!1){return{minHeight:30,padding:"4px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",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 f5({children:e}){return(0,n.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 f6({children:e,streaming:t=!1}){return(0,n.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,n.jsx)(rb,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,n.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function f3({identity:e,status:t,utteranceKey:r,children:a}){let i=ah(e?.sessionId,e?.provider,e?.credentialId,e?.model),s=cx(i?.alias,t,r);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[i&&e?.provider&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,n.jsx)(ax,{seed:i.seed,size:40,provider:e.provider}),(0,n.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:i.alias})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[a,s&&(0,n.jsx)("img",{src:s.src,alt:s.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function f7({title:e,sessionId:t,sessionPath:r,sessionName:i,historyStore:s,flights:o,sessionCensus:l,client:c,visible:d=!0,onClose:u,onReturnFocus:p}){let h,m,f=(0,a.useMemo)(()=>c??function(e=(e,t)=>fetch(e,t),t="/api/sidecars/sidechat/ask"){return{async ask(r){let n;try{n=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:r.sessionPath,question:r.question,history:r.history.slice(-fq)}),signal:r.signal})}catch(e){if(r.signal?.aborted)throw e;throw new f0("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!n.ok)throw new f0("http",await f8(n),n.status);if(!n.body)throw new f0("stream","사이드채팅 스트림을 열 수 없습니다.");let a=n.body.getReader(),i=new f2,s="",o=null,l=e=>{for(let t of e)if(r.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 f0("server",t.v)};try{for(;;){let e=await a.read();if(e.done)break;l(i.push(e.value))}l(i.finish())}catch(e){if(r.signal?.aborted||e instanceof f0)throw e;throw new f0("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{a.releaseLock()}if(!s)throw new f0("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:s,model:o}}}}(),[c]),g=t?.toLowerCase()??null,[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)({}),w=g??"",k=b[w]??"",j=(e,t)=>{y(r=>{if((r[e]??"")===t)return r;let n={...r};return t?n[e]=t:delete n[e],n})},[S,C]=(0,a.useState)(0),[N,T]=(0,a.useState)({}),[I,M]=(0,a.useState)({}),[E,$]=(0,a.useState)({}),[R,L]=(0,a.useState)(null),[A,P]=(0,a.useState)(null),[F,_]=(0,a.useState)({}),[z,W]=(0,a.useState)({}),[O,D]=(0,a.useState)({}),H=(0,a.useRef)((h=new Set,m=new Set,{claim:e=>!(!e||h.has(e)||m.has(e))&&(h.add(e),!0),markSent(e){h.delete(e),m.add(e)},release(e){h.delete(e)}})),U=(0,a.useRef)(!0),B=(0,a.useRef)(g),q=(0,a.useRef)(d),V=(0,a.useRef)(null),K=(0,a.useRef)(!1),G=(0,a.useRef)(0),J=(0,a.useRef)(null);B.current=g,q.current=d,(0,a.useEffect)(()=>(U.current=!0,()=>{U.current=!1}),[]),(0,a.useEffect)(()=>{v(g?s.read(g):[])},[s,g]);let Z=(0,a.useRef)(null);(0,a.useEffect)(()=>{L(null),Z.current=null},[g]),(0,a.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 r=t.messages;if(!Array.isArray(r))return null;for(let e=r.length-1;e>=0;e-=1){let t=r[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 n="credentialId"in t?t.credentialId:void 0,a="model"in t?t.model:void 0;return{provider:t.provider,..."string"==typeof a&&a?{model:a}:{},..."number"==typeof n&&Number.isSafeInteger(n)&&n>0?{credentialId:n}:{}}}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,a.useEffect)(()=>{if(!g)return;let e=()=>{if(!U.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)T(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),y(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;$(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,a.useEffect)(()=>{l&&s.cleanup(l,g)},[s,g,l]),(0,a.useEffect)(()=>{d&&V.current?.focus()},[d,g]),(0,a.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||!r){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=o.begin(g,e);if(!t)return;let{signal:n}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await f.ask({sessionPath:r,question:e,history:s.history(g),signal:n,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(r){let t=o.read(g)?.text??"";if(n.aborted){let r=!1;t&&(s.append(g,{q:e,a:t,at:Date.now()}),r=!0),o.finish(g,{kind:"aborted",saved:r})}else{let n=r instanceof f0?r.kind:"unknown",a=r instanceof Error?r.message:String(r);o.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:n,errorMessage:a})}}finally{U.current&&q.current&&V.current?.focus()}},X=async(e,t,r)=>{if(!g)return;let n=`${g}:${t}`;if(H.current.claim(n)){W(e=>({...e,[n]:"sending"})),D(e=>{let t={...e};return delete t[n],t});try{var a,i;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=(a=e.q,i=e.a,t=r.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",a,"","[사이드채팅 답변]",i,...t?["","[추가 지시]",t]:[]].join("\n"));await uV(g,{type:l?"steer":"prompt",message:c}),H.current.markSent(n),W(e=>({...e,[n]:"sent"}))}catch(e){H.current.release(n),W(e=>{let t={...e};return delete t[n],t}),D(t=>({...t,[n]: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=I[g??""],er=g?o.read(g):null,en=x.length>0||ee.length>0||null!==er,ea=er?.model??E[g??""],ei=!g||!r,es=null!==er,eo=!es&&!ei&&k.trim().length>0,el=!g||es,ec=R?.sessionId===g?R:null;return(0,n.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==er,"data-state":g&&r?er?"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,n.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,n.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,n.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,n.jsxs)("div",{title:r??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:[i||g?.slice(0,8)||"세션 없음",ea?` \xb7 ${ea}`:""]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>{g&&null===o.read(g)&&(s.clear(g),v([]),T(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:el,style:f4(el),children:"Clear"}),u&&(0,n.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...f4(),width:32,padding:0},children:(0,n.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,n.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,n.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&&r?(0,n.jsxs)(n.Fragment,{children:[x.map((e,t)=>{let r=`${e.at}:${t}`,a=`${g}:${r}`,i=z[a],s=A===a;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,n.jsx)(f5,{children:e.q}),(0,n.jsx)(f3,{identity:ec,status:"settled",utteranceKey:r,children:(0,n.jsx)(f6,{children:e.a})}),"sent"===i?(0,n.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,n.jsxs)(n.Fragment,{children:[!s&&(0,n.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>P(a),style:{...f4(),alignSelf:"flex-start"},children:"메인에 보내기"}),s&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,n.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,n.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value:F[a]??"",onChange:e=>_(t=>({...t,[a]: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,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void X(e,r,F[a]??""),disabled:"sending"===i,style:f4("sending"===i),children:"sending"===i?"보내는 중…":"메인으로 전송"}),"sending"!==i&&(0,n.jsx)("button",{type:"button",onClick:()=>P(null),style:f4(),children:"취소"})]})]}),O[a]&&(0,n.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:O[a]})]})]},r)}),ee.map((e,t)=>(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,n.jsx)(f5,{children:e.question}),(0,n.jsxs)(f3,{identity:ec,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,n.jsx)(f6,{children:e.partialAnswer}),(0,n.jsx)("div",{role:"alert","data-error-kind":e.kind,style:{padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:e.message})]})]},`${e.question}:${t}`)),er&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,n.jsx)(f5,{children:er.question}),(0,n.jsx)(f3,{identity:ec,status:"streaming",utteranceKey:`stream:${er.question}`,children:(0,n.jsx)(f6,{streaming:!0,children:er.text})})]}),!en&&(0,n.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,n.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,n.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,n.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),et&&(0,n.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:et})]}),(0,n.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,n.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,n.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,r=Date.now()-G.current<100;if(K.current||t.isComposing||229===t.keyCode||r){r&&e.preventDefault();return}es||(e.preventDefault(),Q())},disabled:es||ei,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,n.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ei?"세션 파일이 준비되면 질문할 수 있습니다.":es?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,n.jsx)("button",{type:"submit",disabled:!es&&!eo,style:f4(!es&&!eo),children:es?"중단":"전송"})]})]})]})}let f9="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",ge="pointer-coarse:min-h-11 pointer-coarse:min-w-11 max-sm:min-h-11 max-sm:min-w-11";function gt(...e){return e.filter(Boolean).join(" ")}function gr(e,t){let r=Math.floor((e-t)/6e4);if(r<=0)return"리셋됨";let n=Math.floor(r/1440),a=Math.floor(r%1440/60),i=r%60;return n>0?`${n}d ${a}h 후 리셋`:a>0?`${a}h ${i}m 후 리셋`:`${i}m 후 리셋`}function gn(e,t){if(!e)return null;let r=Date.parse(e);if(!Number.isFinite(r))return null;let n=Math.floor((r-t)/6e4);if(n<=0)return"만료됨";let a=Math.floor(n/1440),i=Math.floor(n%1440/60),s=n%60;return a>0?`${a}d ${i}h 후 만료`:i>0?`${i}h ${s}m 후 만료`:`${s}m 후 만료`}function ga(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 gi(e,t){return!1!==t?ga(e):"number"==typeof e&&Number.isFinite(e)&&0!==e?`≥${ga(e)}`:"가격 미상"}function gs(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function go(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 gl(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function gc(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function gd(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function gu({label:e,value:t}){return(0,n.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,n.jsx)("dt",{className:"text-xs text-text-muted",children:e}),(0,n.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:t})]})}function gp({state:e,loading:t,subject:r}){return t&&"idle"===e.status?(0,n.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[r," 불러오는 중…"]}):"error"===e.status?(0,n.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,n.jsxs)("div",{className:"font-medium",children:[r,"을 불러오지 못했습니다."]}),(0,n.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:e.error.message}),(0,n.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===e.status?(0,n.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 gh(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),n=String(t.getMinutes()).padStart(2,"0");return`${t.getMonth()+1}/${t.getDate()} ${r}:${n}`}function gm({limit:e,now:t,detailed:r}){let a="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,i=Math.max(0,Math.min(100,100*a)),s=Math.round(100*a),o=function(e,t){let r=e.window,n=e.amount?.usedFraction;if(!r?.resetsAt||"number"!=typeof n)return null;let a=Math.max(0,r.resetsAt-t),i=100*n,s=Math.max(0,100-i);if(!r.durationMs){let e=a/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?s/e:s}}let o=Math.min(r.durationMs,Math.max(0,r.durationMs-a)),l=r.durationMs>432e5,c=l?864e5:36e5,d=r.durationMs/c,u=a/c,p=o/r.durationMs*100;return{burnOnly:!1,unit:l?"하루":"시간",partial:u<1,burn:u>=1?s/u:s,pacePct:p,deltaPct:i-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*a,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,m=l?"unknown"===l.quality||null==l.usedPct?"구간 사용 — 기록 부족":"approx"===l.quality?`구간 사용 ≈${l.usedPct.toFixed(0)}% \xb7 추정`:"estimate"===l.quality?`구간 사용 ≥${l.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${l.usedPct.toFixed(1)}%`:null;return(0,n.jsxs)("div",{className:"usage-limit py-2",children:[(0,n.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:e.label||e.id}),a>=1?(0,n.jsx)("span",{className:"usage-chip","data-tone":"danger",children:a>1?"한도 초과":"한도 도달"}):null,null!=h?(0,n.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${h.toFixed(1)}%`}):null,(0,n.jsxs)("span",{className:gt("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[s,"%"]})]}),(0,n.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,n.jsx)("div",{className:gt("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${i}%`}}),null!=c&&null!=d&&d>c?(0,n.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,n.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,a>1?(0,n.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),m||e.window?.resetsAt?(0,n.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,n.jsx)("span",{className:"min-w-0 truncate",children:m??""}),e.window?.resetsAt?(0,n.jsx)("span",{className:"shrink-0",children:gr(e.window.resetsAt,t)}):null]}):null,r?(0,n.jsxs)("dl",{className:"m-0 mt-1.5 border-s-2 border-border ps-2.5",children:[o?.pacePct!=null?(0,n.jsx)(gu,{label:"페이스",value:`${o.pacePct.toFixed(1)}%`}):null,o?(0,n.jsx)(gu,{label:o.partial?"남은 한도":`앞으로 ${o.unit}`,value:`${o.burn.toFixed(1)}%`}):null,o?.nominal!=null?(0,n.jsx)(gu,{label:"균등 배분 기준",value:`${o.nominal.toFixed(1)}%/${"하루"===o.unit?"일":"시간"} \xb7 계산값`}):null,l?(0,n.jsx)(gu,{label:"구간",value:`${gh(l.slotStart)} ~ ${gh(l.slotEnd)} \xb7 ${l.slotIndex+1}/${l.slotCount}`}):null,l?(0,n.jsx)(gu,{label:"기록 품질",value:function(e){let t;if("unknown"===e.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";if("estimate"===e.quality){let t=null==e.firstSeenAt?"?":gh(e.firstSeenAt);return`추정 \xb7 구간 시작 표본이 없어 ${t}부터 센 최소량${e.paceOver?" \xb7 주간 진도 초과":""}`}let r=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?r?`실측 \xb7 경계 ${r} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${r??"?"} 전 표본`}(l)}):null]}):null]})}let gf={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:fable":"페이블 주간","anthropic:7d:opus":"Opus 주간","anthropic:7d:sonnet":"Sonnet 주간"},gg={fable:"페이블",opus:"Opus",sonnet:"Sonnet"};function gx(e){let t=e.clears??[],r=[...new Set(t.map(e=>gf[e]).filter(e=>void 0!==e))],n=t.map(e=>/^anthropic:7d:(.+)$/.exec(e)?.[1]).find(e=>void 0!==e);return{name:t.includes("anthropic:7d")?"전체 리셋":n?`${gg[n]??n} 리셋`:t.includes("anthropic:5h")?"5시간 리셋":"리셋",covers:r.length?`${r.join("\xb7")} 한도`:null}}function gv({confirmId:e,pending:t,primaryRef:r,summary:a,onConfirm:i,onCancel:s}){return(0,n.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,n.jsx)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:a}),(0,n.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,n.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,n.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,n.jsx)("button",{ref:r,type:"button",className:gt(f9,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:i,children:t?"사용 중…":"리셋 사용"}),(0,n.jsx)("button",{type:"button",className:f9,disabled:t,onClick:s,children:"취소"})]})]})}function gb({report:e,brokerOk:t,now:r,active:i,identity:s,recommendation:o,pendingAction:l,feedback:c,onToggle:d,onReset:u}){let p=e.metadata??{},h=s??nV([e])[0],m=e.credentialId,f=Number.isSafeInteger(m)&&m>0,g=e.accountRole,x="usage-only"===g?"사용량":"control-only"===g?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>r,b=i?"active":e.disabled?"off":v?"auto-blocked":"idle",y="toggle"===l?"전환 중…":"reset"===l?"리셋 사용 중…":f?i?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${gr(e.autoBlockedUntilMs,r)}`:"control-only"===g?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===g?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,a.useId)(),k=(0,a.useId)(),[j,S]=(0,a.useState)(!1),[C,N]=(0,a.useState)(!1),[T,I]=(0,a.useState)(null),M=(0,a.useRef)(null),E=(0,a.useRef)(null),$=(0,a.useRef)(!1),R=(0,a.useRef)(!1),L="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,A="anthropic"===e.provider&&L?.state==="available"?L.credits:[],P=A.find(e=>e.id===L?.nextCreditId)??null,F="anthropic"===e.provider?P?.usable===!0?P:null:function(e){let t=e.savedReset?.credits??[],r=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,n=Number.isFinite(t)?t:null;(!r||null!=n&&(null==r.timestamp||n<r.timestamp))&&(r={id:e.id,expiresAt:e.expiresAt,timestamp:n})}return r?{id:r.id,expiresAt:r.expiresAt}:null}(e),_=F?.id??null,z=gn(F?.expiresAt??null,r),W=L?.availableCount,O=L&&"unavailable"!==L.state?"empty"===L.state||0===W?"없음":"anthropic"===e.provider?`${W??A.length}개`:`${W??L.credits.length}개${z?` \xb7 ${z}`:""}`:"확인 불가",D=(()=>{if("anthropic"!==e.provider||!P)return`저장된 리셋 ${O}`;let t=gx(P);return[`사용할 리셋: ${t.name}`,t.covers,z].filter(Boolean).join(" \xb7 ")})(),H=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let r="number"==typeof e.naturalResetAt?gr(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return r?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${r} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let r=gn(e.expiresAt??null,t),n="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${r&&"만료됨"!==r?r:"곧 만료"}됩니다.${n}`}(o,r),U=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&L?.state==="available"&&0!==W&&null!=_;(0,a.useLayoutEffect)(()=>{if(T)return void E.current?.focus();if($.current){var e;$.current=!1,e=M.current,e?.focus()}},[T]),(0,a.useEffect)(()=>{"reset"!==l&&(e.disabled||!t||L?.state!=="available")&&($.current=!1,I(null))},[t,l,e.disabled,L?.state]);let B=async()=>{if(T&&!R.current){R.current=!0;try{await u(e,T.creditId)}finally{R.current=!1,$.current=!0,I(null)}}},q=(e.limits??[]).reduce((e,t)=>{let n=t.window?.resetsAt;return"number"!=typeof n||n<=r?e:null==e||n<e?n:e},null),V=l?"pending":i?"active":e.disabled?"off":v?"blocked":"idle";return(0,n.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":b,"aria-current":i?"true":void 0,children:[(0,n.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,n.jsx)(ax,{seed:h.seed,size:48,provider:e.provider}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.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,n.jsx)("span",{children:h.alias}),(0,n.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${nq(e.provider)}${x?` \xb7 ${x}`:""}`})]}),(0,n.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,n.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":V,role:l?"status":void 0,children:y}),null!=q&&q-r<=72e5?(0,n.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${gr(q,r).replace(/ 후 리셋$/,"")}`}):null]})]}),f?(0,n.jsxs)("span",{className:"resource-account-toggle",children:[(0,n.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,n.jsx)("button",{type:"button",role:"switch",className:gt(f9,"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:()=>{$.current=!1,I(null),d(e)},children:e.disabled?"OFF":"ON"})]}):null]}),e.disabled?(0,n.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):v?(0,n.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(e.limits??[]).some(nc)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,c?(0,n.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===c.tone?"alert":"status",children:c.message}):null,(0,n.jsxs)("div",{id:k,className:"resource-account-limits divide-y divide-border",children:[j?(0,n.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,n.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,n.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,n.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:C?h.raw:h.masked||"—"}),h.raw?(0,n.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":C,onClick:()=>N(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,n.jsx)(gm,{limit:e,now:r,detailed:j},e.id))]}),(e.limits??[]).length>0||h.raw?(0,n.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?T?(0,n.jsx)(gv,{confirmId:w,pending:"reset"===l,primaryRef:E,summary:T.summary,onConfirm:()=>{B()},onCancel:()=>{$.current=!0,I(null)}}):(0,n.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===W?"empty":"reset"===l?"pending":"ready":"unavailable":"offline",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,n.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,n.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,n.jsx)("span",{className:gt("font-mono text-xs tabular-nums text-text",o?.reason==="expiring-credit"&&"text-warning"),children:O})]}),U?(0,n.jsx)("button",{ref:M,type:"button",className:gt(f9,"ml-auto flex-none"),disabled:null!=l,onClick:()=>{_&&I({creditId:_,summary:D})},children:"리셋 사용"}):t&&e.disabled&&L?.state==="available"?(0,n.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):t&&"anthropic"===e.provider&&A.length>0?(0,n.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"지금은 사용 불가"}):null]}),A.length>0?(0,n.jsx)("ul",{className:"resource-reset-credits m-0 mt-1.5 list-none space-y-1 p-0","aria-label":"저장된 리셋 종류",children:A.map(e=>{let t=gx(e),a=e.id===P?.id,i=gn(e.expiresAt,r),s=e.remainingCount??1;return(0,n.jsxs)("li",{className:"flex flex-wrap items-baseline gap-x-2 text-xs","data-reset-next":a?"true":void 0,children:[(0,n.jsx)("span",{className:gt("font-medium",a?"text-text":"text-text-muted"),children:s>1?`${t.name} ${s}개`:t.name}),a?(0,n.jsx)("span",{className:"usage-chip",children:"다음 사용"}):null,(0,n.jsx)("span",{className:"min-w-0 text-text-muted",children:[t.covers,i].filter(Boolean).join(" \xb7 ")})]},e.id)})}):null,H?(0,n.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:H}):null]}):null]})}function gy({state:e,loading:t,accountState:r,pendingActions:a,feedbackByCredential:i,onToggle:s,onReset:o}){let l=ry(1e4);am();let c=e.data,d=r?.state==="resolved"&&"session-pin"===r.source&&Number.isSafeInteger(r.credentialId)&&r.credentialId>0?r.credentialId:null,u=nV(c?.reports??[]),p=null==d?-1:c?.reports.findIndex(e=>e.credentialId===d)??-1;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(gp,{state:e,loading:t,subject:"사용량"}),c?.brokerOk===!1?(0,n.jsx)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,n.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,n.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,n.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,n.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,n.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),c&&0===c.reports.length?(0,n.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,n.jsx)(gb,{report:e,brokerOk:!0===c.brokerOk,now:l,active:t===p,identity:u[t],recommendation:null==d?void 0:r?.resetRecommendations.find(e=>e.credentialId===d),pendingAction:null==d?null:a.get(d)??null,feedback:null==d?void 0:i.get(d),onToggle:s,onReset:o},`${e.provider}:${d??e.metadata?.accountId??e.metadata?.email??t}`)})]})}let gw={invalid_total:!0,invalid_start_date:!0,start_date_in_future:!0,session_scan_failed:!0,session_scan_partial:!0,internal:!0,settings_unreadable:!0,invalid_balance:!0,invalid_observed_at:!0,observed_at_in_future:!0,routes_unreadable:!0},gk={session:!0,memory:!0,"korean-reply-translation":!0};function gj(e,t,r=""){return t?Object.hasOwn(gw,t)?e(`credits.error.${t}`):r||t:r}function gS({face:e,title:t,model:r,cost:a,costMinimum:i=!1,detail:s,t:o}){return(0,n.jsxs)("li",{className:"flex min-w-0 items-start gap-2 py-1.5",children:[e?(0,n.jsx)(ax,{seed:e.seed,size:28,provider:"hive"}):(0,n.jsx)("span",{className:"w-7 shrink-0","aria-hidden":"true"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-baseline gap-1.5",children:[t?(0,n.jsx)("span",{className:"shrink-0 text-[13px] font-medium text-text",children:t}):null,(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-text-dim",children:r}),(0,n.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-text",children:null===a?o("credits.priceUnknown"):`${i?"≥":""}${ga(a)}`})]}),(0,n.jsx)("div",{className:"mt-0.5 whitespace-pre-line font-mono text-[11px] tabular-nums text-text-muted",children:s})]})]})}function gC({walletName:e,setting:t,onSave:r,onClose:i,t:s}){let o=(0,a.useId)(),[l,c]=(0,a.useState)(t?String(t.totalUsd):""),[d,u]=(0,a.useState)(t?.startDate??""),[p,h]=(0,a.useState)(!1),[m,f]=(0,a.useState)(null),g="min-h-8 w-full min-w-0 border border-border bg-bg px-2 font-mono text-xs text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",x=async e=>{h(!0),f(null);try{await r(e),i()}catch(e){f(s("credits.saveFailed",{reason:gj(s,e instanceof nK?e.code:void 0,e instanceof Error?e.message:String(e))}))}finally{h(!1)}};return(0,n.jsxs)("form",{className:"mt-2 grid gap-2 border border-border bg-bg-raised p-2.5","aria-label":s("credits.formLabel",{wallet:e}),onSubmit:e=>{var t;let r;e.preventDefault();let n=(r=Number((t={totalUsd:l,startDate:d}).totalUsd.replace(/[$,\s]/g,"")),t.totalUsd.trim()&&Number.isFinite(r)?{totalUsd:r,startDate:t.startDate.trim()}:null);n?x(n):f(s("credits.invalid.total"))},children:[(0,n.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,n.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${o}-total`,children:[s("credits.totalUsd"),(0,n.jsx)("input",{id:`${o}-total`,className:g,inputMode:"decimal",value:l,onChange:e=>c(e.target.value),placeholder:"300",required:!0})]}),(0,n.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${o}-start`,children:[s("credits.startDate"),(0,n.jsx)("input",{id:`${o}-start`,className:g,type:"date",value:d,onChange:e=>u(e.target.value),required:!0})]})]}),m?(0,n.jsx)("div",{className:"text-xs text-danger",role:"alert",children:m}):null,(0,n.jsxs)("div",{className:"flex flex-wrap justify-end gap-1.5",children:[t?(0,n.jsx)("button",{type:"button",className:gt(f9,"me-auto"),disabled:p,onClick:()=>{x(null)},children:s("credits.clear")}):null,(0,n.jsx)("button",{type:"button",className:f9,disabled:p,onClick:i,children:s("credits.cancel")}),(0,n.jsx)("button",{type:"submit",className:f9,disabled:p,children:p?s("credits.saving"):s("credits.save")})]})]})}function gN({wallet:e,setting:t,balance:r,now:i,onSave:o,onSaveBalance:l,t:c}){let d=(0,a.useId)(),[u,p]=(0,a.useState)(!1),h=c("credits.wallet.hive"),m=function(e){if(null===e.totalUsd||e.totalUsd<=0)return{spentFraction:null,tone:"normal"};let t=e.spentUsd/e.totalUsd;return{spentFraction:Math.max(0,Math.min(1,t)),tone:t>=1?"danger":t>=.9?"warning":"normal"}}(e),f="start-date"===e.sinceSource?c("credits.since",{date:e.since}):c("credits.sinceDefault"),g=e.spentComplete||e.upperBoundRows?ga(e.spentUsd):`≥${ga(e.spentUsd)}`,x=null===e.remainingUsd?null:`${e.remainingUpperBound?"≤":""}${ga(Math.max(0,e.remainingUsd))}`,v=null===m.spentFraction||null===e.remainingUsd?null:Math.round(100*m.spentFraction);return(0,n.jsxs)("section",{className:"border-b border-border-strong px-4 py-3 last:border-b-0","aria-labelledby":d,"data-credit-wallet":e.wallet,children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("h3",{id:d,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:h}),u?null:(0,n.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>p(!0),children:t?c("credits.edit"):c("credits.enter")}),(0,n.jsx)(gM,{wallet:"hive",walletName:h,t:c})]}),r?(0,n.jsx)(gL,{balance:r,walletName:h,now:i,onSave:l,t:c}):null,(0,n.jsx)("div",{className:gt("text-xs text-text-muted",r?"mt-2":"mt-0.5"),children:`${c(`credits.scope.${e.wallet}`)} \xb7 ${f}`}),"error"===e.status?(0,n.jsx)("div",{className:"mt-1.5 text-xs text-text",role:"alert",children:c("credits.walletError",{reason:gj(c,e.error)})}):null,null!==v?(0,n.jsxs)("div",{className:"py-2",children:[(0,n.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,n.jsx)("span",{className:"text-[13px] text-text-muted",children:c("credits.remaining")}),(0,n.jsx)("span",{className:gt("font-mono text-sm font-semibold tabular-nums","danger"===m.tone?"text-danger":"text-text"),children:x})]}),(0,n.jsx)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":c("credits.meterLabel",{wallet:h}),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":v,children:(0,n.jsx)("div",{className:gt("absolute inset-y-0 left-0","danger"===m.tone?"bg-danger":"bg-metric"),style:{width:`${v}%`}})}),(0,n.jsx)("div",{className:"mt-1 text-right text-[11px] text-text-muted tabular-nums",children:c("credits.usedPct",{pct:v})})]}):null,(0,n.jsxs)("dl",{className:"m-0 mt-1",children:[null!==e.totalUsd?(0,n.jsx)(gu,{label:c("credits.total"),value:ga(e.totalUsd)}):null,(0,n.jsx)(gu,{label:c("credits.spent"),value:g})]}),t||u?null:(0,n.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text-muted",children:c("credits.enterPrompt")}),u?(0,n.jsx)(gC,{walletName:h,setting:t,onSave:o,onClose:()=>p(!1),t:c}):null,e.rows.length>0?(0,n.jsx)("ul",{className:"m-0 mt-1.5 list-none border-t border-border p-0",children:e.rows.map(e=>{let t=nO("hive",e.model)??nD("hive"),r=e.purposes.map(e=>{let t=Object.hasOwn(gk,e.purpose)?c(`credits.purpose.${e.purpose}`):e.purpose;return`${t} ${null===e.costUsd?c("credits.priceUnknown"):ga(e.costUsd)}`}),a=[c("credits.requests",{count:gs(e.requests)}),c("credits.tokens",{input:go(e.inputTokens),output:go(e.outputTokens)}),e.cacheReadTokens>0?c("credits.cacheTokens",{cache:go(e.cacheReadTokens)}):null].filter(Boolean).join(" \xb7 ");return(0,n.jsx)(gS,{face:t,title:t?.alias??e.model,model:e.model,cost:e.costUsd,detail:r.length>0?`${a}
|
|
76
|
+
${r.join(" \xb7 ")}`:a,t:c},e.model)})}):null]})}let gT={input:"inputTokens",output:"outputTokens",cacheRead:"cacheReadTokens",cacheWrite:"cacheWriteTokens"},gI={hive:"https://portal.deploy.com/",exa:"https://dashboard.exa.ai/billing",typesafe:"https://console.typesafe.ai/billing",anthropic:"https://platform.claude.com/settings/billing"};function gM({wallet:e,walletName:t,t:r}){return(0,n.jsxs)("a",{href:gI[e],target:"_blank",rel:"noopener noreferrer",className:gt("inline-flex shrink-0 items-center text-xs text-accent underline-offset-2 hover:underline",ge),"aria-label":r("credits.billingLinkLabel",{wallet:t}),"data-billing-link":e,children:[r("credits.billingLink")," ↗"]})}function gE({wallet:e,balance:t,now:r,onSaveBalance:i,t:s}){let o,l=(0,a.useId)(),c="error"===e.status&&"session_scan_partial"!==e.error,d=null!==e.coverageSince,u=null===e.spentUsd?s("credits.priceUnknown"):`${e.spentComplete?"":"≥"}${ga(e.spentUsd)}`;return(0,n.jsxs)("section",{className:"border-b border-border-strong px-4 py-3 last:border-b-0","aria-labelledby":l,"data-credit-wallet":"anthropic",children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("h3",{id:l,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:s("credits.wallet.anthropic")}),(0,n.jsx)(gM,{wallet:"anthropic",walletName:s("credits.wallet.anthropic"),t:s})]}),t?(0,n.jsx)(gL,{balance:t,walletName:s("credits.wallet.anthropic"),now:r,onSave:i,t:s}):null,(0,n.jsx)("div",{className:gt("text-xs text-text-muted",t?"mt-2":"mt-0.5"),children:`${s("credits.scope.anthropic")} \xb7 ${s("credits.sinceDefault")}`}),(0,n.jsx)("p",{className:"m-0 mt-1 text-xs text-text-muted",children:s("credits.anthropic.note")}),"error"===e.status?(0,n.jsx)("div",{className:"mt-1.5 text-xs text-text",role:"alert",children:s("credits.walletError",{reason:gj(s,e.error)})}):null,c?null:(0,n.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text","data-anthropic-coverage":d?"recorded":"none",children:d?s("credits.anthropic.coverageSince",{date:(o=new Date(e.coverageSince),`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`)}):s("credits.anthropic.noCoverage")}),c?null:(0,n.jsxs)("dl",{className:"m-0 mt-1",children:[d?(0,n.jsx)(gu,{label:s("credits.spent"),value:u}):null,(0,n.jsx)(gu,{label:s("credits.anthropic.oauthExcluded"),value:s("credits.requests",{count:gs(e.oauthRequests)})}),e.unattributedRequests>0?(0,n.jsx)(gu,{label:s("credits.anthropic.unattributedExcluded"),value:s("credits.requests",{count:gs(e.unattributedRequests)})}):null]}),d&&!c&&0===e.rows.length?(0,n.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text-muted",children:s("credits.anthropic.none")}):null,e.rows.length>0?(0,n.jsx)("ul",{className:"m-0 mt-1.5 list-none border-t border-border p-0",children:e.rows.map(e=>{let t=t=>{let r=e.costs[t];return`${s(`credits.category.${t}`)} ${go(e[gT[t]])} ${null===r?s("credits.priceUnknown"):ga(r)}`},r=e.purposes.map(e=>{let t=Object.hasOwn(gk,e.purpose)?s(`credits.purpose.${e.purpose}`):e.purpose,r=null===e.costUsd?s("credits.priceUnknown"):`${e.unpricedRequests>0?"≥":""}${ga(e.costUsd)}`;return`${t} ${r}`}),a=[[s("credits.requests",{count:gs(e.requests)}),t("input"),t("output")].join(" \xb7 "),[t("cacheRead"),t("cacheWrite")].join(" \xb7 "),r.length>0?r.join(" \xb7 "):null].filter(Boolean);return(0,n.jsx)(gS,{face:null,title:"",model:e.model,cost:e.costUsd,costMinimum:e.unpricedRequests>0,detail:a.join("\n"),t:s},e.model)})}):null]})}function g$(e){return rQ(e).replace("T"," ")}function gR({walletName:e,recorded:t,onSave:r,onClose:i,t:s}){let o=(0,a.useId)(),[l,c]=(0,a.useState)(t?String(t.amountUsd):""),[d,u]=(0,a.useState)(()=>rQ(t?.observedAt??Date.now())),[p,h]=(0,a.useState)(!1),[m,f]=(0,a.useState)({}),g="min-h-8 w-full min-w-0 border border-border bg-bg px-2 font-mono text-xs text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent pointer-coarse:min-h-11 max-sm:min-h-11",x={amount:`${o}-amount`,observedAt:`${o}-observed`,hint:`${o}-hint`,amountError:`${o}-amount-error`,observedAtError:`${o}-observed-error`},v=async e=>{h(!0),f({});try{await r(e),i()}catch(n){let e=n instanceof nK?n.code:void 0,t=gj(s,e,n instanceof Error?n.message:String(n)),r="invalid_balance"===e?"amount":"invalid_observed_at"===e||"observed_at_in_future"===e?"observedAt":"form";f({[r]:"form"===r?s("credits.saveFailed",{reason:t}):t})}finally{h(!1)}};return(0,n.jsxs)("form",{className:"mt-2 grid gap-2 border border-border bg-bg-raised p-2.5","aria-label":s("credits.balance.formLabel",{wallet:e}),noValidate:!0,"data-dismissible-layer":!0,onKeyDown:e=>{"Escape"!==e.key||p||(e.preventDefault(),i())},onSubmit:e=>{e.preventDefault();let t=function(e){let t=Number(e.amountUsd.replace(/[$,\s]/g,""));if(!e.amountUsd.trim()||!Number.isFinite(t))return{error:"amount"};let r=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(e.observedAt.trim())?new Date(e.observedAt.trim()).getTime():NaN;return Number.isFinite(r)?{value:{amountUsd:t,observedAt:r}}:{error:"observedAt"}}({amountUsd:l,observedAt:d});"error"in t?f({[t.error]:s("amount"===t.error?"credits.invalid.amount":"credits.invalid.observedAt")}):v(t.value)},children:[(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsx)("label",{className:"text-[11px] text-text-muted",htmlFor:x.amount,children:s("credits.balance.amount")}),(0,n.jsx)("input",{id:x.amount,className:g,inputMode:"decimal",autoComplete:"off",value:l,onChange:e=>c(e.target.value),"aria-invalid":!!m.amount||void 0,"aria-describedby":m.amount?x.amountError:void 0,autoFocus:!0,required:!0}),m.amount?(0,n.jsx)("p",{id:x.amountError,className:"m-0 text-xs text-danger",role:"alert",children:m.amount}):null]}),(0,n.jsxs)("div",{className:"grid gap-1",children:[(0,n.jsx)("label",{className:"text-[11px] text-text-muted",htmlFor:x.observedAt,children:s("credits.balance.observedAt")}),(0,n.jsx)("input",{id:x.observedAt,className:g,type:"datetime-local",value:d,onChange:e=>u(e.target.value),"aria-invalid":!!m.observedAt||void 0,"aria-describedby":m.observedAt?x.observedAtError:x.hint,required:!0}),m.observedAt?(0,n.jsx)("p",{id:x.observedAtError,className:"m-0 text-xs text-danger",role:"alert",children:m.observedAt}):(0,n.jsx)("p",{id:x.hint,className:"m-0 text-[11px] text-text-muted",children:s("credits.balance.observedAtHint")})]}),m.form?(0,n.jsx)("div",{className:"text-xs text-danger",role:"alert",children:m.form}):null,(0,n.jsxs)("div",{className:"flex flex-wrap justify-end gap-1.5",children:[t?(0,n.jsx)("button",{type:"button",className:gt(f9,ge,"me-auto"),disabled:p,onClick:()=>{v(null)},children:s("credits.clear")}):null,(0,n.jsx)("button",{type:"button",className:gt(f9,ge),disabled:p,onClick:i,children:s("credits.cancel")}),(0,n.jsx)("button",{type:"submit",className:gt(f9,ge),disabled:p,children:p?s("credits.saving"):s("credits.save")})]})]})}function gL({balance:e,walletName:t,now:r,onSave:i,t:o}){let[l,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=e.recorded,p=(0,a.useRef)(!1);(0,a.useLayoutEffect)(()=>{!l&&p.current&&(p.current=!1,d.current?.focus())},[l]);let h="unverified"===e.evidence?o("credits.evidence.unverified"):null!==e.lastPaidUseAt?o("credits.evidence.lastPaidUse",{time:g$(e.lastPaidUseAt)}):null;return(0,n.jsxs)("div",{"data-balance-source":e.source,"data-balance-state":u?"recorded":"unknown",children:[(0,n.jsxs)("p",{className:"m-0 mt-0.5 text-xs text-text-muted","data-balance-evidence":e.evidence,children:[o(`credits.route.${e.wallet}`),h?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("br",{}),h]}):null]}),(0,n.jsxs)("div",{className:"mt-2 flex min-w-0 items-baseline justify-between gap-2",children:[(0,n.jsxs)("span",{className:"min-w-0 text-[13px] text-text-muted",children:[o("credits.balance.label"),(0,n.jsx)("span",{className:"ms-1.5 border border-border px-1 text-[11px]",children:o("credits.balance.source")})]}),u?(0,n.jsx)("span",{className:"shrink-0 font-mono text-sm font-semibold tabular-nums text-text","data-balance-amount":!0,children:`$${u.amountUsd.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}):(0,n.jsx)("span",{className:"shrink-0 text-xs text-text-muted",children:o("credits.balance.none")})]}),(0,n.jsxs)("div",{className:"mt-1 flex min-w-0 flex-wrap items-center justify-between gap-x-2 gap-y-1",children:[u?(0,n.jsx)("time",{className:"min-w-0 text-[11px] tabular-nums text-text-muted",dateTime:new Date(u.observedAt).toISOString(),children:`${o("credits.balance.observed",{time:g$(u.observedAt)})} \xb7 ${function(e,t,r){let n=Math.max(0,Math.floor((r-t)/6e4));if(n<1)return e("credits.balance.age.now");if(n<60)return e("credits.balance.age.minutes",{count:n});let a=Math.floor(n/60);return a<48?e("credits.balance.age.hours",{count:a}):e("credits.balance.age.days",{count:Math.floor(a/24)})}(o,u.observedAt,r)}`}):(0,n.jsx)("span",{}),l?null:(0,n.jsx)(s.r,{ref:d,variant:"neutralWeak",size:"xsmall",className:ge,onClick:()=>c(!0),"aria-label":`${t} ${o(u?"credits.balance.edit":"credits.balance.record")}`,children:o(u?"credits.balance.edit":"credits.balance.record")})]}),l?(0,n.jsx)(gR,{walletName:t,recorded:u,onSave:t=>i(e.wallet,t),onClose:()=>{p.current=!0,c(!1)},t:o}):null]})}function gA({balance:e,now:t,onSaveBalance:r,t:i}){let s=(0,a.useId)(),o=i(`credits.wallet.${e.wallet}`);return(0,n.jsxs)("section",{className:"border-b border-border-strong px-4 py-3 last:border-b-0","aria-labelledby":s,"data-credit-wallet":e.wallet,children:[(0,n.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,n.jsx)("h3",{id:s,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:o}),(0,n.jsx)(gM,{wallet:e.wallet,walletName:o,t:i})]}),(0,n.jsx)(gL,{balance:e,walletName:o,now:t,onSave:r,t:i})]})}function gP({state:e,loading:t,now:r,onSave:a,onSaveBalance:i,t:s}){let o=e.data,l=new Map((o?.balances&&!o.balancesError?o.balances:[]).map(e=>[e.wallet,e])),c=e=>{let t=l.get(e);return t?(0,n.jsx)(gA,{balance:t,now:r,onSaveBalance:i,t:s}):null},d=o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(gN,{wallet:o.hive,setting:o.settings.hive,balance:l.get("hive")??null,now:r,onSave:a,onSaveBalance:i,t:s}),c("exa"),c("typesafe"),o.anthropic?(0,n.jsx)(gE,{wallet:o.anthropic,balance:l.get("anthropic")??null,now:r,onSaveBalance:i,t:s}):null]}):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h2",{className:"resource-group-heading",children:s("credits.heading")}),(0,n.jsx)("p",{className:"m-0 border-b border-border px-4 py-2 text-xs text-text-muted",children:s("credits.estimateNote")}),t&&"idle"===e.status?(0,n.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:s("credits.loading")}):null,"error"===e.status||"stale"===e.status?(0,n.jsx)("div",{className:"border-b border-border px-4 py-2 text-xs text-text",role:"alert",children:s("credits.loadFailed",{reason:e.error.message})}):null,o?.settingsError?(0,n.jsx)("div",{className:"border-b border-border px-4 py-2 text-xs text-text",role:"alert",children:s("credits.settingsError")}):null,o?.balancesError?(0,n.jsx)("div",{className:"border-b border-border px-4 py-2 text-xs text-text",role:"alert",children:gj(s,o.balancesError)}):null,d]})}function gF({refreshToken:e}){let{t}=(0,z.s)(),[r,i]=(0,a.useState)({status:"idle",data:null,error:null}),[s,o]=(0,a.useState)(!1),l=(0,a.useRef)(r),c=(0,a.useRef)(null);l.current=r;let d=(0,a.useCallback)(async e=>{c.current?.abort();let t=new AbortController;c.current=t,o(!0);let r=await n2({refresh:e,previous:l.current.data,signal:t.signal});c.current!==t||t.signal.aborted||(i(r),o(!1))},[]);(0,a.useEffect)(()=>{d(e>0)},[d,e]),(0,a.useEffect)(()=>()=>c.current?.abort(),[]);let u=(0,a.useCallback)(async e=>{await n8(e),await d(!1)},[d]),p=(0,a.useCallback)(async(e,t)=>{await n4(e,t),await d(!1)},[d]),h=ry(6e4);return(0,n.jsx)(gP,{state:r,loading:s,now:h,onSave:u,onSaveBalance:p,t:t})}function g_({model:e}){var t,r;let a=Math.max(1,Math.min(100,100*e.costShare)),i="unpriced"!==e.pricing&&"partial"!==e.pricing,s="unpriced"===e.pricing?gi(0,!1):`${gi(e.cost,i)} \xb7 ${gl(e.costShare)}`;return(0,n.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,n.jsx)("h3",{className:"m-0 min-w-0 flex-1 truncate text-sm font-semibold text-text",title:e.model,children:e.model}),(0,n.jsx)("span",{className:"text-xs text-text-muted",children:e.provider}),(0,n.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:s})]}),(0,n.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,n.jsx)("div",{className:"h-full bg-metric",style:{width:`${a}%`}})}),(0,n.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,n.jsx)(gu,{label:"요청",value:gs(e.requests)}),(0,n.jsx)(gu,{label:"요청당",value:gi(e.costPerRequest,i)}),(0,n.jsx)(gu,{label:"토큰/요청",value:go(e.tokensPerRequest)}),(0,n.jsx)(gu,{label:"출력/요청",value:go(e.outputPerRequest)}),(0,n.jsx)(gu,{label:"캐시율",value:(t=e.cacheRate,"not-reported"===(r=e.cacheStatus)?"미보고":"unknown"===r?"알 수 없음":gl(t,1))}),(0,n.jsx)(gu,{label:"TTFT",value:gc(e.avgTtft)})]})]})}function gz({agent:e}){let t={main:"메인",subagent:"SubAgent",advisor:"advisor"}[e.agentType]??e.agentType,r=Math.max(1,Math.min(100,100*e.costShare));return(0,n.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,n.jsx)("h3",{className:"m-0 text-sm font-semibold text-text",children:t}),(0,n.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[gi(e.cost,e.costComplete)," \xb7 ",gl(e.costShare)]})]}),(0,n.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,n.jsx)("div",{className:"h-full bg-metric",style:{width:`${r}%`}})}),(0,n.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,n.jsx)(gu,{label:"요청",value:gs(e.requests)}),(0,n.jsx)(gu,{label:"요청당",value:gi(e.costPerRequest,e.costComplete)}),(0,n.jsx)(gu,{label:"토큰/요청",value:go(e.tokensPerRequest)})]})]})}function gW({day:e}){let t=e.models.slice(0,3).map(e=>e.model).join(", ");return(0,n.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,n.jsx)("span",{className:"font-mono text-xs tabular-nums text-text-muted",children:gd(e.timestamp)}),(0,n.jsx)("span",{className:"truncate text-xs text-text-muted",title:t,children:t}),(0,n.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:gi(e.cost,e.costComplete)})]})}function gO({state:e,loading:t}){let r=e.data,a=r?.overall.unpricedModels??0,i=r?.overall.cacheExcludedModels??0;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(gp,{state:e,loading:t,subject:"모델 집계"}),r?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("section",{"aria-labelledby":"resource-overall-heading",children:[(0,n.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,n.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4 px-4 py-3",children:[(0,n.jsx)(gu,{label:"요청",value:gs(r.overall.requests)}),(0,n.jsx)(gu,{label:"추정 비용",value:gi(r.overall.cost,r.overall.costComplete)}),(0,n.jsx)(gu,{label:"토큰",value:go(r.overall.tokens)}),(0,n.jsx)(gu,{label:i>0?"캐시율(일부)":"캐시율",value:gl(r.overall.cacheRate,1)}),(0,n.jsx)(gu,{label:a>0?"캐시 절감(일부)":"캐시 절감",value:gl(r.overall.cacheSavings,1)}),(0,n.jsx)(gu,{label:"평균 TTFT",value:gc(r.overall.avgTtft)})]})]}),(0,n.jsxs)("section",{"aria-labelledby":"resource-models-heading",children:[(0,n.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:"모델별"}),r.models.length?r.models.map(e=>(0,n.jsx)(g_,{model:e},`${e.provider}:${e.model}`)):(0,n.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"모델 기록이 없습니다."})]}),(0,n.jsxs)("section",{"aria-labelledby":"resource-agents-heading",children:[(0,n.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:"에이전트 종류별"}),r.agents.length?r.agents.map(e=>(0,n.jsx)(gz,{agent:e},e.agentType)):(0,n.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"기록이 없습니다."})]}),r.daily.length?(0,n.jsxs)("section",{"aria-labelledby":"resource-daily-heading",children:[(0,n.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:"일별 추정 비용"}),r.daily.map(e=>(0,n.jsx)(gW,{day:e},e.timestamp))]}):null,(0,n.jsxs)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:["`omp stats` 기준 누적값입니다. 금액은 토큰 단가로 계산한 추정치이며 실제 청구액이나 구독 사용량이 아닙니다. 구독 한도 %는 계정 한도 탭에서 확인하세요.",a>0?` 가격을 다 매기지 못한 모델이 ${a}개 있어 추정 비용\xb7비중\xb7캐시 절감은 단가를 아는 사용량만 셉니다. ≥가 붙은 금액은 추정 비용의 최솟값입니다. 에이전트 종류별 집계는 모델을 나누지 않아 모든 행에 ≥를 붙입니다.`:null,i>0?` 캐시 사용량을 보고하지 않거나 보고 여부를 알 수 없는 모델 ${i}개는 캐시율 계산에서 뺐습니다.`:null]})]}):null]})}function gD({reports:e,providerConnections:t}){return am(),(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("section",{className:"character-roster-intro","aria-labelledby":"character-roster-heading",children:[(0,n.jsx)("h2",{id:"character-roster-heading",children:"호출 가능한 캐릭터"}),(0,n.jsxs)("p",{children:[(0,n.jsx)("strong",{children:"호출\xb7불러\xb7소환"}),"은 캐릭터를 SubAgent로 이 대화에 부릅니다.",(0,n.jsx)("strong",{children:" 교체"}),"는 이 대화의 Main을 바꿉니다."]})]}),(0,n.jsx)("div",{className:"character-roster",role:"list","aria-label":"호출 가능한 캐릭터 목록",children:nv.map(r=>{let a=`character-roster-${r.seed}`,i=`character-roster-${r.seed}-status`,s=`${r.provider}/${r.model}`,o=!1,l=!1;if(e){for(let t of e)if(t.provider===r.provider&&(o=!0,!0!==t.disabled)){l=!0;break}}let c="web6"!==r.provider&&(t?.get(r.provider)===!1||o&&!l);return(0,n.jsxs)("article",{className:gt("character-roster-item",c&&"is-unavailable"),role:"listitem","aria-labelledby":a,"aria-describedby":c?i:void 0,children:[(0,n.jsxs)("div",{className:"character-roster-identity",children:[(0,n.jsx)(ax,{seed:r.seed,size:48,provider:r.provider}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h3",{id:a,children:r.alias}),c?(0,n.jsx)("span",{id:i,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,n.jsx)("p",{children:r.voice})]})]}),(0,n.jsxs)("dl",{className:"character-roster-model",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"모델"}),(0,n.jsx)("dd",{title:s,children:s})]}),void 0!==r.oauthPosition?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"계정"}),(0,n.jsxs)("dd",{children:["OAuth ",r.oauthPosition]})]}):null]}),(0,n.jsxs)("dl",{className:"character-roster-examples",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"호출"}),(0,n.jsxs)("dd",{children:[(0,n.jsx)("code",{children:r.summonExample}),(0,n.jsx)("span",{children:r.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Main 교체"}),(0,n.jsxs)("dd",{children:[r.switchExample?(0,n.jsx)("code",{children:r.switchExample}):(0,n.jsx)("strong",{children:"교체 불가"}),(0,n.jsx)("span",{children:r.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},r.alias)})})]})}function gH({open:e,sessionId:t,activeTab:r,onTabChange:i,usage:o,className:l}){let c=(0,a.useId)(),d=o.state,u=o.loading,[p,h]=(0,a.useState)({status:"idle",data:null,error:null}),[m,f]=(0,a.useState)(null),[g,x]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null),[y,w]=(0,a.useState)(()=>new Map),[k,j]=(0,a.useState)(()=>new Map),[S,C]=(0,a.useState)(0),N=(0,a.useRef)(p),T=(0,a.useRef)(null),I=(0,a.useRef)(null),M=(0,a.useRef)(new Set),E=(0,a.useRef)(new Set);N.current=p,(0,a.useEffect)(()=>{if(!e||"characters"!==r)return;let t=new AbortController;return b(null),Promise.all([fetch("/api/auth/all-providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}),fetch("/api/auth/providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()})]).then(([e,r])=>{if(t.signal.aborted)return;let n=new Map(e.providers.map(e=>[e.id,e.configured]));for(let e of r.providers)n.set(e.id,!0===n.get(e.id)||e.loggedIn);b(n)}).catch(()=>{t.signal.aborted||b(null)}),()=>t.abort()},[r,e,d.data]),(0,a.useEffect)(()=>{var n;let a,i,s,o,l,c,d,u,p,h;if(f(null),!e||"usage"!==r||!t)return;let m=(i=(n={onClear(){f(null)},onResult(e){f("fresh"===e.status?e.data:null)}}).intervalMs??2500,s=n.setIntervalImpl??setInterval,o=n.clearIntervalImpl??clearInterval,l=null,c=null,d=0,u=!1,p=()=>{o(a),a=void 0},h=async e=>{c?.abort();let t=c=new AbortController,r=++d,a=await n0(e,{signal:t.signal,fetchImpl:n.fetchImpl});u||r!==d||l!==e||t.signal.aborted||n.onResult(a)},{setSessionId(e){u||e===l||(d+=1,c?.abort(),c=null,p(),l=e,n.onClear(e),e&&(h(e),a=s(()=>{l&&h(l)},i)))},stop(){u||(u=!0,d+=1,c?.abort(),c=null,p(),l=null)}});return T.current=m,m.setSessionId(t),()=>{m.stop(),T.current===m&&(T.current=null)}},[r,e,t]);let $=(0,a.useCallback)(async e=>{I.current?.abort();let t=new AbortController;I.current=t,x(!0);let r=await n1({refresh:e,previous:N.current.data,signal:t.signal});I.current!==t||t.signal.aborted||(h(r),x(!1))},[]);(0,a.useEffect)(()=>{e&&"models"===r&&("idle"===N.current.status||"error"===N.current.status)&&$(!1)},[r,e,$]),(0,a.useEffect)(()=>()=>{for(let e of(I.current?.abort(),M.current))e.abort()},[]);let R=(0,a.useCallback)(()=>{"models"===r?$(!0):(o.refresh(),C(e=>e+1))},[r,$,o]),L=(0,a.useCallback)(()=>o.refresh(),[o]),A=(0,a.useCallback)(async e=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let t=e.credentialId,r=n7(E.current,t);if(!r)return;let n=new AbortController;M.current.add(n),o.setPaused(!0),w(e=>new Map(e).set(t,"toggle")),j(e=>{let r=new Map(e);return r.delete(t),r});try{await n6(t,!0===e.disabled,{signal:n.signal});let r=await L();n.signal.aborted||j(n=>new Map(n).set(t,{tone:"status",message:"fresh"===r.status?`계정을 ${e.disabled?"켰습니다":"껐습니다"}.`:"계정 설정 저장됨 \xb7 표시 상태 새로고침 실패."}))}catch(e){if(!n.signal.aborted){let r=e instanceof nK&&("timeout"===e.kind||e.outcomeUnknown);j(n=>new Map(n).set(t,r?{tone:"error",message:"적용 여부 확인 필요 — 새로고침으로 계정 상태를 확인하세요."}:{tone:"error",message:`계정 전환 실패: ${e instanceof Error?e.message:String(e)}`}))}}finally{M.current.delete(n),r(),o.setPaused(E.current.size>0),w(e=>{let r=new Map(e);return r.delete(t),r})}},[L,o]),P=(0,a.useCallback)(async(e,t)=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let r=e.credentialId,n=n7(E.current,r);if(!n)return;let a=new AbortController;M.current.add(a),o.setPaused(!0),w(e=>new Map(e).set(r,"reset")),j(e=>{let t=new Map(e);return t.delete(r),t});try{let e=await n3(r,t,{signal:a.signal}),n=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),i=await L();if(e.ok){let e="fresh"===i.status?i.data.reports.find(e=>e.credentialId===r):void 0,t=e?.savedReset?.availableCount;n.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}a.signal.aborted||j(e=>new Map(e).set(r,n))}catch(e){e instanceof nK&&(e.outcomeUnknown||"timeout"===e.kind)&&!a.signal.aborted&&await L(),a.signal.aborted||j(t=>new Map(t).set(r,function(e){if(e instanceof nK){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{M.current.delete(a),n(),o.setPaused(E.current.size>0),w(e=>{let t=new Map(e);return t.delete(r),t})}},[L,o]);if(!e)return null;let F="models"===r?p.data?.generatedAt:d.data?.generatedAt,_="models"===r?p.data?.range:void 0,z=_?.from&&_.to?`${gd(_.from)}~${gd(_.to)}`:F?new Date(F).toLocaleTimeString():"",W="models"===r?g:"usage"===r&&u,O=W?"models"===r?"집계 중…":"불러오는 중…":"새로고침";return(0,n.jsxs)("section",{className:gt("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",l),"aria-labelledby":c,"aria-busy":W,children:[(0,n.jsx)("h1",{id:c,className:"sr-only",children:"캐릭터"}),(0,n.jsxs)(fI.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:r,onValueChange:e=>i(e),children:[(0,n.jsxs)(fI.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,n.jsx)(fI.J.Trigger,{value:"characters",children:"캐릭터"}),(0,n.jsx)(fI.J.Trigger,{value:"usage",children:"계정 한도"}),(0,n.jsx)(fI.J.Trigger,{value:"models",children:"모델 통계"}),(0,n.jsx)(fI.J.Indicator,{})]}),(0,n.jsx)(fI.J.Content,{value:"characters",className:"resource-view-content",children:(0,n.jsx)(gD,{reports:d.data?.reports,providerConnections:v})}),(0,n.jsxs)(fI.J.Content,{value:"usage",className:"resource-view-content",children:[(0,n.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:z}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:W,children:O})]}),(0,n.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,n.jsx)(gy,{state:d,loading:u,accountState:m?.sessionId===t?m:null,pendingActions:y,feedbackByCredential:k,onToggle:e=>{A(e)},onReset:P}),(0,n.jsx)(gF,{refreshToken:S})]}),(0,n.jsxs)(fI.J.Content,{value:"models",className:"resource-view-content",children:[(0,n.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:z}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:R,disabled:W,children:O})]}),(0,n.jsx)(gO,{state:p,loading:g})]})]})]})}let gU="unknown",gB="/api/runs";class gq extends Error{constructor(e,t,r=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=r}}let gV=["completed","error","aborted","interrupted","running"],gK=["main","maker","checker","advisor","unattributed"],gG=["primary","rework","review"],gJ=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],gZ=["all","attributed"],gY=["single","unknown"],gX=["config","harness"];function gQ(e){return"object"==typeof e&&null!==e}function g0(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function g1(e){return!!gQ(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&&gV.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 g2(e){return!!gQ(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&gK.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&gG.includes(e.purpose))&&g0(e.models)&&g0(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 g8(e){return!!gQ(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 g4(e){return!!gQ(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 g5(e){return!!gQ(e)&&"string"==typeof e.kind&&gK.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)&&g0(e.models)&&g0(e.efforts)&&gY.includes(e.pairing)}function g6(e){return!!gQ(e)&&(null===e.revision||"string"==typeof e.revision)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)}function g3(e){return!!gQ(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(g5)&&"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(g6)}function g7(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&gJ.includes(e))}async function g9(e){try{return await e.json()}catch{throw new gq("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}let xe={groupBy:"config",harness:null};function xt(e,t){return e instanceof gq||e instanceof Error?e.message:t}function xr(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function xn(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 xa(e){if("number"!=typeof e||!Number.isFinite(e))return"—";let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;let r=Math.round(t/1e3);if(r<60)return`${(t/1e3).toFixed(1)}s`;let n=Math.floor(r/60),a=r-60*n;return n<60?0===a?`${n}m`:`${n}m ${a}s`:`${Math.floor(n/60)}h ${n%60}m`}let xi={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"},xs={ok:"efficiency.sawToolOk",failed:"efficiency.sawToolFailed",noMatch:"efficiency.sawToolNoMatch",cancelled:"efficiency.sawToolCancelled",missing:"efficiency.sawToolMissing"},xo={failed:"critical",noMatch:"neutral",cancelled:"neutral",missing:"warning"};async function xl(e,t){let r,n=await fetch(e,{method:"GET",signal:t});try{r=await n.json()}catch{throw Error(`HTTP ${n.status}: invalid JSON`)}if(!n.ok)throw Error(r&&"object"==typeof r&&"error"in r&&"string"==typeof r.error?r.error:`HTTP ${n.status}`);if(null===r)throw Error(`HTTP ${n.status}: empty body`);return r}function xc(e,t,r){return`${gB}/${encodeURIComponent(e)}/${t}?${new URLSearchParams(r).toString()}`}function xd(e){return e>0?new Date(e).toLocaleTimeString(void 0,{hour12:!1}):"—"}function xu({runId:e,role:t,entryId:r,call:i,label:s,t:o}){let[l,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)({status:"idle",value:null,error:null});return(0,n.jsxs)("div",{className:"run-saw-full-wrap",children:[(0,n.jsx)("button",{type:"button",className:"run-saw-link","aria-expanded":l,onClick:()=>{let n=!l;if(c(n),!n||"ready"===d.status||"loading"===d.status)return;u({status:"loading",value:null,error:null});let a={role:t,entry:r};i&&(a.call=i),xl(xc(e,"turns",a)).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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("pre",{className:"run-saw-full",children:d.value.text}),d.value.truncated?(0,n.jsx)("p",{className:"run-saw-dim",children:o("efficiency.sawTruncated",{value:xr(d.value.text.length)})}):null]}):"error"===d.status?(0,n.jsx)("p",{className:"run-saw-dim",role:"alert",children:d.error}):(0,n.jsx)("p",{className:"run-saw-dim",role:"status",children:o("efficiency.sawLoading")}):null]})}function xp({event:e,runId:t,role:r,t:a}){let i=e.preview;if("compaction"===e.kind&&(null!=e.tokensBefore||null!=e.tokensAfter)){let t=a("efficiency.sawCompactionValue",{before:xn(e.tokensBefore??null),after:xn(e.tokensAfter??null)});i=i?`${t} \xb7 ${i}`:t}else void 0!==e.memoryIds&&(i=a("efficiency.sawMemoryIds",{value:e.memoryIds}));return(0,n.jsxs)("li",{className:"run-saw-event",children:[(0,n.jsxs)("div",{className:"run-saw-event-head",children:[(0,n.jsx)("span",{className:"run-saw-kind",children:a(xi[e.kind])}),(0,n.jsx)("span",{className:"run-saw-source",children:e.source}),(0,n.jsx)("span",{className:"run-saw-dim",children:xd(e.at)}),e.hiddenFromChat?(0,n.jsx)("span",{className:"run-saw-dim",children:a("efficiency.sawHiddenFromChat")}):null,e.sentToModel?null:(0,n.jsx)("span",{className:"run-saw-dim",children:a("efficiency.sawNotSent")})]}),i?(0,n.jsx)("p",{className:"run-saw-preview",children:i}):null,e.chars>e.preview.length?(0,n.jsx)(xu,{runId:t,role:r,entryId:e.entryId,call:null,label:a("efficiency.sawShowFull"),t:a}):null]})}function xh({call:e,runId:t,role:r,turnEntryId:a,t:i}){return(0,n.jsxs)("li",{className:"run-saw-tool",children:[(0,n.jsxs)("div",{className:"run-saw-tool-head",children:[(0,n.jsx)("span",{className:"run-saw-tool-name",children:e.name}),(0,n.jsx)("span",{className:"run-saw-num",children:xa(e.durationMs)}),null!==e.resultChars?(0,n.jsx)("span",{className:"run-saw-dim",children:i("efficiency.sawResultChars",{value:xr(e.resultChars)})}):null,"ok"!==e.status?(0,n.jsx)(rT.E,{tone:xo[e.status],variant:"weak",size:"medium",children:i(xs[e.status])}):null]}),(0,n.jsx)("code",{className:"run-saw-args",children:e.argsPreview}),(0,n.jsxs)("div",{className:"run-saw-tool-actions",children:[e.argsChars>e.argsPreview.length?(0,n.jsx)(xu,{runId:t,role:r,entryId:a,call:e.toolCallId,label:i("efficiency.sawShowArgs"),t:i}):null,e.resultEntryId?(0,n.jsx)(xu,{runId:t,role:r,entryId:e.resultEntryId,call:null,label:i("efficiency.sawShowResult"),t:i}):null]})]})}function xm({turn:e,runId:t,role:r,t:a}){let i=[e.model,xa(e.durationMs),e.usage?a("efficiency.sawUsage",{input:xn(e.usage.input),output:xn(e.usage.output),cacheRead:xn(e.usage.cacheRead)}):null,e.stopReason?a("efficiency.sawStop",{value:e.stopReason}):null].filter(Boolean).join(" \xb7 ");return(0,n.jsxs)("li",{className:"run-saw-turn",children:[(0,n.jsxs)("div",{className:"run-saw-turn-head",children:[(0,n.jsx)("span",{className:"run-saw-turn-label",children:a("efficiency.sawTurnLabel",{index:e.index})}),(0,n.jsx)("span",{className:"run-saw-dim",children:xd(e.at)})]}),(0,n.jsx)("p",{className:"run-saw-turn-meta",children:i}),e.toolsAdded.length>0||e.toolsRemoved.length>0?(0,n.jsx)("p",{className:"run-saw-dim",title:[...e.toolsAdded.map(e=>`+${e}`),...e.toolsRemoved.map(e=>`−${e}`)].join(" "),children:a("efficiency.sawToolsChanged",{added:e.toolsAdded.join(", ")||"0",removed:e.toolsRemoved.join(", ")||"0"})}):null,e.before.length>0?(0,n.jsxs)("div",{className:"run-saw-group",children:[(0,n.jsx)("p",{className:"run-saw-group-label",children:a("efficiency.sawBefore")}),(0,n.jsx)("ul",{className:"run-saw-events",children:e.before.map(e=>(0,n.jsx)(xp,{event:e,runId:t,role:r,t:a},e.entryId))})]}):null,e.toolCalls.length>0?(0,n.jsx)("ul",{className:"run-saw-tools",children:e.toolCalls.map(i=>(0,n.jsx)(xh,{call:i,runId:t,role:r,turnEntryId:e.entryId,t:a},i.toolCallId))}):null]})}function xf({runId:e,role:t,t:r}){let[i,o]=(0,a.useState)(null),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let r=new AbortController;return o(null),c(null),xl(xc(e,"prelude",{role:t}),r.signal).then(o).catch(e=>{r.signal.aborted||c(e instanceof Error?e.message:String(e))}),()=>r.abort()},[e,t]);let p=i?.recorded.digests.at(-1)??null,h=i?.rebuilt;return(0,n.jsxs)("section",{className:"run-saw-prelude","aria-label":r("efficiency.sawPreludeTitle"),children:[(0,n.jsx)("h4",{className:"run-saw-subtitle",children:r("efficiency.sawPreludeTitle")}),l?(0,n.jsx)("p",{className:"run-saw-dim",role:"alert",children:l}):null,i||l?null:(0,n.jsx)("p",{className:"run-saw-dim",role:"status",children:r("efficiency.sawLoading")}),i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"run-saw-group-label",children:r("efficiency.sawPreludeRecorded")}),(0,n.jsx)("p",{className:"run-saw-line",children:p?r("efficiency.sawPreludeDigest",{value:p.digest}):r("efficiency.sawPreludeDigestNone")}),i.recorded.activeTools?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"run-saw-line",children:r("efficiency.sawPreludeTools",{value:i.recorded.activeTools.length})}),(0,n.jsx)("p",{className:"run-saw-names",children:i.recorded.activeTools.join(" \xb7 ")})]}):null,i.recorded.memoryRecall?(0,n.jsxs)("div",{className:"run-saw-group",children:[(0,n.jsx)("p",{className:"run-saw-line",children:r("efficiency.sawPreludeMemory")}),(0,n.jsx)("p",{className:"run-saw-preview",children:i.recorded.memoryRecall.preview}),i.recorded.memoryRecall.chars>i.recorded.memoryRecall.preview.length?(0,n.jsx)(xu,{runId:e,role:t,entryId:i.recorded.memoryRecall.entryId,call:null,label:r("efficiency.sawShowFull"),t:r}):null]}):null,h?.status==="not-loaded"?(0,n.jsx)("p",{className:"run-saw-approx",children:r("efficiency.sawPreludeNotLoaded")}):h?.status==="available"?(0,n.jsx)("div",{className:"run-saw-actions",children:(0,n.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{u(!0),xl(xc(e,"prelude",{role:t,rebuild:"1"})).then(o).catch(e=>c(e instanceof Error?e.message:String(e))).finally(()=>u(!1))},disabled:d,children:r(d?"efficiency.sawPreludeLoading":"efficiency.sawPreludeReconstruct")})}):h?.status==="rebuilt"?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"run-saw-approx",children:r("efficiency.sawPreludeApprox")}),null!==h.matchesRecorded?(0,n.jsx)("p",{className:"run-saw-line",children:r(h.matchesRecorded?"efficiency.sawPreludeMatch":"efficiency.sawPreludeMismatch")}):null,(0,n.jsx)("pre",{className:"run-saw-full",children:h.text}),h.truncated?(0,n.jsx)("p",{className:"run-saw-dim",children:r("efficiency.sawTruncated",{value:xr(h.text.length)})}):null]}):null]}):null]})}let xg={status:"idle",page:null,turns:[],loadingMore:!1,error:null};function xx({runId:e,t}){let[r,i]=(0,a.useState)(!1),[o,c]=(0,a.useState)("main"),[d,u]=(0,a.useState)(!1),[p,h]=(0,a.useState)(xg),m=(0,a.useRef)(null),f=(0,a.useCallback)(t=>{m.current?.abort();let r=new AbortController;m.current=r,h(e=>0===t?{...xg,status:"loading"}:{...e,loadingMore:!0});let n={role:o,offset:String(t),limit:String(30)};d&&(n.injectedOnly="1"),xl(xc(e,"turns",n),r.signal).then(e=>h(r=>({status:"ready",page:e,turns:0===t?e.turns:[...r.turns,...e.turns],loadingMore:!1,error:null}))).catch(e=>{r.signal.aborted||h(r=>({...r,status:0===t?"error":r.status,loadingMore:!1,error:e instanceof Error?e.message:String(e)}))})},[e,o,d]);(0,a.useEffect)(()=>{r&&f(0)},[r,f]),(0,a.useEffect)(()=>()=>m.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,n.jsxs)("section",{className:"run-saw","aria-label":t("efficiency.sawSection"),children:[(0,n.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.sawSection")}),(0,n.jsx)("p",{className:"run-saw-approx",children:t("efficiency.sawApproxNote")}),r?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"run-saw-controls",children:[g&&g.roles.length>1?(0,n.jsxs)("label",{className:"run-saw-role",children:[(0,n.jsx)("span",{children:t("efficiency.sawRole")}),(0,n.jsx)("select",{className:"efficiency-folder-select",value:o,onChange:e=>c(e.target.value),children:g.roles.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]}):null,(0,n.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:d,onPressedChange:u,children:t("efficiency.sawOnlyInjected")})]}),"loading"===p.status||"idle"===p.status?(0,n.jsx)("p",{className:"efficiency-empty",role:"status",children:t("efficiency.sawLoading")}):"error"===p.status?(0,n.jsxs)("div",{className:"efficiency-empty",role:"alert",children:[(0,n.jsx)("div",{children:t("efficiency.sawError")}),(0,n.jsx)("div",{className:"run-saw-dim",children:p.error})]}):g?(0,n.jsxs)(n.Fragment,{children:[(0,n.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,n.jsx)("p",{className:"run-saw-names",children:v.map(([e,t])=>`${e} ${t}`).join(" \xb7 ")}):null,(0,n.jsx)("p",{className:"run-saw-dim run-saw-pad",children:t("efficiency.sawSecretsMasked")}),0===p.turns.length?(0,n.jsx)("p",{className:"efficiency-empty",children:t(d?"efficiency.sawFilterEmpty":"efficiency.sawEmpty")}):(0,n.jsx)("ol",{className:"run-saw-turns",children:p.turns.map(r=>(0,n.jsx)(xm,{turn:r,runId:e,role:g.role,t:t},r.entryId))}),g.trailing.length>0&&x<=0?(0,n.jsxs)("div",{className:"run-saw-group run-saw-trailing",children:[(0,n.jsx)("p",{className:"run-saw-group-label",children:t("efficiency.sawTrailing")}),(0,n.jsx)("ul",{className:"run-saw-events",children:g.trailing.map(r=>(0,n.jsx)(xp,{event:r,runId:e,role:g.role,t:t},r.entryId))})]}):null,(0,n.jsxs)("div",{className:"run-saw-actions",children:[(0,n.jsx)("span",{className:"run-saw-dim",children:t("efficiency.sawShown",{shown:p.turns.length,total:g.total})}),x>0?(0,n.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>f(p.turns.length),disabled:p.loadingMore,children:p.loadingMore?t("efficiency.sawLoading"):t("efficiency.sawMore",{value:Math.min(x,30)})}):null]}),p.error?(0,n.jsx)("p",{className:"run-saw-dim run-saw-pad",role:"alert",children:p.error}):null,(0,n.jsx)(xf,{runId:e,role:g.role,t:t})]}):null]}):(0,n.jsx)("div",{className:"run-saw-actions",children:(0,n.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>i(!0),children:t("efficiency.sawOpen")})})]})}let xv={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},xb={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function xy(...e){return e.filter(Boolean).join(" ")}function xw(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 xk(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function xj(e,t){return null===e?t("efficiency.harnessUnknown"):e.slice(0,7)}function xS({label:e,value:t}){return(0,n.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,n.jsx)("dt",{className:"min-w-0 flex-1 text-xs text-text-muted [overflow-wrap:anywhere]",children:e}),(0,n.jsx)("dd",{className:"m-0 flex-none text-right font-mono text-xs tabular-nums text-text",children:t})]})}function xC({share:e,label:t}){let r=Number.isFinite(e)?Math.max(1,Math.min(100,100*e)):1;return(0,n.jsxs)("div",{className:"efficiency-bar","aria-hidden":"true",children:[(0,n.jsx)("div",{className:"efficiency-bar-fill",style:{width:`${r}%`}}),(0,n.jsx)("span",{className:"efficiency-bar-value",children:t})]})}function xN({costUsd:e,unpriced:t,t:r}){return(0,n.jsxs)("span",{className:"font-mono tabular-nums",children:[r("efficiency.estimatedCostValue").replace("{value}",xw(e)),t>0?` \xb7 ${r("efficiency.unpricedLowerBound")}`:""]})}function xT({outcome:e,t}){return(0,n.jsx)(rT.E,{tone:xv[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function xI({purpose:e,t}){return null===e?(0,n.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,n.jsx)(rT.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 xM({run:e,selected:t,onSelect:r,t:a}){let i=e.title&&e.title.trim().length>0?e.title:a("efficiency.noTitle");return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",onClick:r,"aria-current":t?"true":void 0,className:xy("efficiency-run-item",t&&"is-selected"),children:[(0,n.jsxs)("span",{className:"efficiency-run-top",children:[(0,n.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,n.jsx)("span",{className:"efficiency-run-title",title:i,children:i}),(0,n.jsx)(xT,{outcome:e.outcome,t:a})]}),(0,n.jsxs)("span",{className:"efficiency-run-meta",children:[(0,n.jsx)("span",{className:"font-mono tabular-nums",children:a("efficiency.elapsedValue").replace("{value}",xa(e.wallClockMs))}),(0,n.jsx)(xN,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:a}),(0,n.jsx)("span",{className:"font-mono tabular-nums",title:e.harnessRevision??a("efficiency.harnessUnknown"),children:a("efficiency.harnessValue").replace("{value}",xj(e.harnessRevision,a))})]})]})})}function xE({role:e,t}){let r=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),a=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort"),i=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,n.jsxs)("details",{className:"efficiency-role",children:[(0,n.jsxs)("summary",{className:"efficiency-role-summary",children:[(0,n.jsxs)("span",{className:"efficiency-role-head",children:[(0,n.jsx)("span",{className:"efficiency-role-id",children:e.id}),(0,n.jsx)(rT.E,{tone:xb[e.kind]??"neutral",variant:"weak",size:"medium",children:s}),(0,n.jsx)(xI,{purpose:e.purpose,t:t})]}),(0,n.jsx)("span",{className:"efficiency-model-line",title:r,children:r}),(0,n.jsxs)("span",{className:"efficiency-role-stats",children:[(0,n.jsxs)("span",{children:[t("efficiency.busyTime")," ",(0,n.jsx)("span",{className:"efficiency-role-stat-value",children:xa(e.busyMs)})]}),(0,n.jsxs)("span",{children:[t("efficiency.estimatedCost")," ",(0,n.jsx)("span",{className:"efficiency-role-stat-value",children:xw(e.estimatedCostUsd)})]}),(0,n.jsxs)("span",{children:[t("efficiency.tokens")," ",(0,n.jsx)("span",{className:"efficiency-role-stat-value",children:xn(e.totalTokens)})]})]})]}),(0,n.jsxs)("div",{className:"efficiency-role-body",children:[(0,n.jsxs)("p",{className:"efficiency-dim",children:[t("efficiency.effortLabel").replace("{value}",a),` \xb7 ${t("efficiency.requestsValue").replace("{value}",String(e.requestCount))}`,` \xb7 ${t("efficiency.toolCallsValue").replace("{value}",String(e.toolCalls))}`]}),(0,n.jsxs)("dl",{className:"efficiency-metrics",children:[(0,n.jsx)(xS,{label:t("efficiency.unpricedRequests"),value:xr(e.unpricedRequests)}),(0,n.jsx)(xS,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?xa(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,n.jsx)(xS,{label:t("efficiency.outputTokens"),value:xn(i)})]}),e.ttftRequests>0&&e.ttftRequests<e.requestCount?(0,n.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.firstTokenPartial",{recorded:e.ttftRequests,total:e.requestCount})}):null,e.untimedRequests>0?(0,n.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.untimedLowerBound").replace("{value}",xr(e.untimedRequests))}):null,e.unpricedRequests>0?(0,n.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.unpricedLowerBound")}):null,e.helpers.length>0?(0,n.jsxs)("section",{className:"efficiency-helpers","aria-label":t("efficiency.helpersTitle"),children:[(0,n.jsx)("h4",{className:"efficiency-helpers-title",children:t("efficiency.helpersTitle")}),(0,n.jsx)("ul",{className:"efficiency-helper-list",children:e.helpers.map(e=>(0,n.jsxs)("li",{className:"efficiency-helper",children:[(0,n.jsx)("span",{className:"efficiency-helper-name",children:`${e.purpose} \xb7 ${e.model}`}),(0,n.jsx)("span",{className:"efficiency-helper-value",children:t("efficiency.helperCallsValue",{count:e.requestCount,output:xn(e.outputTokens),tokens:xn(e.totalTokens),cost:xw(e.estimatedCostUsd)})})]},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,n.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.helpersIncludedNote")})]}):null]})]})}function x$({item:e,t}){let r="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,n.jsxs)("li",{className:"efficiency-bottleneck","data-kind":e.kind,children:[(0,n.jsx)("span",{className:"efficiency-bottleneck-label",children:r}),(0,n.jsx)("span",{className:"efficiency-meter","aria-hidden":"true",children:(0,n.jsx)("span",{className:"efficiency-meter-fill",style:{inlineSize:`${Number.isFinite(e.relative)?Math.max(1,Math.min(100,100*e.relative)):1}%`}})}),(0,n.jsx)("span",{className:"efficiency-bottleneck-value",children:xa(e.ms)})]})}function xR({detail:e,t}){return(0,n.jsxs)("div",{className:"efficiency-detail",children:[(0,n.jsxs)("section",{"aria-label":t("efficiency.summarySection"),children:[(0,n.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.summarySection")}),(0,n.jsxs)("div",{className:"efficiency-dual",children:[(0,n.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,n.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.elapsed")}),(0,n.jsx)("span",{className:"efficiency-dual-value",children:xa(e.wallClockMs)})]}),(0,n.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,n.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.busyTotal")}),(0,n.jsx)("span",{className:"efficiency-dual-value",children:xa(e.busyMs)})]})]}),(0,n.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,n.jsxs)("dl",{className:"efficiency-metrics",children:[(0,n.jsx)(xS,{label:t("efficiency.estimatedCost"),value:xw(e.estimatedCostUsd)}),(0,n.jsx)(xS,{label:t("efficiency.tokens"),value:xn(e.totalTokens)}),(0,n.jsx)(xS,{label:t("efficiency.harness"),value:xj(e.harnessRevision,t)})]}),e.unpricedRequests>0?(0,n.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(0,n.jsxs)("section",{"aria-label":t("efficiency.bottlenecksSection"),children:[(0,n.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.bottlenecksSection")}),(0,n.jsx)("p",{className:"efficiency-note",children:t("efficiency.bottleneckOrderNote")}),e.bottlenecks.length>0?(0,n.jsx)("ol",{className:"efficiency-bottlenecks",children:e.bottlenecks.map(e=>(0,n.jsx)(x$,{item:e,t:t},`${e.kind}:${e.id}`))}):(0,n.jsx)("p",{className:"efficiency-empty",children:t("efficiency.bottlenecksEmpty")}),e.unmeasuredMs>0?(0,n.jsx)("p",{className:"efficiency-note",children:t("efficiency.unmeasuredGapValue").replace("{value}",xa(e.unmeasuredMs))}):null]}),(0,n.jsxs)("section",{"aria-label":t("efficiency.rolesSection"),children:[(0,n.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.rolesSection")}),e.roles.length>0?(0,n.jsx)("div",{className:"efficiency-roles",children:e.roles.map(e=>(0,n.jsx)(xE,{role:e,t:t},e.id))},e.runId):(0,n.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),e.toolTotals.length>0?(0,n.jsxs)("section",{"aria-label":t("efficiency.toolsSection"),children:[(0,n.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.toolsSection")}),(0,n.jsx)("dl",{className:"efficiency-metrics",children:e.toolTotals.map(e=>(0,n.jsx)(xS,{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:xr(e.calls)},e.toolName))})]}):null,(0,n.jsx)(xx,{runId:e.runId,t:t},e.runId)]})}function xL(e){return e.map(e=>{let t=e.effort??"–",r=e.count>1?` x${e.count}`:"";return`${e.kind} ${e.model}:${t}${r}`}).join(" \xb7 ")}function xA({response:e,t}){return(0,n.jsx)("section",{className:"efficiency-card",children:(0,n.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,n.jsx)(xS,{label:t("efficiency.scopeSessions"),value:xr(e.sessionCount)}),(0,n.jsx)(xS,{label:t("efficiency.scopeRuns"),value:xr(e.runCount)}),(0,n.jsx)(xS,{label:t("efficiency.scopeExcludedRuns"),value:xr(e.excludedRunCount)})]})})}function xP({config:e,baselineRuns:t,t:r}){let a=t>0?e.runCount/t:0,i=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:xj(e[0].revision,t),full:e[0].revision??t("efficiency.harnessUnknown")};let r=e.map(e=>`${xj(e.revision,t)} \xd7${e.runCount}`),n=r.slice(0,4).join(" \xb7 ");return{text:r.length>4?`${n} \xb7 +${r.length-4}`:n,full:e.map(e=>`${e.revision??t("efficiency.harnessUnknown")} \xd7${e.runCount}`).join("\n")}}(e.harnesses,r);return(0,n.jsxs)("section",{className:"efficiency-card",children:[(0,n.jsx)("p",{className:"efficiency-model-line",title:xL(e.roles),children:xL(e.roles)}),(0,n.jsx)("p",{className:"efficiency-dim font-mono tabular-nums",title:o.full,children:r("efficiency.harnessValue").replace("{value}",o.text)}),e.roles.some(e=>"unknown"===e.pairing)?(0,n.jsx)("p",{className:"efficiency-note",children:r("efficiency.mixedPairingNote")}):null,(0,n.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,n.jsx)("span",{className:"efficiency-dim",children:r("efficiency.runsValue").replace("{value}",String(e.runCount))}),(0,n.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:xk(a)})]}),(0,n.jsx)(xC,{share:a,label:xk(a)}),(0,n.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,n.jsx)(xS,{label:r("efficiency.medianElapsed"),value:xa(e.medianWallClockMs)}),(0,n.jsx)(xS,{label:r("efficiency.medianBusy"),value:xa(e.medianBusyMs)}),(0,n.jsx)(xS,{label:r("efficiency.medianTokens"),value:xn(e.medianTotalTokens)}),(0,n.jsx)(xS,{label:r("efficiency.medianEstimatedCost"),value:xw(e.medianEstimatedCostUsd)}),(0,n.jsx)(xS,{label:r("efficiency.totalEstimatedCost"),value:xw(e.totalEstimatedCostUsd)}),(0,n.jsx)(xS,{label:r("efficiency.reworkRate"),value:xk(i,1)}),(0,n.jsx)(xS,{label:r("efficiency.errorRate"),value:xk(s,1)}),(0,n.jsx)(xS,{label:r("efficiency.unpricedRuns"),value:xr(e.unpricedRuns)}),(0,n.jsx)(xS,{label:r("efficiency.untimedRuns"),value:xr(e.untimedRuns)})]}),e.untimedRuns>0?(0,n.jsx)("p",{className:"efficiency-note",children:r("efficiency.untimedMedianLowerBound").replace("{value}",xr(e.untimedRuns))}):null,e.unpricedRuns>0?(0,n.jsx)("p",{className:"efficiency-note",children:r("efficiency.unpricedLowerBound")}):null]})}function xF({open:e,sessionId:t,activeTab:r,onTabChange:i,client:o,className:c}){let d=(0,a.useId)(),u=(0,a.useId)(),{t:p}=(0,z.s)(),h=function({sessionId:e,visible:t,activeTab:r,client:n}){let[i]=(0,a.useState)(()=>n??function(e=(e,t)=>fetch(e,t)){let t=async(t,r)=>{let n;try{n=await e(t,r)}catch(e){if(r.signal?.aborted)throw e;throw new gq("unreachable","효율 기록에 연결할 수 없습니다.")}let a=await g9(n);if(!n.ok){var i;throw new gq("http",(i=`HTTP ${n.status}`,null!==a&&"object"==typeof a&&"error"in a&&"string"==typeof a.error&&a.error?a.error:i),n.status)}return{response:n,body:a}};return{async listRuns(e,r,n){let{response:a,body:i}=await t(`${gB}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(r))}`,{method:"GET",signal:n});return function(e,t,r=null){try{if(!gQ(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(g1)&&g7(e.unmeasured)))throw new gq("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new gq("invalid-response",t,r)}}(i,"실행 목록 응답이 올바르지 않습니다.",a.status)},async getRun(e,r){let{response:n,body:a}=await t(`${gB}/${encodeURIComponent(e)}`,{method:"GET",signal:r});return function(e,t,r=null){try{if(!g1(e)||!(Array.isArray(e.roles)&&e.roles.every(g2)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(g8)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(g4)&&g7(e.unmeasured)))throw new gq("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new gq("invalid-response",t,r)}}(a,"실행 상세 응답이 올바르지 않습니다.",n.status)},async listExperiments(e,r,n,a,i){let s=new URLSearchParams;null!==e&&""!==e&&s.set("folder",e),s.set("sessions",String(r)),s.set("scope",n),i?.groupBy==="harness"&&s.set("groupBy","harness"),i?.harness&&s.set("harness",i.harness);let{response:o,body:l}=await t(`/api/experiments?${s.toString()}`,{method:"GET",signal:a});return function(e,t,r=null){try{if(!gQ(e)||!((null===e.folder||"string"==typeof e.folder)&&g0(e.folders)&&"string"==typeof e.scope&&gZ.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(g3)&&"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&&gX.includes(e.groupBy)&&(null===e.harness||"string"==typeof e.harness)&&Array.isArray(e.harnesses)&&e.harnesses.every(g6)&&g7(e.unmeasured)))throw new gq("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new gq("invalid-response",t,r)}}(l,"구성 비교 응답이 올바르지 않습니다.",o.status)}}}()),[s,o]=(0,a.useState)({status:"idle",runs:[],error:null}),[l,c]=(0,a.useState)({status:"idle",runId:null,detail:null,error:null}),[d,u]=(0,a.useState)({status:"idle",response:null,error:null}),[p,h]=(0,a.useState)(null),[m,f]=(0,a.useState)(null),g=(0,a.useRef)(null),x=(0,a.useRef)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null);(0,a.useEffect)(()=>{x.current?.abort(),x.current=null,h(null),c({status:"idle",runId:null,detail:null,error:null}),o({status:"idle",runs:[],error:null})},[e]);let y=(0,a.useCallback)(()=>{if(!t||"governor"!==r||!e)return;g.current?.abort();let n=new AbortController;g.current=n,o(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),i.listRuns(e,20,n.signal).then(e=>{if(!n.signal.aborted&&g.current===n){if(0===e.runs.length)return void o({status:"empty",runs:[],error:null});o({status:"ready",runs:e.runs,error:null})}}).catch(e=>{n.signal.aborted||g.current!==n||o({status:"error",runs:[],error:xt(e,"실행 목록을 불러오지 못했습니다.")})})},[r,i,e,t]),w=(0,a.useCallback)(e=>{if(!t)return;x.current?.abort();let r=new AbortController;x.current=r,c({status:"loading",runId:e,detail:null,error:null}),i.getRun(e,r.signal).then(t=>{r.signal.aborted||x.current!==r||c({status:"ready",runId:e,detail:t,error:null})}).catch(t=>{r.signal.aborted||x.current!==r||c({status:"error",runId:e,detail:null,error:xt(t,"실행 상세를 불러오지 못했습니다.")})})},[i,t]),k=(0,a.useCallback)((e,n="all",a=xe)=>{if(!t||"lab"!==r)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})),i.listExperiments(e,30,n,s.signal,a).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:xt(e,"구성 비교를 불러오지 못했습니다.")})})},[r,i,t]);(0,a.useEffect)(()=>{if(t&&"governor"===r)return y(),()=>{g.current?.abort(),g.current=null}},[r,y,e,t]),(0,a.useEffect)(()=>{if(t&&"lab"===r)return k(b.current),()=>{v.current?.abort(),v.current=null}},[r,k,t]),(0,a.useEffect)(()=>{if(t&&"governor"===r&&null!==p)return w(p),()=>{x.current?.abort(),x.current=null}},[r,w,p,t]),(0,a.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,a.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,a.useCallback)(()=>{y()},[y]),refreshExperiments:(0,a.useCallback)((e,t="all",r=xe)=>{let n=void 0===e?b.current:e;void 0!==e&&(b.current=e,f(e)),k(n,t,r)},[k]),experimentFolder:m}}({sessionId:t,visible:e,activeTab:r,client:o}),[m,f]=(0,a.useState)(""),g=(0,a.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),x=(0,a.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),v=h.experimentFolder,b=h.experiments.response?.scope??"all",y={groupBy:h.experiments.response?.groupBy??"config",harness:h.experiments.response?.harness??null},w=h.experiments.response?.harnesses??[];if(!e)return null;let k="governor"===r&&"loading"===h.list.status||"lab"===r&&"loading"===h.experiments.status,j=k?p("efficiency.refreshing"):p("efficiency.refresh"),S="governor"===r?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,n.jsxs)("section",{className:xy("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,n.jsxs)("header",{className:"flex min-h-12 items-center gap-3 border-b border-border bg-bg px-3",children:[(0,n.jsx)("h1",{id:d,className:"m-0 text-sm font-semibold text-text",children:p("efficiency.title")}),(0,n.jsx)("span",{className:"min-w-0 flex-1 truncate text-right font-mono text-[11px] tabular-nums text-text-dim",children:S}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===r?h.refreshRuns():h.refreshExperiments(void 0,b,y)},disabled:k,children:j})]}),(0,n.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,n.jsx)("button",{type:"button",role:"tab","aria-selected":r===e,id:`${u}-${e}-tab`,"aria-controls":u,className:xy("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",r===e&&"bg-bg-selected font-semibold text-text"),onClick:()=>i(e),children:"governor"===e?p("efficiency.governor"):p("efficiency.lab")},e))}),"lab"===r?(0,n.jsxs)("div",{className:"efficiency-folderbar",children:[(0,n.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-folder`,children:p("efficiency.folder")}),(0,n.jsxs)("select",{id:`${u}-folder`,className:"efficiency-folder-select",value:v??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;f(t??""),h.refreshExperiments(t,b,y)},children:[(0,n.jsx)("option",{value:"",children:p("efficiency.folderAll")}),g.map(e=>(0,n.jsx)("option",{value:e,children:e},e)),v&&!g.includes(v)?(0,n.jsx)("option",{value:v,children:v}):null]}),(0,n.jsx)("input",{className:"efficiency-folder-input",value:m,placeholder:p("efficiency.folderPlaceholder"),"aria-label":p("efficiency.folder"),onChange:e=>f(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===m.trim()?null:m.trim();h.refreshExperiments(e,b,y)}}}),(0,n.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-harness`,children:p("efficiency.harness")}),(0,n.jsxs)("select",{id:`${u}-harness`,className:"efficiency-folder-select font-mono",value:y.harness??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;h.refreshExperiments(void 0,b,{groupBy:y.groupBy,harness:t})},children:[(0,n.jsx)("option",{value:"",children:p("efficiency.harnessAll")}),w.map(e=>(0,n.jsx)("option",{value:e.revision??gU,children:`${xj(e.revision,p)} (${e.runCount})`},e.revision??gU)),y.harness&&!w.some(e=>(e.revision??gU)===y.harness)?(0,n.jsx)("option",{value:y.harness,children:y.harness===gU?p("efficiency.harnessUnknown"):y.harness.slice(0,7)}):null]}),(0,n.jsxs)("div",{className:"col-span-full flex flex-col items-start gap-2",children:[(0,n.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===b,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all",y),children:p("efficiency.scopeAttributed")}),(0,n.jsx)(rT.E,{tone:"attributed"===b?"informative":"neutral",variant:"weak",size:"medium",children:p("attributed"===b?"efficiency.scopeAttributed":"efficiency.scopeAll")}),(0,n.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"harness"===y.groupBy,onPressedChange:e=>h.refreshExperiments(void 0,b,{groupBy:e?"harness":"config",harness:y.harness}),children:p("efficiency.groupByHarness")})]})]}):null,(0,n.jsx)("div",{id:u,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",role:"tabpanel","aria-labelledby":`${u}-${r}-tab`,children:"governor"===r?t?"idle"===h.list.status||"loading"===h.list.status?(0,n.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingRuns")}):"error"===h.list.status?(0,n.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,n.jsx)("div",{className:"font-medium",children:p("efficiency.runsError")}),(0,n.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.list.error})]}):"empty"===h.list.status?(0,n.jsx)("p",{className:"efficiency-empty",children:p("efficiency.runsEmpty")}):(0,n.jsxs)("div",{className:"efficiency-governor",children:[(0,n.jsx)("ul",{className:"efficiency-run-list",children:h.list.runs.map(e=>(0,n.jsx)(xM,{run:e,selected:h.selectedRunId===e.runId,onSelect:()=>h.selectRun(h.selectedRunId===e.runId?null:e.runId),t:p},e.runId))}),(0,n.jsx)("div",{className:"efficiency-detail-pane",children:null===h.selectedRunId||"idle"===h.detail.status?(0,n.jsx)("p",{className:"efficiency-empty",children:p("efficiency.selectRun")}):"loading"===h.detail.status?(0,n.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingDetail")}):"error"===h.detail.status?(0,n.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,n.jsx)("div",{className:"font-medium",children:p("efficiency.detailError")}),(0,n.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.detail.error})]}):h.detail.detail?(0,n.jsx)(xR,{detail:h.detail.detail,t:p}):null})]}):(0,n.jsx)("p",{className:"efficiency-empty",children:p("efficiency.noSession")}):(()=>{if("idle"===h.experiments.status||"loading"===h.experiments.status)return(0,n.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingExperiments")});if("error"===h.experiments.status)return(0,n.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,n.jsx)("div",{className:"font-medium",children:p("efficiency.experimentsError")}),(0,n.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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,n.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")}),(0,n.jsxs)("div",{className:"efficiency-stack",children:[(0,n.jsx)(xA,{response:e,t:p}),e.configs.map(t=>(0,n.jsx)(xP,{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,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"efficiency-empty",children:p("efficiency.experimentsEmpty")}),e?(0,n.jsx)("div",{className:"efficiency-stack",children:(0,n.jsx)(xA,{response:e,t:p})}):null,(0,n.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,n.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")})]})})()})]})}var x_=r(96607),xz=r(29213),xW=r.n(xz);let xO="cuelo-plugin-lab-open",xD="/api/plugin-lab",xH=(0,n.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,n.jsx)("path",{d:"M13 8a5 5 0 1 1-1.46-3.54M13 2.5v3h-3"})});async function xU(e){try{let t=await e.json();if("string"==typeof t.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}function xB(e){return e.hasPanel&&e.enabled}let xq=new Map;function xV({title:e,visible:t,sessionId:r,labWidgets:i,onInsertDraft:o}){let{t:l}=(0,z.s)(),[c,d]=(0,a.useState)({kind:"loading"}),[u,p]=(0,a.useState)(()=>new Set),[h,m]=(0,a.useState)({}),[f,g]=(0,a.useState)(null),x=(0,a.useRef)(0);(0,a.useEffect)(()=>{g(function(){try{return window.localStorage.getItem(xO)}catch{return null}}())},[]);let v=(0,a.useCallback)(async()=>{let e=++x.current;d(e=>"ready"===e.kind?e:{kind:"loading"});try{let t=await fetch(xD,{cache:"no-store"});if(!t.ok)throw Error(await xU(t));let r=await t.json();e===x.current&&d({kind:"ready",plugins:r.plugins??[]})}catch(t){e===x.current&&d({kind:"error",message:t instanceof Error?t.message:String(t)})}},[]);(0,a.useEffect)(()=>{t&&v()},[t,v]);let b=(0,a.useCallback)(async(e,t)=>{p(t=>new Set(t).add(e.id)),m(t=>({...t,[e.id]:null}));try{let r=await fetch(`${xD}/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:t})});if(!r.ok)throw Error(await xU(r));let n=await r.json();d(e=>"ready"===e.kind?{kind:"ready",plugins:e.plugins.map(e=>e.id===n.plugin.id?n.plugin:e)}:e),v()}catch(t){m(r=>({...r,[e.id]:t instanceof Error?t.message:String(t)}))}finally{p(t=>{let r=new Set(t);return r.delete(e.id),r})}},[v]),y=(0,a.useCallback)(e=>{g(e);try{e?window.localStorage.setItem(xO,e):window.localStorage.removeItem(xO)}catch{}},[]),w="ready"===c.kind?c.plugins:[],k=f?w.find(e=>e.id===f&&xB(e))??null:null;if(k)return(0,n.jsx)(xG,{plugin:k,sessionId:r,labWidgets:i,onInsertDraft:o,onBack:()=>y(null)});let j=w.some(e=>e.hasExtension);return(0,n.jsxs)("section",{className:xW().view,"aria-label":e,children:[(0,n.jsx)(p6,{title:e,subtitle:"ready"===c.kind?l("pluginLab.counts",{count:w.length}):void 0,actions:[{id:"refresh",label:l("pluginLab.refresh"),icon:xH,onClick:()=>void v()}]}),(0,n.jsxs)("div",{className:xW().toolbar,children:[(0,n.jsx)(s.r,{variant:"neutralWeak",size:"small",disabled:!o,onClick:()=>o?.(l("pluginLab.starter")),title:o?l("pluginLab.createHint"):l("pluginLab.noComposer"),children:l("pluginLab.create")}),j&&(0,n.jsx)("p",{className:xW().hint,children:l("pluginLab.applyHint")})]}),(0,n.jsxs)("div",{className:xW().body,children:["loading"===c.kind&&(0,n.jsx)("p",{className:xW().message,role:"status",children:l("pluginLab.loading")}),"error"===c.kind&&(0,n.jsxs)("div",{className:xW().message,role:"alert",children:[(0,n.jsx)("p",{className:xW().errorText,children:l("pluginLab.loadFailed",{error:c.message})}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"small",onClick:()=>void v(),children:l("pluginLab.retry")})]}),"ready"===c.kind&&0===w.length&&(0,n.jsx)("p",{className:xW().message,children:l("pluginLab.empty")}),"ready"===c.kind&&w.length>0&&(0,n.jsx)("ul",{className:xW().list,"aria-label":l("pluginLab.listLabel"),children:w.map(e=>(0,n.jsx)(xK,{plugin:e,busy:u.has(e.id),error:h[e.id]??null,onToggle:t=>void b(e,t),onOpen:()=>y(e.id)},e.id))})]})]})}function xK({plugin:e,busy:t,error:r,onToggle:i,onOpen:o}){let{t:l,locale:c}=(0,z.s)(),d=e.enabled,[u,p]=(0,a.useState)(!1),h=(0,a.useMemo)(()=>[...e.enhancements??[]].reverse(),[e.enhancements]);return(0,n.jsxs)("li",{className:xW().card,"data-enabled":d?"true":"false","aria-busy":t||void 0,children:[(0,n.jsxs)("div",{className:xW().cardHead,children:[(0,n.jsxs)("div",{className:xW().titleBlock,children:[(0,n.jsx)("div",{className:xW().titleLine,children:(0,n.jsx)("span",{className:xW().name,title:e.name,children:e.name})}),(0,n.jsx)("span",{className:xW().id,title:e.id,children:e.id})]}),(0,n.jsx)("div",{className:xW().control,children:(0,n.jsxs)(x_.h.Root,{className:xW().switch,size:"24",tone:"brand",checked:e.enabled,disabled:t,onCheckedChange:i,"aria-label":l("pluginLab.toggleLabel",{name:e.name}),children:[(0,n.jsx)(x_.h.HiddenInput,{}),(0,n.jsx)(x_.h.Label,{className:xW().switchLabel,children:t?l("pluginLab.saving"):e.enabled?l("pluginLab.on"):l("pluginLab.off")}),(0,n.jsx)(x_.h.Control,{children:(0,n.jsx)(x_.h.Thumb,{})})]})})]}),e.description&&(0,n.jsx)("p",{className:xW().description,children:e.description}),h.length>0&&(0,n.jsxs)("div",{className:xW().enhancement,children:[(0,n.jsx)("span",{className:xW().metaLabel,children:l("pluginLab.enhancements")}),h.slice(0,u?h.length:3).map((e,t)=>{var r;let a;return(0,n.jsxs)("div",{className:xW().enhancement,children:[(0,n.jsx)("p",{className:xW().enhancementHead,children:(0,n.jsx)("time",{className:xW().enhancementDate,dateTime:e.at,title:l("pluginLab.enhancementDateHint"),children:(r=e.at,(a=xq.get(c))||(a=new Intl.DateTimeFormat(c,{dateStyle:"medium"}),xq.set(c,a)),a.format(new Date(r)))})}),(0,n.jsx)("p",{className:xW().enhancementSummary,children:e.summary})]},`${e.at}-${t}`)}),h.length>3&&(0,n.jsx)("div",{className:xW().cardActions,children:(0,n.jsx)(s.r,{variant:"neutralWeak",size:"small","aria-expanded":u,onClick:()=>p(e=>!e),children:u?l("pluginLab.showFewerEnhancements"):l("pluginLab.showAllEnhancements",{count:h.length})})})]}),e.tools.length>0&&(0,n.jsxs)("div",{className:xW().tools,children:[(0,n.jsx)("span",{className:xW().metaLabel,children:l("pluginLab.tools")}),(0,n.jsx)("ul",{className:xW().toolList,"aria-label":l("pluginLab.tools"),children:e.tools.map(e=>(0,n.jsx)("li",{className:xW().tool,children:e},e))})]}),e.problem&&(0,n.jsxs)("p",{className:xW().problem,children:[(0,n.jsx)("span",{className:xW().problemLabel,children:l("pluginLab.problem")}),(0,n.jsx)("span",{children:e.problem})]}),r&&(0,n.jsx)("p",{className:xW().problem,role:"alert",children:l("pluginLab.toggleFailed",{error:r})}),xB(e)&&(0,n.jsx)("div",{className:xW().cardActions,children:(0,n.jsx)(s.r,{variant:"neutralWeak",size:"small",onClick:o,"aria-label":l("pluginLab.openPanelLabel",{name:e.name}),children:l("pluginLab.openPanel")})})]})}function xG({plugin:e,sessionId:t,labWidgets:r,onInsertDraft:i,onBack:s}){let{t:o}=(0,z.s)(),{theme:l}=rh(),c=(0,a.useRef)(null),d=(0,a.useMemo)(()=>{var n,a;return r.sessionId===t?(n=r.widgets,a=e.id,n.filter(e=>c_(e.key)===a).flatMap(e=>[...e.lines])):[]},[r,t,e.id]),u=(0,a.useRef)({sessionId:null,lines:[],theme:"light"}),p=(0,a.useRef)(i),[h,m]=(0,a.useState)(null);(0,a.useEffect)(()=>{p.current=i},[i]);let f=(0,a.useMemo)(()=>{var t;let r;return t={frame:()=>c.current?.contentWindow??null,state:()=>u.current,insertDraft:e=>{let t=p.current;return t?(t(e),m(o("pluginLab.draftInserted")),!0):(m(o("pluginLab.noComposer")),!1)},recordDraft:()=>{fetch(`${xD}/${encodeURIComponent(e.id)}/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"draft"})}).then(e=>{e.ok||m(o("pluginLab.draftNotRecorded"))},()=>m(o("pluginLab.draftNotRecorded")))}},{publishState:r=()=>{let e=t.frame();if(!e)return;let{sessionId:r,lines:n,theme:a}=t.state();e.postMessage({type:"cuelo-lab:state",sessionId:r,lines:[...n],...a?{theme:a}:{}},"*")},handleMessage(e){let n=function(e,t){if(!t||e.source!==t||"null"!==e.origin||"object"!=typeof e.data||null===e.data||Array.isArray(e.data))return null;let r=e.data,n=Object.keys(r).sort().join(",");if("cuelo-lab:ready"===r.type)return"type"===n?{type:"cuelo-lab:ready"}:null;if("cuelo-lab:draft"!==r.type||"text,type"!==n||"string"!=typeof r.text)return null;let a=function(e){if(e.length<=4e3)return e;let t=e.slice(0,4e3),r=t.charCodeAt(t.length-1);return r>=55296&&r<=56319?t.slice(0,-1):t}(r.text);return a.trim()?{type:"cuelo-lab:draft",text:a}:null}(e,t.frame());if(n){if("cuelo-lab:ready"===n.type)return void r();t.insertDraft(n.text)&&t.recordDraft()}}}},[e.id,o]);return(0,a.useEffect)(()=>(window.addEventListener("message",f.handleMessage),()=>window.removeEventListener("message",f.handleMessage)),[f]),(0,a.useEffect)(()=>{u.current={sessionId:t,lines:d,theme:l},f.publishState()},[f,t,d,l]),(0,n.jsxs)("section",{className:xW().view,"aria-label":o("pluginLab.frameTitle",{name:e.name}),children:[(0,n.jsx)(p6,{back:{label:o("pluginLab.back"),onClick:s},title:e.name,subtitle:o("pluginLab.panelSubtitle",{id:e.id})}),(0,n.jsx)("div",{className:xW().stage,children:(0,n.jsx)("iframe",{ref:c,className:xW().frame,title:o("pluginLab.frameTitle",{name:e.name}),src:`${xD}/${encodeURIComponent(e.id)}/panel`,sandbox:"allow-scripts",referrerPolicy:"no-referrer"})}),(0,n.jsxs)("div",{className:xW().status,children:[(0,n.jsx)("span",{className:xW().lines,"data-live":d.length>0?"true":"false",children:d.length>0?o("pluginLab.lines",{count:d.length}):o("pluginLab.noLines")}),(0,n.jsx)("span",{role:"status",className:xW().notice,children:h})]})]})}function xJ(e){return`request:${e}`}function xZ(e){return`memory:${e}`}function xY(e){return`doc:${e}`}function xX(e){return`file:${e}`}var xQ=r(2498),x0=r.n(xQ);let x1="cuelo-memory-trace-scope",x2="cuelo-memory-trace-request:";function x8(e){return e.replace(/\b[\w.-]+=[0-9a-f]{12,}\b/gi,"").replace(/\b[0-9a-f]{16,}\b/gi,"").replace(/\s{2,}/g," ").trim()}function x4(e){return e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/`+/g,"").replace(/\*\*|__/g,"").replace(/(^|\n)[ \t]*(?:#{1,6}|[-*+]|\d+[.)])[ \t]+/g,"$1").replace(/\s+/g," ").trim()}let x5=/^\[(하네스 통지|자동 재개)\]\s*/;function x6(e){let t=/^(\S+) · ([\s\S]*)$/.exec(e);return t?`${t[1]} \xb7 ${x4(t[2])}`:x4(e)}let x3=(0,n.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,n.jsx)("path",{d:"M13 8a5 5 0 1 1-1.46-3.54M13 2.5v3h-3"})}),x7=["recall","jev","docmap","docs","lessons","saved"],x9={recall:"memoryTrace.stageRecall",jev:"memoryTrace.stageJev",docmap:"memoryTrace.stageDocmap",docs:"memoryTrace.stageDocs",lessons:"memoryTrace.stageLessons",saved:"memoryTrace.stageSaved"};function ve(e,t){let r=e=>e.some(e=>xZ(e.id)===t);return r(e.recalled)||e.explicit.some(e=>r(e.memories))?"recall":e.lessons.some(e=>xX(e.file)===t||xY(e.file)===t||r(e.memories))?"lessons":e.docs.some(e=>xY(e.path)===t)?"docs":e.candidates.some(e=>xY(e.path)===t)?"docmap":e.saved.some(e=>e.nodeId===t)?"saved":[...e.verdicts.keys()].some(e=>xZ(e)===t)?"jev":null}async function vt(e){try{let t=await e.json();if("string"==typeof t.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}function vr({title:e,visible:t,sessionId:r}){let i,{t:o,locale:l}=(0,z.s)(),[c,d]=(0,a.useState)({kind:"idle"}),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)("request"),b=(0,a.useRef)(0),y=(0,a.useRef)(null),w=(0,a.useRef)(null),k=(0,a.useRef)(null),[j,S]=(0,a.useState)(!1),C=(0,a.useCallback)(()=>{let e=k.current;S(!!(e&&e.scrollTop+e.clientHeight<e.scrollHeight-2))},[]);(0,a.useEffect)(()=>{v(function(){try{return"session"===window.localStorage.getItem(x1)?"session":"request"}catch{return"request"}}())},[]),(0,a.useEffect)(()=>{p(r?function(e){try{return window.sessionStorage.getItem(x2+e)}catch{return null}}(r):null),g(null)},[r]);let N=(0,a.useCallback)(async()=>{let e=++b.current;if(y.current?.abort(),!r)return void d({kind:"idle"});let t=new AbortController;y.current=t,d(e=>"ready"===e.kind&&e.trace.sessionId===r?e:{kind:"loading"});try{let n=await fetch(`/api/sessions/${encodeURIComponent(r)}/memory-trace`,{cache:"no-store",signal:t.signal});if(!n.ok)throw Error(await vt(n));let a=await n.json();e===b.current&&d({kind:"ready",trace:a})}catch(r){if(t.signal.aborted)return;e===b.current&&d({kind:"error",message:r instanceof Error?r.message:String(r)})}},[r]);(0,a.useEffect)(()=>t?(N(),()=>y.current?.abort()):void 0,[t,N]);let T="ready"===c.kind&&c.trace.sessionId===r?c.trace:null,I=(0,a.useMemo)(()=>T?T.requests.map((e,t)=>{let r,n,a;return r={index:t+1,request:e,recalled:[],explicit:[],verdicts:new Map,jev:[],candidates:[],docs:[],lessons:[],saved:[],counts:{recall:0,jev:0,docmap:0,docs:0,lessons:0,saved:0},happened:{recall:!1,jev:!1,docmap:!1,docs:!1,lessons:!1,saved:!1}},n=new Map,a=new Set,e.steps.forEach((e,t)=>{switch(e.kind){case"recall":for(let t of e.memories)a.has(t.id)||(a.add(t.id),r.recalled.push(t));break;case"explicit-recall":for(let t of(r.explicit.push({target:e.target,query:e.query,memories:e.memories}),e.memories))a.add(t.id);break;case"jev":for(let t of(r.jev.push({buckets:e.buckets,unknown:e.unknownCount,unrelated:e.unrelatedCount}),e.buckets))for(let e of t.ids)r.verdicts.set(e,{short:t.shortLabel,label:t.label});break;case"docmap":for(let t of e.candidates)r.candidates.some(e=>e.path===t.path)||r.candidates.push(t);break;case"doc-read":{let t=n.get(e.path);t?e.selector&&!t.selectors.includes(e.selector)&&t.selectors.push(e.selector):n.set(e.path,{path:e.path,selectors:e.selector?[e.selector]:[],candidate:e.candidate});break}case"edit-lesson":r.lessons.push({file:e.file,memories:e.memories});break;case"saved":var i;r.saved.push({nodeId:(i=e.entryId,`saved:${i}:${t}`),source:e.source,text:e.text})}}),r.docs=[...n.values()],r.counts={recall:a.size,jev:r.jev.reduce((e,t)=>e+t.buckets.reduce((e,t)=>e+t.ids.length,0),0),docmap:r.candidates.length,docs:r.docs.length,lessons:r.lessons.reduce((e,t)=>e+t.memories.length,0),saved:r.saved.length},r.happened={recall:r.recalled.length>0||r.explicit.length>0,jev:r.jev.length>0,docmap:r.candidates.length>0,docs:r.docs.length>0,lessons:r.lessons.length>0,saved:r.saved.length>0},r}):[],[T]),M=(0,a.useMemo)(()=>I.filter(e=>e.request.steps.length>0),[I]),E=(0,a.useMemo)(()=>[...M].reverse(),[M]),$=M.find(e=>e.request.entryId===u)??E[0]??null;(0,a.useEffect)(()=>{let e=k.current;if(!e)return;C();let t=new ResizeObserver(C);return t.observe(e),()=>t.disconnect()},[C,E]),(0,a.useEffect)(()=>{$&&m(e=>e&&$.happened[e]?e:x7.find(e=>$.happened[e])??"recall")},[$]),(0,a.useEffect)(()=>{if(!f)return;let e=CSS.escape(f),t=w.current?.querySelector(`[data-node="${e}"], [data-alt-node="${e}"]`);t?.scrollIntoView({block:"nearest"})},[f,h,$]);let R=e=>{if(p(e),r)try{window.sessionStorage.setItem(x2+r,e)}catch{}},L=(0,a.useMemo)(()=>new Intl.DateTimeFormat(l,{hour:"2-digit",minute:"2-digit"}),[l]);return i=r?"error"===c.kind?(0,n.jsxs)("div",{className:x0().message,role:"alert",children:[(0,n.jsx)("p",{className:x0().errorText,children:o("memoryTrace.error",{error:c.message})}),(0,n.jsx)(s.r,{variant:"neutralOutline",size:"small",onClick:()=>void N(),children:o("memoryTrace.retry")})]}):T?0===M.length?(0,n.jsx)("p",{className:x0().message,children:o("memoryTrace.empty")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("section",{className:x0().requests,"aria-label":o("memoryTrace.requestsLabel"),children:[(0,n.jsxs)("h3",{className:x0().sectionTitle,children:[o("memoryTrace.requestsLabel"),(0,n.jsx)("span",{className:x0().sectionCount,children:M.length})]}),(0,n.jsx)("div",{className:x0().requestScroller,"data-more":j?"true":void 0,children:(0,n.jsx)("ul",{className:x0().requestList,ref:k,onScroll:C,children:E.map(e=>{let t=e===$;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:x0().requestRow,"aria-current":t?"true":void 0,onClick:()=>{R(e.request.entryId),g(null)},title:e.request.preview,children:[(0,n.jsxs)("span",{className:x0().requestIndex,children:["#",e.index]}),(0,n.jsx)("span",{className:x0().requestTime,children:e.request.at?L.format(e.request.at):""}),(0,n.jsx)(va,{preview:e.request.preview,className:x0().requestPreview}),(0,n.jsx)("span",{className:x0().miniRail,"aria-hidden":"true",children:x7.map(t=>(0,n.jsx)("span",{"data-on":e.happened[t]?"true":"false"},t))})]})},e.request.entryId)})})})]}),$&&(0,n.jsxs)("section",{className:x0().flow,"aria-label":o("memoryTrace.flowLabel"),children:[(0,n.jsxs)("h3",{className:x0().sectionTitle,children:[(0,n.jsx)("span",{className:x0().titleText,children:o("memoryTrace.requestHeading",{index:$.index})}),(0,n.jsx)(va,{preview:$.request.preview,className:x0().flowPreview})]}),(0,n.jsx)("ol",{className:x0().rail,children:x7.map((e,t)=>{let r=$.counts[e],a=h===e;return(0,n.jsx)("li",{className:x0().station,"data-filled":$.happened[e]?"true":"false","data-open":a?"true":void 0,children:(0,n.jsxs)("button",{type:"button",className:x0().stationButton,"aria-expanded":a,"aria-controls":"memory-trace-detail",onClick:()=>{m(e),g(null)},children:[(0,n.jsx)("span",{className:x0().stationStep,"aria-hidden":"true",children:t+1}),(0,n.jsx)("span",{className:x0().stationCount,children:r}),(0,n.jsx)("span",{className:x0().stationLabel,children:o(x9[e])}),"docmap"===e&&$.candidates.length>0&&(0,n.jsx)("span",{className:x0().stationNote,children:o("memoryTrace.openedSummary",{opened:$.candidates.filter(e=>e.opened).length,skipped:$.candidates.filter(e=>!e.opened).length})})]})},e)})}),(0,n.jsx)("div",{id:"memory-trace-detail",className:x0().detail,ref:w,role:"region","aria-label":h?o(x9[h]):void 0,children:h&&(0,n.jsx)(vs,{flow:$,stage:h,focusNode:f})})]}),T&&$&&(0,n.jsx)(vu,{trace:T,selected:$,scope:x,onScopeChange:e=>{v(e);try{window.localStorage.setItem(x1,e)}catch{}},focusNode:f,onSelectNode:e=>{if("request"===e.kind){R(e.id.slice(8)),g(null);return}let t=t=>e.edited?"lessons"===ve(t,e.id):null!==ve(t,e.id),r=($&&t($)?$:E.find(t))??($&&ve($,e.id)?$:E.find(t=>null!==ve(t,e.id)))??null;r&&(R(r.request.entryId),m(ve(r,e.id)),g(e.id))}})]}):(0,n.jsx)("p",{className:x0().message,role:"status",children:o("memoryTrace.loading")}):(0,n.jsx)("p",{className:x0().message,children:o("memoryTrace.noSession")}),(0,n.jsxs)("section",{className:x0().view,"aria-label":e,children:[(0,n.jsx)(p6,{title:e,subtitle:T?o("memoryTrace.requests",{count:M.length}):void 0,actions:r?[{id:"refresh",label:o("memoryTrace.refresh"),icon:x3,onClick:()=>void N(),disabled:"loading"===c.kind}]:[]}),(0,n.jsx)("div",{className:x0().body,"aria-busy":"loading"===c.kind?"true":void 0,children:i})]})}function vn({memory:e,verdict:t,focused:r}){let{t:a}=(0,z.s)();return(0,n.jsxs)("li",{className:x0().item,"data-node":xZ(e.id),"data-focused":r?"true":void 0,children:[(0,n.jsxs)("div",{className:x0().itemHead,children:[(0,n.jsx)("code",{className:x0().memoryId,children:e.id}),e.date&&(0,n.jsx)("span",{className:x0().itemMeta,children:e.date}),t&&(0,n.jsx)(rT.E,{size:"medium",variant:"weak",tone:"neutral",title:t.label,children:t.short})]}),(0,n.jsx)("p",{className:x0().itemText,"data-empty":e.preview?void 0:"true",children:e.preview?x4(e.preview):a("memoryTrace.noMemoryText")})]})}function va({preview:e,className:t}){let r,{t:a}=(0,z.s)(),{notice:i,text:s}=(r=x5.exec(e))?{notice:"자동 재개"===r[1]?"resume":"harness",text:e.slice(r[0].length)}:{notice:null,text:e},o=x8(s);return(0,n.jsxs)("span",{className:t,title:e,children:[i&&(0,n.jsx)("span",{className:x0().noticeChip,children:a("harness"===i?"memoryTrace.noticeHarness":"memoryTrace.noticeResume")}),o||(i?"":a("memoryTrace.noPreview"))]})}function vi({path:e}){return(0,n.jsx)("span",{className:x0().path,title:e,dir:"rtl",children:(0,n.jsx)("bdi",{dir:"ltr",children:e})})}function vs({flow:e,stage:t,focusNode:r}){let{t:a}=(0,z.s)();if(!e.happened[t])return(0,n.jsx)("p",{className:x0().stageEmpty,children:a("memoryTrace.stageEmpty")});switch(t){case"recall":return(0,n.jsxs)(n.Fragment,{children:[e.recalled.length>0&&(0,n.jsxs)("div",{className:x0().group,children:[(0,n.jsx)("h4",{className:x0().groupTitle,children:a("memoryTrace.autoRecall")}),(0,n.jsx)("ul",{className:x0().items,children:e.recalled.map(t=>(0,n.jsx)(vn,{memory:t,verdict:e.verdicts.get(t.id),focused:r===xZ(t.id)},t.id))})]}),e.explicit.map((t,i)=>(0,n.jsxs)("div",{className:x0().group,children:[(0,n.jsxs)("h4",{className:x0().groupTitle,children:[a("memoryTrace.explicitRecall"),(0,n.jsx)("code",{className:x0().groupCode,children:t.target})]}),t.query&&(0,n.jsxs)("p",{className:x0().query,children:[a("memoryTrace.query")," \xb7 ",t.query]}),0===t.memories.length?(0,n.jsx)("p",{className:x0().itemMeta,children:a("memoryTrace.noResults")}):(0,n.jsx)("ul",{className:x0().items,children:t.memories.map(t=>(0,n.jsx)(vn,{memory:t,verdict:e.verdicts.get(t.id),focused:r===xZ(t.id)},t.id))})]},`${t.target}-${i}`))]});case"jev":return(0,n.jsx)(n.Fragment,{children:e.jev.map((e,t)=>(0,n.jsxs)("div",{className:x0().group,children:[e.buckets.map(e=>(0,n.jsxs)("div",{className:x0().bucket,children:[(0,n.jsxs)("h4",{className:x0().groupTitle,title:e.label,children:[e.shortLabel,(0,n.jsx)("span",{className:x0().sectionCount,children:e.ids.length})]}),(0,n.jsx)("ul",{className:x0().idList,children:e.ids.map(e=>(0,n.jsx)("li",{"data-node":xZ(e),"data-focused":r===xZ(e)?"true":void 0,children:(0,n.jsx)("code",{className:x0().memoryId,children:e})},e))})]},e.label)),(0,n.jsxs)("p",{className:x0().itemMeta,children:[null!==e.unknown&&a("memoryTrace.jevUnknown",{count:e.unknown}),null!==e.unknown&&null!==e.unrelated&&" \xb7 ",null!==e.unrelated&&a("memoryTrace.jevUnrelated",{count:e.unrelated})]})]},t))});case"docmap":return(0,n.jsx)("ul",{className:x0().items,children:e.candidates.map(e=>(0,n.jsxs)("li",{className:x0().item,"data-node":xY(e.path),"data-focused":r===xY(e.path)?"true":void 0,"data-skipped":e.opened?void 0:"true",children:[(0,n.jsxs)("div",{className:x0().itemHead,children:[(0,n.jsx)(vi,{path:e.path}),(0,n.jsx)(rT.E,{size:"medium",variant:e.opened?"solid":"weak",tone:e.opened?"positive":"neutral",children:e.opened?a("memoryTrace.opened"):a("memoryTrace.candidateOnly")})]}),(e.status||e.map)&&(0,n.jsxs)("p",{className:x0().itemText,children:[e.status&&(0,n.jsxs)("span",{className:x0().itemMeta,children:["STATUS ",e.status]}),e.status&&e.map&&" \xb7 ",e.map]})]},e.path))});case"docs":return(0,n.jsx)("ul",{className:x0().items,children:e.docs.map(e=>(0,n.jsxs)("li",{className:x0().item,"data-node":xY(e.path),"data-focused":r===xY(e.path)?"true":void 0,children:[(0,n.jsxs)("div",{className:x0().itemHead,children:[(0,n.jsx)(vi,{path:e.path}),e.candidate&&(0,n.jsx)(rT.E,{size:"medium",variant:"weak",tone:"informative",children:a("memoryTrace.fromMap")})]}),e.selectors.length>0&&(0,n.jsx)("p",{className:x0().itemMeta,children:a("memoryTrace.lines",{lines:e.selectors.join(", ")})})]},e.path))});case"lessons":return(0,n.jsx)(n.Fragment,{children:e.lessons.map((e,t)=>(0,n.jsxs)("div",{className:x0().group,"data-node":xX(e.file),"data-alt-node":xY(e.file),"data-focused":r===xX(e.file)||r===xY(e.file)?"true":void 0,children:[(0,n.jsxs)("h4",{className:x0().groupTitle,children:[a("memoryTrace.lessonFor"),(0,n.jsx)(vi,{path:e.file})]}),(0,n.jsx)("ul",{className:x0().items,children:e.memories.map(e=>(0,n.jsx)(vn,{memory:e,focused:r===xZ(e.id)},e.id))})]},`${e.file}-${t}`))});case"saved":return(0,n.jsx)("ul",{className:x0().items,children:e.saved.map(e=>(0,n.jsxs)("li",{className:x0().item,"data-node":e.nodeId,"data-focused":r===e.nodeId?"true":void 0,children:[(0,n.jsx)("div",{className:x0().itemHead,children:(0,n.jsx)(rT.E,{size:"medium",variant:"weak",tone:"neutral",children:"autolearn"===e.source?a("memoryTrace.savedAuto"):e.source})}),(0,n.jsx)("p",{className:x0().itemText,children:x4(e.text)})]},e.nodeId))})}}let vo=["apply","excepted","conflict","unconfirmed","unlisted"],vl={apply:"memoryTrace.verdictApply",excepted:"memoryTrace.verdictExcepted",conflict:"memoryTrace.verdictConflict",unconfirmed:"memoryTrace.verdictUnconfirmed",unlisted:"memoryTrace.verdictUnlisted"};function vc(e){return/[\u1100-\u11ff\u3000-\u9fff\uac00-\ud7af\uff00-\uffef]/.test(e)?12:6.8}function vd({kind:e}){switch(e){case"memory":return(0,n.jsx)("circle",{r:5});case"doc":return(0,n.jsx)("rect",{x:-5,y:-5,width:10,height:10,rx:1.5});case"file":return(0,n.jsx)("rect",{x:-5,y:-5,width:10,height:10,transform:"rotate(45)",rx:1});case"request":return(0,n.jsx)("rect",{x:-20,y:-9,width:40,height:18,rx:9})}}function vu({trace:e,selected:t,scope:r,onScopeChange:i,focusNode:s,onSelectNode:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null),[d,u]=(0,a.useState)(0),[p,h]=(0,a.useState)(280),[m,f]=(0,a.useState)(null),g=(0,a.useCallback)(()=>{let e=c.current,t=e?.closest(`.${x0().body}`);if(!e||!t)return;let r=e.getBoundingClientRect().top-t.getBoundingClientRect().top+t.scrollTop,n=Number.parseFloat(getComputedStyle(t).paddingBlockEnd)||0,a=Math.max(280,Math.floor(t.clientHeight-r-n-2));h(e=>Math.abs(e-a)>1?a:e)},[]);(0,a.useLayoutEffect)(g),(0,a.useEffect)(()=>{let e=c.current,t=e?.closest(`.${x0().body}`);if(!e)return;let r=new ResizeObserver(()=>{u(Math.round(e.getBoundingClientRect().width)-2),g()});return r.observe(e),t&&r.observe(t),()=>r.disconnect()},[g]);let x=(0,a.useMemo)(()=>new Map(e.requests.map((e,t)=>[xJ(e.entryId),t+1])),[e]),v=(0,a.useMemo)(()=>{let t=new Map(e.nodes.filter(e=>"doc"===e.kind).map(e=>[e.title,e.id])),r=new Map;for(let n of e.nodes){let e="file"===n.kind?t.get(n.title):void 0;e&&r.set(n.id,e)}let n=new Set(r.values());return{nodes:e.nodes.filter(e=>!r.has(e.id)).map(e=>n.has(e.id)?{...e,edited:!0}:e),edges:e.edges.map(e=>({...e,from:r.get(e.from)??e.from,to:r.get(e.to)??e.to})),alias:r}},[e]),{nodes:b,edges:y}=(0,a.useMemo)(()=>{if("session"===r){let e=new Set(v.edges.flatMap(e=>[e.from,e.to]));return{nodes:v.nodes.filter(t=>e.has(t.id)),edges:v.edges}}let e=xJ(t.request.entryId),n=new Set([e]),a=v.edges.filter(t=>t.from===e);for(let e of a)n.add(e.to);let i=new Set(t.lessons.flatMap(e=>e.memories.map(t=>{let r;return`${r=e.file,v.alias.get(xX(r))??xX(r)}\u0000${xZ(t.id)}`}))),s=v.edges.filter(e=>"lesson"===e.kind&&i.has(`${e.from}\u0000${e.to}`));for(let e of s)n.add(e.to);return{nodes:v.nodes.filter(e=>n.has(e.id)),edges:[...a,...s]}},[v,r,t]),w=(0,a.useMemo)(()=>d>0?function(e,t,r,n,a){let i=e.filter(e=>"request"===e.kind).sort((e,t)=>(a.get(t.id)??0)-(a.get(e.id)??0)),s=new Map(i.map((e,t)=>[e.id,t])),o=new Map;for(let e of t)(o.get(e.from)??o.set(e.from,[]).get(e.from)).push(e.to),(o.get(e.to)??o.set(e.to,[]).get(e.to)).push(e.from);let l=new Map(e.map((e,t)=>[e.id,t])),c=e=>e.map(e=>({node:e,w:(e=>{let t=[];for(let r of o.get(e)??[]){let e=s.get(r);if(void 0!==e)t.push(e);else for(let e of o.get(r)??[]){let r=s.get(e);void 0!==r&&t.push(r)}}return t.length>0?t.reduce((e,t)=>e+t,0)/t.length:Number.MAX_SAFE_INTEGER})(e.id)})).sort((e,t)=>e.w-t.w||(l.get(e.node.id)??0)-(l.get(t.node.id)??0)).map(e=>e.node),d=[c(e.filter(e=>"memory"===e.kind)),i,[...c(e.filter(e=>"doc"===e.kind)),...c(e.filter(e=>"file"===e.kind))]],u=Math.max(1,...d.map(e=>e.length)),p=Math.min(60,Math.max(36,(n-30-16)/u)),h=Math.ceil(30+u*p+16),m=Math.min(160,Math.max(28,Math.round(.1*r))),f=Math.max(0,r-32-22-40-2*m),g=Math.round(.56*f),x=16+g+6+5,v=x+m+20,b=[x,v,v+20+m],y=new Map;return d.forEach((e,t)=>{let r=30+(u-e.length)*p/2+p/2;e.forEach((e,n)=>{y.set(e.id,{node:e,x:b[t],y:Math.round(r+n*p),column:t})})}),{placed:y,height:h,xs:b,neighbours:o,rowH:p,leftLabel:g,rightLabel:f-g}}(b,y,d,p,x):null,[b,y,d,p,x]),k=(0,a.useMemo)(()=>{let e=new Map;if(!t.happened.jev)return e;for(let r of t.recalled)e.set(xZ(r.id),"unlisted");for(let[n,a]of t.verdicts){var r;e.set(xZ(n),(r=a.label).includes("충돌")?"conflict":r.includes("불충족")||r.includes("예외")?"excepted":r.startsWith("적용")?"apply":"unconfirmed")}return e},[t]),j=(0,a.useMemo)(()=>{let e=new Set(b.flatMap(e=>k.get(e.id)??[]));return vo.filter(t=>e.has(t))},[b,k]),S=m??s,C=(0,a.useMemo)(()=>S&&w?new Set([S,...w.neighbours.get(S)??[]]):null,[S,w]),N=(0,a.useMemo)(()=>{if("request"===r||!w)return null;let e=S??xJ(t.request.entryId),n=new Set([e]);for(let t of w.neighbours.get(e)??[])if(n.add(t),t.startsWith("file:")||t.startsWith("doc:"))for(let e of w.neighbours.get(t)??[])e.startsWith("memory:")&&n.add(e);return n},[r,w,S,t]),T={request:l("memoryTrace.legendRequest"),memory:l("memoryTrace.legendMemory"),doc:l("memoryTrace.legendDoc"),file:l("memoryTrace.legendFile")},I=e=>e.edited?`${T.doc} \xb7 ${T.file}`:T[e.kind],M=(0,a.useMemo)(()=>{let e=new Map;if(!w)return e;for(let t of y){let r=w.placed.get(t.from),n=w.placed.get(t.to);if(!r||!n)continue;let a=r.x<=n.x?`${t.from}|${t.to}`:`${t.to}|${t.from}`;(e.get(a)??e.set(a,[]).get(a)).push(t.kind)}return e},[y,w]),E=`memory-trace-arrow-${(0,a.useId)().replace(/[^a-zA-Z0-9_-]/g,"")}`,$=S&&w?w.placed.get(S)?.node??null:null,R=$?k.get($.id):void 0;return(0,n.jsxs)("section",{className:x0().graph,"aria-label":l("memoryTrace.graphLabel"),children:[(0,n.jsxs)("div",{className:x0().graphHead,children:[(0,n.jsx)("h3",{className:x0().sectionTitle,children:l("memoryTrace.graphLabel")}),(0,n.jsxs)(pQ.A.Root,{className:x0().scopeSwitch,"aria-label":l("memoryTrace.graphScope"),value:r,onValueChange:e=>i(e),children:[["request","session"].map(e=>(0,n.jsxs)(pQ.A.Item,{value:e,children:[(0,n.jsx)(pQ.A.ItemHiddenInput,{}),"request"===e?l("memoryTrace.scopeRequest"):l("memoryTrace.scopeSession")]},e)),(0,n.jsx)(pQ.A.Indicator,{})]})]}),(0,n.jsxs)("ul",{className:x0().legend,children:[["request","memory","doc","file"].map(e=>(0,n.jsxs)("li",{"data-kind":e,children:[(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"-7 -7 14 14","aria-hidden":"true",children:(0,n.jsx)("g",{className:x0().legendMark,children:"request"===e?(0,n.jsx)("rect",{x:-6,y:-4,width:12,height:8,rx:4}):(0,n.jsx)(vd,{kind:e})})}),T[e]]},e)),["recalled","opened","lesson","candidate"].map(e=>(0,n.jsxs)("li",{"data-kind":`edge-${e}`,children:[(0,n.jsx)("svg",{width:"20",height:"8","aria-hidden":"true",children:(0,n.jsx)("line",{x1:"1",y1:"4",x2:"19",y2:"4"})}),l("recalled"===e?"memoryTrace.edgeRecalled":"opened"===e?"memoryTrace.opened":"lesson"===e?"memoryTrace.edgeLesson":"memoryTrace.candidateOnly")]},e)),b.some(e=>e.edited)&&(0,n.jsxs)("li",{"data-kind":"edited",children:[(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"-7 -7 14 14","aria-hidden":"true",children:(0,n.jsx)("g",{className:x0().legendMark,children:(0,n.jsx)(vd,{kind:"doc"})})}),l("memoryTrace.legendDocEdited")]})]}),j.length>0&&(0,n.jsxs)("ul",{className:x0().legend,"aria-label":l("memoryTrace.verdictLegend"),children:[(0,n.jsx)("li",{className:x0().legendTitle,children:l("memoryTrace.verdictLegend")}),j.map(e=>(0,n.jsxs)("li",{"data-verdict":e,children:[(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"-8 -8 16 16","aria-hidden":"true",children:[(0,n.jsx)("circle",{className:x0().ring,r:7.5}),(0,n.jsx)("circle",{className:x0().legendMemory,r:4})]}),l(vl[e])]},e))]}),(0,n.jsx)("p",{className:x0().graphCaption,"aria-live":"polite",children:$?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("span",{className:x0().captionKind,children:["request"===$.kind?`#${x.get($.id)??""}`:I($),R?` \xb7 ${l(vl[R])}`:""]}),"request"===$.kind?x8($.title):"memory"===$.kind?x6($.title):$.title]}):l("memoryTrace.graphHint")}),(0,n.jsx)("div",{className:x0().graphFrame,ref:c,children:b.length<=1?(0,n.jsx)("p",{className:x0().stageEmpty,children:l("memoryTrace.graphEmpty")}):w&&(0,n.jsxs)("svg",{className:x0().graphSvg,width:d,height:w.height,viewBox:`0 0 ${d} ${w.height}`,role:"group","aria-label":l("memoryTrace.graphLabel"),onPointerLeave:()=>f(null),children:[(0,n.jsx)("defs",{children:(0,n.jsx)("marker",{id:E,viewBox:"0 0 8 8",refX:"7",refY:"4",markerWidth:"7",markerHeight:"7",orient:"auto-start-reverse",children:(0,n.jsx)("path",{className:x0().arrow,d:"M0,0.5 L8,4 L0,7.5 z"})})}),(0,n.jsxs)("g",{className:x0().columnHeads,"aria-hidden":"true",children:[(0,n.jsx)("text",{x:w.xs[0],y:16,textAnchor:"end",children:T.memory}),(0,n.jsx)("text",{x:w.xs[1],y:16,textAnchor:"middle",children:T.request}),(0,n.jsxs)("text",{x:w.xs[2],y:16,textAnchor:"start",children:[T.doc," \xb7 ",T.file]})]}),(0,n.jsx)("g",{className:x0().edges,"aria-hidden":"true",children:y.map(e=>{let t=w.placed.get(e.from),r=w.placed.get(e.to);if(!t||!r)return null;let[a,i]=t.x<=r.x?[t,r]:[r,t],s=M.get(`${a.node.id}|${i.node.id}`)??[e.kind],o=(s.indexOf(e.kind)-(s.length-1)/2)*4,l=a.y+o,c=i.y+o,d=1===a.column?a.x+(a.x<i.x?20:-20):a.x+5,u=0===a.column&&2===i.column,p=1===i.column?i.x-20:i.x-5-3*!!u,h=(d+p)/2,m=u?d+Math.max(12,(w.xs[1]-20-d)*.4):null,f=u&&[...w.placed.values()].some(e=>1===e.column&&12>Math.abs(e.y-c)),g=c+(c+w.rowH/2>w.height-16?-1:1)*(w.rowH/2),x=w.xs[1]+20+8,v=null===m?`M${d},${l} C${h},${l} ${h},${c} ${p},${c}`:f?`M${d},${l} C${(d+m)/2},${l} ${(d+m)/2},${g} ${m},${g} L${x},${g} C${(x+p)/2},${g} ${(x+p)/2},${c} ${p},${c}`:`M${d},${l} C${(d+m)/2},${l} ${(d+m)/2},${c} ${m},${c} L${p},${c}`,b=null!==S&&(e.from===S||e.to===S),y=null!==N&&!(N.has(e.from)&&N.has(e.to));return(0,n.jsx)("path",{d:v,"data-kind":e.kind,"data-on":b?"true":void 0,"data-dim":y&&!b?"true":void 0,markerEnd:u?`url(#${E})`:void 0},`${e.from}|${e.to}|${e.kind}`)})}),(0,n.jsx)("g",{className:x0().nodes,children:[...w.placed.values()].map(({node:e,x:r,y:a,column:i})=>{let s=w.neighbours.get(e.id)?.length??0,c=0===i?w.leftLabel:w.rightLabel,d="request"===e.kind?[`#${x.get(e.id)??""}`]:"memory"===e.kind?function(e,t,r=2){if(t<24)return[];let n=[],a="",i=0;for(let s of e.trim()){let e=vc(s);if(i+e>t){if(n.length===r-1)return n.push(`${a.slice(0,-1).trimEnd()}…`),n;let e=a.lastIndexOf(" "),t=e>0?a.slice(0,e):a;n.push(t),i=[...a=a.slice(t.length).trimStart()].reduce((e,t)=>e+vc(t),0)}a+=s,i+=e}return a&&n.push(a),n}(x4(e.label),c):[function(e,t){let r=[...e];if(r.reduce((e,t)=>e+vc(t),0)<=t)return e;let n=vc("…"),a=r.length;for(;a>0&&n+vc(r[a-1])<=t;)a-=1,n+=vc(r[a]);return`…${r.slice(a).join("")}`}(e.title,c)],u=k.get(e.id),p=w.rowH-4,h=0===i?-11:11*(2===i);return(0,n.jsxs)("g",{className:x0().node,"data-kind":e.kind,"data-on":C?.has(e.id)?"true":void 0,"data-dim":N&&!N.has(e.id)?"true":void 0,"data-current":e.id===xJ(t.request.entryId)?"true":void 0,"data-verdict":u,"data-edited":e.edited?"true":void 0,transform:`translate(${r},${a})`,tabIndex:0,role:"button","aria-label":l("memoryTrace.nodeLabel",{kind:I(e),label:"memory"===e.kind?x6(e.title):e.title,count:s}),onPointerEnter:()=>f(e.id),onFocus:()=>f(e.id),onBlur:()=>f(null),onClick:()=>o(e),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),o(e))},children:[(0,n.jsx)("title",{children:"request"===e.kind?x8(e.title):"memory"===e.kind?x6(e.title):e.title}),(0,n.jsx)("rect",{className:x0().hit,x:0===i?-11-c-4:1===i?-24:-9,y:-p/2,width:1===i?48:c+10+6+8,height:p}),u&&(0,n.jsx)("circle",{className:x0().ring,r:8}),(0,n.jsx)("g",{className:x0().mark,children:(0,n.jsx)(vd,{kind:e.kind})}),(0,n.jsx)("text",{className:x0().nodeText,x:h,y:4-(d.length-1)*14/2,textAnchor:0===i?"end":2===i?"start":"middle",children:d.map((e,t)=>(0,n.jsx)("tspan",{x:h,dy:14*(0!==t),children:e},t))})]},e.id)})})]})})]})}function vp({cwd:e,onOpenFile:t}){let r,{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(!e)return;let t=new AbortController;return fetch(`/api/project-docs?cwd=${encodeURIComponent(e)}`,{signal:t.signal}).then(async r=>{let n=await r.json();t.signal.aborted||(403===r.status?o({kind:"denied",cwd:e}):r.ok?o({kind:"ready",cwd:e,docs:n}):o({kind:"error",cwd:e,message:n.error??`HTTP ${r.status}`}))}).catch(r=>{t.signal.aborted||o({kind:"error",cwd:e,message:r instanceof Error?r.message:String(r)})}),()=>t.abort()},[e]);let l=e&&s?.cwd===e?s:null,c=(e,r,a)=>(0,n.jsx)("li",{className:"file-doc-shortcuts-item",children:"found"===a.state&&a.path?(0,n.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:a.path,"aria-label":`${e} — ${a.path}`,onClick:()=>t(a.path),children:[(0,n.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,n.jsx)("span",{className:"file-doc-shortcuts-file",children:r})]}):(0,n.jsxs)("div",{className:"file-doc-shortcuts-unavailable",title:a.path??void 0,children:[(0,n.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,n.jsx)("span",{className:"file-doc-shortcuts-file",children:"denied"===a.state?i("files.docs.denied",{file:r}):i("files.docs.missing",{file:r})})]})});if(e)if(l)if("denied"===l.kind)r=(0,n.jsx)("p",{className:"file-doc-shortcuts-status",children:i("files.docs.projectDenied")});else if("error"===l.kind)r=(0,n.jsx)("p",{className:"file-doc-shortcuts-status",role:"alert",children:i("files.docs.loadFailed",{error:l.message})});else{let{docs:e}=l,a="missing"===e.handoff.state&&"missing"===e.docMap.state&&"missing"===e.history.state;r=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"file-doc-shortcuts-project",title:e.projectDir,children:i("files.docs.projectDir",{path:e.projectDir})}),a?(0,n.jsx)("p",{className:"file-doc-shortcuts-status",children:i("files.docs.noneFound")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("ul",{className:"file-doc-shortcuts-list",children:[c(i("files.docs.current"),"HANDOFF.md",e.handoff),c(i("files.docs.map"),"doc/README.md",e.docMap)]}),(0,n.jsx)("h3",{className:"file-doc-shortcuts-heading",id:"file-doc-shortcuts-records",children:i("files.docs.records")}),e.history.records.length>0?(0,n.jsx)("ul",{className:"file-doc-shortcuts-list","aria-labelledby":"file-doc-shortcuts-records",children:e.history.records.map(e=>(0,n.jsx)("li",{className:"file-doc-shortcuts-item",children:(0,n.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:e.path,"aria-label":`${i("files.docs.records")} ${e.date} ${e.topic} — ${e.fileName}`,onClick:()=>t(e.path),children:[(0,n.jsx)("span",{className:"file-doc-shortcuts-date",children:e.date}),(0,n.jsxs)("span",{className:"file-doc-shortcuts-file",children:[e.topic,"main.md"===e.fileName?"":` \xb7 ${e.fileName}`]})]})},e.path))}):(0,n.jsx)("p",{className:"file-doc-shortcuts-status",children:"denied"===e.history.state?i("files.docs.denied",{file:"doc/history"}):i("files.docs.missing",{file:"doc/history"})})]})]})}else r=(0,n.jsx)("p",{className:"file-doc-shortcuts-status",role:"status",children:i("files.docs.loading")});else r=(0,n.jsx)("p",{className:"file-doc-shortcuts-status",children:i("files.docs.noProject")});return(0,n.jsxs)("section",{className:"file-doc-shortcuts","aria-labelledby":"file-doc-shortcuts-title",children:[(0,n.jsx)("h2",{className:"file-doc-shortcuts-title",id:"file-doc-shortcuts-title",children:i("files.noneOpen")}),r]})}function vh(e){return"message"===e.type&&"message"in e}function vm(e){let t=e,r=t.branchPreview,n=vh(t.entry)?t.entry:null,a=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],r??=t.branchPreview,!n&&vh(t.entry)&&(n=t.entry),a+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:a,branchPreview:r,labelEntry:n??t.entry}}function vf({node:e,activePathIds:t,depth:r,isLast:a,parentLines:i,onSelect:s}){let{node:o,skipped:l,branchPreview:c,labelEntry:d}=vm(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,r=t.content,n="";if("string"==typeof r?n=r:Array.isArray(r)&&(n=r.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),n.length>40&&(n=n.slice(0,40)+"…"),n)return n;if("assistant"===t.role)return"[assistant]"}return e.type}(d),m=c?c.role??null:vh(d)?d.message.role:null;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>s(o.entry.id),children:[i.map((e,t)=>(0,n.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,n.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,n.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,n.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:a?"50%":0,width:1,background:"var(--border)"}}),(0,n.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,n.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,n.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:"var(--radius-control)",padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),l>0&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",l]}),(0,n.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,n.jsx)(vf,{node:e,activePathIds:t,depth:r+1,isLast:l===o.children.length-1,parentLines:[...i,!a],onSelect:s},e.entry.id))]})}function vg({tree:e,activeLeafId:t,onLeafChange:r,hasSession:i}){let{t:s}=(0,z.s)(),o=(0,a.useMemo)(()=>t?new Set(function e(r,n){for(let a of r){let r=[...n,a.entry.id];if(a.entry.id===t||a.compressedEntryIds?.includes(t))return r;let i=e(a.children,r);if(i)return i}return null}(e,[])??[]):new Set,[e,t]),l=(0,a.useCallback)(e=>{r(e)},[r]),c=i?!function e(t){if(t.length>1)return!0;for(let r of t)if(r.children.length>1||e(r.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=vm(e[0]).node;return t.children.length>1?t.children:[]}(e);return!c&&d.length>0?(0,n.jsx)("div",{className:"branch-navigator-tree",children:d.map((e,t)=>(0,n.jsx)(vf,{node:e,activePathIds:o,depth:0,isLast:t===d.length-1,parentLines:[],onSelect:l},e.entry.id))}):(0,n.jsx)("p",{className:"branch-navigator-empty",children:c??s("i18n.noBranches")})}function vx(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function vv(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function vb(e){let t=e.currentTime;[523.25,659.25].forEach((r,n)=>{let a=e.createOscillator(),i=e.createGain();a.connect(i),i.connect(e.destination),a.type="sine",a.frequency.value=r;let s=t+.18*n;i.gain.setValueAtTime(0,s),i.gain.linearRampToValueAtTime(.18,s+.02),i.gain.exponentialRampToValueAtTime(.001,s+.45),a.start(s),a.stop(s+.45)})}async function vy(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function vw(e){let t=e.window?.durationMs;if("number"==typeof t&&Number.isFinite(t)&&t>0)return t>=5184e5?"weekly":t<=432e5?"short":"other";let r=e.scope?.windowId,n=`${"string"==typeof r?r:""} ${e.id} ${e.label??""}`.toLowerCase();return/(^|[^0-9])7d\b|week|7 day|주간/.test(n)?"weekly":/(^|[^0-9])(5h|1h)\b|hour|시간/.test(n)?"short":"other"}let vk="omp-sidebar-usage-collapsed",vj="omp-sidebar-usage-order";function vS(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function vC(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function vN({direction:e}){return(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.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 vT({usage:e,onOpen:t,onRelogin:r}){var i,s;let o,l,c,d,{t:u}=(0,z.s)(),p=B(),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)(""),[w,k]=(0,a.useState)(null),j=(0,a.useRef)(null),[S,C]=(0,a.useState)(!0);(0,a.useEffect)(()=>{try{C("0"!==window.localStorage.getItem(vk))}catch{}v(function(){try{let e=JSON.parse(window.localStorage.getItem(vj)??"[]");return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}catch{return[]}}())},[]);let N=e.bai,T=e.state.data?.reports??[],I=ry(1e4),M=(o=nV(T),l=[],c=[],T.forEach((e,t)=>{let r=e.authError;if(!0===e.disabled&&!r)return;let n=o[t],a="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>I,i=!0===e.disabled?[]:e.limits??[],s=i.some(e=>e.scope?.shared===!0&&nc(e)),d=i.some(e=>null!==vS(e)&&"short"!==vw(e)),u=[];for(let e of i){let t=vS(e);null!==t&&(!d||"short"!==vw(e)||function(e){let t=e.amount?.usedFraction,r="number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null;return nc(e)||"warning"===e.status||null!==r&&r>=90}(e))&&u.push({key:e.id,label:e.label||e.id,percent:Math.round(100*t),state:a?"blocked":s?"account-spent":nc(e)?"spent":"usable"})}if(0===u.length&&!r)return;let p=r?"auth":a?"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:n.alias,seed:n.seed,masked:n.masked,..."string"==typeof e.accountKey?{accountKey:e.accountKey}:{},rows:u,state:p,...r?{authError:r}:{},usable:"ok"===p&&u.some(e=>"usable"===e.state)};(h.usable?l:c).push(h)}),i=[...l,...c],d=new Map(x.map((e,t)=>[e,t])),[...i.filter(e=>d.has(e.orderKey)).sort((e,t)=>d.get(e.orderKey)-d.get(t.orderKey)),...i.filter(e=>!d.has(e.orderKey))]);(0,a.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}"]`),r=e?.querySelector(`[data-direction="${"up"===w.direction?"down":"up"}"]`);(t&&!t.disabled?t:r)?.focus(),k(null)},[w]);let E=(e,t)=>{let r,n,a,i="up"===t?e-1:e+1;if(i<0||i>=M.length)return;let s=M.map(e=>e.orderKey);[s[e],s[i]]=[s[i],s[e]];let o=(r=new Set(s),n=[...x,...s.filter(e=>!x.includes(e))],a=0,n.map(e=>r.has(e)?s[a++]:e));v(o);try{window.localStorage.setItem(vj,JSON.stringify(o))}catch{}y(u("usage.moved",{account:M[e].alias,position:i+1})),k({orderKey:M[e].orderKey,direction:t})},$=e=>Math.max(1,e.rows.length),R=0,L=h||f?M:M.filter(e=>!(R>=2)&&(R+=$(e),!0)),A=M.slice(L.length).reduce((e,t)=>e+$(t),0),P=M.filter(e=>"auth"===e.state).length,F="measured"===N.status?(s=N.tokens)>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(Math.round(s)):u("empty"===N.status?"usage.baiEmpty":"usage.baiUnmeasured"),_="measured"===N.status&&null!==N.from&&null!==N.to?u("usage.baiRange",{from:vC(N.from),to:vC(N.to)}):null,W=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,D=u("usage.open",{rows:[...L.flatMap(e=>{let t=W(e);return 0===e.rows.length?[`${e.alias} (${t??""}${e.authError?`: ${e.authError.message}`:""})`]:e.rows.map(r=>{let n=O(r)??t;return`${e.alias} ${r.label} ${r.percent}%${null===n?"":` (${n})`}`})}),`${u("usage.bai")} ${F}${null===_?"":` \xb7 ${_}`}`].join(", ")})+(A>0?u("usage.openMore",{count:A}):""),H=M[0],U=void 0===H?{label:u("usage.bai"),value:F,danger:!1}:0===H.rows.length?{label:H.alias,value:W(H)??"",danger:!0}:{label:H.rows[0].label,value:`${H.rows[0].percent}%`,danger:H.rows[0].percent>=90},q=P>0?u("usage.authIssues",{count:P}):null,V=(0,n.jsxs)("div",{className:"navigator-usage",role:"group","aria-label":u("usage.title"),"data-editing":f?"":void 0,onClick:e=>{f||e.target instanceof Element&&e.target.closest("button, a")||t()},children:[(0,n.jsxs)("span",{className:"navigator-usage-header",children:[(0,n.jsx)("button",{type:"button",className:"navigator-usage-open","aria-label":D,onClick:t,children:u("usage.title")}),null===q?null:(0,n.jsx)("span",{className:"navigator-usage-alert",children:q}),M.length>1&&(0,n.jsx)("button",{type:"button",className:"navigator-usage-edit","data-active":f?"":void 0,onClick:()=>g(e=>!e),children:f?u("usage.reorderDone"):u("usage.reorder")})]}),(0,n.jsx)("div",{ref:j,role:f?"list":void 0,"aria-label":f?u("usage.reorderGroup"):void 0,className:"navigator-usage-groups",children:0===M.length?(0,n.jsx)("span",{className:"navigator-usage-empty",children:u("usage.none")}):L.map((e,t)=>{let a=W(e);return(0,n.jsxs)("div",{className:"navigator-usage-group","data-order-key":e.orderKey,role:f?"listitem":void 0,children:[(0,n.jsxs)("span",{className:"navigator-usage-account",children:[(0,n.jsx)(ax,{seed:e.seed,size:24,provider:e.provider}),(0,n.jsx)("span",{className:"navigator-usage-alias",children:e.alias}),null===a?null:(0,n.jsx)("span",{className:"navigator-usage-state","data-tone":"auth"===e.state?"danger":void 0,children:a}),f&&(0,n.jsxs)("span",{className:"navigator-usage-moves",children:[(0,n.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"up","aria-label":u("usage.moveUp",{account:e.alias}),disabled:0===t,onClick:()=>E(t,"up"),children:(0,n.jsx)(vN,{direction:"up"})}),(0,n.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:()=>E(t,"down"),children:(0,n.jsx)(vN,{direction:"down"})})]})]}),e.authError&&(0,n.jsxs)("span",{className:"navigator-usage-auth",children:[(0,n.jsx)("span",{className:"navigator-usage-reason",children:e.authError.message}),e.authError.reloginRequired&&r&&!f&&(0,n.jsx)("button",{type:"button",className:"navigator-usage-relogin","aria-label":u("usage.reloginFor",{account:e.alias}),onClick:()=>r({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,n.jsxs)("span",{className:"navigator-usage-row",children:[(0,n.jsxs)("span",{className:"navigator-usage-head",children:[(0,n.jsx)("span",{className:"navigator-usage-label",children:e.label}),null===t?null:(0,n.jsx)("span",{className:"navigator-usage-state",children:t}),(0,n.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,n.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,n.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)})]},e.orderKey)})}),!f&&(A>0||h)&&(0,n.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":h,onClick:()=>m(e=>!e),children:h?u("usage.showLess"):u("usage.showMore",{count:A})}),(0,n.jsxs)("span",{className:"navigator-usage-row",children:[(0,n.jsxs)("span",{className:"navigator-usage-head",children:[(0,n.jsx)("span",{className:"navigator-usage-label",children:u("usage.bai")}),(0,n.jsx)("span",{className:"navigator-usage-value",style:"measured"===N.status?void 0:{color:"var(--text-muted)"},children:F})]}),null===_?null:(0,n.jsx)("span",{className:"navigator-usage-account",children:_})]}),(0,n.jsx)("span",{className:"navigator-usage-live","aria-live":"polite",children:b})]});return p?(0,n.jsxs)("div",{className:"navigator-usage-shell",children:[(0,n.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!S,"aria-label":S?`${D}${null===q?"":`, ${q}`}`:u("usage.showLess"),onClick:()=>{let e=!S;C(e);try{window.localStorage.setItem(vk,e?"1":"0")}catch{}},children:[(0,n.jsx)("span",{className:"navigator-usage-label",children:S?U.label:u("usage.showLess")}),S&&(0,n.jsx)("span",{className:"navigator-usage-value",style:U.danger?{color:"var(--danger)"}:void 0,children:U.value}),S&&null!==q&&(0,n.jsx)("span",{className:"navigator-usage-alert",children:q}),(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:S?"rotate(0deg)":"rotate(180deg)"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),S?null:V]}):V}let vI=["casual","polite","formal","haggling","urgent"],vM=["male","female"],vE=["20s","30s","40s","50s","60s"],v$=["child","younger","older","parent","grandparent"],vR=(e,t)=>"string"==typeof t&&e.includes(t)?t:void 0;function vL(e){if(!e||"object"!=typeof e)return{};let t={},r=vR(vI,e.mood),n=vR(vM,e.gender),a=vR(vE,e.age),i=vR(vM,e.partnerGender),s=vR(v$,e.partnerAge);return r&&(t.mood=r),n&&(t.gender=n),a&&(t.age=a),i&&(t.partnerGender=i),s&&(t.partnerAge=s),t}let vA=[{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:"ไทย"},{code:"zh",tag:"zh-CN",englishName:"Chinese",nativeName:"中文"}];function vP(e){return"string"==typeof e?vA.find(t=>t.code===e):void 0}let vF=/[ăâđêôơưàáạảãằắặẳẵầấậẩẫèéẹẻẽềếệểễìíịỉĩòóọỏõồốộổỗờớợởỡùúụủũừứựửữỳýỵỷỹ]/giu,v_=/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9d]/u,vz={ko:/[\uac00-\ud7a3\u1100-\u11ff\u3130-\u318f]/gu,ja:/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9d\u4e00-\u9fff]/gu,zh:/[\u4e00-\u9fff]/gu,th:/[\u0e00-\u0e7f]/gu,vi:vF,en:/[a-z]/giu};function vW(e,t,r){let n=vz[t];return!n||"en"===t&&e.match(vF)||"zh"===t&&v_.test(e)||"ja"===t&&"zh"===r&&!v_.test(e)?0:e.match(n)?.length??0}function vO(e,t,r){let n=vW(e,t.code,r.code),a=vW(e,r.code,t.code);if(n!==a)return n>a?t:r}let vD=String.raw`\d(?:[\d,.:/-]*\d)?`,vH=String.raw`(?:[kK](?![A-Za-z])|%|만|억|천|백)`,vU=String.raw`(?:원|동|위안|달러|엔|바트|đồng|nghìn|ngàn|triệu|tỷ|VND|[$€£¥₩₫]|개|명|시|분|번|층|년|월|일|(?:kg|km|cm|ml|g|m)(?![A-Za-z]))`,vB=String.raw`[$€£¥₩₫]?`,vq=RegExp(`${vB}${vD}(?:\\s?${vH})*(?:\\s?${vD}(?:\\s?${vH})+)*(?:\\s?${vU}){0,2}`,"gu");function vV(e=[],t){return{turns:{},drafts:[],seen:e.filter(e=>"assistant"===e.role).map(e=>e.id),born:{},lastSegmentId:e.reduce((e,t)=>Math.max(e,t.id),-1),nextTurnId:t?.nextTurnId??0,nextDraftId:t?.nextDraftId??0}}let vK=e=>[...e.replace(/\s/gu,"")].slice(-24).join(""),vG=e=>e.match(/[\p{L}\p{N}]/gu)?.length??0,vJ=e=>e.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^\p{L}\p{N}]/gu,""),vZ=[["en","vi"],["ja","zh"]];function vY(e,t,r,n,a){let i=n.echo||vO(n.input,t.mine,t.theirs)?.code===r.code||function(e,t){let r=vJ(e).slice(0,400),n=vJ(t);if(r.length<8||n.length<8)return 0;let a=n.slice(0,Math.min(400,r.length+Math.ceil(.15*r.length)));return 1-function(e,t){let r=Array.from({length:t.length+1},(e,t)=>t);for(let n=1;n<=e.length;n+=1){let a=[n];for(let i=1;i<=t.length;i+=1)a[i]=Math.min(r[i]+1,a[i-1]+1,r[i-1]+ +(e[n-1]!==t[i-1]));r=a}return r[t.length]}(r,a)/Math.max(r.length,a.length)}(n.output,n.input)>=.8;n.echo=i;let s=e.drafts.findIndex(e=>e.language.code===r.code&&e.turnId===n.id),o=n.output.trim();if(i||n.dead){if(s<0)return e;let t=e.drafts.flatMap((e,t)=>t!==s?[e]:null===e.matched?[]:[{...e,text:""}]);return{...e,drafts:t}}if(!o||s<0&&vQ(n)&&a-n.outputSince<800)return e;if(s>=0)return e.drafts[s].text===o?e:{...e,drafts:e.drafts.map((e,t)=>t===s?{...e,text:o}:e)};let l={id:e.nextDraftId,language:r,pair:t,turnId:n.id,text:o,createdAt:a,after:e.lastSegmentId,matched:null};return{...e,drafts:[...e.drafts,l],nextDraftId:e.nextDraftId+1}}function vX(e,t,r){return{...e,turns:{...e.turns,[t.code]:r.slice(-12)}}}let vQ=e=>void 0===vO(e.input,e.pair.mine,e.pair.theirs),v0=(e,t)=>vQ(t)&&!t.echo&&!t.dead&&""!==t.output.trim()&&!e.drafts.some(e=>e.turnId===t.id&&e.language.code===t.target.code);function v1(e,t,r){let n=function(e,t){let r=e;for(let n of Object.values(e.turns))for(let e of n)v0(r,e)&&t-e.outputSince>=800&&(r=vY(r,e.pair,e.target,{...e},t));return r}(e,r),a=new Set(n.seen),i={...n.born},s=n.drafts.filter(e=>null===e.matched&&r-e.createdAt>2e4),o=n.drafts.filter(e=>!s.includes(e)),l=[...s],c=!1;for(let e of t){if("assistant"!==e.role||a.has(e.id)||vG(e.text)<(e.final?4:6))continue;let t=vO(vK(e.text),e.mine,e.theirs);if(t){i[e.id]?.code!==t.code&&(i[e.id]={at:r,code:t.code},c=!0);let n=()=>o.filter(r=>null===r.matched&&r.text&&r.language.code===t.code&&r.createdAt<=i[e.id].at);for(;n().length>1&&r-n()[0].createdAt>15e3;){let e=n()[0];l.push(e),o=o.filter(t=>t!==e)}let s=n()[0];if(s){o=o.map(t=>t===s?{...s,matched:e.id}:t),a.add(e.id),c=!0;continue}}e.final&&(a.add(e.id),c=!0)}let d=new Set(t.map(e=>e.id)),u=o.filter(e=>null===e.matched?r-e.createdAt>2e4:!d.has(e.matched));l.push(...u.filter(e=>null===e.matched)),o=o.filter(e=>!u.includes(e));let p=n.turns;if(l.length>0)for(let e of(p={...p},l))p[e.language.code]=(p[e.language.code]??[]).map(t=>t.id===e.turnId?{...t,dead:!0}:t);let h=t.reduce((e,t)=>Math.max(e,t.id),n.lastSegmentId);return c||0!==l.length||0!==u.length||h!==n.lastSegmentId?{...n,turns:p,drafts:o,seen:[...a],born:i,lastSegmentId:h}:n}function v2(){return{segments:[],open:{user:null,assistant:null},nextId:0,call:0}}function v8(e){return{...e,open:{user:null,assistant:null},call:e.call+1}}function v4(e){return vO(e.text,e.mine,e.theirs)}function v5(e,t){let r=t.code===e.mine.code;return"user"===e.role===r?"me":"them"}let v6={worklet:"/interpreter-noise/rnnoiseWorklet.js",wasm:"/interpreter-noise/rnnoise.wasm",simdWasm:"/interpreter-noise/rnnoise_simd.wasm"};async function v3(e,t,n,a=v6){if("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode||"object"!=typeof WebAssembly)throw Error("AudioWorklet or WebAssembly is not available");if(0===e.getAudioTracks().length)throw Error("the stream has no audio track");let i=Promise.withResolvers();i.promise.catch(()=>{});let s=()=>i.reject(Error("setup cancelled"));n?.aborted?s():n?.addEventListener("abort",s,{once:!0});let o=e=>Promise.race([e,i.promise]),l=null,c=!1,d=null,u=null,p=null,h=null,m=()=>{if(c)return;c=!0;let e=l;e&&(e.onstatechange=null,u&&(u.onprocessorerror=null,u.destroy(),u.disconnect()),d?.disconnect(),p?.disconnect(),h?.stop(),"closed"!==e.state&&e.close().catch(()=>{}))};n?.addEventListener("abort",m,{once:!0});try{let i;if(n?.aborted)throw Error("setup cancelled");let s=await o(r.e(5211).then(r.bind(r,55211)));if(n?.aborted)throw Error("setup cancelled");let{RnnoiseWorkletNode:m,loadRnnoise:f}=s,g=new AudioContext({sampleRate:48e3,latencyHint:"interactive"});l=g;let[x]=await Promise.all([o(f({url:a.wasm,simdUrl:a.simdWasm},n?{signal:n}:void 0)),o(g.audioWorklet.addModule(a.worklet))]);if(c)throw Error("setup cancelled");if(i=new Uint8Array(x,0,Math.min(4,x.byteLength)),4!==i.length||0!==i[0]||97!==i[1]||115!==i[2]||109!==i[3])throw Error("the RNNoise wasm did not load");if(48e3!==g.sampleRate)throw Error(`the browser ran the context at ${g.sampleRate} Hz`);if(await o(g.resume()),"running"!==g.state||c)throw Error(`the audio context is ${g.state}`);d=g.createMediaStreamSource(e),u=new m(g,{maxChannels:2,wasmBinary:x}),p=g.createGain();let v=g.createMediaStreamDestination();if(d.connect(u),u.connect(p),p.connect(v),!(h=v.stream.getAudioTracks()[0]??null))throw Error("the audio graph produced no track");u.onprocessorerror=()=>{c||t("the RNNoise processor failed")},g.onstatechange=()=>{c||"running"===g.state||t(`the audio context is ${g.state}`)}}catch(e){throw m(),e}finally{n?.removeEventListener("abort",m),n?.removeEventListener("abort",s)}let f=p,g=!1;return{track:h,setMuted:e=>{c||e===g||(g=e,f.gain.setTargetAtTime(+!e,l.currentTime,.005))},close:m}}class v7{#e;#t;constructor(e=500){this.#t=-1/0,this.#e=e}update(e,t){return e&&(this.#t=t),t-this.#t<this.#e}reset(){this.#t=-1/0}}let v9=e=>{fetch(`/api/live/call/${encodeURIComponent(e)}`,{method:"DELETE"}).catch(()=>{})};async function be(e,t){let r=e?.getSettings().noiseSuppression;if(e&&"boolean"==typeof r&&r!==t)try{await e.applyConstraints({echoCancellation:!0,noiseSuppression:t,autoGainControl:!0})}catch(e){console.warn("[interpreter] cannot change the browser noise suppression:",e instanceof Error?e.message:String(e))}}let bt=({mine:e,theirs:t,profile:r})=>`${e.code}>${t.code}|${r.mood??""}|${r.gender??""}|${r.age??""}|${r.partnerGender??""}|${r.partnerAge??""}`;async function br(e,t,r){let n=await fetch("/api/live/draft-secret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mine:e.code,theirs:t.code}),signal:r});if(!n.ok)throw Error(`the secret request failed (${n.status})`);let a=await n.json(),i=a&&"object"==typeof a&&"sessions"in a&&Array.isArray(a.sessions)?a.sessions:[],s=[];for(let r of[e,t]){let e=i.find(e=>e&&"object"==typeof e&&"language"in e&&e.language===r.code),t=e&&"object"==typeof e&&"secret"in e?e.secret:void 0;if("string"!=typeof t||!t)throw Error("the secret answer was incomplete");s.push({language:r,secret:t})}return s}var bn=r(66592),ba=r.n(bn);async function*bi(e){let t=e.getReader(),r=new TextDecoder("utf-8",{fatal:!0}),n="";try{for(;;){let e,a=await t.read();for(n+=r.decode(a.value,{stream:!a.done});-1!==(e=n.indexOf("\n\n"));){let t=n.slice(0,e);if(n=n.slice(e+2),!t.startsWith("data: "))throw Error("Invalid interpreter stream frame");let r=JSON.parse(t.slice(6));if(!r||"delta"!==r.type&&"done"!==r.type&&"error"!==r.type)throw Error("Invalid interpreter stream event");if("delta"===r.type&&"string"!=typeof r.text)throw Error("Invalid interpreter delta");if("done"===r.type&&("string"!=typeof r.text||!r.text.trim()||"string"!=typeof r.source||"string"!=typeof r.target))throw Error("Invalid interpreter completion");if("error"===r.type&&"live-auth"!==r.error&&"live-upstream"!==r.error)throw Error("Invalid interpreter failure");if(yield r,"delta"!==r.type)return}if(a.done)throw Error("Interpreter stream ended before completion")}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}function bs({mine:e,theirs:t,profile:r,visible:i}){let{tt:s}=en(),[o,l]=(0,a.useState)(e.code),[c,d]=(0,a.useState)(""),[u,p]=(0,a.useState)([]),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),b=(0,a.useRef)(null),y=(0,a.useRef)(!1),w=(0,a.useRef)(null),k=(0,a.useRef)(null),j=o===e.code?e:t,S=o===e.code?t:e;(0,a.useEffect)(()=>(i||(b.current?.abort(),b.current=null,m(!1),v(null)),()=>{b.current?.abort(),b.current=null}),[i]),(0,a.useEffect)(()=>{i&&w.current?.scrollIntoView({block:"nearest"})},[u,i,x?.translation]);let C=e=>{b.current?.abort(),b.current=null,m(!1),v(null),g(null),l(e)},N=async n=>{if(n.preventDefault(),y.current||b.current||!c.trim())return;let a=new AbortController;b.current=a,m(!0),g(null);let i=c.trim();v({source:j,target:S,original:i,translation:""});try{let n=await fetch("/api/live/interpret/text",{method:"POST",headers:{"Content-Type":"application/json"},signal:a.signal,body:JSON.stringify({mine:e.code,theirs:t.code,source:j.code,profile:r,text:i,history:u.flatMap(e=>[{role:"user",text:e.original},{role:"assistant",text:e.translation}]).slice(-24)})});if(!n.ok){let e=await n.json();b.current!==a||a.signal.aborted||g("live-auth"===e.error?"live-auth":"live-upstream");return}if(!n.body||!n.headers.get("Content-Type")?.includes("text/event-stream"))throw Error("Invalid translation response");for await(let e of bi(n.body)){if(b.current!==a||a.signal.aborted)return;if("delta"===e.type)v(t=>t?{...t,translation:t.translation+e.text}:null);else if("error"===e.type)g(e.error);else{if(e.source!==j.code||e.target!==S.code)throw Error("Invalid translation direction");p(t=>[...t,{source:j,target:S,original:i,translation:e.text}].slice(-12)),d("")}}}catch{b.current!==a||a.signal.aborted||g("live-upstream")}finally{b.current===a&&(b.current=null,m(!1),v(null),k.current?.focus())}};return(0,n.jsxs)("div",{className:ba().root,hidden:!i,children:[(0,n.jsxs)("div",{className:ba().results,role:"log","aria-label":s("translator.conversation"),children:[u.map((e,t)=>(0,n.jsxs)("article",{className:ba().turn,children:[(0,n.jsxs)("p",{className:ba().label,children:[s("translator.original")," — ",e.source.nativeName]}),(0,n.jsx)("p",{className:ba().original,lang:e.source.tag,children:e.original}),(0,n.jsxs)("p",{className:ba().label,children:[s("translator.translation")," — ",e.target.nativeName]}),(0,n.jsx)("p",{className:ba().translation,lang:e.target.tag,children:e.translation})]},t)),x?(0,n.jsxs)("article",{className:ba().turn,"aria-busy":"true",children:[(0,n.jsxs)("p",{className:ba().label,children:[s("translator.original")," — ",x.source.nativeName]}),(0,n.jsx)("p",{className:ba().original,lang:x.source.tag,children:x.original}),(0,n.jsxs)("p",{className:ba().label,children:[s("translator.typePending")," — ",x.target.nativeName]}),(0,n.jsx)("p",{className:ba().translation,lang:x.target.tag,children:x.translation})]}):null,(0,n.jsx)("div",{ref:w})]}),(0,n.jsxs)("form",{className:ba().composer,onSubmit:N,children:[(0,n.jsxs)("div",{className:ba().direction,children:[(0,n.jsxs)("label",{children:[s("translator.source"),(0,n.jsxs)("select",{value:o,onChange:e=>C(e.target.value),children:[(0,n.jsx)("option",{value:e.code,children:e.nativeName}),(0,n.jsx)("option",{value:t.code,children:t.nativeName})]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>C(S.code),children:s("translator.swapDirection")}),(0,n.jsxs)("span",{"aria-live":"polite",children:["→ ",S.nativeName]})]}),(0,n.jsxs)("label",{className:ba().field,children:[s("translator.typeLabel"),(0,n.jsx)("textarea",{ref:k,value:c,lang:j.tag,maxLength:2e3,rows:3,readOnly:h,"aria-busy":h,placeholder:s("translator.typePlaceholder"),onChange:e=>d(e.target.value),onCompositionStart:()=>{y.current=!0},onCompositionEnd:()=>{y.current=!1}})]}),f?(0,n.jsx)("p",{className:ba().error,role:"alert",children:s("live-auth"===f?"translator.typeAuth":"translator.typeError")}):null,(0,n.jsx)("button",{className:ba().submit,type:"submit",disabled:h||!c.trim(),children:s(h?"translator.typePending":"translator.typeSubmit")})]})]})}let bo="cuelo-translator",bl=[.85,1,1.3];function bc(){let e={mine:vA[0],theirs:vA[1],profile:{},face:!1,size:1,voice:!1,echoGuard:!0,noiseSuppression:!1,fastDrafts:!1};try{let t=JSON.parse(window.localStorage.getItem(bo)??"null");if(!t||"object"!=typeof t)return e;let r=vP(t.mine)??e.mine,n=vP(t.theirs)??e.theirs,a=r.code===n.code?{mine:e.mine,theirs:e.theirs}:{mine:r,theirs:n},i="number"==typeof t.size&&Number.isInteger(t.size)&&t.size>=0&&t.size<bl.length?t.size:1;return{...a,profile:vL(t.profile),face:!0===t.face,size:i,voice:!0===t.voice,echoGuard:!1!==t.echoGuard,noiseSuppression:!0===t.noiseSuppression,fastDrafts:!0===t.fastDrafts}}catch{return e}}function bd(){return(0,n.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,n.jsx)("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),(0,n.jsx)("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v3"})]})}function bu(){return(0,n.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:(0,n.jsx)("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2.5"})})}function bp(){return(0,n.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M15 5l-7 7 7 7"})})}function bh(){return(0,n.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("rect",{x:"5",y:"2.5",width:"14",height:"19",rx:"2.5"}),(0,n.jsx)("path",{d:"M5 12h14M9 7.5h6M9 16.5h6M12 5.5v2M12 16.5v2"})]})}function bm(){return(0,n.jsx)("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,n.jsx)("path",{d:"M6 9l6 6 6-6"})})}function bf(){return(0,n.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})})}let bg=e=>e.language??v4(e.segment),bx=e=>{var t;let r;return e.language?v5(e.segment,e.language):(r=v4(t=e.segment))?v5(t,r):void 0};function bv({lines:e,language:t,unknownLabel:r,flipped:a,emptyHint:i}){let s=e.map(e=>({line:e,known:bg(e)})).filter(({known:e})=>void 0===e||e.code===t.code).slice(-3);return(0,n.jsxs)("div",{className:"translator-face-pane","data-flipped":a?"true":void 0,lang:t.tag,children:[(0,n.jsx)("p",{className:"translator-face-label",children:t.nativeName}),(0,n.jsxs)("div",{className:"translator-face-lines",children:[0===s.length&&i?(0,n.jsx)("p",{className:"translator-face-empty",children:i}):null,s.map(({line:e,known:t},a)=>(0,n.jsxs)("p",{className:"translator-face-line","data-latest":a===s.length-1?"true":void 0,"data-side":bx(e)??"them","data-draft":e.draft?"true":void 0,"data-language":t?void 0:"unknown",lang:t?void 0:"",children:[t?null:(0,n.jsx)("span",{className:"translator-face-unknown",children:r}),(0,n.jsx)(bb,{text:e.segment.text})]},e.key))]})]})}function bb({text:e}){return(0,n.jsx)(n.Fragment,{children:(function(e){let t=[],r=0;for(let n of e.matchAll(vq)){let a=n.index??0;a>r&&t.push({text:e.slice(r,a),number:!1}),t.push({text:n[0],number:!0}),r=a+n[0].length}return r<e.length&&t.push({text:e.slice(r),number:!1}),t})(e).map((e,t)=>e.number?(0,n.jsx)("span",{className:"translator-number",children:e.text},t):e.text)})}function by({role:e,label:t,lines:r,pending:i,jumpLabel:s,layoutKey:o}){let l=(0,a.useRef)(null),c=(0,a.useRef)(!0),[d,u]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{let e=l.current;e&&c.current&&(e.scrollTop=e.scrollHeight)},[r,i,o]),(0,n.jsxs)("section",{className:"translator-stream","data-role":e,"aria-label":t,children:[(0,n.jsx)("h3",{className:"translator-stream-label",children:t}),(0,n.jsxs)("div",{ref:l,className:"translator-log",role:"log","aria-label":t,onScroll:()=>{let e=l.current;e&&(c.current=e.scrollHeight-e.scrollTop-e.clientHeight<=32,u(!c.current))},children:[r.map((t,a)=>{let i=bg(t);return(0,n.jsx)("div",{className:"translator-entry","data-side":bx(t)??"them","data-latest":a===r.length-1?"true":void 0,"data-draft":t.draft?"true":void 0,children:(0,n.jsx)("div",{className:"translator-bubble",children:(0,n.jsx)("p",{className:"assistant"===e?"translator-translation":"translator-original",lang:i?.tag,children:(0,n.jsx)(bb,{text:t.segment.text})})})},t.key)}),i?(0,n.jsx)("p",{className:"translator-pending",children:i}):null]}),d?(0,n.jsx)("button",{type:"button",className:"translator-jump",onClick:()=>{let e=l.current;e&&(e.scrollTop=e.scrollHeight)},children:s}):null]})}function bw({visible:e=!0,onBack:t}){let{tt:r,locale:i}=en(),[o,l]=(0,a.useState)(bc),[c,d]=(0,a.useState)("voice"),{mine:u,theirs:p,profile:h,face:m,size:f,voice:g,echoGuard:x,noiseSuppression:v,fastDrafts:b}=o,[y,w]=(0,a.useState)([]),[k,j]=(0,a.useState)(!1),S=(0,a.useRef)(v2()),[C,N]=(0,a.useState)(0),T=(0,a.useRef)(o);(0,a.useEffect)(()=>{window.localStorage.setItem(bo,JSON.stringify({mine:u.code,theirs:p.code,profile:h,face:m,size:f,voice:g,echoGuard:x,noiseSuppression:v,fastDrafts:b}))},[x,m,b,u,v,h,f,p,g]);let I=(0,a.useRef)(()=>{}),M=(0,a.useCallback)(e=>{S.current=function(e,t,r){let n=t.text.replace(/([.!?])(?=[\p{Lu}\p{Lo}])/gu,"$1 "),{segments:a,nextId:i}=e,s=e.open[t.role];if(null===s){if(!n.trim())return e;a=[...a,{id:s=i++,role:t.role,text:n,final:t.final,...r,call:e.call}]}else a=a.map(e=>e.id===s?{...e,text:n,final:t.final}:e);return{...e,segments:a,nextId:i,open:{...e.open,[t.role]:t.final?null:s}}}(S.current,e,T.current),w(S.current.segments),I.current(S.current.segments)},[]),E=function({onTranscript:e,getHistory:t,onReconnect:r,muteMicWhilePlaying:n=!1,playVoice:i=!0,suppressNoise:s=!1}){let[o,l]=(0,a.useState)("idle"),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)(null),j=(0,a.useRef)(!1),S=(0,a.useRef)(new Set),C=(0,a.useCallback)(e=>{if(j.current!==e)for(let t of(j.current=e,S.current))t(e)},[]),N=(0,a.useRef)(null),T=(0,a.useRef)(null),I=(0,a.useRef)(null),M=(0,a.useRef)(null),E=(0,a.useRef)(null),$=(0,a.useRef)(null),R=(0,a.useRef)(null),L=(0,a.useRef)(null),A=(0,a.useRef)(null),P=(0,a.useRef)(!1),F=(0,a.useRef)(!1),_=(0,a.useRef)(!1),z=(0,a.useRef)(0),W=(0,a.useRef)([]),O=(0,a.useRef)(0),D=(0,a.useRef)(!1),H=(0,a.useRef)(void 0),U=(0,a.useRef)(void 0),B=(0,a.useRef)(0),q=(0,a.useRef)(e),V=(0,a.useRef)(t),K=(0,a.useRef)(r),G=(0,a.useRef)(n),J=(0,a.useRef)(i),Z=(0,a.useRef)(s),Y=(0,a.useRef)(null),X=(0,a.useRef)(null),Q=(0,a.useRef)(null),ee=(0,a.useRef)(Promise.resolve()),et=(0,a.useRef)(async()=>{});(0,a.useEffect)(()=>{q.current=e,V.current=t,K.current=r,G.current=n,J.current=i,E.current&&(E.current.muted=!i)},[t,n,r,e,i]),(0,a.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let er=(0,a.useCallback)(()=>{B.current+=1;let e=L.current;L.current=null,F.current=!1,_.current=!1,window.clearTimeout(U.current),U.current=void 0,window.clearTimeout(H.current),H.current=void 0,R.current?.close(),R.current=null,N.current?.close(),N.current=null,T.current=null,I.current=null,e&&v9(e)},[]),en=(0,a.useCallback)(()=>{let e=$.current;$.current=null,e&&(window.clearInterval(e.timer),e.source?.disconnect(),"closed"!==e.context.state&&e.context.close().catch(()=>{}))},[]),ea=(0,a.useCallback)(()=>{let e=Y.current;Y.current=null,e?.close()},[]),ei=(0,a.useCallback)(()=>{let e=$.current,t=M.current?.getAudioTracks()[0];if(!e||!t)return;e.analyser.getFloatTimeDomainData(e.samples);let r=e.gate.update(function(e){if(0===e.length)return 0;let t=0;for(let r of e)t+=r*r;return Math.sqrt(t/e.length)}(e.samples)>=.01,performance.now()),n=G.current&&J.current&&r;t.enabled===n&&(t.enabled=!n),C(n),Y.current?.setMuted(n)},[C]),es=(0,a.useCallback)(()=>{if(en(),"function"!=typeof window.AudioContext)return;let e=null;try{(e=new window.AudioContext).resume().catch(()=>{});let t=e.createAnalyser();t.fftSize=1024;let r=e.createGain();r.gain.value=0,t.connect(r),r.connect(e.destination),$.current={context:e,analyser:t,samples:new Float32Array(t.fftSize),source:null,remote:null,gate:new v7,timer:window.setInterval(ei,50)}}catch(t){e&&"closed"!==e.state&&e.close().catch(()=>{}),console.warn("[interpreter] echo guard unavailable:",t instanceof Error?t.message:String(t))}},[ei,en]),eo=(0,a.useCallback)(()=>{for(let e of(er(),en(),Q.current?.abort(),k(null),C(!1),ea(),X.current=null,A.current=null,P.current=!1,M.current?.getTracks()??[]))e.stop();M.current=null;let e=E.current;E.current=null,e&&(e.srcObject=null,e.remove())},[ea,er,C,en]),el=(0,a.useCallback)(e=>{eo(),g(!1),y(!1),l(e)},[eo]),ec=(0,a.useCallback)((e,t)=>{P.current?(d(e),p(t??null),el("error")):eo()},[eo,el]),ed=(0,a.useCallback)(()=>P.current&&F.current&&_.current,[]),eu=(0,a.useCallback)(e=>{B.current===e&&ed()&&(g(!1),D.current=!0,l("live"))},[ed]),ep=(0,a.useCallback)(()=>{let e=I.current;if(!e)return;let t=E.current;t&&t.srcObject!==e&&(t.srcObject=e);let r=$.current;if(r&&r.remote!==e){r.source?.disconnect(),r.source=null,r.remote=e;try{r.source=r.context.createMediaStreamSource(e),r.source.connect(r.analyser)}catch(e){console.warn("[interpreter] echo guard cannot read the interpreted voice:",e instanceof Error?e.message:String(e))}}},[]),eh=(0,a.useCallback)(async e=>{let t=e.getAudioTracks()[0]??null;if(!t)return null;if(Z.current&&!Y.current&&X.current!==e){let t=new AbortController;Q.current=t;let r=window.setTimeout(()=>t.abort(),3e3);try{Y.current=await v3(e,t=>{M.current===e&&(console.warn("[interpreter] noise suppression stopped, using the raw microphone:",t),X.current=e,ea(),et.current(B.current,e).catch(()=>{}))},t.signal)}catch(t){Z.current&&M.current===e&&(X.current=e,console.warn("[interpreter] noise suppression unavailable, using the raw microphone:",t instanceof Error?t.message:String(t)))}finally{window.clearTimeout(r),Q.current===t&&(Q.current=null)}M.current!==e&&ea()}return Z.current&&M.current===e&&Y.current?Y.current.track:t},[ea]),em=(0,a.useCallback)((e,t)=>{let r=async()=>{let r=T.current;if(B.current!==e||!r)return;let n=await eh(t);if(B.current!==e||T.current!==r)return;let a=t.getAudioTracks()[0]??null;await be(a,n===a);try{await r.replaceTrack(n)}catch(e){if(n===a)throw e;console.warn("[interpreter] the call refused the denoised track, using the raw microphone:",e instanceof Error?e.message:String(e)),X.current=t,ea(),await be(a,!0),await r.replaceTrack(a),k(a);return}k(n),Y.current&&Y.current.track!==n&&ea()},n=ee.current.then(r);return ee.current=n.catch(()=>{}),n},[eh,ea]);(0,a.useEffect)(()=>{et.current=em},[em]),(0,a.useEffect)(()=>{Z.current=s,X.current=null,s||Q.current?.abort();let e=M.current;e&&T.current&&em(B.current,e).catch(e=>{console.warn("[interpreter] cannot switch the microphone track:",e instanceof Error?e.message:String(e))})},[em,s]);let ef=(0,a.useCallback)(async(e,t)=>{if(B.current===e&&T.current){try{await em(e,t)}catch(t){B.current===e&&ec("failed",t instanceof Error?t.message:String(t));return}B.current===e&&(_.current=!0,ep(),eu(e))}},[ep,ec,em,eu]),eg=(0,a.useRef)(()=>{}),ex=(0,a.useCallback)((e,t)=>{P.current&&D.current&&M.current&&"auth"!==e?eg.current({reason:e,message:t}):ec(e,t)},[ec]),ev=(0,a.useCallback)(async(e,t)=>{try{let r,n,a=new RTCPeerConnection;if(N.current=a,T.current=a.addTransceiver("audio",{direction:"sendrecv"}).sender,a.ontrack=t=>{B.current===e&&N.current===a&&(I.current=t.streams[0]??new MediaStream([t.track]),ep())},a.onconnectionstatechange=()=>{B.current===e&&"failed"===a.connectionState&&ex("failed","connection failed")},await a.setLocalDescription(await a.createOffer()),await da(a),B.current!==e)return!1;let i=a.localDescription?.sdp;if(!i)throw Error("The browser produced no offer SDP.");let s=await fetch("/api/live/interpret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:i,mine:t.mine.code,theirs:t.theirs.code,context:{profile:t.profile,history:function(e,t){if(0===t.length)return e;let r=new Set(t.map(e=>e.id));return e.filter(e=>!r.has(e.id))}(V.current(),W.current)}})}),o=await s.json().catch(()=>({})),c="",d="";if(o&&"object"==typeof o&&("error"in o&&(r=o.error),"message"in o&&"string"==typeof o.message&&(n=o.message),"callId"in o&&"string"==typeof o.callId&&(c=o.callId),"sdp"in o&&"string"==typeof o.sdp&&(d=o.sdp)),!s.ok||!c||!d)return B.current===e&&ex(di(s.status,r),n),!1;if(B.current!==e)return v9(c),!1;if(await a.setRemoteDescription({type:"answer",sdp:d}),B.current!==e)return a.close(),v9(c),!1;L.current=c;let u=new EventSource(`/api/live/events?callId=${encodeURIComponent(c)}`);return R.current=u,u.onmessage=t=>{let r;if(B.current===e){try{r=JSON.parse(t.data)}catch{return}if(r&&"object"==typeof r&&"type"in r){var n,a;if("state"===r.type&&"state"in r){if("string"!=typeof r.state||(n=r.state,!0!==dn[n]))return;"connecting"===r.state||"live"===r.state||"working"===r.state?ed()&&l(r.state):"error"===r.state?ex("upstream",r.state):P.current&&D.current&&M.current?eg.current():P.current?el(r.state):eo();return}if("transcript"===r.type&&"role"in r&&"text"in r&&"final"in r){P.current&&("user"===r.role||"assistant"===r.role)&&"string"==typeof r.text&&(r.text.trim()&&(z.current=0),"user"===r.role&&r.text.trim()&&(O.current=0),"assistant"===r.role&&r.text.trim()&&y(!1),q.current({role:r.role,text:r.text,final:!0===r.final}));return}if("generation-stopped"===r.type){let e;if(!P.current)return;y(!0),W.current.push(...(e=(a=V.current()).findLastIndex(e=>"user"===e.role))<0?[]:a.slice(e)),O.current+=1,O.current>2?ec("upstream","Codex stopped the interpretation repeatedly."):D.current&&M.current&&eg.current();return}"error"===r.type&&"message"in r&&"string"==typeof r.message&&ex("upstream",r.message)}}},u.onerror=()=>{B.current===e&&L.current&&ex("failed")},F.current=!0,eu(e),!0}catch(t){return B.current===e&&ex("failed",t instanceof Error?t.message:String(t)),!1}},[ep,ec,ed,ex,eo,eu,el]),eb=(0,a.useCallback)(e=>{let t=A.current,r=M.current;if(!P.current||!t||!r)return;if(z.current+=1,z.current>10)return void(e?ec(e.reason,e.message):(v("idle"),el("idle")));er();let n=B.current;g(!0),l("connecting"),K.current();let a=()=>{B.current===n&&ev(n,t).then(e=>{e&&ef(n,r)})};e?H.current=window.setTimeout(a,2e3):a()},[ef,er,ec,ev,el]);(0,a.useEffect)(()=>{eg.current=eb},[eb]);let ey=(0,a.useCallback)(async e=>{let t;try{t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!Z.current,autoGainControl:!0}})}catch(r){let t=r instanceof DOMException?r.name:"";B.current===e&&ec("NotAllowedError"===t||"SecurityError"===t?"mic-denied":"mic-unavailable");return}if(B.current!==e||!T.current){for(let e of t.getTracks())e.stop();return}M.current=t,await ef(e,t)},[ef,ec]),ew=(0,a.useCallback)((e,t,r)=>{let n={mine:e,theirs:t,profile:r};if(A.current&&bt(A.current)===bt(n)||P.current)return;eo(),A.current=n;let a=B.current;U.current=window.setTimeout(()=>{B.current!==a||P.current||eo()},25e3),ev(a,n)},[ev,eo]),ek=(0,a.useCallback)((e,t,r)=>{let n={mine:e,theirs:t,profile:r},a=null!==A.current&&bt(A.current)===bt(n)&&!P.current&&null!==N.current;a||(eo(),A.current=n),window.clearTimeout(U.current),U.current=void 0,P.current=!0,z.current=0,W.current=[],O.current=0,D.current=!1;let i=B.current;d(null),p(null),v(null),g(!1),y(!1),l("connecting");let s=document.createElement("audio");s.autoplay=!0,s.muted=!J.current,E.current=s,es(),ep(),a||ev(i,n),ey(i)},[ey,ep,ev,eo,es]),ej=(0,a.useCallback)(()=>el("idle"),[el]);return(0,a.useEffect)(()=>()=>eo(),[eo]),{state:o,failure:c,detail:u,supported:h,reconnecting:f,ended:x,skipped:b,sendTrack:w,isBlocked:(0,a.useCallback)(()=>j.current,[]),onBlockedChange:(0,a.useCallback)(e=>(S.current.add(e),()=>void S.current.delete(e)),[]),prepare:ew,start:ek,stop:ej}}({onTranscript:M,getHistory:(0,a.useCallback)(()=>S.current.segments.filter(e=>e.text.trim()).slice(-24).map(({id:e,role:t,text:r})=>({id:e,role:t,text:r})),[]),onReconnect:(0,a.useCallback)(()=>{S.current=v8(S.current),N(S.current.call)},[]),muteMicWhilePlaying:x,playVoice:g,suppressNoise:v}),$="connecting"===E.state||"live"===E.state||"working"===E.state,R=function({enabled:e,epoch:t,pairRef:r,segments:n,sendTrack:i,isBlocked:s,onBlockedChange:o}){let[l,c]=(0,a.useState)(()=>vV()),d=(0,a.useRef)(l),u=(0,a.useRef)(n),p=(0,a.useRef)(i),h=(0,a.useRef)(s),m=(0,a.useRef)(o),f=(0,a.useRef)(null),g=(0,a.useRef)(e),x=(0,a.useCallback)(e=>{d.current=e,c(e)},[]);(0,a.useEffect)(()=>{u.current=n,p.current=i,h.current=s,m.current=o,g.current=e});let v=(0,a.useCallback)(e=>{g.current&&x(v1(d.current,e,performance.now()))},[x]),b=(0,a.useCallback)(()=>{x(vV([],d.current))},[x]);(0,a.useEffect)(()=>{var t;let n,a,i,s,o,l,c,g,v,b,y,w,k,j,S,C,N;if(x(vV(u.current,d.current)),!e)return;let T=r.current,I=(t={mine:T.mine,theirs:T.theirs,isBlocked:()=>h.current(),onBlockedChange:e=>m.current(e),onInput:(e,t)=>x(function(e,t,r,n,a){let i;if(!n)return e;let s=(e.turns[r.code]??[]).map(e=>({...e})),o=s.at(-1),l=o?a-o.inputAt:1/0,c=void 0!==o&&l<=1500&&!(l>600&&function(e,t,r){if(vZ.some(t=>t.includes(e.mine.code)&&t.includes(e.theirs.code)))return!1;let n=vO(t,e.mine,e.theirs),a=vO(r,e.mine,e.theirs);return void 0!==n&&void 0!==a&&n.code!==a.code}(t,o.input,n)),d=e;return c&&o?(i=o,i.input+=n,i.inputAt=a):(i={id:d.nextTurnId,pair:t,target:r,input:n,output:"",inputAt:a,outputAt:-1/0,outputSince:a,echo:!1,dead:!1},d={...d,nextTurnId:d.nextTurnId+1},s.push(i)),vY(vX(d,r,s),t,r,i,a)}(d.current,T,e,t,performance.now())),onOutput:(e,t)=>x(function(e,t,r,n,a){if(!n)return e;let i=(e.turns[r.code]??[]).map(e=>({...e})),s=i.at(-1),o=[...i].reverse().find(e=>a-e.outputAt<=1200)??(s&&a-Math.max(s.inputAt,s.outputAt)<=1500?s:void 0),l=e;return o||(o={id:l.nextTurnId,pair:t,target:r,input:"",output:"",inputAt:a,outputAt:a,outputSince:a,echo:!1,dead:!1},l={...l,nextTurnId:l.nextTurnId+1},i.push(o)),o.output||(o.outputSince=a),o.output+=n,o.outputAt=a,vY(vX(l,r,i),t,r,o,a)}(d.current,T,e,t,performance.now()))},i=new AbortController,s=[],o=null,l=null,c=null,g=null,v=0,b=!1,y=!1,w=()=>{for(let e of s.splice(0))e.onclose=null,e.onmessage=null,e.onerror=null,(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)},k=()=>{if(c?.disconnect(),c=null,o&&l&&g)try{(c=o.createMediaStreamSource(new MediaStream([g]))).connect(l)}catch{console.warn("[interpreter] draft captions cannot read the microphone")}},j=()=>{y=!0,n?.(),n=void 0,c?.disconnect(),c=null,l&&(l.port.onmessage=null),l?.disconnect(),l=null,o&&"closed"!==o.state&&o.close().catch(()=>{}),o=null},S=()=>{if(w(),!b&&void 0===a){if(v>=2){console.warn("[interpreter] draft captions stopped; the interpretation goes on without them"),j();return}v+=1,a=window.setTimeout(()=>{a=void 0,N()},2e3)}},C=()=>{b||(b=!0,i.abort(),window.clearTimeout(a),a=void 0,w(),j())},N=async()=>{if(!b)try{let e=await br(t.mine,t.theirs,i.signal);if(b)return;let r=e=>void s.push(e);await Promise.all(e.map(e=>{var n;return n={onInput:t.onInput,onOutput:t.onOutput,onDown:S,register:r},new Promise((t,r)=>{let a=new WebSocket("wss://api.openai.com/v1/realtime/translations?model=gpt-realtime-translate",["realtime",`openai-insecure-api-key.${e.secret}`]);n.register(a);let i=!1;a.onopen=()=>{i=!0,a.send(JSON.stringify({type:"session.update",session:{audio:{input:{transcription:{model:"gpt-realtime-whisper"},noise_reduction:{type:"near_field"}},output:{language:e.language.code}}}})),t(a)},a.onmessage=t=>{let r;try{r=JSON.parse(String(t.data))}catch{return}if(!r||"object"!=typeof r||!("type"in r))return;let a="delta"in r&&"string"==typeof r.delta?r.delta:"";"session.input_transcript.delta"===r.type?n.onInput(e.language,a):"session.output_transcript.delta"===r.type?n.onOutput(e.language,a):"error"===r.type&&(console.warn("[interpreter] a draft session reported an error"),n.onDown())},a.onerror=()=>{i||r(Error("the draft socket could not open"))},a.onclose=()=>{i?n.onDown():r(Error("the draft socket closed before it opened"))}})})),b&&w()}catch{S()}},(async()=>{if("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode){console.warn("[interpreter] draft captions need AudioWorklet"),C();return}try{let e=new AudioContext({sampleRate:24e3});if(o=e,await e.audioWorklet.addModule("/interpreter-draft/capture.js"),b||y||(await e.resume().catch(()=>{}),b||y))return;let r=new AudioWorkletNode(e,"interpreter-draft-capture",{numberOfOutputs:0,processorOptions:{chunkSamples:2400}});r.port.onmessage=e=>{if(!s.some(e=>e.readyState===WebSocket.OPEN))return;let t=JSON.stringify({type:"session.input_audio_buffer.append",audio:function(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}(new Uint8Array(e.data))});for(let e of s)e.readyState===WebSocket.OPEN&&e.send(t)},l=r,r.port.postMessage({muted:t.isBlocked()}),n=t.onBlockedChange(e=>r.port.postMessage({muted:e})),k()}catch{console.warn("[interpreter] draft captions cannot capture the microphone"),C()}})(),N(),{setTrack:e=>{g=e,k()},close:()=>{C()}});return f.current=I,I.setTrack(p.current),()=>{I.close(),f.current=null,x(vV(u.current,d.current))}},[x,e,t,r]),(0,a.useEffect)(()=>{f.current?.setTrack(i)},[i]);let y=l.drafts.length>0||Object.values(l.turns).some(e=>e.some(e=>v0(l,e)));return(0,a.useEffect)(()=>{if(!y)return;let e=window.setInterval(()=>x(v1(d.current,u.current,performance.now())),250);return()=>window.clearInterval(e)},[x,y]),{state:l,reset:b,reconcile:v}}({enabled:b&&$,epoch:C,pairRef:T,segments:y,sendTrack:E.sendTrack,isBlocked:E.isBlocked,onBlockedChange:E.onBlockedChange}),{reconcile:L}=R;(0,a.useEffect)(()=>{I.current=L},[L]);let A=e=>{T.current=e,S.current=v8(S.current),N(S.current.call),E.start(e.mine,e.theirs,e.profile)},P=e=>{e.mine.code!==e.theirs.code&&(l(e),$&&A(e))},F=e=>{P({...o,profile:vL({...h,...e})})},{prepare:_,supported:z,stop:W}=E,O=(0,a.useRef)(W);(0,a.useEffect)(()=>{O.current=W}),(0,a.useEffect)(()=>{e||O.current()},[e]),(0,a.useEffect)(()=>{e&&"voice"===c&&!$&&!0===z&&window.isSecureContext&&_(u,p,h)},[$,u,c,_,h,z,p,e]),(0,a.useEffect)(()=>{"text"===c&&O.current()},[c]),(0,a.useEffect)(()=>{if(!$||!("wakeLock"in navigator))return;let e=null,t=!1,r=()=>{"visible"===document.visibilityState&&(!e||e.released)&&navigator.wakeLock.request("screen").then(r=>{t?r.release():e=r}).catch(()=>{})};return r(),document.addEventListener("visibilitychange",r),()=>{t=!0,document.removeEventListener("visibilitychange",r),e?.release()}},[$]);let D=!1===E.supported,H=!window.isSecureContext,U="error"===E.state&&E.failure?function(e,t,r){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:r??""});default:return e("translator.failed",{error:r??""})}}(r,E.failure,E.detail):E.skipped&&$?r("translator.generationSkipped"):"idle"!==E.ended||$?H?r("translator.insecure"):D?r("translator.unsupported"):null:r("translator.idleStopped"),B=y.at(-1),q=$&&void 0!==B&&B.call===C&&"user"===B.role,V="error"===E.state?"error":E.reconnecting?"reconnecting":"connecting"===E.state?"connecting":"live"===E.state||"working"===E.state?q?"translating":"listening":"idle",K="reconnecting"===V?r("translator.reconnecting"):"connecting"===V?r("translator.connecting"):"translating"===V?r("translator.translating"):"listening"===V?r("translator.live"):"error"===V?r("translator.errorStatus"):"",G="text"===c||$||y.length>0,J=!G||k,Z={"--translator-scale":String(bl[f]??1)},Y="ko"===i?"가":"A",X=$||!(D||H||null===E.supported),Q=(0,a.useMemo)(()=>(function(e,t){let r=new Map(t.drafts.filter(e=>null!==e.matched).map(e=>[e.matched,e])),n=[],a=t.drafts.some(e=>null===e.matched&&e.text);for(let i of e)!r.has(i.id)&&(a&&"assistant"===i.role&&!i.final&&!t.seen.includes(i.id)&&6>vG(i.text)||n.push({order:i.id,line:{key:`s${i.id}`,segment:i,draft:!1}}));for(let r of t.drafts){let t=r.after+.5+1e-6*r.id;if(null===r.matched){if(!r.text)continue;let e={id:-1-r.id,role:"assistant",text:r.text,final:!1,mine:r.pair.mine,theirs:r.pair.theirs,call:0};n.push({order:t,line:{key:`d${r.id}`,segment:e,draft:!0,language:r.language}});continue}let a=e.find(e=>e.id===r.matched);if(!a)continue;let i=""!==r.text&&!a.final&&a.text.trim().length<r.text.length;n.push({order:t,line:{key:`d${r.id}`,segment:i?{...a,text:r.text}:a,draft:i,language:r.language}})}return n.sort((e,t)=>e.order-t.order).map(e=>e.line)})(y,R.state),[y,R.state]),ee=(0,a.useMemo)(()=>Q.filter(e=>"assistant"===e.segment.role),[Q]),et=(0,a.useMemo)(()=>Q.filter(e=>"user"===e.segment.role),[Q]),er=`${f}|${J?"setup":""}|${$?"active":""}`,ea=()=>{$?E.stop():(j(!1),A(o))},ei=e=>vA.map(t=>(0,n.jsx)("option",{value:t.code,disabled:t.code===e.code,children:t.nativeName},t.code)),es=(0,n.jsxs)("p",{className:"translator-status","data-phase":V,role:"status","aria-live":"polite",children:["idle"===V?null:(0,n.jsx)("span",{className:"translator-status-dot","aria-hidden":"true"}),K]}),eo=e=>(0,n.jsxs)("button",{type:"button",className:"translator-call-button","data-compact":e?"true":void 0,"aria-pressed":$,disabled:!X,onClick:ea,children:[$?(0,n.jsx)(bu,{}):(0,n.jsx)(bd,{}),$?r("translator.stop"):r("translator.start")]});return m&&"voice"===c?(0,n.jsxs)("section",{className:"translator-view","data-face":"true","aria-label":r("translator.title"),hidden:!e,style:Z,children:[(0,n.jsx)("h2",{className:"sr-only",children:r("translator.title")}),(0,n.jsxs)("div",{className:"translator-face",role:"log","aria-label":r("translator.conversation"),children:[(0,n.jsx)(bv,{lines:Q,language:p,unknownLabel:r("translator.unknownLanguage"),flipped:!0}),(0,n.jsxs)("div",{className:"translator-face-bar",children:[U?(0,n.jsx)("p",{className:"translator-face-notice","data-tone":"error"===E.state?"danger":void 0,role:"error"===E.state?"alert":"status",children:U}):null,"idle"===V?null:es,(0,n.jsxs)("div",{className:"translator-face-controls",children:[eo(!0),(0,n.jsxs)("button",{type:"button",className:"translator-face-exit",onClick:()=>l({...o,face:!1}),children:[(0,n.jsx)(bf,{}),r("translator.faceExit")]})]})]}),(0,n.jsx)(bv,{lines:Q,language:u,unknownLabel:r("translator.unknownLanguage"),emptyHint:$?void 0:r("translator.empty")})]})]}):(0,n.jsxs)("section",{className:"translator-view","data-active":$?"true":void 0,"aria-label":r("translator.title"),hidden:!e,style:Z,children:[(0,n.jsxs)("header",{className:"translator-header",children:[(0,n.jsxs)("div",{className:`translator-bar ${ba().toolbar}`,children:[t?(0,n.jsx)("button",{type:"button",className:"translator-icon-button","aria-label":r("translator.back"),title:r("translator.back"),onClick:t,children:(0,n.jsx)(bp,{})}):null,(0,n.jsxs)("div",{className:ba().modes,role:"group","aria-label":r("translator.title"),children:[(0,n.jsx)("button",{type:"button","aria-pressed":"voice"===c,onClick:()=>d("voice"),children:r("translator.modeVoice")}),(0,n.jsx)("button",{type:"button","aria-pressed":"text"===c,onClick:()=>{E.stop(),j(!1),d("text")},children:r("translator.modeType")})]}),G?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h2",{className:"sr-only",children:r("translator.title")}),(0,n.jsxs)("button",{type:"button",className:"translator-pair","aria-expanded":k,"aria-controls":"translator-setup","aria-label":`${r("translator.setup")}: ${u.nativeName} ⇄ ${p.nativeName}`,onClick:()=>j(e=>!e),children:[(0,n.jsxs)("span",{className:"translator-pair-text",children:[(0,n.jsx)("span",{lang:u.tag,children:u.nativeName}),(0,n.jsx)("span",{"aria-hidden":"true",children:" ⇄ "}),(0,n.jsx)("span",{lang:p.tag,children:p.nativeName})]}),(0,n.jsx)(bm,{})]})]}):(0,n.jsx)("h2",{className:"translator-title",children:r("translator.title")}),(0,n.jsxs)("div",{className:"translator-tools",children:[(0,n.jsx)("button",{type:"button",className:"translator-icon-button translator-size-button","aria-label":r("translator.sizeDown"),title:r("translator.sizeDown"),disabled:f<=0,onClick:()=>l({...o,size:Math.max(0,f-1)}),children:(0,n.jsx)("span",{"aria-hidden":"true","data-size":"down",children:Y})}),(0,n.jsx)("button",{type:"button",className:"translator-icon-button translator-size-button","aria-label":r("translator.sizeUp"),title:r("translator.sizeUp"),disabled:f>=bl.length-1,onClick:()=>l({...o,size:Math.min(bl.length-1,f+1)}),children:(0,n.jsx)("span",{"aria-hidden":"true","data-size":"up",children:Y})}),"voice"===c?(0,n.jsx)("button",{type:"button",className:"translator-icon-button","aria-pressed":!1,"aria-label":r("translator.face"),title:r("translator.faceHint"),onClick:()=>l({...o,face:!0}),children:(0,n.jsx)(bh,{})}):null]})]}),J?(0,n.jsxs)("div",{id:"translator-setup",className:"translator-setup",children:[(0,n.jsxs)("div",{className:"translator-languages",children:[(0,n.jsxs)("label",{className:"translator-language",children:[(0,n.jsx)("span",{children:r("translator.me")}),(0,n.jsx)("select",{"aria-label":r("translator.myLanguage"),value:u.code,onChange:e=>{let t=vP(e.target.value);t&&P({...o,mine:t})},children:ei(p)})]}),(0,n.jsx)("button",{type:"button",className:"translator-swap","aria-label":r("translator.swap"),title:r("translator.swap"),onClick:()=>P({...o,mine:p,theirs:u}),children:"⇄"}),(0,n.jsxs)("label",{className:"translator-language",children:[(0,n.jsx)("span",{children:r("translator.them")}),(0,n.jsx)("select",{"aria-label":r("translator.theirLanguage"),value:p.code,onChange:e=>{let t=vP(e.target.value);t&&P({...o,theirs:t})},children:ei(u)})]})]}),(0,n.jsxs)("div",{className:"translator-context",children:[(0,n.jsxs)("label",{className:"translator-language",children:[(0,n.jsx)("span",{children:r("translator.mood")}),(0,n.jsxs)("select",{value:h.mood??"",onChange:e=>F({mood:e.target.value}),children:[(0,n.jsx)("option",{value:"",children:r("translator.notSet")}),vI.map(e=>(0,n.jsx)("option",{value:e,children:r(`translator.mood.${e}`)},e))]})]}),(0,n.jsxs)("label",{className:"translator-language",children:[(0,n.jsx)("span",{children:r("translator.gender")}),(0,n.jsxs)("select",{value:h.gender??"",onChange:e=>F({gender:e.target.value}),children:[(0,n.jsx)("option",{value:"",children:r("translator.notSet")}),vM.map(e=>(0,n.jsx)("option",{value:e,children:r(`translator.gender.${e}`)},e))]})]}),(0,n.jsxs)("label",{className:"translator-language",children:[(0,n.jsx)("span",{children:r("translator.age")}),(0,n.jsxs)("select",{value:h.age??"",onChange:e=>F({age:e.target.value}),children:[(0,n.jsx)("option",{value:"",children:r("translator.notSet")}),vE.map(e=>(0,n.jsx)("option",{value:e,children:r(`translator.age.${e}`)},e))]})]})]}),(0,n.jsxs)("div",{className:"translator-context",children:[(0,n.jsxs)("label",{className:"translator-language",children:[(0,n.jsx)("span",{children:r("translator.partnerGender")}),(0,n.jsxs)("select",{value:h.partnerGender??"",onChange:e=>F({partnerGender:e.target.value}),children:[(0,n.jsx)("option",{value:"",children:r("translator.notSet")}),vM.map(e=>(0,n.jsx)("option",{value:e,children:r(`translator.gender.${e}`)},e))]})]}),(0,n.jsxs)("label",{className:"translator-language",children:[(0,n.jsx)("span",{children:r("translator.partnerAge")}),(0,n.jsxs)("select",{value:h.partnerAge??"",onChange:e=>F({partnerAge:e.target.value}),children:[(0,n.jsx)("option",{value:"",children:r("translator.notSet")}),v$.map(e=>(0,n.jsx)("option",{value:e,children:r(`translator.partnerAge.${e}`)},e))]})]})]}),"voice"===c?(0,n.jsxs)("div",{className:"translator-options",children:[(0,n.jsxs)("label",{className:"translator-toggle",children:[(0,n.jsx)("input",{type:"checkbox",checked:g,"aria-describedby":"translator-voice-hint",onChange:e=>l({...o,voice:e.target.checked})}),(0,n.jsx)("span",{children:r("translator.voice")})]}),(0,n.jsx)("p",{id:"translator-voice-hint",className:"translator-options-note",children:r("translator.voiceHint")}),g?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"translator-toggle",children:[(0,n.jsx)("input",{type:"checkbox",checked:x,"aria-describedby":"translator-echo-guard-hint",onChange:e=>l({...o,echoGuard:e.target.checked})}),(0,n.jsx)("span",{children:r("translator.echoGuard")})]}),(0,n.jsx)("p",{id:"translator-echo-guard-hint",className:"translator-options-note",children:r("translator.echoGuardHint")})]}):null,(0,n.jsxs)("label",{className:"translator-toggle",children:[(0,n.jsx)("input",{type:"checkbox",checked:v,"aria-describedby":"translator-noise-suppression-hint",onChange:e=>l({...o,noiseSuppression:e.target.checked})}),(0,n.jsx)("span",{children:r("translator.noiseSuppression")})]}),(0,n.jsx)("p",{id:"translator-noise-suppression-hint",className:"translator-options-note",children:r("translator.noiseSuppressionHint")}),(0,n.jsxs)("label",{className:"translator-toggle",children:[(0,n.jsx)("input",{type:"checkbox",checked:b,"aria-describedby":"translator-fast-drafts-hint",onChange:e=>l({...o,fastDrafts:e.target.checked})}),(0,n.jsx)("span",{children:r("translator.fastDrafts")})]}),(0,n.jsx)("p",{id:"translator-fast-drafts-hint",className:"translator-options-note",children:r("translator.fastDraftsHint")})]}):null,y.length>0?(0,n.jsx)(s.r,{variant:"ghost",size:"small",className:"translator-clear",onClick:()=>{var e;e=S.current,S.current={...v2(),call:e.call,nextId:e.nextId},w([]),R.reset()},children:r("translator.clear")}):null]}):null]}),"voice"===c&&U?(0,n.jsx)("p",{className:"translator-banner","data-tone":"error"===E.state?"danger":void 0,role:"error"===E.state?"alert":"status",children:U}):null,(0,n.jsx)(bs,{mine:u,theirs:p,profile:h,visible:e&&"text"===c},`${u.code}>${p.code}`),"voice"===c&&(0!==y.length||$?(0,n.jsxs)("div",{className:"translator-streams","aria-label":r("translator.conversation"),children:[(0,n.jsx)(by,{role:"assistant",label:r("translator.translation"),lines:ee,pending:"translating"===V?r("translator.translationPending"):null,jumpLabel:r("translator.jumpLatest"),layoutKey:er}),(0,n.jsx)(by,{role:"user",label:r("translator.original"),lines:et,pending:null,jumpLabel:r("translator.jumpLatest"),layoutKey:er})]}):(0,n.jsx)("div",{className:"translator-log",children:(0,n.jsx)("p",{className:"translator-empty",children:r("translator.empty")})})),"voice"===c?(0,n.jsxs)("div",{className:"translator-dock",children:[es,eo($)]}):null]})}function bk({onOpen:e}){let{tt:t}=en();return(0,n.jsxs)("div",{id:"navigator-translator-panel",className:"translator-panel",children:[(0,n.jsx)("p",{className:"translator-panel-hint",children:t("translator.panelHint")}),e?(0,n.jsx)("button",{type:"button",className:"translator-panel-open",onClick:e,children:t("translator.open")}):null]})}let bj="git pull --ff-only && node install.mjs setup",bS={done:!0,"handed-off":!0,"restart-required":!0,failed:!0};function bC(e){return"unknown"===e?e:`v${e}`}function bN(){let{locale:e,t}=(0,z.s)(),r=B(),[i,s]=(0,a.useState)(null),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),h=(0,a.useRef)(null),m=(0,a.useRef)(null),f=(0,a.useRef)(null),g=(0,a.useRef)(null),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(null),[w,k]=(0,a.useState)(!1),[j,S]=(0,a.useState)(null),[C,N]=(0,a.useState)(!1),T=(0,a.useCallback)(()=>{let e=m.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:r,maxHeight:n}=d3(e.top,e.bottom,t,d7(t,.72,620),{margin:12,minHeight:0}),a=Math.min(430,window.innerWidth-24),i=Math.max(12,window.innerWidth-a-12);v({left:Math.min(e.right+8,i),width:a,maxHeight:n,..."above"===r?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,a.useEffect)(()=>o?(T(),window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),window.visualViewport?.addEventListener("resize",T),window.visualViewport?.addEventListener("scroll",T),()=>{window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0),window.visualViewport?.removeEventListener("resize",T),window.visualViewport?.removeEventListener("scroll",T)}):void v(null),[o,T]),(0,a.useEffect)(()=>{let e,t=!1,r=null,n=0,a=()=>{clearTimeout(e),e=void 0},i=()=>{a(),t||"visible"!==document.visibilityState||(e=setTimeout(()=>void o(),36e5))},o=async()=>{if(t||r)return;let e=new AbortController;r=e,n=Date.now();try{let r=await fetch("/api/updates",{cache:"no-store",signal:e.signal});if(!r.ok)return;let n=await r.json();t||s(n)}catch{}finally{r===e&&(r=null),i()}},l=()=>{"visible"!==document.visibilityState?a():r||(Date.now()-n>=1e4?o():void 0===e&&i())};return o(),document.addEventListener("visibilitychange",l),window.addEventListener("focus",l),window.addEventListener("online",l),()=>{t=!0,a(),r?.abort(),document.removeEventListener("visibilitychange",l),window.removeEventListener("focus",l),window.removeEventListener("online",l)}},[]);let I=(0,a.useCallback)(async e=>{try{let t=await fetch("/api/updates/apply",{cache:"no-store",signal:e});if(!t.ok)return null;return await t.json()}catch{return null}},[]);(0,a.useEffect)(()=>{let e=new AbortController;return I(e.signal).then(t=>{t&&!e.signal.aborted&&(y(t),t.running&&t.job&&S(t.job.currentVersion))}),()=>e.abort()},[I]);let M=(0,a.useCallback)(async e=>{d(null);let r=0;try{let e=await fetch("/api/agent/running",{cache:"no-store"});if(e.ok){let t=await e.json();r=t.runningSessionIds?.length??0}}catch{r=0}let n=r>0?t("updates.applyConfirmBusy",{version:bC(e),count:r}):t("updates.applyConfirm",{version:bC(e)});if(window.confirm(n)){k(!0);try{let e=await fetch("/api/updates/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),r=await e.json();if(!e.ok)return void d(r.error??t("updates.applyStartFailed",{reason:String(e.status)}));y(r),r.job&&S(r.job.currentVersion)}catch(e){d(t("updates.applyStartFailed",{reason:e instanceof Error?e.message:String(e)}))}finally{k(!1)}}},[t]);if((0,a.useEffect)(()=>{let e;if(!j)return;let t=!1,r=async()=>{let n=await I();if(!t){if(N(null===n),n){if(y(n),n.runningVersion!==j&&"unknown"!==n.runningVersion)return void window.location.reload();if(n.job&&bS[n.job.phase]&&!n.running)return void S(null)}e=setTimeout(()=>void r(),n?2e3:5e3)}};return e=setTimeout(()=>void r(),2e3),()=>{t=!0,clearTimeout(e)}},[j,I]),(0,a.useEffect)(()=>()=>{clearTimeout(h.current??void 0),h.current=null},[]),(0,a.useEffect)(()=>{if(!o)return;let e=e=>{m.current?.contains(e.target)||f.current?.contains(e.target)||l(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),l(!1),g.current?.focus({preventScroll:!0}))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[o]),!i?.updateAvailable||!i.latestRelease)return null;let E=i.latestRelease,$=E.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(E.publishedAt)):null,R=E.body.trim()||E.name,L=b?.job??null,A=w||!!j||!!b?.running,P=async e=>{try{await rm(e),clearTimeout(h.current??void 0),p(e),h.current=setTimeout(()=>p(null),1600)}catch{d(t("updates.copyFailed"))}};return(0,n.jsxs)("div",{ref:m,"data-dismissible-layer":o?"":void 0,style:{position:"relative",width:"100%"},children:[(0,n.jsxs)("button",{ref:g,type:"button","aria-expanded":o,"aria-haspopup":"dialog",onClick:()=>{l(e=>!e),d(null)},title:t("updates.availableTitle",{version:bC(E.version)}),style:{width:"100%",minHeight:r?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:"var(--radius-surface)",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,n.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,n.jsx)("span",{children:t("updates.available")}),(0,n.jsx)("span",{style:{color:"var(--text)",fontVariantNumeric:"tabular-nums"},children:bC(E.version)})]}),o&&x&&(0,q.createPortal)((0,n.jsxs)("div",{ref:f,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:x.left,top:x.top,bottom:x.bottom,zIndex:700,width:x.width,maxHeight:x.maxHeight,display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"0 18px 46px rgba(0,0,0,0.28)"},children:[(0,n.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,n.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.dialogEyebrow")}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text)",fontSize:15,fontWeight:650},children:t("updates.dialogTitle")})]}),(0,n.jsx)("div",{style:{color:"var(--warning)",fontFamily:"var(--font-mono)",fontSize:12,fontVariantNumeric:"tabular-nums"},children:bC(E.version)})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 14px",marginTop:9,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{children:t("updates.current",{version:bC(i.currentAppVersion)})}),$&&(0,n.jsx)("span",{children:$})]})]}),(0,n.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,n.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.changelog")}),(0,n.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,n.jsx)(rb,{children:R})})]}),(0,n.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px 12px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:9,marginBottom:10},children:(0,n.jsx)("a",{href:E.htmlUrl,target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",fontSize:11,textDecoration:"underline",textUnderlineOffset:3},children:t("updates.viewRelease")})}),b?.supported&&(0,n.jsxs)("div",{style:{marginBottom:11},children:[(0,n.jsx)("button",{type:"button",onClick:()=>void M(E.version),disabled:A,style:{width:"100%",minHeight:r?44:32,padding:"6px 12px",border:"none",borderRadius:"var(--radius-control)",background:"var(--accent)",color:"var(--bg)",fontSize:12,fontWeight:600,cursor:A?"not-allowed":"pointer",opacity:A?.65:1},children:A?t("updates.applyBusy"):t("updates.apply")}),L&&(0,n.jsxs)("div",{style:{marginTop:8,fontSize:11,lineHeight:1.45},children:[(0,n.jsxs)("div",{role:"status","aria-live":"polite",style:{color:"failed"===L.phase?"var(--danger)":"var(--text)",fontFamily:"var(--font-mono)"},children:[t(`updates.phase.${L.phase}`),L.targetRef?` \xb7 ${L.targetRef}`:""]}),"failed"===L.phase&&L.error&&(0,n.jsx)("div",{style:{marginTop:4,color:"var(--danger)",overflowWrap:"anywhere"},children:L.error}),"handed-off"===L.phase&&(0,n.jsx)("div",{style:{marginTop:4,color:"var(--text-muted)"},children:t("updates.handedOff")}),j&&(0,n.jsx)("div",{style:{marginTop:4,color:C?"var(--warning)":"var(--text-muted)"},children:t("updates.waitingForRestart")}),(0,n.jsx)("div",{style:{marginTop:4,color:"var(--text-dim)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)"},children:t("updates.logPath",{path:L.logPath})})]})]}),b&&!b.supported&&b.reason&&(0,n.jsxs)("div",{style:{marginBottom:10,color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,n.jsx)("div",{children:t("updates.unsupported")}),(0,n.jsx)("div",{style:{marginTop:4,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:t("updates.unsupportedReason",{reason:b.reason})})]}),(0,n.jsxs)("div",{style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,n.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)"},children:t("updates.manual")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,marginTop:6,padding:"6px 7px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("code",{style:{flex:1,minWidth:0,overflowWrap:"anywhere",color:"var(--text)"},children:bj}),(0,n.jsx)("button",{type:"button",onClick:()=>void P(bj),title:u===bj?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":u===bj?t("updates.commandCopied"):t("updates.copyCommand"),style:{flex:"0 0 auto",width:r?44:24,height:r?44:24,padding:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:u===bj?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:u===bj?(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.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,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,n.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]}),c&&(0,n.jsx)("div",{role:"alert",style:{marginTop:9,color:"var(--danger)",fontSize:11,lineHeight:1.45},children:c})]})]}),document.body)]})}let bT={ok:"정상",watch:"주의",problem:"문제",unknown:"미확인"};function bI(e){let t=Date.parse(e);return Number.isNaN(t)?null:new Date(t+324e5).toISOString()}function bM(e){return bI(e)?.slice(0,10)??e}function bE(e){let t=bI(e);return t?`${t.slice(0,10)} ${t.slice(11,16)}`:e}function b$(e){let t=Date.parse(e);return Number.isNaN(t)?e:bM(new Date(t-1).toISOString())}function bR(e){let{currentStart:t,currentEnd:r,previousStart:n}=e.window;return{current:`${bM(t)} ~ ${b$(r)}`,previous:`${bM(n)} ~ ${b$(t)}`}}function bL(e){let[t,r]=String(e).split("."),n=t.startsWith("-")?"-":"",a=(n?t.slice(1):t).replace(/\B(?=(\d{3})+(?!\d))/g,",");return`${n}${a}${r?`.${r}`:""}`}function bA(e,t){let r=10**t;return Math.round(e*r)/r}function bP(e,t){if(null===t)return"측정 불가";switch(e){case"count":return`${bL(bA(t,2))}건`;case"ratio":return`${(100*t).toFixed(1)}%`;case"usd":return`$${bL(bA(t,2))}`;case"ms":return t>=1e3?`${bL(bA(t/1e3,1))}초`:`${bL(bA(t,0))}ms`;case"tokens":return`${bL(Math.round(t))} 토큰`}}function bF(e,t=""){let{unit:r,current:n,previous:a}=e;if(null===n||null===a)return null;let i=n-a;if(0===i)return"없음";let s=i>0?"+":"-";if("ratio"===r)return`${s}${(100*Math.abs(i)).toFixed(1)}%p`;let o=bP(r,Math.abs(i)),l=0===a?"":` (${s}${bA(Math.abs(i)/Math.abs(a)*100,0)}%)`;return`${s}${o}${t}${l}`}function b_(e){return e<36e5?`${Math.max(0,Math.floor(e/6e4))}분`:e<864e5?`${Math.floor(e/36e5)}시간`:`${bA(e/864e5,1)}일`}let bz="관찰 중";function bW(e,t){let r=t.perDay?"/일":"",n=(e,r)=>null!==e&&t.perDay?r>0?e/(r/864e5):null:e,a=n(e.current,t.afterMs),i=n(t.before,t.beforeMs),s=t=>`${bP(e.unit,t)}${null===t?"":r}`;return{after:t.observing?bz:s(a),before:s(i),afterWindow:b_(t.afterMs),beforeWindow:b_(t.beforeMs),change:t.observing?bz:bF({unit:e.unit,current:a,previous:i},r)}}let bO={date:0,"after-deploy":0,condition:1,none:2};function bD(e){return[...e].sort((e,t)=>e.overdue!==t.overdue?e.overdue?-1:1:e.dueDate&&t.dueDate&&e.dueDate!==t.dueDate?e.dueDate<t.dueDate?-1:1:!!e.dueDate!=!!t.dueDate?e.dueDate?-1:1:bO[e.dueKind]-bO[t.dueKind])}function bH(e){if("condition"===e.dueKind)return"조건이 생기면 점검";if(!e.dueDate)return"점검일 미기재";let t="after-deploy"===e.dueKind?"배포일 기준 계산":"점검일";return`${t} ${e.dueDate}${e.overdue?" \xb7 기한 지남":""}`}function bU(e,t){let r=e.sections.find(e=>e.id===t);if(!r)throw Error(`upkeep section not found: ${t}`);return r}function bB(e){return e.metrics.filter(e=>"ok"!==e.status&&!e.check)}function bq(e){let t=e.filter(e=>e.check);return t.length?["",`점검 완료 표시한 지표 ${t.length}개는 뺐습니다: ${t.map(e=>e.label).join(", ")}`]:[]}function bV(e){let t=bR(e);return[`- 최근 7일: ${t.current}`,`- 비교 기간(직전 7일): ${t.previous}`,`- 보고서 생성: ${bE(e.generatedAt)} (세션 파일 ${bL(e.scannedFiles)}개를 읽음)`]}function bK(e,t){if(!t||!e.timestamp)return null;let r=Date.parse(t.markedAt);return Date.parse(e.timestamp)<r?"고침 전":e.since&&Date.parse(e.since)<r?"고침 전 사용 포함":null}function bG(e,t){return[`${t} (${e.path}, 「${e.title}」):`,"```text",e.text,"```"]}function bJ(e){let{fix:t}=e,r=t?null:bF(e),n=t?bW(e,t):null,a=t&&n?[`- 고침 표시: ${bE(t.markedAt)}. 판정은 이 시각 이후 기록만으로 냈습니다.`,`- 고침 뒤 값(표시 뒤 ${n.afterWindow}): ${n.after}`,`- 고침 전 값(최근 7일 중 표시 전 ${n.beforeWindow}): ${n.before}${!t.observing&&n.change?` (고침 전 대비 변화 ${n.change})`:""}`]:[`- 최근 7일 값: ${bP(e.unit,e.current)}`];return a.push(`- 직전 7일 값: ${bP(e.unit,e.previous)}${r?` (변화 ${r})`:""}`,`- 판정: ${bT[e.status]}`,`- 판정 기준: ${e.criterion}`),e.note&&a.push(`- 해석 주의: ${e.note}`),e.check&&a.push(`- 점검 완료: ${bE(e.check.checkedAt)}${e.check.note?` \xb7 ${e.check.note}`:""}. 원인을 확인했지만 고친 게 아니라 행 판정은 그대로이고, 섹션 판정과 전체\xb7섹션 프롬프트에서는 빠집니다.`),a.push(`- 지표 id(${e.fixable?"고침\xb7점검 표시용":"점검 표시용"}): \`${e.id}\``),e.handoff&&a.push("",...bG(e.handoff,"이 기준을 적은 HANDOFF 항목")),a.push("","근거 사례:"),e.evidence.length?a.push(...e.evidence.map(e=>{let r,n;return r=[e.label],void 0!==e.count&&r.push(`${bL(e.count)}회`),e.sessionId&&r.push(`세션 ${e.sessionId}`),e.sessionPath&&r.push(e.sessionPath),e.timestamp&&r.push(bE(e.timestamp)),(n=bK(e,t))&&r.push(n),e.detail&&r.push(e.detail),`- ${r.join(" \xb7 ")}`})):a.push("- 보고서에 사례가 없습니다. 아래 요청 1번에서 직접 찾아야 합니다."),a}function bZ(e){return[`- 기한: ${bH(e)}`,`- 출처: ${e.ref.path}의 「${e.section}」 절`,"",...bG(e.ref,"HANDOFF 원문")]}function bY(e){return e.warnings.length?["","이 섹션을 만들 때 읽지 못한 자료:",...e.warnings.map(e=>`- ${e}`)]:[]}let bX=["요청:","1. 위 근거 사례의 세션 파일과 경로를 직접 열어, 이 판정이 나온 원인을 찾아 주세요. 근거가 부족하면 그 사실부터 알려 주세요.","2. 원인이 CUELO-private 저장소 범위 안이면 고치고, 고친 동작을 실제로 검증해 주세요.","3. HANDOFF.md와 작업 기록(doc/history)에 원인\xb7조치\xb7검증 결과를 남겨 주세요.","4. 사용자 결정이 필요한 일(기준 변경, 비용, 삭제, 상시 승인 범위 밖의 배포 등)이면 고치지 말고 멈춰서 저에게 물어봐 주세요. 이미 확인된 상시 승인 범위의 배포는 재승인을 요청하지 말고 해당 프로젝트의 검증, 커밋과 푸시, 배포 절차를 따라 주세요.",'5. 고쳐서 live 배포와 검증까지 끝난 지표만 고침 표시를 남겨 주세요. 이 CUELO 서버의 `POST /api/upkeep`에 JSON `{"metricId": "<지표 id>", "at": "<고친 동작이 live에 들어간 시각, ISO>"}`을 보내면 됩니다(최근 7일 안, 미래 불가). 원인은 확인했지만 사용자 결정에 따른 사용량처럼 고친 게 아닌 지표는 고침 표시 대신 점검 표시를 남겨 주세요: `POST /api/upkeep/check`에 JSON `{"metricId": "<지표 id>", "note": "<확인한 원인 한 줄>"}`(행 판정은 그대로 두고, 7일 동안 「점검 완료」로 붙어 섹션 판정과 전체\xb7섹션 프롬프트에서 빠집니다). 비밀번호 잠금 등으로 API를 부를 수 없으면 표시 대신 지표 id와 시각\xb7사유를 결과에 적어 주세요.'],bQ=["요청:","1. 이 항목이 적어 둔 관찰\xb7점검을 지금 해 주세요. 판정은 원문에 적힌 조건과 기준으로만 내려 주세요.","2. 점검에서 결함이 나오고 CUELO-private 저장소 범위 안이면 고치고 검증해 주세요.","3. 결과에 맞게 HANDOFF.md 항목(끝났으면 정리, 남으면 다음 점검일)과 작업 기록(doc/history)을 고쳐 주세요.","4. 사용자 결정이 필요한 일이면 고치지 말고 멈춰서 저에게 물어봐 주세요."];function b0(e){let t=e.filter((t,r)=>""!==t||r>0&&""!==e[r-1]);for(;""===t[0];)t.shift();for(;""===t.at(-1);)t.pop();return t.join("\n")}let b1=e=>`보고서를 읽지 못했습니다: ${e}`,b2=e=>`고침 표시를 바꾸지 못했습니다: ${e}`,b8=e=>`점검 표시를 바꾸지 못했습니다: ${e}`,b4="전체 점검 프롬프트",b5=(e,t)=>`${e} \xb7 ${t} 프롬프트`,b6=e=>`「${e}」`,b3="직전 7일",b7="기준",b9="고침 표시",ye="고침 취소",yt=(e,t)=>`${e} \xb7 「${t}」`,yr="점검 완료 표시",yn="점검 취소",ya="실제 문제",yi="오탐",ys=(e,t)=>`${e} (${t})`,yo="알림 닫기",yl={problem:0,watch:1,unknown:2,ok:4},yc=e=>e.check&&"ok"!==e.status?3:yl[e.status];function yd({status:e,text:t}){return(0,n.jsx)("span",{className:"upkeep-status","data-status":e,children:t})}function yu(e){return e.split(/(\([^()]{1,24}\))/).map((e,t)=>t%2?(0,n.jsx)("span",{className:"upkeep-nowrap",children:e},t):e)}function yp({build:e,onStart:t,target:r,label:i="작업 프롬프트로 새 세션",primary:s=!1,children:o}){let[l,c]=(0,a.useState)("idle");(0,a.useEffect)(()=>{if("idle"===l)return;let e=window.setTimeout(()=>c("idle"),2e3);return()=>window.clearTimeout(e)},[l]);let d="copied"===l?"복사함":"failed"===l?"복사 실패":"복사";return(0,n.jsxs)("div",{className:"upkeep-actions",children:[(0,n.jsx)("button",{type:"button",className:"upkeep-button","data-variant":s?"primary":void 0,"aria-label":s?void 0:b5(i,r),onClick:()=>t(e()),children:i}),(0,n.jsx)("button",{type:"button",className:"upkeep-button","aria-label":b5(d,r),onClick:()=>{rm(e()).then(()=>c("copied"),()=>c("failed"))},children:(0,n.jsx)("span",{"aria-live":"polite",children:d})}),o]})}function yh({report:e,section:t,metric:r,sectionCriterion:a,onStart:i,onMark:s,busy:o}){let l,c,d,u,{fix:p,check:h}=r,m=p||r.fixable&&("watch"===r.status||"problem"===r.status)?(0,n.jsx)("button",{type:"button",className:"upkeep-button","data-fix-metric":r.id,"aria-label":yt(p?ye:b9,r.label),disabled:o,onClick:()=>s("fix",r.id,!p,t.id),children:p?ye:b9}):null,f=h||"watch"===r.status||"problem"===r.status?(0,n.jsx)("button",{type:"button",className:"upkeep-button","data-check-metric":r.id,"aria-label":yt(h?yn:yr,r.label),disabled:o,onClick:()=>s("check",r.id,!h,t.id),children:h?yn:yr}):null,g=m||f?(0,n.jsxs)(n.Fragment,{children:[m,f]}):null,x=bF(r),v=p?bW(r,p):null;return(0,n.jsxs)("li",{className:"upkeep-row","data-status":r.status,"data-metric-row":r.id,children:[(0,n.jsxs)("div",{className:"upkeep-row-head",children:[(0,n.jsx)("h4",{children:r.label}),(0,n.jsxs)("span",{className:"upkeep-row-marks",children:[h?(0,n.jsx)("span",{className:"upkeep-checked",children:(l=bE(h.checkedAt).slice(5),`점검 완료 ${l}`)}):null,(0,n.jsx)(yd,{status:r.status,text:bT[r.status]})]})]}),v?(0,n.jsxs)("dl",{className:"upkeep-values",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:ys("고침 뒤",v.afterWindow)}),(0,n.jsx)("dd",{children:v.after})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:ys("고침 전",v.beforeWindow)}),(0,n.jsx)("dd",{children:v.before})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"고침 전 대비"}),(0,n.jsx)("dd",{children:v.change??"—"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:b3}),(0,n.jsx)("dd",{children:bP(r.unit,r.previous)})]})]}):(0,n.jsxs)("dl",{className:"upkeep-values",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"최근 7일"}),(0,n.jsx)("dd",{children:bP(r.unit,r.current)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:b3}),(0,n.jsx)("dd",{children:bP(r.unit,r.previous)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"변화"}),(0,n.jsx)("dd",{children:x??"—"})]})]}),p?(0,n.jsx)("p",{className:"upkeep-line",children:(0,n.jsx)("span",{className:"upkeep-line-label",children:(c=bE(p.markedAt).slice(5),`고침 ${c} 이후 기준`)})}):null,h?.note?(0,n.jsxs)("p",{className:"upkeep-line",children:[(0,n.jsx)("span",{className:"upkeep-line-label",children:"점검 사유"}),h.note]}):null,r.criterionId?(0,n.jsxs)("p",{className:"upkeep-line",title:"실제 문제 / (실제 문제 + 오탐) 비율이며 판정 안 함은 제외합니다.",children:[(0,n.jsx)("span",{className:"upkeep-line-label",children:"규칙 정밀도 (최근 7일 점검)"}),r.precision?(d=r.precision,`${null===d.precision?"—":`${Math.round(100*d.precision)}%`} (실제 문제 ${d.real}건, 오탐 ${d.falsePositive}건)`):"판정 없음"]}):null,r.criterion!==a?(0,n.jsxs)("p",{className:"upkeep-line",children:[(0,n.jsx)("span",{className:"upkeep-line-label",children:b7}),yu(r.criterion)]}):null,r.handoff?(0,n.jsxs)("p",{className:"upkeep-line",children:[(0,n.jsx)("span",{className:"upkeep-line-label",children:"HANDOFF 기준"}),r.handoff.path," \xb7 「",r.handoff.title,"」"]}):null,r.note?(0,n.jsx)("p",{className:"upkeep-line upkeep-note",children:yu(r.note)}):null,r.evidence.length?(0,n.jsxs)("details",{className:"upkeep-details",children:[(0,n.jsx)("summary",{children:(u=r.evidence.length,`근거 사례 ${u}건`)}),(0,n.jsx)("ul",{className:"upkeep-evidence",children:r.evidence.map((e,t)=>(0,n.jsxs)("li",{children:[(0,n.jsxs)("span",{className:"upkeep-evidence-label",children:[e.label,void 0!==e.count?` \xb7 ${e.count}회`:"",e.timestamp?` \xb7 ${bE(e.timestamp)}`:"",bK(e,p)?` \xb7 ${bK(e,p)}`:""]}),e.detail?(0,n.jsx)("span",{className:"upkeep-evidence-detail",children:e.detail}):null,e.sessionId?(0,n.jsxs)("a",{className:"upkeep-evidence-link",href:`/?session=${encodeURIComponent(e.sessionId)}`,target:"_blank",rel:"noopener",title:e.sessionPath??e.sessionId,children:["세션 열기"," \xb7 ",e.sessionId]}):e.sessionPath?(0,n.jsx)("span",{className:"upkeep-evidence-detail",children:e.sessionPath}):null]},`${e.sessionId??e.label}-${t}`))})]}):null,"ok"!==r.status?(0,n.jsx)(yp,{build:()=>(function(e,t,r){let n=bU(e,t),a=n.metrics.find(e=>e.id===r);if(!a)throw Error(`upkeep metric not found: ${t}/${r}`);return b0([`CUELO 보수 점검: ${n.title} › ${a.label}`,"","점검 기간:",...bV(e),"",`「${a.label}」 지표 판정이 「${bT[a.status]}」입니다.`,...bJ(a),"",...bX])})(e,t.id,r.id),onStart:i,target:b6(r.label),children:g}):g?(0,n.jsx)("div",{className:"upkeep-actions",children:g}):null,f?(0,n.jsx)("div",{className:"upkeep-actions",children:["real","false-positive"].map(e=>(0,n.jsx)("button",{type:"button",className:"upkeep-button","data-variant":h?.verdict===e?"primary":void 0,"aria-label":yt("real"===e?ya:yi,r.label),"aria-pressed":h?.verdict===e,disabled:o,onClick:()=>s("check",r.id,!0,t.id,e),children:"real"===e?ya:yi},e))}):null]})}function ym({report:e,item:t,onStart:r}){let a,i;return(0,n.jsxs)("li",{className:"upkeep-row","data-status":t.overdue?"problem":"unknown",children:[(0,n.jsxs)("div",{className:"upkeep-row-head",children:[(0,n.jsx)("h4",{children:t.ref.title}),(0,n.jsx)(yd,{status:t.overdue?"problem":"unknown",text:bH(t)})]}),(0,n.jsx)("p",{className:"upkeep-line upkeep-note",children:(a=t.ref.path,i=t.section,`${a} \xb7 「${i}」`)}),(0,n.jsxs)("details",{className:"upkeep-details",children:[(0,n.jsx)("summary",{children:"원문 보기"}),(0,n.jsx)("pre",{className:"upkeep-quote",children:t.ref.text})]}),(0,n.jsx)(yp,{build:()=>b0([`CUELO 보수 점검: HANDOFF 점검 기한 › ${t.ref.title}`,"","점검 기간:",...bV(e),"",t.overdue?"HANDOFF에 적힌 점검일이 지났습니다.":"HANDOFF에 남아 있는 점검 항목입니다.",...bZ(t),"",...bQ]),onStart:r,target:b6(t.ref.title)})]})}function yf({open:e,onClose:t,onStartSession:r}){let i,s,[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)({phase:"idle"}),u=(0,a.useRef)(null),p=(0,a.useRef)(null),h=(0,a.useRef)(null),[m,f]=(0,a.useState)(!1),g=(0,a.useCallback)(async(e,t,r={})=>{p.current?.abort();let n=new AbortController;p.current=n,d({phase:"loading"});try{let t=await fetch(e,{cache:"no-store",...r,signal:n.signal}),a=await t.json().catch(()=>null);if(!t.ok||!a||!Array.isArray(a.sections))throw Error(a?.error??`HTTP ${t.status}`);l(a),d({phase:"ready"})}catch(e){if(n.signal.aborted)return;d({phase:"error",error:t(e instanceof Error?e.message:String(e))})}},[]),x=(0,a.useCallback)(e=>g(`/api/upkeep${e?"?refresh=1":""}`,b1),[g]),v=(0,a.useCallback)((e,t,r,n,a)=>{h.current={kind:e,metricId:t,sectionId:n},g("fix"===e?"/api/upkeep":"/api/upkeep/check","fix"===e?b2:b8,{method:r?"POST":"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({metricId:t,verdict:a})})},[g]);(0,a.useEffect)(()=>{let e=h.current,t=u.current;if(!e||!t||"loading"===c.phase)return;h.current=null;let r=CSS.escape(e.metricId),n=t.querySelector(`[data-${e.kind}-metric="${r}"]`)??t.querySelector(`[data-metric-row="${r}"] :is(button:not([disabled]), summary)`)??t.querySelector(`#upkeep-section-${e.sectionId} h3`);n?.focus()},[o,c.phase]),(0,a.useEffect)(()=>()=>p.current?.abort(),[]),(0,a.useEffect)(()=>{e&&!o&&"idle"===c.phase&&x(!1)},[x,c.phase,e,o]),(0,a.useEffect)(()=>{let t=u.current;if(!e||!t)return;let r=()=>Array.from(t.querySelectorAll("a[href], button:not([disabled]), summary, [tabindex]:not([tabindex='-1'])")).filter(e=>e.getClientRects().length>0);(r()[0]??t).focus();let n=e=>{if("Tab"!==e.key)return;let n=r();if(!n.length)return;let a=document.activeElement,i=n[0],s=n[n.length-1];e.shiftKey&&(a===i||!t.contains(a))?(e.preventDefault(),s.focus()):e.shiftKey||a!==s&&t.contains(a)||(e.preventDefault(),i.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[e]);let b=(0,a.useCallback)(e=>r(e,o?.repoCwd??null),[r,o?.repoCwd]),y="loading"===c.phase,w=o?bR(o):null,k=!!o&&o.sections.some(e=>bB(e).length>0||(e.items??[]).some(e=>e.overdue)||e.warnings.length>0);return(0,n.jsxs)("section",{ref:u,className:"upkeep-view",role:"dialog","aria-modal":"true","aria-labelledby":"upkeep-title",tabIndex:-1,hidden:!e,onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),t())},children:[(0,n.jsxs)("header",{className:"upkeep-header",children:[(0,n.jsxs)("div",{className:"upkeep-header-bar",children:[(0,n.jsxs)("button",{type:"button",className:"upkeep-back",onClick:t,children:[(0,n.jsx)("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,n.jsx)("polyline",{points:"15 18 9 12 15 6"})}),"대화로"]}),(0,n.jsx)("h2",{id:"upkeep-title",children:"보수 점검"}),(0,n.jsx)("button",{type:"button",className:"upkeep-button",onClick:()=>void x(!0),disabled:y,"aria-busy":y,children:y?"읽는 중…":"다시 읽기"})]}),o&&w?(0,n.jsxs)("p",{className:"upkeep-meta",children:[(0,n.jsxs)("span",{children:["최근 7일"," ",w.current]}),(0,n.jsxs)("span",{children:["직전 7일"," ",w.previous]}),(0,n.jsxs)("span",{children:["생성"," ",bE(o.generatedAt)]}),(0,n.jsx)("span",{children:(i=o.scannedFiles.toLocaleString("ko-KR"),s=(o.scanMs/1e3).toFixed(1),`세션 파일 ${i}개 \xb7 ${s}초`)})]}):null]}),(0,n.jsx)("div",{className:"upkeep-body","aria-busy":y,children:o?(0,n.jsxs)(n.Fragment,{children:["error"===c.phase?(0,n.jsx)("p",{className:"upkeep-banner",role:"alert",children:c.error}):null,null===o.repoCwd?(0,n.jsx)("p",{className:"upkeep-banner",children:"CUELO 저장소 경로를 찾지 못했습니다. 「작업 프롬프트로 새 세션」은 프롬프트를 복사만 합니다."}):null,(0,n.jsx)("nav",{className:"upkeep-strip","aria-label":"섹션별 상태",children:o.sections.map(e=>(0,n.jsxs)("button",{type:"button",className:"upkeep-strip-item","data-status":e.status,onClick:()=>{var t;let r;return t=e.id,r=u.current?.querySelector(`#upkeep-section-${t} h3`),void(r?.scrollIntoView({block:"start",behavior:"smooth"}),r?.focus({preventScroll:!0}))},children:[(0,n.jsx)("span",{className:"upkeep-strip-title",children:e.title}),(0,n.jsx)(yd,{status:e.status,text:bT[e.status]})]},e.id))}),(0,n.jsxs)("div",{className:"upkeep-full",children:[(0,n.jsx)("p",{children:k?b4:"정상이 아닌 지표와 기한 지난 항목이 없습니다."}),k?(0,n.jsx)(yp,{build:()=>(function(e){let t=["CUELO 보수 전체 점검","","점검 기간:",...bV(e),"","보수 대시보드에서 정상이 아닌 지표, 점검일이 지난 HANDOFF 항목, 읽지 못한 자료만 모았습니다. 섹션 순서대로 처리하고, 항목마다 원인과 조치를 따로 적어 주세요.",...bq(e.sections.flatMap(e=>e.metrics))],r=0;for(let n of e.sections){let e=bB(n),a=bD(n.items??[]).filter(e=>e.overdue);if(e.length||a.length||n.warnings.length){for(let i of(r+=e.length+a.length,t.push("",`# ${n.title} (${bT[n.status]})`),e))t.push("",`## ${i.label}`,...bJ(i));for(let e of a)t.push("",`## 점검일 지남: ${e.ref.title}`,...bZ(e));t.push(...bY(n))}}return r||t.push("","이번 보고서에는 정상이 아닌 지표와 기한 지난 항목이 없습니다."),t.push("",...bX,"6. 점검일이 지난 HANDOFF 항목은 원문에 적힌 조건과 기준으로 판정하고, 결과에 맞게 그 항목을 고쳐 주세요."),b0(t)})(o),onStart:b,target:"전체 점검",label:`${b4}로 새 세션`,primary:!0}):null]}),o.sections.map(e=>{let t,r,a,i=bD(e.items??[]),s=i.filter(e=>e.overdue||e.dueDate),l=i.filter(e=>!e.overdue&&!e.dueDate),c=function(e){let t=new Map;for(let r of e)t.set(r.criterion,(t.get(r.criterion)??0)+1);let r=null;for(let[e,n]of t)(null===r||n>(t.get(r)??0))&&(r=e);return r}(e.metrics),d=e=>(0,n.jsx)(ym,{report:o,item:e,onStart:b},`${e.ref.path}-${e.ref.title}`);return(0,n.jsxs)("section",{id:`upkeep-section-${e.id}`,className:"upkeep-section","aria-labelledby":`upkeep-heading-${e.id}`,children:[(0,n.jsxs)("div",{className:"upkeep-section-head",children:[(0,n.jsxs)("div",{className:"upkeep-section-title",children:[(0,n.jsx)("h3",{id:`upkeep-heading-${e.id}`,tabIndex:-1,children:e.title}),(0,n.jsx)(yd,{status:e.status,text:bT[e.status]})]}),(0,n.jsx)("p",{className:"upkeep-summary",children:e.summary}),c?(0,n.jsxs)("p",{className:"upkeep-line",children:[(0,n.jsx)("span",{className:"upkeep-line-label",children:b7}),yu(c)]}):null,(0,n.jsx)(yp,{build:()=>(function(e,t){let r=bU(e,t),n=bB(r),a=n.length?n:r.metrics.filter(e=>!e.check),i=bD(r.items??[]),s=i.filter(e=>e.overdue),o=s.length?s:i,l=[`CUELO 보수 점검: ${r.title} 섹션`,"","점검 기간:",...bV(e),"",`섹션 판정: ${bT[r.status]} \xb7 ${r.summary}`];for(let e of(a.length&&l.push(n.length?"아래는 이 섹션에서 정상이 아닌 지표입니다.":"이 섹션에서 점검 완료 표시가 없는 지표는 모두 정상으로 나왔습니다. 판정이 맞는지 근거로 확인해 주세요."),l.push(...bq(r.metrics)),a))l.push("",`## ${e.label}`,...bJ(e));if(o.length)for(let e of(l.push("",s.length?"점검일이 지난 HANDOFF 항목:":"남아 있는 HANDOFF 점검 항목:"),o))l.push("",`## ${e.ref.title}`,...bZ(e));return l.push(...bY(r),"",...a.length?bX:bQ),b0(l)})(o,e.id),onStart:b,target:(t=e.title,`${t} 섹션`),label:"섹션 프롬프트"})]}),e.warnings.length?(0,n.jsxs)("div",{className:"upkeep-warnings",children:[(0,n.jsx)("span",{className:"upkeep-line-label",children:"읽지 못한 자료"}),(0,n.jsx)("ul",{children:e.warnings.map(e=>(0,n.jsx)("li",{children:e},e))})]}):null,e.metrics.length?(0,n.jsx)("ul",{className:"upkeep-rows",children:[...e.metrics].sort((e,t)=>yc(e)-yc(t)).map(t=>(0,n.jsx)(yh,{report:o,section:e,metric:t,sectionCriterion:c,onStart:b,onMark:v,busy:y},t.id))}):"ops"!==e.id?(0,n.jsx)("p",{className:"upkeep-note",children:"이 섹션에는 지표가 없습니다."}):null,"ops"===e.id?i.length?(0,n.jsxs)(n.Fragment,{children:[s.length?(0,n.jsx)("ul",{className:"upkeep-rows",children:s.map(d)}):null,l.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"upkeep-button upkeep-fold","aria-expanded":m,"aria-controls":"upkeep-due-folded",onClick:()=>f(e=>!e),children:m?(r=l.length,`조건부\xb7날짜 없음 ${r}건 접기`):(a=l.length,`조건부\xb7날짜 없음 ${a}건 보기`)}),(0,n.jsx)("ul",{id:"upkeep-due-folded",className:"upkeep-rows",hidden:!m,children:l.map(d)})]}):null]}):(0,n.jsx)("p",{className:"upkeep-note",children:"HANDOFF에 남은 점검 항목이 없습니다."}):null]},e.id)})]}):"error"===c.phase?(0,n.jsxs)("div",{className:"upkeep-empty",role:"alert",children:[(0,n.jsx)("p",{children:c.error}),(0,n.jsx)("button",{type:"button",className:"upkeep-button",onClick:()=>void x(!1),children:"다시 시도"})]}):(0,n.jsx)("p",{className:"upkeep-empty",role:"status",children:"세션 기록을 읽는 중입니다. 몇 초 걸립니다."})})]})}function yg({message:e,onDismiss:t}){return((0,a.useEffect)(()=>{if(!e)return;let r=window.setTimeout(t,8e3);return()=>window.clearTimeout(r)},[e,t]),e)?(0,n.jsxs)("div",{className:"upkeep-notice",role:"status",children:[(0,n.jsx)("p",{children:e}),(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":yo,title:yo,children:"✕"})]}):null}let yx="pi-web:last-open-by-workspace";function yv(){try{return window.localStorage}catch{return null}}function yb(e){let t=e.getItem(yx);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function yy(e,t=yv()){if(t)try{let r=yb(t);if(!(e in r))return;delete r[e],0===Object.keys(r).length?t.removeItem(yx):t.setItem(yx,JSON.stringify(r))}catch{}}let yw="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",yk="omp-web:wide-chat";function yj(){try{return fX(window.localStorage)}catch{return fX(null)}}function yS(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 yC({auxiliaryDeck:e,resourcePanel:t}={}){var r,p,m,f,k;let j,S,C,N,T,I,M,E,$,R,L,A,P,F,_,W,O,D,q,V,K,G=(0,i.useRouter)(),J=(0,i.useSearchParams)(),[Z]=(0,a.useState)(()=>{let e;return{requestedCwd:e=J.get("cwd")?.trim()||null,sessionId:e?null:J.get("session")}}),{preference:Y,toggleTheme:X}=rh(),{locale:Q,setLocale:ee,t:et,supportedLocales:er}=(0,z.s)(),en=function(){let[e,t]=(0,a.useState)(null),[r,n]=(0,a.useState)(!1),i=(0,a.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,a.useEffect)(()=>{try{n("1"===window.localStorage.getItem(fC))}catch{}return i(),window.addEventListener("focus",i),()=>window.removeEventListener("focus",i)},[i]),{permission:e,dismissed:r,request:(0,a.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,i)},[i]),dismiss:(0,a.useCallback)(()=>{n(!0);try{window.localStorage.setItem(fC,"1")}catch{}},[])}}(),ea=(0,a.useSyncExternalStore)(H.subscribe,H.getSnapshot,U);(0,a.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,r=null,n=()=>{r=null,function({hasFocusedEditable:e,innerHeight:t,viewportHeight:r,viewportScale:n}){let a=.01>Math.abs(n-1);return e&&a&&t-r>1}({hasFocusedEditable:pv(),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 n=0!==window.scrollX||0!==window.scrollY,a=.01>Math.abs(e.scale-1);n&&a&&window.scrollTo(0,0)},a=()=>{null!==r&&window.cancelAnimationFrame(r),r=window.requestAnimationFrame(n)};return a(),e.addEventListener("resize",a),e.addEventListener("scroll",a),window.addEventListener("resize",a),window.addEventListener("focusin",a),window.addEventListener("focusout",a),window.addEventListener("pageshow",a),()=>{e.removeEventListener("resize",a),e.removeEventListener("scroll",a),window.removeEventListener("resize",a),window.removeEventListener("focusin",a),window.removeEventListener("focusout",a),window.removeEventListener("pageshow",a),null!==r&&window.cancelAnimationFrame(r),t.style.removeProperty("--app-viewport-height")}},[]);let ei=pC(),es=B(),{soundEnabled:eo,onSoundToggle:el,playCueSound:ec,preloadCueSound:ed,unlockAudio:eu,soundEnabledRef:ep}=function(){let[e,t]=(0,a.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),r=(0,a.useRef)(e);(0,a.useEffect)(()=>{r.current=e},[e]);let n=(0,a.useRef)(null),i=(0,a.useRef)(null),s=(0,a.useRef)(0),o=(0,a.useRef)(new Map),l=(0,a.useRef)(new Map),c=(0,a.useRef)(new Map),d=(0,a.useRef)(null);am();let u=(0,a.useRef)(new Map),p=(0,a.useRef)(new Map),h=(0,a.useRef)(new Map),m=(0,a.useCallback)(e=>{let t=p.current.get(e);return t||(t=vy(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),f=(0,a.useCallback)(()=>{if(n.current&&"closed"!==n.current.state)return n.current;try{n.current=new AudioContext}catch{return null}return n.current},[]),g=(0,a.useCallback)(()=>(d.current??=nn(),d.current),[]);(0,a.useEffect)(()=>{g()},[g]);let x=(0,a.useCallback)(async e=>{if(!e)return;let t=await g(),n=nR(e);for(let a of r2){let i=n?nr(n$(n),n.id,a):nt(t,e,a);if(i){for(let e of i.stickers){if(h.current.has(e))continue;let t=new Image;t.decoding="async",t.src=e,h.current.set(e,t)}if(r.current)for(let e of i.voices)m(e).catch(()=>{})}}},[g,m]),v=(0,a.useCallback)(()=>{s.current+=1;let e=i.current;if(i.current=null,e)try{e.stop()}catch{}},[]),b=(0,a.useCallback)((e=!1)=>{if(!e&&!r.current)return;let t=f();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[f]);(0,a.useEffect)(()=>{let e=()=>b(),t={capture:!0,passive:!0};return window.addEventListener("pointerdown",e,t),window.addEventListener("keydown",e,t),()=>{window.removeEventListener("pointerdown",e,t),window.removeEventListener("keydown",e,t)}},[b]);let y=(0,a.useCallback)(()=>{let e=!r.current;e?b(!0):v(),r.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,b]),w=(0,a.useCallback)(e=>{if(!r.current)return;let t=f();if(!t)return;v();let n=s.current,a=()=>{if(n===s.current&&r.current&&(!e||e()))try{vb(t)}catch{}};"suspended"===t.state?t.resume().then(a).catch(()=>{}):a()},[f,v]);return{soundEnabled:e,onSoundToggle:y,playCueSound:(0,a.useCallback)(async(e,t="done",n)=>{let a=await g(),d=nR(e),p=null===t?null:d?nr(n$(d),d.id,t):nt(a,e,t),h=`${d?.alias??e??""}\u0000${t??""}`,x=p?na(p.stickers,l.current.get(h)??null):null;null!==x&&l.current.set(h,x);let b=p?na(p.voices,o.current.get(h)??null):null,y=b?p?.lines.get(b)??null:null;!b&&p&&null!==(y=na(p.captions,c.current.get(h)??null))&&c.current.set(h,y);let k={sticker:x,text:y};if(!r.current||n&&!n())return k;let j=f();if(!j)return k;if(!b)return null!==t&&r4[t]||w(n),k;v();let S=s.current,C=()=>S!==s.current||!r.current||void 0!==n&&!n();return(async()=>{if(!("suspended"===j.state&&(await j.resume().catch(()=>{}),C())))try{let e=u.current.get(b);e||(e=m(b).then(e=>j.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(b),e}),u.current.set(b,e));let t=await e;if(C())return;let r=j.createBufferSource(),n=j.createGain();r.buffer=t,r.connect(n),n.connect(j.destination),n.gain.setValueAtTime(.82,j.currentTime),r.onended=()=>{i.current===r&&(i.current=null)},i.current=r,r.start(),o.current.set(h,b)}catch{if(C()||null!==t&&r4[t])return;try{vb(j)}catch{}}})(),k},[f,w,v,g,m]),preloadCueSound:x,unlockAudio:b,soundEnabledRef:r}}(),eh=function(){let[e,t]=(0,a.useState)({status:"idle",data:null,error:null}),[r,n]=(0,a.useState)(!0),[i,s]=(0,a.useState)(null),o=(0,a.useRef)(null),l=(0,a.useRef)(null),c=(0,a.useCallback)(()=>{l.current?.abort();let e=new AbortController;l.current=e,n1({signal:e.signal}).then(t=>{e.signal.aborted||s(t)})},[]);(0,a.useEffect)(()=>{var e;let r,a,i,s,d,u,p,h,m,f,g=(a=(e={onResult(e){t(e),n(!1)}}).intervalMs??15e3,i=e.setIntervalImpl??setInterval,s=e.clearIntervalImpl??clearInterval,d=e.initialData??null,u=null,p=0,h=!1,m=!1,f=async t=>{u?.abort(),u=new AbortController;let r=++p,n=await nQ({refresh:t,previous:d,signal:u.signal,fetchImpl:e.fetchImpl});return h&&r===p&&(n.data&&(d=n.data),e.onResult(n)),n},{start(){h||(h=!0,f(!1),r=i(()=>{m||f(!1)},a))},refresh:()=>h?f(!0):Promise.resolve(nZ(d,new nK("사용량 폴링이 중지되었습니다.","aborted"))),setPaused(e){m=e},stop(){h=!1,p+=1,u?.abort(),u=null,s(r),r=void 0}});return o.current=g,g.start(),c(),()=>{g.stop(),l.current?.abort(),o.current===g&&(o.current=null)}},[c]);let d=(0,a.useCallback)(async()=>{let e=o.current;if(!e)return{status:"error",data:null,error:new nK("사용량 폴링이 시작되지 않았습니다.","aborted")};n(!0),c();let t=await e.refresh();return n(!1),t},[c]);return{state:e,loading:r,refresh:d,setPaused:(0,a.useCallback)(e=>{o.current?.setPaused(e)},[]),bai:(0,a.useMemo)(()=>(function(e){let t=e?.data;if(!t)return{status:"unmeasured"};let r=t.models.filter(e=>"b-ai"===e.provider);return 0===r.length?{status:"empty"}:{status:"measured",tokens:r.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}})(i),[i])}}();r=eh.state.data?.reports,(0,a.useEffect)(()=>{ad(r)},[r]);let[ef,eg]=(0,a.useState)(!1),[ex,ev]=(0,a.useState)(!1),[eb,ey]=(0,a.useState)(!1),[ew,ek]=(0,a.useState)(!1),[ej,eS]=(0,a.useState)(null),eC=(0,a.useCallback)(()=>eS(null),[]),eN=(0,a.useRef)(new Set),eT=(0,a.useCallback)(()=>{ep.current&&ec(null,"done")},[ec,ep]),[eI,eM]=(0,a.useState)(null),[eE,e$]=(0,a.useState)(null),[eR,eL]=(0,a.useState)(null),eA=(0,a.useRef)(0),eP=(0,a.useRef)(null),[eF,e_]=(0,a.useState)(null),ez=(0,a.useRef)(0),eW=(0,a.useCallback)(e=>{e_(t=>t?.id===e?null:t)},[]),[eO,eD]=(0,a.useState)(!1);(0,a.useEffect)(()=>{try{eD("1"===window.localStorage.getItem(yk))}catch{}},[]);let eH=(0,a.useCallback)(()=>{eD(e=>{let t=!e;try{window.localStorage.setItem(yk,t?"1":"0")}catch{}return t})},[]),[eU,eB]=(0,a.useState)(null),[eq,eV]=(0,a.useState)(()=>Z.requestedCwd?"validating":"idle"),[eK,eG]=(0,a.useState)(null),[eJ,eZ]=(0,a.useState)(0),[eY,eX]=(0,a.useState)(0),[eQ,e0]=(0,a.useState)(0),[e1,e2]=(0,a.useState)(0),[e8,e4]=(0,a.useState)(!1),[e5,e6]=(0,a.useState)(null),[e3,e7]=(0,a.useState)(null),[e9]=(0,a.useState)(()=>{let e;return e=0,{reset(){e+=1,e7(null)},check(t,r){let n=++e;e7("checking"),t().then(t=>{n===e&&e7("fresh"===t.status?function(e,t){if(!t.accountKey)return"unknown";let r=e.filter(e=>e.provider===t.provider&&e.accountKey===t.accountKey);return r.some(e=>!0!==e.disabled&&!e.authError)?"recovered":r.length>0?"still-failing":"unknown"}(t.data.reports,r):"unknown")},()=>{n===e&&e7("unknown")})}}}),[te,tt]=(0,a.useState)(null),[tr,tn]=(0,a.useState)(0),ta=(0,a.useRef)(null),ti=(0,a.useRef)(null),[ts,to]=(0,a.useState)(!1),[tl,tc]=(0,a.useState)(!1),[td,tu]=(0,a.useState)(null),[tp,th]=(0,a.useReducer)(g,h),[tm,tf]=(0,a.useState)("characters"),[tg,tx]=(0,a.useState)("governor"),[tv,tb]=(0,a.useState)({sessionId:null,widgets:[]}),[ty,tw]=(0,a.useState)(()=>x(0)),[tk]=(0,a.useState)(yj),[tj]=(0,a.useState)(fQ),[tS,tC]=(0,a.useState)([]),[tN,tT]=(0,a.useState)({sessions:[],complete:!1}),[tI,tM]=(0,a.useState)(!1),[tE,t$]=(0,a.useState)(!1),[tR,tL]=(0,a.useState)(0),tA=(0,a.useRef)(null),tP=(0,a.useRef)(null),t_=(0,a.useRef)(null),tz=(0,a.useCallback)(()=>{tL(e=>e+1)},[]),tW=(0,a.useCallback)(e=>{e&&ev(!0),eg(e),e||tz()},[tz]);(0,a.useEffect)(()=>{"translator"===new URLSearchParams(window.location.search).get("view")&&tW(!0)},[tW]);let tO=(0,a.useCallback)(e=>{e&&ek(!0),ey(e),e||tz()},[tz]);(0,a.useEffect)(()=>{"upkeep"===new URLSearchParams(window.location.search).get("view")&&tO(!0)},[tO]);let tD=(0,a.useCallback)(e=>{tP.current=e},[]),tH=(0,a.useRef)(!1),[tU,tB]=(0,a.useState)(!1),tq=(0,a.useRef)(!1),tV=(0,a.useRef)(!1),tK=(0,a.useRef)(0),[tG,tJ]=(0,a.useState)(!1),[tZ,tY]=(0,a.useState)(!1),tX=(0,a.useRef)(null),[tQ,t0]=(0,a.useState)(null),[t1,t2]=(0,a.useState)(null),t8=(0,a.useRef)(null),t4=(0,a.useRef)(!1);t8.current=tQ,(0,a.useEffect)(()=>{t0(u2())},[]),(0,a.useEffect)(()=>{let e=!1,t=null,r=r=>{if(e||tH.current||"IDLE"===r.phase||!r.requestId||!r.stageHash)return;let n=`${window.location.pathname}${window.location.search}${window.location.hash}`,a=function(e){let t=dE();if(!t.ok)return{entered:!1,error:t.error};let r={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:u0(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(uG,JSON.stringify(r))}catch(e){return{entered:!1,error:e instanceof Error?e.message:String(e)}}let n=new URLSearchParams({mode:"wait",requestId:r.requestId,stageHash:r.stageHash,clientId:r.clientId});return window.location.replace(`/api/update-maintenance?${n}`),{entered:!0}}({requestId:r.requestId,stageHash:r.stageHash,sessionId:eI?.id??null,resumeUrl:n});if(a.entered){tH.current=!0;return}t=a.error},n=async()=>{if(!e&&!tH.current)try{let o=t4.current?null:t8.current,l=await u4({sessionId:eI?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:o?{requestId:o.requestId,stageHash:o.stageHash}:null});tK.current=0;let c=(n=tq.current,a=tX.current,((i=l.serverBootId)&&a?i!==a:n)?"reload":n?"resume":"continue");if("reload"===c){var n,a,i,s=eI?.id??null;dE();try{sessionStorage.setItem(uZ,JSON.stringify({schemaVersion:1,sessionId:s,at:Date.now()}))}catch{}window.location.reload();return}"resume"===c&&(tq.current=!1,tB(!1),tJ(!1)),l.serverBootId&&(tX.current=l.serverBootId),tV.current=!0,!e&&l.update&&(t2(l.update),l.update.cleanup&&"running"!==l.update.cleanup.status&&(t4.current=!0)),r(l)}catch{tK.current+=1,!e&&tV.current&&tK.current>=2&&(tq.current=!0,tB(!0))}},a=e=>{r(e.detail??{}),t&&n()};window.addEventListener("ompweb:update-maintenance",a),n();let i=window.setInterval(()=>void n(),2e3);return()=>{e=!0,window.clearInterval(i),window.removeEventListener("ompweb:update-maintenance",a)}},[eI?.id]),(0,a.useEffect)(()=>{if(!tU)return;let e=window.setTimeout(()=>tJ(!0),12e4);return()=>window.clearTimeout(e)},[tU]),(0,a.useEffect)(()=>{(function(e,t=Date.now()){let r,n=sessionStorage.getItem(uZ);if(!n)return!1;try{r=JSON.parse(n)}catch{r=null}return!r||1!==r.schemaVersion||"number"!=typeof r.at||t-r.at>6e4||null!==r.sessionId&&"string"!=typeof r.sessionId?(sessionStorage.removeItem(uZ),!1):r.sessionId===e&&(sessionStorage.removeItem(uZ),!0)})(eI?.id??null)&&tY(!0)},[eI?.id]),(0,a.useEffect)(()=>{if(!tZ)return;let e=window.setTimeout(()=>tY(!1),8e3);return()=>window.clearTimeout(e)},[tZ]);let t5=tQ?.requestId??null,t6=tQ?.dismissed??!0,t3=t1?.requestId??null,t7=t1?.deploymentCompleted??!1,t9=t1?.cleanup?.status??null;(0,a.useEffect)(()=>{if(!t5||t6||t3!==t5||!t7)return;let e=uQ(t9);if(null===e)return;let t=window.setTimeout(()=>{t0(u8(t5))},e);return()=>window.clearTimeout(t)},[t5,t6,t3,t7,t9]),(0,a.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(uG);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&&eI?.id!==e.sessionId)return;let t=!1;return u6(e).then(e=>{t||"resumed"!==e||(t4.current=!1,t0(u2()),eZ(e=>e+1),e0(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[eI?.id]);let re=(0,a.useCallback)(e=>{if("Tab"!==e.key)return;let t=t_.current;if(!t)return;let r=Array.from(t.querySelectorAll(yw));if(0===r.length)return;let n=e.shiftKey?r[0]:r[r.length-1],a=document.activeElement;a!==n&&t.contains(a)||(e.preventDefault(),(e.shiftKey?r[r.length-1]:r[0]).focus())},[]),[rt,rr]=(0,a.useState)(!0),[rn,ra]=(0,a.useState)(!1),[ri,rs]=(0,a.useState)(!1),ro=(0,a.useRef)(rt),rl=(0,a.useRef)(!1),rc=(0,a.useRef)(!0),rd=(0,a.useRef)(null);ro.current=rt;let ru=(j=(p={clientPainted:rn,compactWorkspace:ea,requestedOpen:rt}).requestedOpen&&p.clientPainted,{laidOut:p.requestedOpen&&(!p.compactWorkspace||p.clientPainted),presented:j,drawer:j&&p.compactWorkspace}),rp=(0,a.useCallback)(e=>{rl.current=e,rr(e),th(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),rf=(0,a.useRef)(null),rg=(0,a.useRef)(!1),rx=(0,a.useRef)(260),rv=(0,a.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:r,rightPanelWidth:n}=e;if(t<=640)return 480;let a=t<960;return Math.min(480,t-(a?320:420)-(!a&&r?n:0))})({viewportWidth:window.innerWidth,rightPanelOpen:!1,rightPanelWidth:0}),[]),rb=function(e){let{ariaLabel:t,cssVariable:r,defaultWidth:n,getDefaultWidth:i,getMaxWidth:s,growthDirection:o,maxWidth:l,minWidth:c,storageKey:d,widthRef:u}=e,p=(0,a.useRef)(null),h=(0,a.useRef)(null),m=(0,a.useRef)(!1),[f,g]=(0,a.useState)(n),[x,v]=(0,a.useState)(!1),b=(0,a.useCallback)(()=>Math.min(l,Math.max(c,s())),[s,l,c]),y=(0,a.useCallback)(e=>{var t;let r,n;return t=b(),r=Number.isFinite(e)?e:c,n=Math.max(c,t),Math.round(Math.max(c,Math.min(n,r)))},[b,c]),w=(0,a.useCallback)(e=>{u.current=e,p.current?.style.setProperty(r,`${e}px`)},[r,u]),k=(0,a.useCallback)((e,t={})=>{let{forcePersist:r=!1,persist:n=!0}=t,a=y(e),i=a!==u.current;return w(a),g(a),n&&(i||r)&&vv(d,a),a},[w,y,d,u]),j=(0,a.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),S=(0,a.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,a.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&S(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),h.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:r,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,a.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 r="right"===o?1:-1,n=y(t.startWidth+(e.clientX-t.startX)*r);w(n),e.currentTarget.setAttribute("aria-valuenow",String(n)),e.currentTarget.setAttribute("aria-valuetext",`${n} px`)},[w,y,S,o]),T=(0,a.useCallback)(e=>{S(e.pointerId)},[S]),I=(0,a.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,a.useCallback)(e=>{S(e.pointerId)},[S]),E=(0,a.useCallback)(()=>{k(i?.()??n,{forcePersist:!0})},[k,n,i]),$=(0,a.useCallback)(()=>{k(u.current)},[k,u]),R=(0,a.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===o?"ArrowRight":"ArrowLeft",n="right"===o?"ArrowLeft":"ArrowRight";e.key===r?(e.preventDefault(),k(u.current+t,{forcePersist:!0})):e.key===n?(e.preventDefault(),k(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),k(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),k(b(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),E())},[k,b,o,c,E,u]);return(0,a.useEffect)(()=>{if(m.current)return;m.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let r=Number.parseInt(t,10);return Number.isFinite(r)?r:null}catch{return null}}(d),t=k(e??i?.()??n,{persist:!1});null!==e&&e!==t&&vv(d,t)},[k,n,i,d]),(0,a.useEffect)(()=>{if(!m.current)return;k(u.current);let e=()=>{k(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[k,u]),(0,a.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,a.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,j(e))},[j]),{isResizing:x,panelRef:p,reclampWidth:$,resetWidth:E,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":b(),"aria-valuemin":c,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:E,onKeyDown:R,onLostPointerCapture:M,onPointerCancel:I,onPointerDown:C,onPointerMove:N,onPointerUp:T,role:"separator",tabIndex:0},width:f}}({ariaLabel:et("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:rv,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:rx}),ry=rb.reclampWidth;(0,a.useEffect)(()=>{let e=rd.current;if(e===ea)return;rs(!0),null!==e&&(e?rl.current=ro.current:rc.current=ro.current),rd.current=ea;let t=ea?rl.current:rc.current;ea?rp(t):rr(t);let r=0,n=requestAnimationFrame(()=>{r=requestAnimationFrame(()=>rs(!1))});return()=>{cancelAnimationFrame(n),r&&cancelAnimationFrame(r)}},[ea,rp]),(0,a.useEffect)(()=>{ra(!0)},[]),(0,a.useEffect)(()=>{let e=rg.current;if(rg.current=ru.drawer,ru.drawer){let e=rb.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(yw)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,r=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||rf.current?.focus()})});return()=>{cancelAnimationFrame(r),t&&cancelAnimationFrame(t)}},[ru.drawer,rb.panelRef]),(0,a.useEffect)(()=>{ry()},[ry,tp.activeView]),(0,a.useEffect)(()=>{let e=tA.current;if(!e)return;let t=e=>{tw(t=>{let r=x(e);return t.navigator===r.navigator&&t.deck===r.deck?t:r})};t(e.getBoundingClientRect().width);let r=new ResizeObserver(e=>{let r=e[0]?.contentRect.width;"number"==typeof r&&t(r)});return r.observe(e),()=>r.disconnect()},[]),(0,a.useEffect)(()=>{if(!tR)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>tP.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[tR]),(0,a.useEffect)(()=>{if("command-palette"!==tp.transientLayer)return;let e=t_.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(yw)?.focus()});return()=>cancelAnimationFrame(t)},[tp.transientLayer]),(0,a.useEffect)(()=>{ea||"navigator-drawer"!==tp.transientLayer||th({type:"close-layer"})},[ea,tp.transientLayer]),(0,a.useEffect)(()=>{let e=new AbortController;return tT(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");tC(t.sessions),tT({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()},[eJ,eI?.id]);let rw=(0,a.useRef)(null),rk=(0,a.useRef)(null),[rj,rS]=(0,a.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),rC=(0,a.useRef)(null),rN=(0,a.useCallback)((e,t,r)=>{rC.current=r,rS(r=>{let n=rU.current;return r.sessionId!==n?{sessionId:n,tree:e,leafId:t,navigation:0}:{...r,tree:e,leafId:t}})},[]),rT=(0,a.useCallback)(e=>{rS(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),rC.current?.(e)},[]),[rM,rE]=(0,a.useState)(null),r$=(0,a.useCallback)(e=>{rE(e)},[]),[rR,rL]=(0,a.useState)(null),[rA,rP]=(0,a.useState)([]),[rF,r_]=(0,a.useState)(null),[rz,rW]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let r=await t.json(),n=r.fields?.find(e=>"task.maxConcurrency"===e.path),a=n?.value??n?.defaultValue,i="number"==typeof a?a:"string"==typeof a?Number.parseInt(a,10):NaN;!e.signal.aborted&&Number.isFinite(i)&&i>0&&r_(i)}).catch(()=>{}),()=>e.abort()},[]);let[rO,rD]=(0,a.useState)({kind:"idle"}),rH=(0,a.useRef)(null),rU=(0,a.useRef)(eI?.id??null);rU.current=eI?.id??null;let rB=(0,a.useCallback)(e=>{rL(e)},[]),[rq,rV]=(0,a.useState)(null),rK=(0,a.useRef)(null),rG=(0,a.useCallback)((e,t)=>{rm(t).then(()=>{rK.current&&clearTimeout(rK.current),rV(e),rK.current=setTimeout(()=>rV(null),1400)})},[]);(0,a.useEffect)(()=>()=>{rK.current&&clearTimeout(rK.current),rH.current&&clearTimeout(rH.current)},[]),(0,a.useEffect)(()=>()=>eP.current?.abort(),[]);let[rJ,rZ]=(0,a.useState)(null),rY=(0,a.useCallback)(e=>{rZ(e)},[]),[rX,rQ]=(0,a.useState)(null),[r0,r1]=(0,a.useState)(null),[r8,r5]=(0,a.useState)(null),[r6,r3]=(0,a.useState)(!1),[r7,r9]=(0,a.useState)("subagents"),ne=(0,a.useCallback)((e,t=!1)=>{th({type:"select-view",view:e}),r1(null),ea&&rp(!1),(t||"chat"===e)&&tz()},[ea,tz,rp]),ni=(0,a.useRef)(!1),ns=(0,a.useCallback)(()=>{ni.current=!0,th({type:"set-deck-expanded",expanded:!tp.deckExpanded})},[tp.deckExpanded]);(0,a.useEffect)(()=>{if(!ni.current)return;ni.current=!1;let e=requestAnimationFrame(()=>{[...document.querySelectorAll("#workspace-auxiliary-panel [data-panel-expand]")].find(e=>e.getClientRects().length>0)?.focus()});return()=>cancelAnimationFrame(e)},[tp.deckExpanded]);let[no,nl]=(0,a.useState)(null),nc=(0,a.useCallback)((e,t=!0)=>{nl(e),t&&ne("subagents")},[ne]),nd=eI?.id??null;(0,a.useEffect)(()=>{nl(null)},[nd]);let[nu,np]=(0,a.useState)(null),nh=(0,a.useCallback)(e=>{yS(e)||(tp.deckExpanded&&"pinned"===ty.deck?th({type:"set-deck-expanded",expanded:!1}):th({type:"select-view",view:"chat"})),np(e)},[ty.deck,tp.deckExpanded]);(0,a.useEffect)(()=>{if(!nu)return;let e=requestAnimationFrame(()=>{yS(nu)?.focus(),np(null)});return()=>cancelAnimationFrame(e)},[nu]);let nm=(0,a.useCallback)(e=>{let t=tp.transientLayer===e;r1(null),ea&&"navigator-drawer"===tp.transientLayer&&rp(!1),th({type:"toggle-layer",layer:e}),t&&tz()},[ea,tz,rp,tp.transientLayer]),nf=(0,a.useCallback)(()=>{if("chat"!==tp.activeView){r9(tp.activeView),ne("chat",!0);return}ne(r7,!0)},[r7,ne,tp.activeView]),ng=(0,a.useCallback)(e=>{r1(null),th({type:"close-layer"}),ea&&rp(!1),e9.reset(),e6(e)},[ea,e9,rp]),nx=(0,a.useCallback)(()=>{e9.reset(),e6(null),tz()},[e9,tz]),nv=eh.refresh,nb=(0,a.useCallback)(()=>{null!==e5&&e9.check(nv,e5)},[nv,e9,e5]),ny=(0,a.useCallback)(()=>ts?(tl||(to(!1),tz()),!0):null!==e5?(nx(),!0):e8?(e4(!1),tz(),!0):r6?(r3(!1),tz(),!0):r0?(r1(null),tz(),!0):tp.transientLayer?("navigator-drawer"===tp.transientLayer&&rp(!1),th({type:"close-layer"}),tz(),!0):tp.deckExpanded&&"pinned"===ty.deck&&document.activeElement?.closest("#workspace-auxiliary-panel")?(ni.current=!0,th({type:"set-deck-expanded",expanded:!1}),!0):"chat"!==tp.activeView&&(th({type:"select-view",view:"chat"}),tz(),!0),[nx,r6,e5,r0,tl,ts,tz,rp,e8,tp.activeView,tp.transientLayer,tp.deckExpanded,ty.deck]),nw=(0,a.useCallback)(e=>{th({type:"close-layer"}),ea&&rp(!1),r1(t=>t===e?null:e)},[ea,rp]),nk=(0,a.useCallback)(()=>{th({type:"close-layer"}),ea&&rp(!1),r1("session")},[ea,rp]),nj=(0,a.useCallback)(()=>{if(r1(null),ea){let e="navigator-drawer"!==tp.transientLayer;rp(e),e||tz();return}th({type:"close-layer"}),rr(e=>{let t=!e;return rc.current=t,t})},[ea,tz,rp,tp.transientLayer]);(0,a.useEffect)(()=>{if(!r0||!rk.current)return;let e=()=>{let e=rk.current.getBoundingClientRect();r5({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(rk.current),()=>t.disconnect()},[r0]);let[nS,nC]=(0,a.useState)([]),[nN,nE]=(0,a.useState)(null),nL=(0,a.useRef)(new Map),nA=(0,a.useCallback)(()=>{"view-stack"===ty.deck&&th({type:"select-view",view:"chat"}),ea&&rp(!1),tz()},[ea,ty.deck,tz,rp]),nP=(0,a.useCallback)((e,t)=>{rw.current?.insertText(d8(e,t)),nA()},[nA]),nF=(0,a.useCallback)((e,t,r)=>{rw.current?.insertText(d4(e,t,r)),nA()},[nA]),n_=(0,a.useCallback)((e,t)=>{let r=rw.current;return!!r&&(r.addAttachments(e),t&&r.insertText(t),nA(),!0)},[nA]),nz=(0,a.useCallback)(e=>{rw.current?.insertText(e),nA()},[nA]),nW=(0,a.useCallback)((e,t)=>{tb({sessionId:e,widgets:t})},[]),nO=Z.sessionId,[nD,nH]=(0,a.useState)(null);rh({cwd:eI?.cwd??eU??nD,syncWithOmp:!0}),S=(0,a.useSyncExternalStore)(fd,fo,()=>!1),(0,a.useEffect)(()=>nI(()=>fc(nT().mode)),[]),(0,a.useEffect)(()=>{if(!S)return;let e=!0;return nM().then(t=>{e&&t&&fc(nT().mode)}),()=>{e=!1}},[S]);let nU=(0,a.useRef)(null),[nB,nq]=(0,a.useState)(()=>!nO),nV=(0,a.useRef)(!1),nG=(0,a.useRef)(0),nJ=(0,a.useCallback)(()=>{nG.current+=1},[]);(0,a.useEffect)(()=>{eI&&function(e,t,r=yv()){if(r)try{let n=yb(r);n[e]=t,r.setItem(yx,JSON.stringify(n))}catch{}}(eI.projectRoot??nU.current??eI.cwd,eI.id)},[eI]),(0,a.useEffect)(()=>{let e=Z.requestedCwd;if(!e)return;let t=new AbortController;return eV("validating"),eG(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}`);nV.current=!0,eB(t.cwd),eV("ready")}).catch(e=>{t.signal.aborted||(eG(e instanceof Error?e.message:String(e)),eV("error"))}),()=>t.abort()},[Z]);let nY=(0,a.useCallback)(e=>{let t=++nG.current,r=function(e,t=yv()){if(!t)return null;try{let r=yb(t)[e];return"string"==typeof r&&r.length>0?r:null}catch{return null}}(e);r&&fetch("/api/sessions").then(e=>e.ok?e.json():null).then(n=>{if(t!==nG.current)return;let a=n?.sessions.find(e=>e.id===r);if(!a){n&&yy(e);return}(a.projectRoot??a.cwd)!==e?yy(e):(eM(a),eX(e=>e+1),new URLSearchParams(window.location.search).get("session")!==a.id&&G.replace(`?session=${encodeURIComponent(a.id)}`,{scroll:!1}))}).catch(()=>{})},[G]),nX=(0,a.useCallback)((e,t)=>{if(nJ(),nH(e),!e)return;let r=t??e,n=nU.current??(eI?eI.projectRoot??eI.cwd:null);if(nU.current=r,nV.current){nV.current=!1;return}n!==r&&(eA.current+=1,eP.current?.abort(),eP.current=null,e$(null),eL(null),eM(null),eB(t=>t&&t!==e?null:t),eX(e=>e+1),rS({sessionId:null,tree:[],leafId:null,navigation:0}),rE(null),r1(null),nC([]),nE(null),th({type:"select-view",view:"chat"}),nY(r),G.replace("/",{scroll:!1}))},["/",G,eI,nJ,nY]),n0=(0,a.useCallback)((e,t,r)=>{eB(null),eL(r),eM(e),rS({sessionId:e.id,tree:[],leafId:null,navigation:0}),eX(e=>e+1),rE(null),nq(!0),ea&&!t&&(rp(!1),th({type:"select-view",view:"chat"})),t&&(nV.current=!0),t||G.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[ea,G,rp]),n2=(0,a.useCallback)((e,t=!1)=>{if(nU.current=e.projectRoot??e.cwd,nJ(),!t&&eI){let t=(eI.projectRoot??eI.cwd)===(e.projectRoot??e.cwd);if(eI.id===e.id&&t){eA.current+=1,eP.current?.abort(),eP.current=null,e$(null),ea&&rp(!1);return}}if(!t&&eE?.id===e.id)return;eA.current+=1;let r=eA.current;if(eP.current?.abort(),t||!eI){eP.current=null,e$(null),n0(e,t,null);return}let n=new AbortController;eP.current=n,e$(e);let a=new URLSearchParams({deferThinking:"1",deferMedia:"1"});fetch(`/api/sessions/${encodeURIComponent(e.id)}?${a}`,{cache:"no-store",signal:n.signal}).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(n.sessionId!==e.id)throw Error("Session preload returned the wrong session");eA.current===r&&n0(e,!1,n)}).catch(t=>{n.signal.aborted||eA.current!==r||(console.error("Failed to preload session before switching:",t),n0(e,!1,null))}).finally(()=>{eA.current===r&&(eP.current=null,e$(null))})},[n0,nJ,ea,eE?.id,eI,rp]),n8=(0,a.useCallback)((e,t)=>{eA.current+=1,eP.current?.abort(),eP.current=null,e$(null),eL(null),nJ(),eM(null),eB(t),eX(e=>e+1),rS({sessionId:null,tree:[],leafId:null,navigation:0}),rE(null),r1(null),th({type:"select-view",view:"chat"}),ea&&rp(!1),G.replace("/",{scroll:!1})},["/",nJ,ea,G,rp]),n4=(0,a.useCallback)((e,t)=>{if(ey(!1),!t){rm(e).then(()=>eS("CUELO 저장소를 찾지 못해 프롬프트를 복사했습니다. 사이드바에서 폴더를 고른 뒤 새 세션 입력창에 붙여 넣으세요."),()=>eS("CUELO 저장소를 찾지 못했고 프롬프트 복사도 실패했습니다. 보수 화면의 「복사」를 다시 눌러 보세요.")),ea&&rp(!0);return}let r=`new:${t}`,n=dL(r);dA(r,{value:n?.value.trim()?`${n.value.trimEnd()}
|
|
77
|
+
|
|
78
|
+
${e}`:e,images:n?.images??[],documents:n?.documents??[]}),n8(`upkeep-${Date.now()}`,t),tz(),eS("프롬프트를 새 세션 입력창에 넣었습니다. 내용을 확인한 뒤 보내세요.")},[n8,ea,tz,rp]),n5=(0,a.useCallback)(e=>{let t=eI?.projectRoot??nU.current??eI?.cwd??nD;if(!t||!eI)return;let r=tS.filter(e=>(e.projectRoot??e.cwd)===t),n=r.findIndex(e=>e.id===eI.id);if(n<0)return;let a=r[n+e];a&&(r1(null),th({type:"close-layer"}),n2(a),tz())},[nD,tS,n2,tz,eI]);m={onNewSession:e=>n8(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>nm("command-palette"),onToggleNavigator:nj,onToggleResources:()=>ne("resource"===tp.activeView?"chat":"resource",!0),onSelectView:e=>ne(e,!0),onCycleView:(0,a.useCallback)(e=>{let t=(d.indexOf(tp.activeView)+e+d.length)%d.length;ne(d[t],!0)},[ne,tp.activeView]),onNavigateSession:n5,onEscape:ny,enabled:!e8&&!ts&&null===e5,activeCwd:nD},(C=(0,a.useRef)(m)).current=m,(0,a.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let r=t.now?.()??Date.now();if(b||e.isComposing||229===e.keyCode||r-y<100)return;let n=e.target,a="u">typeof Element&&n instanceof Element?n:null,i=!!a?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!a?.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()):!(i||a?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(a?.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 r=d[Number(s)-1];return r&&(e.preventDefault(),t.onSelectView(r))}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,C.current)},t=()=>w(!0),r=()=>w(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",r,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",r,{capture:!0})}},[]);let n6=(0,a.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let r=t?.sessions.find(t=>t.id===e);r&&eM(t=>t?.id===e?{...t,...r,transient:r.transient??!1}:t)}).catch(()=>{})},[]),n3=(0,a.useCallback)(e=>{nJ(),eB(null),eM(e),eZ(e=>e+1),n6(e.id),G.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nJ,G,n6]),n7=(0,a.useCallback)(({targetSession:e,title:t,body:r,tag:n})=>{"Notification"in window&&"granted"===Notification.permission&&uB({title:t,body:r,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:n,onClick:()=>{window.focus(),e&&n2(e)}})},[n2]),n9=(0,a.useCallback)(e=>{eZ(e=>e+1),ta.current?.pending&&tn(e=>e+1),e0(e=>e+1),eI&&n6(eI.id),"completed"===e.outcome&&uH()&&n7({targetSession:eI,title:eI?.name??et("i18n.sessionComplete"),body:et("i18n.taskFinished")})},[n7,n6,eI,et]),ae=(0,a.useCallback)(e=>{var t;uH()&&(t=eN.current,!(!uU(e)||t.has(e.id))&&(t.add(e.id),1)&&n7({targetSession:eI,title:et("i18n.attentionNeeded"),body:"custom"===e.method?et("i18n.extensionInputNeeded"):"ask"===e.method?e.questions[0]?.question||et("i18n.extensionInputNeeded"):"form"===e.method?function(e){for(let t of e.sections){let r=cU(t.title),n="";for(let a of t.blocks){if("field"===a.kind){let t=e.fields[a.index],i=cU(t.label),s="choice"===t.kind&&1===t.options.length?cU(t.options[0].label):"";return(i||n||r||s||t.name).replace(/\s+/g," ").trim()}n="text"===a.kind?cU(a.spans):""}}return""}(e.form)||et("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[n7,eI,et]),at=(0,a.useCallback)(async()=>{let e=eI?.id;if(e&&"naming"!==rO.kind){rH.current&&clearTimeout(rH.current),r1(null),rD({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),r=await t.json().catch(()=>({}));if(!t.ok||!r.title)throw Error(r.error||`HTTP ${t.status}`);let n=r.title.trim();if(eZ(e=>e+1),rU.current!==e)return;eM(t=>t?.id===e?{...t,name:n}:t),rL(t=>t?.sessionId===e?{...t,sessionName:n}:t),rD({kind:"success"}),rH.current=setTimeout(()=>rD({kind:"idle"}),1800)}catch(t){if(rU.current!==e)return;rD({kind:"error",message:t instanceof Error?t.message:String(t)}),rH.current=setTimeout(()=>rD({kind:"idle"}),5e3)}}},[rO.kind,eI?.id]);(0,a.useEffect)(()=>{rH.current&&clearTimeout(rH.current),rD({kind:"idle"})},[eI?.id]);let ar=(0,a.useCallback)(e=>{nJ(),eZ(e=>e+1),eX(e=>e+1),eB(null),eM(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),n6(e),G.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[nJ,G,n6]),an=(0,a.useCallback)(()=>{nq(!0)},[]),aa=(0,a.useCallback)(e=>{if(nJ(),eZ(e=>e+1),eI?.id===e){let e=eI.cwd;eM(null),eB(e??null),eX(e=>e+1),rS({sessionId:null,tree:[],leafId:null,navigation:0}),rE(null),r1(null),th({type:"select-view",view:"chat"}),tz(),G.replace("/",{scroll:!1})}},["/",nJ,tz,eI,G]),ai=(0,a.useCallback)((e,t,r)=>{let n=r?.sourceSessionId,a=r?.modeHint,i=`file:${e}`;a&&nL.current.delete(i),nC(r=>{let s=r.find(e=>e.id===i);if(!s)return[...r,{id:i,label:t,filePath:e,sourceSessionId:n,initialDisplayMode:a}];let o=!n||s.sourceSessionId===n,l=!a||s.initialDisplayMode===a;return o&&l?r:r.map(e=>{if(e.id!==i)return e;let t={...e};return n&&(t.sourceSessionId=n),a&&(t.initialDisplayMode=a),t})}),nE(i),th({type:"select-view",view:"files"}),r1(null),ea&&rp(!1)},[ea,rp]),as=(0,a.useCallback)(e=>{ai(e,tF(e),{sourceSessionId:eI?.id??null})},[ai,eI?.id]),ao=(0,a.useCallback)(e=>{nL.current.delete(e);let t=nS.filter(t=>t.id!==e);nC(t),nE(r=>r!==e?r:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===tp.activeView&&ne("chat",!0)},[nS,ne,tp.activeView]),al=(0,a.useCallback)(()=>{eI&&window.open(`/api/sessions/${encodeURIComponent(eI.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[eI]),ac=eU??(null===eI&&nD?nD:null),au=null!==eI||null!==ac,ap="chat"!==tp.activeView,ah=eI?.cwd??ac,af=nB&&!au,ag=(0,a.useCallback)((e,t)=>{ta.current=e,tt(e),tu(e.error?et("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&to(!1),e2(e=>e+1),eX(e=>e+1))},[et]);(0,a.useEffect)(()=>{let e=ti.current!==ah;if(ti.current=ah,e&&(ta.current=null,tt(null),to(!1),tu(null)),!ah)return;let t=ta.current,r=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(ah)}`,{signal:r.signal}).then(async e=>{let r=await e.json();if(!e.ok)throw Error(r.error??`HTTP ${e.status}`);ag(r,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>r.abort()},[ag,ah,tr]);let ax=(0,a.useCallback)(async e=>{if(ah&&!tl){tc(!0),tu(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ah,action:e})}),r=await t.json();if(!t.ok)throw Error(r.error??`HTTP ${t.status}`);let n=ta.current;ag(r,n),(r.trusted||"cancel"===e)&&(to(!1),tz())}catch(e){tu(e instanceof Error?e.message:String(e))}finally{tc(!1)}}},[ag,tl,ah,tz]),av=nS.find(e=>e.id===nN)??null,ab=nD?tF(nD)||nD:null,ay=eI?.cwd??ac,aw=ay?tF(ay)||ay:null,ak=(eI?.name?.trim()||eI?.firstMessage?.trim()||(ac?et("i18n.newSession"):ab)||"CUELO").replace(/\s+/g," ").trim(),aj=ak.length>96?`${ak.slice(0,93)}…`:ak,aS=ab?`${aj} — ${ab} — CUELO`:`${aj} — CUELO`,aC=ab?`${ak} — ${ab}`:ak,aN=eI?.transient?`${aC} \xb7 ${et("session.inMemory")}`:aC,aT=rA.filter(e=>"pending"===e.status||"running"===e.status).length,aI=rz?et("workspace.mainAttention"):tE?et("workspace.mainWaiting"):tI?et("workspace.mainWorking"):et("workspace.mainIdle"),aM=`${rz?"⚠":tE?"○":tI?"●":"○"} Main ${aI} \xb7 Sub ${aT}${rF?`/${rF}`:""}`,aE=(0,a.useCallback)(e=>ne(e,!0),[ne]),a$=(T=(N=(f={deckVisible:ap,pinDecision:ty,deckExpanded:tp.deckExpanded}).deckVisible&&"pinned"===f.pinDecision.deck)&&f.deckExpanded,{replacesTranscript:f.deckVisible&&("view-stack"===f.pinDecision.deck||T),expandable:N,expanded:T,staleExpansion:f.deckExpanded&&!N}),aR=a$.replacesTranscript,aL=a$.expandable?{expanded:a$.expanded,onToggle:ns}:null,aA=a$.staleExpansion;(0,a.useEffect)(()=>{aA&&th({type:"set-deck-expanded",expanded:!1})},[aA]),(0,a.useEffect)(()=>{let e=()=>{document.title!==aS&&(document.title=aS)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[aS]);let aP="ko"===Q?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗",plugins:"플러그인",memory:"기억 추적"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat",plugins:"Plugins",memory:"Memory trace"},aF="chat"!==tp.activeView,a_=aF?aP[tp.activeView]:aP[r7],az=(I=rJ&&Number.isFinite(rJ.contextWindow)&&rJ.contextWindow>0?rJ.contextWindow:null,M=rJ&&"number"==typeof rJ.tokens&&Number.isFinite(rJ.tokens)?Math.max(0,rJ.tokens):null,$=null===(E=rJ&&"number"==typeof rJ.percent&&Number.isFinite(rJ.percent)?rJ.percent:null!==M&&null!==I?M/I*100:null)?"normal":E>90?"critical":E>70?"warning":"normal",R=null===M?"?":vx(M),L=null===I?"?":vx(I),A=null===E?"?":`${E.toFixed(0)}%`,{level:$,percent:E,fillPercent:null===E?0:Math.min(100,Math.max(0,E)),readout:null===I?null:`${A} \xb7 ${R}/${L}`,usedLabel:R,limitLabel:L,percentLabel:A}),aW=az.readout,aO=aW?et("chat.contextUsageTitle",{used:az.usedLabel,limit:az.limitLabel,percent:az.percentLabel}):null,aD="critical"===az.level?et("chat.contextUsageCritical"):"warning"===az.level?et("chat.contextUsageWarning"):null,aH=(k=rR?.userMessages,!eI||eI.transient?"unsaved":("number"==typeof k?k:0)>0||eI.messageCount>0?null:"no-messages"),aU="unsaved"===aH?et("title.unsaved"):"no-messages"===aH?et("title.noMessages"):null,aB=aU??("error"===rO.kind?rO.message:null),aq="naming"===rO.kind?et("title.generating"):"success"===rO.kind?et("title.updated"):"error"===rO.kind?et("title.failed"):et("title.generate"),aV=(0,n.jsxs)("div",{id:"workspace-file-view",className:"workspace-file-view",children:[(0,n.jsx)("div",{className:"workspace-file-tabs",children:(0,n.jsx)(hj,{tabs:nS,activeTabId:nN??"",onSelectTab:nE,onCloseTab:ao})}),(0,n.jsx)("div",{className:"workspace-file-content",children:av?.filePath?(0,n.jsx)(hw,{filePath:av.filePath,cwd:nD??void 0,sourceSessionId:av.sourceSessionId,gitRefreshKey:eQ,initialDisplayMode:av.initialDisplayMode,viewStateStore:nL.current,viewStateKey:av.id,onMentionLines:nF,onAtMention:nP,onInsertText:nz,onOpenFile:e=>ai(e,tF(e),{sourceSessionId:av.sourceSessionId})},av.id):(0,n.jsx)("div",{className:"workspace-file-empty",children:(0,n.jsx)(vp,{cwd:eI?.cwd??nD,onOpenFile:as})})})]}),aK=(0,n.jsx)(gH,{open:"resource"===tp.activeView,sessionId:eI?.id??null,activeTab:tm,onTabChange:tf,usage:eh}),aG=(0,n.jsx)(xF,{open:"efficiency"===tp.activeView,sessionId:eI?.id??null,activeTab:tg,onTabChange:tx}),aJ=(0,n.jsx)(xV,{title:aP.plugins,visible:"plugins"===tp.activeView,sessionId:eI?.id??null,labWidgets:tv,onInsertDraft:au?nz:void 0}),aZ=(0,n.jsx)(vr,{title:aP.memory,visible:"memory"===tp.activeView,sessionId:eI?.id??null}),aY=(0,n.jsx)(fB,{title:aP.process,data:rX,onOpenFile:as}),aX=eI?eI.path?eI.path:rR?.sessionId===eI.id&&rR.sessionFile?rR.sessionFile:null:null,aQ=(0,n.jsx)(f7,{title:aP.sidechat,sessionId:eI?.id??null,sessionPath:aX,sessionName:eI?.name,historyStore:tk,flights:tj,sessionCensus:tN,visible:"sidechat"===tp.activeView}),a0=ap?(0,n.jsx)(fU,{activeView:tp.activeView,onViewChange:e=>ne(e),viewLabels:aP,sessionId:eI?.id??null,sessionPath:aX,sessionName:eI?.name,sessionCwd:eI?.cwd??ac??void 0,liveSubagents:rA,processSlot:aY,fileSlot:aV,sideChatSlot:aQ,resourceSlot:t??aK,efficiencySlot:aG,pluginsSlot:aJ,memorySlot:aZ,visible:!0,onClose:()=>th({type:"select-view",view:"chat"}),onReturnFocus:tz,expand:aL,selectedMaker:no,onSelectMaker:nl,onReturnToDispatch:nh,onOpenFile:as,fileOpen:!!av?.filePath}):null,a1=e??a0,a2=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(em,{selectedSessionId:eE?.id??eI?.id??null,optimisticSession:eE??eI,onSelectSession:n2,onNewSession:n8,initialSessionId:nO,skipInitialProjectSelection:null!==Z.requestedCwd,onInitialRestoreDone:an,refreshKey:eJ,onSessionDeleted:aa,selectedCwd:eI?.cwd??eU??null,onCwdChange:nX,onBackgroundTaskDone:eT,translatorPanel:(0,n.jsx)(bk,{onOpen:ea?()=>rp(!1):void 0}),translatorActive:ef,onTranslatorActiveChange:tW}),(0,n.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[(0,n.jsx)(vT,{usage:eh,onOpen:()=>{tf("usage"),ne("resource",!1)},onRelogin:ng}),(0,n.jsx)(bN,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsxs)("button",{type:"button",className:"navigator-settings-action",onClick:()=>{ea&&rp(!1),tO(!0)},title:"보수 점검 대시보드 열기",style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,cursor:"pointer",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.12s, color 0.12s, border-color 0.12s"},children:[(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})}),"보수"]}),(0,n.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{r1(null),th({type:"close-layer"}),ea&&rp(!1),e4(!0)},title:et("common.settings"),style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",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,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,n.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"})]}),et("common.settings")]})]})]})]}),a8=tQ&&t1&&t1.requestId===tQ.requestId&&t1.deploymentCompleted?t1:null,a4=a8?.cleanup??null,a5=a8&&!tQ?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:uQ(null)};let t=`${e.completedCount}/${e.totalCount} 완료`,r=`${Math.round(e.elapsedSeconds)}초 경과`;return"running"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 중",detail:`${t} \xb7 ${r} \xb7 현재 ${e.currentTarget??"대상 선택 중"}`,dismissible:!1,autoHideMs:null}:"failed"===e.status?{tone:"warning",title:"업데이트 완료 \xb7 산출물 정리 실패",detail:`${t} \xb7 ${r} \xb7 보존 ${e.keptCount}건 \xb7 실패 ${e.failureCount}건. 업데이트 자체는 성공했고 실패 증거는 보존했습니다.`,dismissible:!0,autoHideMs:uQ(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${r} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:uQ(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${r}`,dismissible:!0,autoHideMs:uQ(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${r}`,dismissible:!0,autoHideMs:uQ(e.status)}}(a4):null;return(0,n.jsxs)(rI.Provider,{value:n_,children:[tU?(0,n.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,n.jsxs)("div",{className:"server-restart-card",children:[(0,n.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,n.jsx)("strong",{children:et("restart.title")}),(0,n.jsx)("span",{children:et(tG?"restart.slow":"restart.body")})]})}):null,(0,n.jsxs)("div",{ref:tA,className:"workspace-shell","data-active-view":tp.activeView,"data-deck-mode":ty.deck,"data-deck-visible":ap,"data-chat-wide":eO?"true":void 0,children:[(0,n.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${ru.drawer?" is-open":""}${rn?"":" sidebar-mobile-pending"}${ri?" sidebar-mode-shift":""}`,onClick:()=>{rp(!1),tz()}}),(0,n.jsx)("div",{ref:rb.panelRef,id:"session-sidebar",className:`sidebar-container${ru.laidOut?" sidebar-open":" sidebar-closed"}${rn?"":" sidebar-mobile-pending"}${ri?" sidebar-mode-shift":""}${rb.isResizing?" sidebar-resizing":""}`,"aria-hidden":ea&&!ru.presented,inert:ea&&!ru.presented,style:{"--sidebar-width":`${rb.width}px`},children:a2}),ru.laidOut&&(0,n.jsx)("div",{...rb.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${rb.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${et("layout.resizeSidebar")}: ${et("layout.resizeHint")}`}),(0,n.jsxs)("div",{className:"workspace-session-region","data-active-view":tp.activeView,"aria-hidden":ru.drawer,inert:ru.drawer,children:[(0,n.jsxs)("div",{ref:rk,className:"workspace-header-stack","data-soft-keyboard":ei&&es?"open":void 0,children:[a5&&tQ&&(0,n.jsxs)("div",{className:"workspace-update-banner","data-tone":a5.tone,role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"workspace-update-banner-title",children:a5.title}),(0,n.jsx)("span",{className:"workspace-update-banner-detail",children:a5.detail}),a5.dismissible&&(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>t0(u8(tQ.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tZ&&!(a5&&tQ)&&(0,n.jsxs)("div",{className:"workspace-update-banner","data-tone":"positive",role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"workspace-update-banner-title",children:et("restart.returnedTitle")}),(0,n.jsx)("span",{className:"workspace-update-banner-detail",children:et("restart.returnedBody")}),(0,n.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tY(!1),"aria-label":et("restart.returnedDismiss"),children:et("i18n.close")})]}),(0,n.jsx)(fN,{variant:"banner",locale:Q,...en}),(0,n.jsxs)("header",{className:"workspace-header-seam",children:[(0,n.jsx)(s.r,{ref:rf,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:nj,"aria-controls":"session-sidebar","aria-expanded":ru.presented,title:ru.presented?et("sidebar.hide"):et("sidebar.show"),"aria-label":ru.presented?et("sidebar.hide"):et("sidebar.show"),children:ru.presented?(0,n.jsx)(o.In,{size:"16px",svg:(0,n.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,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,n.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}):(0,n.jsx)(o.In,{size:"18px",svg:(0,n.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,n.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,n.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})})}),(0,n.jsxs)("div",{className:"workspace-session-identity",title:aN,children:[(0,n.jsxs)("div",{className:"workspace-session-identity-line",children:[aw&&(0,n.jsx)("em",{className:"workspace-session-project",children:aw}),(0,n.jsx)("strong",{children:aj})]}),(0,n.jsx)("span",{className:"workspace-session-status","aria-live":"polite",children:aM})]}),(0,n.jsx)("span",{className:"sr-only",role:"status",children:"error"===rO.kind?rO.message:""}),au&&te?.requiresTrust&&!te.trusted&&(0,n.jsxs)(s.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{tu(te.error?et("trust.applyFailed",{error:te.error}):null),r1(null),th({type:"close-layer"}),to(!0),te.pending&&tn(e=>e+1)},title:et("grant"===te.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":et("grant"===te.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,n.jsx)("path",{d:"M12 8v4"}),(0,n.jsx)("path",{d:"M12 16h.01"})]}),!ea&&(0,n.jsx)("span",{children:et("trust.resourcesNotLoaded")})]}),au&&nd&&(0,n.jsx)(pq,{sessionId:nd,refreshKey:String(tI),compact:ea}),au&&aW&&(0,n.jsxs)(s.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:nk,"aria-expanded":"session"===r0,title:aO??et("session.title"),"aria-label":aD?`${aO}. ${aD}`:aO??void 0,children:[(0,n.jsx)("span",{className:"workspace-context-meter","aria-hidden":"true",children:(0,n.jsx)("span",{className:"workspace-context-meter-fill","data-level":az.level,style:{inlineSize:`${az.fillPercent}%`}})}),(0,n.jsx)("span",{className:"workspace-context-readout","data-level":az.level,children:aW})]}),au&&(0,n.jsx)(l.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:aF,onPressedChange:nf,"aria-controls":"workspace-auxiliary-panel",title:"ko"===Q?"보조 패널":"Auxiliary panel",children:(0,n.jsx)("span",{className:"workspace-panel-toggle-label",children:a_})}),(0,n.jsxs)(c.k.Root,{open:r6,onOpenChange:e=>r3(e),placement:"bottom-end",strategy:"fixed",children:[(0,n.jsx)(c.k.Trigger,{asChild:!0,children:(0,n.jsx)(s.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===Q?"더 보기":"More","aria-label":"ko"===Q?"더 보기":"More",children:(0,n.jsx)(o.In,{size:"16px",svg:(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"12",cy:"5",r:"1"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,n.jsx)("circle",{cx:"12",cy:"19",r:"1"})]})})})}),(0,n.jsx)(c.k.Positioner,{children:(0,n.jsx)(c.k.Content,{"aria-label":"ko"===Q?"세션 및 환경 메뉴":"Session and environment menu",children:(0,n.jsxs)(c.k.ScrollArea,{children:[(0,n.jsxs)(c.k.Group,{children:[(0,n.jsx)(c.k.GroupLabel,{children:"ko"===Q?"세션":"Session"}),(0,n.jsx)(c.k.Item,{onClick:nk,children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:et("session.title")})})}),(0,n.jsx)(c.k.Item,{onClick:al,disabled:!eI,children:(0,n.jsxs)(c.k.ItemBody,{children:[(0,n.jsx)(c.k.ItemLabel,{children:et("history.label")}),!eI&&(0,n.jsx)(c.k.ItemDescription,{children:et("history.unsaved")})]})}),(0,n.jsx)(c.k.Item,{onClick:()=>void at(),disabled:null!==aU||"naming"===rO.kind,children:(0,n.jsxs)(c.k.ItemBody,{children:[(0,n.jsx)(c.k.ItemLabel,{children:aq}),aB&&(0,n.jsx)(c.k.ItemDescription,{children:aB})]})}),(0,n.jsx)(c.k.Item,{onClick:()=>nw("branches"),children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:et("i18n.branches")})})}),(0,n.jsx)(c.k.Item,{onClick:()=>nw("system"),children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:et("system.label")})})})]}),(0,n.jsxs)(c.k.Group,{children:[(0,n.jsx)(c.k.GroupLabel,{children:"ko"===Q?"환경":"Environment"}),(0,n.jsx)(fN,{variant:"menu",locale:Q,...en}),(0,n.jsx)(c.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();X({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:et("light"===Y?"theme.light":"dark"===Y?"theme.dark":"theme.auto")})})}),er.map(e=>(0,n.jsx)(c.k.Item,{role:"menuitemradio","aria-checked":Q===e.id,onClick:()=>ee(e.id),children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:e.label})})},e.id)),(0,n.jsx)(c.k.Item,{onClick:()=>{r1(null),th({type:"close-layer"}),ea&&rp(!1),e4(!0)},children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:et("common.settings")})})})]})]})})})]})]}),r0&&r8&&(0,n.jsxs)("div",{style:{position:"fixed",top:r8.top,left:r8.left,width:r8.width,maxHeight:`calc(100dvh - ${r8.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===r0&&(0,n.jsx)("div",{className:"workspace-top-panel","aria-label":et("i18n.branches"),children:(0,n.jsx)(vg,{tree:rj.sessionId===(eI?.id??null)?rj.tree:[],activeLeafId:rj.sessionId===(eI?.id??null)?rj.leafId:null,onLeafChange:rT,hasSession:!!eI})}),"system"===r0&&(0,n.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:rM?(0,n.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:rM}):""===rM?(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:et("system.empty")}):(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:et("system.load")})}),"session"===r0&&(0,n.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:rR?(P=rR.totalActiveMs??0,F=[...rR.sessionName?[{label:et("session.name"),value:rR.sessionName,copyField:null}]:[],{label:et("session.file"),value:rR.sessionFile??et("session.inMemory"),copyField:"file"},{label:et("session.id"),value:rR.sessionId,copyField:"id"},...P>0?[{label:et("session.totalActive"),value:(e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),r=Math.floor(t/3600),n=Math.floor(t%3600/60),a=t%60;return r>0?`${r}h ${n}m`:n>0?`${n}m ${a}s`:`${a}s`})(P),copyField:null}]:[]],_=[[et("session.user"),rR.userMessages.toLocaleString(Q)],[et("session.assistant"),rR.assistantMessages.toLocaleString(Q)],[et("session.toolCalls"),rR.toolCalls.toLocaleString(Q)],[et("session.toolResults"),rR.toolResults.toLocaleString(Q)],[et("session.total"),rR.totalMessages.toLocaleString(Q)]],W=[[et("session.input"),rR.tokens.input.toLocaleString(Q)],[et("session.output"),rR.tokens.output.toLocaleString(Q)],...rR.tokens.cacheRead>0?[[et("session.cacheRead"),rR.tokens.cacheRead.toLocaleString(Q)]]:[],...rR.tokens.cacheWrite>0?[[et("session.cacheWrite"),rR.tokens.cacheWrite.toLocaleString(Q)]]:[],[et("session.total"),rR.tokens.total.toLocaleString(Q)]],O=rJ??rR.contextUsage,D=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),q=[...rR.cost>0?[[et("session.cost"),`$${rR.cost.toFixed(4)}`]]:[],...O?.contextWindow?[[et("session.context"),`${null!==O.tokens?D(O.tokens):"?"} / ${D(O.contextWindow)}${null!==O.percent?` \xb7 ${O.percent.toFixed(1)}%`:""}`]]:[],...rR.tokens.cacheRead+rR.tokens.cacheWrite>0&&rR.tokens.cacheRead+rR.tokens.cacheWrite+rR.tokens.input>0?[[et("session.cacheHitRate"),`${(rR.tokens.cacheRead/(rR.tokens.cacheRead+rR.tokens.cacheWrite+rR.tokens.input)*100).toFixed(1)}%`]]:[]],V=(e,t,r="left",a=!1)=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:a?"max-content max-content":"auto minmax(0, 1fr)",columnGap:a?14:12,rowGap:4,justifyContent:a?"start":void 0},children:t.map(([t,i])=>(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:a?"normal":"anywhere",textAlign:r,whiteSpace:"right"===r?"nowrap":"normal"},children:i})]},`${e}:${t}`))})]}),K=(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:et("session.infoSection")}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:F.map(e=>{var t,r;let a;return(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,n.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,n.jsx)("div",{children:e.copyField?(t=e.copyField,r=e.value,a=rq===t,(0,n.jsx)("button",{type:"button",title:a?et("session.copied"):et("file"===t?"session.copyFile":"session.copyId"),onClick:()=>rG(t,r),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:a?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",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=a?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:a?(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,n.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,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:ea?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:ea?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[K,V(et("session.messages"),_),V(et("session.tokens"),[...W,...q],"right",!0)]})):(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:et("session.load")})})]})]}),(0,n.jsxs)("div",{className:"chat-content-layout",children:[(0,n.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-translator-open":ef?"true":void 0,children:[au?(0,n.jsx)(pF,{session:eI,newSessionCwd:ac,initialSessionData:eR,transitioning:null!==eE,onAgentEnd:n9,onAttentionNeeded:ae,onSessionCreated:n3,onSessionForked:ar,modelsRefreshKey:e1,chatInputRef:rw,onBranchDataChange:rN,onSystemPromptChange:r$,onSessionStatsChange:rB,onSessionStatsPanelOpen:nk,onContextUsageChange:rY,onSubagentsChange:rP,onLabWidgetsChange:nW,onOpenWorkspaceView:aE,onOpenSessionList:ru.presented?void 0:nj,onOpenMaker:nc,selectedMaker:no,onProcessLogChange:rQ,onOpenFile:as,transcriptReplacement:aR?(0,n.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:a1}):null,onComposerFocusChange:tD,onSessionBusyChange:tM,onWaitingChange:t$,onAttentionChange:rW,soundEnabled:eo,onSoundToggle:el,playCueSound:ec,preloadCueSound:ed,unlockAudio:eu,jumpRequest:eF,onJumpHandled:eW},eY):aR?(0,n.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:a1}):"validating"===eq?(0,n.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,n.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:et("workspace.opening")}),(0,n.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:Z.requestedCwd})]}):"error"===eq?(0,n.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,n.jsx)("div",{style:{fontSize:14,color:"var(--danger)"},children:et("workspace.unable")}),(0,n.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:Z.requestedCwd}),(0,n.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eK})]}):af?nD?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:et("workspace.selectSession")}):(0,n.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,n.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,n.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,n.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:et("workspace.getStarted")}),(0,n.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,n.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),et("workspace.selectProject"),(0,n.jsx)("br",{}),(0,n.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),et("workspace.addModels")]})]})]}):null,ex?(0,n.jsx)(bw,{visible:ef,onBack:()=>tW(!1)}):null]}),"pinned"===ty.deck&&ap&&!a$.expanded&&(0,n.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:a1})]})]}),"command-palette"===tp.transientLayer&&(0,n.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(th({type:"close-layer"}),tz())},children:(0,n.jsxs)("div",{ref:t_,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:re,"aria-label":"ko"===Q?"명령 팔레트":"Command palette",children:[(0,n.jsxs)("header",{children:[(0,n.jsx)("strong",{children:"ko"===Q?"명령 팔레트":"Command palette"}),(0,n.jsx)("kbd",{children:"Ctrl K"})]}),(0,n.jsx)(pV,{t:et,onPick:(e,t)=>{th({type:"close-layer"}),ne("chat",!1),ez.current+=1,e_({id:ez.current,sessionId:e.id,entryId:t.entryId}),n2(e)}}),(0,n.jsxs)("div",{className:"workspace-command-list",children:[d.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>ne(e,!0),children:[(0,n.jsx)("span",{children:aP[e]}),(0,n.jsx)("small",{children:tp.activeView===e?"ko"===Q?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>{tf(e),ne("resource",!1)},children:[(0,n.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,n.jsx)("small",{children:aP.resource})]},e)),(0,n.jsxs)("button",{type:"button",onClick:nj,children:[(0,n.jsx)("span",{children:ru.presented?et("sidebar.hide"):et("sidebar.show")}),(0,n.jsx)("small",{children:"Ctrl B"})]}),(0,n.jsx)("button",{type:"button",onClick:eH,children:(0,n.jsx)("span",{children:et(eO?"palette.wideChatOff":"palette.wideChatOn")})}),(0,n.jsx)("button",{type:"button",onClick:()=>{th({type:"close-layer"}),e4(!0)},children:(0,n.jsx)("span",{children:et("common.settings")})})]})]})})]}),ew?(0,n.jsx)(yf,{open:eb,onClose:()=>tO(!1),onStartSession:n4}):null,(0,n.jsx)(yg,{message:ej,onDismiss:eC}),e8&&(0,n.jsx)(fj,{cwd:ah,sessionId:eI?.id??null,onClose:()=>{e4(!1),tn(e=>e+1),tz()},onModelsChanged:()=>e2(e=>e+1),onReloaded:()=>eX(e=>e+1)}),null!==e5&&(0,n.jsx)(mM,{cwd:ah,onClose:nx,onModelsChanged:()=>e2(e=>e+1),relogin:{target:e5,outcome:e3,onLoginSucceeded:nb}}),ts&&ah&&(0,n.jsx)(fT,{cwd:ah,busy:tl,scheduled:te?.pending==="grant",error:td,onCancel:()=>{tl||(to(!1),tz())},onConfirm:()=>void ax("grant"),onCancelSchedule:()=>void ax("cancel")})]})}},84183:(e,t,r)=>{"use strict";r.d(t,{I18nProvider:()=>h,s:()=>m});var n=r(95155),a=r(12115);let i=JSON.parse('{"savedPrompts.title":"저장된 프롬프트","savedPrompts.loading":"불러오는 중...","savedPrompts.empty":"저장된 프롬프트 없음","savedPrompts.save":"현재 입력을 프롬프트로 저장","savedPrompts.saved":"저장됨","savedPrompts.delete":"삭제","savedPrompts.confirmDelete":"삭제할까요?","savedPrompts.cancel":"취소","savedPrompts.hint":"텍스트 입력 후 //를 입력하여 저장하세요. 변수: {{project_name}} {{session_name}} {{cwd}} {{date}}","savedPrompts.error":"저장된 프롬프트 요청 실패: {error}","memoryTrace.refresh":"새로고침","memoryTrace.noSession":"세션을 고르면 기억을 찾은 과정이 보여요.","memoryTrace.loading":"세션 기록을 읽는 중…","memoryTrace.error":"기억 추적을 불러오지 못했어요. {error}","memoryTrace.retry":"다시 불러오기","memoryTrace.empty":"이 세션에는 기억\xb7지도 기록이 없어요","memoryTrace.requests":"기록 있는 요청 {count}개","memoryTrace.requestsLabel":"요청","memoryTrace.requestHeading":"요청 #{index}","memoryTrace.noPreview":"(글 없음)","memoryTrace.flowLabel":"요청 흐름","memoryTrace.stageRecall":"기억 불러옴","memoryTrace.stageJev":"JEV 대조","memoryTrace.stageDocmap":"지도 후보","memoryTrace.stageDocs":"연 문서","memoryTrace.stageLessons":"편집 전 교훈","memoryTrace.stageSaved":"새로 저장","memoryTrace.stageEmpty":"이 요청에서는 이 단계가 없었어요.","memoryTrace.openedSummary":"{opened}개 열어 봄 \xb7 {skipped}개 후보만","memoryTrace.opened":"열어 봄","memoryTrace.candidateOnly":"후보만","memoryTrace.fromMap":"지도 후보","memoryTrace.lines":"읽은 줄 {lines}","memoryTrace.autoRecall":"요청 전에 자동으로 불러옴","memoryTrace.explicitRecall":"작업 중 직접 찾음","memoryTrace.query":"질의","memoryTrace.noResults":"돌아온 기억이 없어요.","memoryTrace.noMemoryText":"이 기록에는 기억 글이 남아 있지 않아요.","memoryTrace.jevUnknown":"판정 불명 {count}개","memoryTrace.jevUnrelated":"무관 {count}개","memoryTrace.lessonFor":"편집 전에 띄운 기억","memoryTrace.savedAuto":"자동 저장","memoryTrace.graphLabel":"연결 그래프","memoryTrace.graphScope":"그래프 범위","memoryTrace.scopeRequest":"이 요청","memoryTrace.scopeSession":"세션 전체","memoryTrace.legendRequest":"요청","memoryTrace.legendMemory":"기억","memoryTrace.legendDoc":"지도 문서","memoryTrace.legendFile":"편집 파일","memoryTrace.graphEmpty":"이 범위에는 이어진 항목이 없어요.","memoryTrace.nodeLabel":"{kind}: {label}, 연결 {count}개","memoryTrace.edgeRecalled":"불러옴","memoryTrace.edgeLesson":"편집 전 교훈","memoryTrace.verdictLegend":"JEV 판정","memoryTrace.verdictApply":"적용 조건 일치","memoryTrace.verdictExcepted":"조건 불충족\xb7예외","memoryTrace.verdictConflict":"요청과 충돌","memoryTrace.verdictUnconfirmed":"조건 미확인","memoryTrace.verdictUnlisted":"무관\xb7판정 불명","memoryTrace.graphHint":"노드를 가리키거나 포커스하면 전체 글이 여기 나와요.","memoryTrace.legendDocEdited":"열고 편집한 파일","memoryTrace.noticeHarness":"하네스","memoryTrace.noticeResume":"자동 재개","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":"소스에서 실행 중이면 서버를 먼저 멈추고 아래 명령으로 갱신한 뒤 다시 시작하세요. 별도 --home 경로를 사용한다면 setup에도 같은 --home 옵션을 붙이세요.","updates.copyCommand":"명령어 복사","updates.commandCopied":"명령어 복사됨","updates.copyFailed":"명령어를 복사할 수 없습니다","updates.apply":"지금 업데이트","updates.applyBusy":"업데이트 중…","updates.applyConfirm":"CUELO {version}(으)로 업데이트하고 다시 시작할까요?\\n\\n업데이트하는 동안 서버가 잠시 멈추고 이 화면은 진행 상황을 보여 줍니다. 새 버전이 응답하면 자동으로 새로 고칩니다.","updates.applyConfirmBusy":"CUELO {version}(으)로 업데이트하고 다시 시작할까요?\\n\\n실행 중인 세션 {count}개가 중단되고 서버가 잠시 멈춥니다. 이 화면은 진행 상황을 보여 주며, 새 버전이 응답하면 자동으로 새로 고칩니다.","updates.unsupported":"이 설치 방식은 앱에서 바로 바꿀 수 없습니다. 아래 명령을 사용하세요.","updates.unsupportedReason":"감지 결과: {reason}","updates.phase.starting":"업데이트 준비 중","updates.phase.fetching":"새 버전 받는 중","updates.phase.installing":"패키지 설치 중","updates.phase.building":"빌드 중","updates.phase.restarting":"서버 다시 시작 중","updates.phase.done":"업데이트 완료","updates.phase.handed-off":"서비스 갱신으로 넘김","updates.phase.restart-required":"설치 완료 — CUELO를 직접 다시 시작하세요","updates.phase.failed":"업데이트 실패","updates.waitingForRestart":"서버가 다시 시작되기를 기다리고 있습니다. 새 버전이 응답하면 화면을 새로 고칩니다.","updates.handedOff":"WSL 서비스 갱신이 자체 대기 화면에서 진행됩니다. 끝나면 이 화면이 새로 고쳐집니다.","updates.logPath":"로그: {path}","updates.applyStartFailed":"업데이트를 시작하지 못했습니다: {reason}","sidebar.hide":"사이드바 숨기기","sidebar.show":"사이드바 표시","theme.light":"라이트 모드 (클릭하면 다크)","theme.dark":"다크 모드 (클릭하면 시스템)","theme.auto":"시스템 테마 (클릭하면 라이트)","theme.graphite":"흑연 테마 (배경화면)","theme.graphiteHint":"흑연색 화면에 지금 캐릭터 모드의 배경화면을 깝니다. 다크 모드에서만 적용되고 이 브라우저에만 저장됩니다.","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":"확인할 결과가 없습니다.","navigator.acknowledgeResults":"모두 확인","navigator.acknowledgeResultsHint":"지금 확인할 결과로 보이는 대화를 모두 본 것으로 표시합니다. 답을 기다리는 대화는 남습니다.","sidebar.waitingForAnswer":"답 기다림","sidebar.waitingForAnswerHint":"질문이나 승인 요청에 답할 때까지 멈춰 있습니다","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}개 접기","todo.ready":"지금 가능","todo.waiting":"선행 대기: {tasks}","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.agentFormHint":"양식을 채워 제출하세요.","chat.askFormAutoSubmitHint":"{seconds}초 동안 응답이 없으면 지금 입력된 값을 그대로 제출합니다. 입력하면 대기 시간이 다시 시작됩니다.","chat.formOther":"기타","chat.formOtherPlaceholder":"직접 입력","chat.formRequired":"필수","chat.formInvalid":"표시된 항목을 확인한 뒤 제출하세요.","chat.formImageUnavailable":"이미지를 불러오지 못했습니다","chat.formError.required":"필수 항목입니다","chat.formError.selectAtLeastOne":"하나 이상 선택하세요","chat.formError.enterNumber":"숫자를 입력하세요","chat.formError.min":"{value} 이상이어야 합니다","chat.formError.max":"{value} 이하여야 합니다","chat.formError.minLength":"{value}자 이상 입력하세요","chat.formError.maxLength":"{value}자 이하로 입력하세요","chat.formError.email":"이메일 주소를 입력하세요","chat.formError.url":"전체 URL을 입력하세요","chat.formError.pattern":"형식이 맞지 않습니다 ({pattern})","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.recoveredError":"이 시도는 실패해 자동으로 다시 보냈습니다.","chat.recoveredErrorDetail":"오류 보기","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.transcribeFallbackTitle":"{name} 기본 받아쓰기에 실패했습니다. ChatGPT/Codex로 이어서 받아쓸까요?","chat.transcribeFallbackProgress":"{total}조각 중 {done}조각은 이미 받아써서 그대로 둡니다. 실패한 조각과 남은 조각만 보냅니다.","chat.transcribeFallbackUsageNotice":"ChatGPT/Codex는 기본 받아쓰기와 다른 제공자이며, 로그인한 계정의 사용량에 포함됩니다. ChatGPT/Codex로 받아쓰기를 누르기 전에는 아무것도 보내지 않습니다.","chat.transcribeFallbackStart":"ChatGPT/Codex로 받아쓰기","chat.transcribeFallbackExpired":"이 선택은 만료됐거나 이미 사용됐습니다. 아무것도 보내지 않았습니다. 다시 시도하면 기본 받아쓰기부터 시작합니다.","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 프로필에 등록된 캐릭터가 해당 자리의 얼굴\xb7이름\xb7말투\xb7스티커\xb7음성을 대신합니다. 등록되지 않은 자리는 그대로입니다.","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\xb7도구 역할 자리는 지정하기 전에도 목록에 표시됩니다. 쓸 자리만 직접 모델을 고르세요. 저장해도 로그인하거나 모델을 시험 호출하지 않습니다.","roles.harnessUnset":"미설정","roles.harness.implSol":"Maker: 한정된 설계와 깊은 원인 추적, 재작업","roles.harness.implSonnet":"Maker: 일반 구현과 보통 UI","roles.harness.implOpus":"Maker: 어려운 UI/UX","roles.harness.implDeepSeek":"Maker: 명세가 확정된 반복 작업, Main이 직접 고를 때만 사용","roles.harness.makerHardUiOpus":"Maker: 어려운 UI/UX (HARD)","roles.harness.makerHardCodeOpus":"Maker: HARD 코드, Main이 직접 고를 때만 사용","roles.harness.makerHardCodeSonnet":"Maker: 방향이 정해진 구현과 보통 UI (HARD)","roles.harness.crossReviewOpenAI":"교차검수 \xb7 OpenAI 필수 검토 (openai / openai-codex)","roles.harness.crossReviewAnthropic":"교차검수 \xb7 Anthropic 필수 검토 (anthropic)","roles.harness.crossReviewAdvisory":"교차검수 \xb7 보조 검토, 기다리지 않음 (제공자 무관)","roles.harness.preflightAnthropic":"계획 자문: 공동 사전 점검","roles.harness.skim":"도구 \xb7 다중 파일 소스 읽기 (skim)","roles.harness.draft":"도구 \xb7 문서 초안 작성 (draft)","roles.harness.ocr":"도구 \xb7 이미지 글자 전사 (ocr)","roles.harness.interpreter":"도구 \xb7 한영 통역 (interpreter)","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.outputSpeed":"{rate} tok/s","chat.outputSpeedTitle":"마지막 답변의 출력 속도(초당 출력 토큰, 요청 시작부터 생성 끝까지 기준)","chat.outputSpeedLive":"~{rate} tok/s","chat.outputSpeedLiveTitle":"지금 답변의 출력 속도 추정(받은 글자를 토큰으로 어림, 요청 시작부터 지금까지 기준). 답변이 끝나면 실제 토큰 수로 바뀝니다","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.livePaceLabel":"말 빠르기","chat.livePaceHelp":"천천히를 고르면 또박또박 느리게 말합니다.","chat.livePaceNormal":"보통","chat.livePaceSlow":"천천히","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":"프로젝트 신뢰","computerTakeover.allow":"가로채기 허용","computerTakeover.active":"가로채기 허용 중","computerTakeover.allowHint":"이 세션에서만 화면 가로채기를 허용합니다. 끄거나 세션이 닫히면 다시 거부로 돌아갑니다.","computerTakeover.activeHint":"이 세션은 화면 가로채기가 허용된 상태입니다. 누르면 끕니다.","computerTakeover.shared":"서버와 같은 폴더에서 연 세션은 따로 허용할 수 없습니다.","computerTakeover.failed":"가로채기 설정을 바꾸지 못했습니다: {error}","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.deviceLogin":"기기 코드로 로그인","i18n.deviceLoginGuide":"아래 주소를 열어 로그인한 뒤 이 코드를 입력하세요. 이 서버의 localhost로 돌아올 필요가 없어서 원격 서버에서도 됩니다.","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.providerAnthropicSubscription":"Anthropic 구독","i18n.providerAnthropicApi":"Anthropic API","i18n.noOutput":"(출력 없음)","i18n.noSummary":"(요약 없음)","i18n.conversationCompacted":"대화가 압축됨","i18n.compactionDescription":"이 지점 이전의 대화 기록이 다음 요약으로 압축되었습니다:","i18n.fileContext":"파일 컨텍스트: {details}","i18n.readFiles":"읽은 파일","i18n.modifiedFiles":"수정된 파일","i18n.hiddenExtensionMessage":"숨겨진 확장 메시지","i18n.noMessage":"(메시지 없음)","i18n.showOriginalReply":"영어 원문 보기","i18n.hideOriginalReply":"영어 원문 접기","i18n.showInputTranslation":"영어 통역 보기","i18n.hideInputTranslation":"영어 통역 접기","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}줄 삭제","toolRun.askTimedOut":"시간 안에 답이 없어 입력된 값이 제출되었습니다.","panel.expand":"패널 넓게 보기","panel.restore":"원래 크기로","panel.more":"더 보기","panel.liveSync":"실시간 반영","panel.subagentsCount":"기록 {count}건","panel.refresh":"기록 새로고침","panel.close":"패널 닫기","pluginLab.counts":"플러그인 {count}개","pluginLab.refresh":"목록 새로고침","pluginLab.create":"새 플러그인 만들기","pluginLab.createHint":"요청을 입력창에 넣습니다. 다듬어서 보내세요.","pluginLab.starter":"plugin-lab 스킬로 내 프로필에 쓸 플러그인을 하나 만들어 줘.\\n- 하려는 일: \\n- 필요한 도구: \\n- 패널에 보여 줄 내용(없으면 비워 둠): \\n저장소 정식 폴더에 바로 만들고 이번 턴에 리뷰, 버전, CI, 배포까지 끝내 줘.","pluginLab.loading":"플러그인 목록을 불러오는 중…","pluginLab.loadFailed":"플러그인 목록을 불러오지 못했습니다: {error}","pluginLab.retry":"다시 불러오기","pluginLab.empty":"아직 플러그인이 없습니다. 「새 플러그인 만들기」로 요청을 입력창에 넣어 보세요.","pluginLab.listLabel":"플러그인 목록","pluginLab.on":"켜짐","pluginLab.off":"꺼짐","pluginLab.toggleLabel":"{name} 사용","pluginLab.toggleFailed":"상태를 바꾸지 못했습니다: {error}","pluginLab.tools":"도구","pluginLab.enhancements":"보강 이력","pluginLab.enhancementDateHint":"기록 시각","pluginLab.showAllEnhancements":"전체 {count}개 보기","pluginLab.showFewerEnhancements":"접기","pluginLab.problem":"문제","pluginLab.openPanel":"패널 열기","pluginLab.openPanelLabel":"{name} 패널 열기","pluginLab.back":"플러그인 목록으로","pluginLab.panelSubtitle":"격리 실행 \xb7 lab:{id}","pluginLab.frameTitle":"{name} 패널","pluginLab.lines":"에이전트 데이터 {count}줄","pluginLab.noLines":"이 세션에서 받은 에이전트 데이터 없음","pluginLab.draftInserted":"패널이 만든 초안을 입력창에 넣었습니다. 확인하고 보내세요.","pluginLab.applyHint":"도구 변경은 새 세션이나 /reload 뒤에 적용됩니다.","pluginLab.noComposer":"대화를 열어야 입력창에 넣을 수 있습니다.","pluginLab.draftNotRecorded":"초안은 입력창에 넣었지만 사용 기록은 남기지 못했습니다.","pluginLab.saving":"바꾸는 중…","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":"상세 없음","credits.heading":"API 크레딧","credits.estimateNote":"결제 화면 잔액은 표시된 시각에 직접 확인해 적어 둔 값이라 이후 사용량은 빠져 있습니다. 추정 사용량과 추정 잔액은 이 PC의 토큰 수에 공개 단가를 곱한 어림값이며 청구서 금액이 아닙니다.","credits.loading":"API 크레딧 불러오는 중…","credits.loadFailed":"API 크레딧을 불러오지 못했습니다: {reason}","credits.wallet.hive":"Hive","credits.scope.hive":"이 PC 기록","credits.since":"{date}부터","credits.sinceDefault":"최근 30일","credits.total":"총액","credits.spent":"추정 사용","credits.remaining":"추정 잔액","credits.meterLabel":"{wallet} 크레딧 사용","credits.usedPct":"사용 {pct}%","credits.enterPrompt":"총액과 시작일을 넣으면 추정 잔액을 계산합니다.","credits.enter":"크레딧 입력","credits.edit":"수정","credits.formLabel":"{wallet} 크레딧","credits.totalUsd":"총액(USD)","credits.startDate":"시작일","credits.save":"저장","credits.saving":"저장 중…","credits.cancel":"취소","credits.clear":"지우기","credits.saveFailed":"저장하지 못했습니다: {reason}","credits.invalid.total":"총액을 숫자로 넣어 주세요.","credits.error.invalid_total":"총액은 0보다 큰 숫자여야 합니다","credits.error.invalid_start_date":"시작일을 확인하세요","credits.error.start_date_in_future":"시작일이 미래입니다","credits.error.session_scan_failed":"세션 기록을 읽지 못했습니다","credits.error.session_scan_partial":"일부 세션 기록을 읽지 못해 추정 사용이 실제보다 적을 수 있습니다","credits.error.internal":"예상하지 못한 오류가 났습니다","credits.error.settings_unreadable":"크레딧 설정 파일을 읽지 못해 덮어쓰지 않았습니다","credits.walletError":"사용량을 읽지 못했습니다: {reason}","credits.settingsError":"크레딧 설정 파일을 읽지 못했습니다. 다시 입력해 주세요.","credits.tokens":"입력 {input} \xb7 출력 {output}","credits.cacheTokens":"캐시 {cache}","credits.requests":"{count}회","credits.priceUnknown":"단가 미상","credits.purpose.session":"대화\xb7에이전트","credits.purpose.memory":"기억","credits.purpose.korean-reply-translation":"답변 번역","credits.wallet.anthropic":"Anthropic API","credits.billingLink":"실제 잔액 보기","credits.billingLinkLabel":"{wallet} 결제 화면에서 실제 잔액 보기(새 탭)","credits.scope.anthropic":"이 PC 기록","credits.anthropic.note":"토큰이 기록된 API 키 요청만 집계하며 구독(OAuth) 요청과 토큰 없는 실패는 제외합니다. 금액은 공개 단가 기준 추정치이며 청구서나 잔액이 아닙니다.","credits.anthropic.noCoverage":"이 기간에 인증 방식이 기록된 요청이 없어 API 키 사용량을 알 수 없습니다.","credits.anthropic.coverageSince":"인증 방식 최초 기록: {date} (이후 모든 요청의 기록을 보장하지는 않습니다)","credits.anthropic.none":"이 기간에 기록된 API 키 요청이 없습니다.","credits.anthropic.oauthExcluded":"구독(OAuth) 제외","credits.anthropic.unattributedExcluded":"인증 미기록 제외","credits.category.input":"입력","credits.category.output":"출력","credits.category.cacheRead":"캐시 읽기","credits.category.cacheWrite":"캐시 쓰기","credits.balance.label":"결제 화면 잔액","credits.balance.source":"직접 기록","credits.balance.observed":"{time} 확인","credits.balance.age.now":"방금","credits.balance.age.minutes":"{count}분 전","credits.balance.age.hours":"{count}시간 전","credits.balance.age.days":"{count}일 전","credits.balance.none":"기록된 잔액 없음","credits.balance.record":"잔액 기록","credits.balance.edit":"잔액 변경","credits.balance.formLabel":"{wallet} 결제 화면 잔액","credits.balance.amount":"잔액(USD)","credits.balance.observedAt":"확인 시각","credits.balance.observedAtHint":"제공자 결제 화면에서 잔액을 확인한 시각입니다.","credits.invalid.amount":"잔액을 숫자로 넣어 주세요.","credits.invalid.observedAt":"확인 시각을 넣어 주세요.","credits.error.invalid_balance":"잔액은 0 이상의 숫자여야 합니다","credits.error.invalid_observed_at":"확인 시각을 확인하세요","credits.error.observed_at_in_future":"확인 시각이 지금보다 늦습니다","credits.error.routes_unreadable":"설정 파일을 읽지 못해 사용 중인 API를 확인할 수 없습니다","credits.wallet.exa":"Exa","credits.wallet.typesafe":"TypeSafe Jev","credits.route.hive":"모델 역할(기억\xb7skim 등)에 배정됨","credits.route.exa":"기본 웹 검색 경로","credits.route.typesafe":"기본 빠른 판정(Jev) 경로","credits.route.anthropic":"구독 주간 한도를 다 쓰면 쓰는 API 키 대체 경로","credits.evidence.lastPaidUse":"이 PC 마지막 유료 사용: {time}","credits.evidence.unverified":"일부 세션 기록을 읽지 못해 최근 유료 사용을 확인하지 못했습니다."}'),s=["en","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:{"savedPrompts.title":"Saved prompts","savedPrompts.loading":"Loading...","savedPrompts.empty":"No saved prompts","savedPrompts.save":"Save current input as prompt","savedPrompts.saved":"Saved","savedPrompts.delete":"Delete","savedPrompts.confirmDelete":"Delete?","savedPrompts.cancel":"Cancel","savedPrompts.hint":"Type text then // to save. Variables: {{project_name}} {{session_name}} {{cwd}} {{date}}","savedPrompts.error":"Saved prompt request failed: {error}","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? Stop the server first, run this update command, then start it again. If you use a custom --home path, pass the same --home option to setup.","updates.copyCommand":"Copy command","updates.commandCopied":"Command copied","updates.copyFailed":"Unable to copy the command","updates.apply":"Update now","updates.applyBusy":"Updating…","updates.applyConfirm":"Update CUELO to {version} and restart?\n\nThe server stops for a moment while it updates, and this panel shows the progress. The page reloads by itself when the new version answers.","updates.applyConfirmBusy":"Update CUELO to {version} and restart?\n\n{count} running session(s) will be interrupted and the server stops for a moment. This panel shows the progress, and the page reloads by itself when the new version answers.","updates.unsupported":"This installation cannot be updated from the app. Use the command below.","updates.unsupportedReason":"Detected: {reason}","updates.phase.starting":"Preparing the update","updates.phase.fetching":"Fetching the new version","updates.phase.installing":"Installing the package","updates.phase.building":"Building","updates.phase.restarting":"Restarting the server","updates.phase.done":"Update complete","updates.phase.handed-off":"Handed off to the service update","updates.phase.restart-required":"Installed. Restart CUELO yourself.","updates.phase.failed":"Update failed","updates.waitingForRestart":"Waiting for the server to come back. The page reloads when the new version answers.","updates.handedOff":"The WSL service update runs in its own wait screen. This page reloads when it finishes.","updates.logPath":"Log: {path}","updates.applyStartFailed":"Could not start the update: {reason}","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)","theme.graphite":"Graphite theme (wallpaper)","theme.graphiteHint":"Graphite surfaces with a wallpaper for the current character mode. Dark mode only, saved in this browser.","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, and conversations waiting for your answer","navigator.resultsToCheckEmpty":"Nothing to review.","navigator.acknowledgeResults":"Mark all reviewed","navigator.acknowledgeResultsHint":"Marks every conversation now listed to review as seen. Conversations waiting for your answer stay.","sidebar.waitingForAnswer":"Needs answer","sidebar.waitingForAnswerHint":"Paused until you answer its question or approval request","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","todo.ready":"Ready","todo.waiting":"Waiting for: {tasks}","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.agentFormHint":"Fill in the form and submit it.","chat.askFormAutoSubmitHint":"If you do not respond in {seconds}s, the values currently in the form are submitted. Editing restarts the wait.","chat.formOther":"Other","chat.formOtherPlaceholder":"Type your own answer","chat.formRequired":"Required","chat.formInvalid":"Check the marked fields before you submit.","chat.formImageUnavailable":"Image could not be loaded","chat.formError.required":"Required","chat.formError.selectAtLeastOne":"Select at least one","chat.formError.enterNumber":"Enter a number","chat.formError.min":"Must be at least {value}","chat.formError.max":"Must be at most {value}","chat.formError.minLength":"Needs at least {value} characters","chat.formError.maxLength":"At most {value} characters","chat.formError.email":"Enter an email address","chat.formError.url":"Enter a full URL","chat.formError.pattern":"Must match {pattern}","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.recoveredError":"This attempt failed and was retried automatically.","chat.recoveredErrorDetail":"Show error","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.transcribeFallbackTitle":"Primary transcription failed for {name}. Continue with ChatGPT/Codex?","chat.transcribeFallbackProgress":"{done} of {total} parts already have a transcript, which stays; continuing sends only the failed part and the rest.","chat.transcribeFallbackUsageNotice":"ChatGPT/Codex is a separate provider; its transcription counts toward the signed-in account's usage. CUELO sends nothing until you continue.","chat.transcribeFallbackStart":"Continue with ChatGPT/Codex","chat.transcribeFallbackExpired":"This fallback choice expired or you already used it. CUELO sent nothing; try again to start over.","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 characters registered in this PC's profile replace the face, name, voice, stickers and sounds of their seats. Seats without an entry 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 and tool 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.implSol":"Maker: bounded design, deep diagnosis and rework","roles.harness.implSonnet":"Maker: general implementation and routine UI","roles.harness.implOpus":"Maker: difficult UI/UX","roles.harness.implDeepSeek":"Maker: fully specified repetitive work, explicit selection","roles.harness.makerHardUiOpus":"Maker: difficult UI/UX (HARD)","roles.harness.makerHardCodeOpus":"Maker: HARD code, explicit selection","roles.harness.makerHardCodeSonnet":"Maker: settled implementation and routine UI (HARD)","roles.harness.crossReviewOpenAI":"Cross-review \xb7 required OpenAI reviewer (openai / openai-codex)","roles.harness.crossReviewAnthropic":"Cross-review \xb7 required Anthropic reviewer (anthropic)","roles.harness.crossReviewAdvisory":"Cross-review \xb7 advisory reviewer, non-blocking (any provider)","roles.harness.preflightAnthropic":"Plan advice: joint preflight","roles.harness.skim":"Tool \xb7 multi-file source reading (skim)","roles.harness.draft":"Tool \xb7 document drafting (draft)","roles.harness.ocr":"Tool \xb7 image text transcription (ocr)","roles.harness.interpreter":"Tool \xb7 Korean–English interpreter (interpreter)","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.outputSpeed":"{rate} tok/s","chat.outputSpeedTitle":"Output speed of the last answer (output tokens per second, from request start to the end of generation)","chat.outputSpeedLive":"~{rate} tok/s","chat.outputSpeedLiveTitle":"Estimated output speed of the answer in progress (received text approximated as tokens, from request start until now). Switches to the real token count when the answer ends","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 and how fast it speaks. The choice applies from the next call.","chat.liveVoiceSpeakerGroup":"Voice","chat.liveVoiceCodexLabel":"Codex voice","chat.liveVoiceCodexHelp":"Speaks in live calls and interpreter calls.","chat.livePaceLabel":"Speaking pace","chat.livePaceHelp":"Slow makes the voice speak slowly and clearly.","chat.livePaceNormal":"Normal","chat.livePaceSlow":"Slow","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","computerTakeover.allow":"Allow takeover","computerTakeover.active":"Takeover allowed","computerTakeover.allowHint":"Allow screen takeover for this session only. It goes back to refused when you turn it off or the session closes.","computerTakeover.activeHint":"Screen takeover is allowed in this session. Click to turn it off.","computerTakeover.shared":"A session opened in the server's own folder cannot be allowed separately.","computerTakeover.failed":"Could not change takeover: {error}","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.deviceLogin":"Log in with device code","i18n.deviceLoginGuide":"Open the page below, sign in, and enter this code. Nothing has to reach this server's localhost, so it also works on a remote server.","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.providerAnthropicSubscription":"Anthropic subscription","i18n.providerAnthropicApi":"Anthropic API","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.showInputTranslation":"Show English translation","i18n.hideInputTranslation":"Hide English translation","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","toolRun.askTimedOut":"No answer before the timeout. The form's current values were submitted.","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","pluginLab.counts":"{count} plugins","pluginLab.refresh":"Refresh list","pluginLab.create":"New plugin","pluginLab.createHint":"Puts a request into the message box. Edit it, then send.","pluginLab.starter":"Use the plugin-lab skill to build a plugin for my profile.\n- What it should do: \n- Tools it needs: \n- What its panel shows (leave empty for none): \nWrite it straight into the repository's formal plugin folder and ship it through review, version, CI and deploy in this turn.","pluginLab.loading":"Loading plugins…","pluginLab.loadFailed":"Could not load plugins: {error}","pluginLab.retry":"Load again","pluginLab.empty":"No plugins yet. Use “New plugin” to put a request into the message box.","pluginLab.listLabel":"Plugins","pluginLab.on":"On","pluginLab.off":"Off","pluginLab.toggleLabel":"Use {name}","pluginLab.toggleFailed":"Could not change the state: {error}","pluginLab.tools":"Tools","pluginLab.enhancements":"Enhancements","pluginLab.enhancementDateHint":"Recorded date","pluginLab.showAllEnhancements":"Show all {count}","pluginLab.showFewerEnhancements":"Show fewer","pluginLab.problem":"Problem","pluginLab.openPanel":"Open panel","pluginLab.openPanelLabel":"Open the {name} panel","pluginLab.back":"Back to plugins","pluginLab.panelSubtitle":"Sandboxed \xb7 lab:{id}","pluginLab.frameTitle":"{name} panel","pluginLab.lines":"{count} lines of agent data","pluginLab.noLines":"No agent data in this session","pluginLab.draftInserted":"The panel's draft is in the message box. Check it, then send.","pluginLab.applyHint":"Tool changes apply in a new session or after /reload.","pluginLab.noComposer":"Open a conversation to use the message box.","pluginLab.draftNotRecorded":"The draft is in the message box, but its use was not recorded.","pluginLab.saving":"Changing…","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","credits.heading":"API credits","credits.estimateNote":"The billing-page balance is what you read on the provider's billing page at the shown time. Later usage is not included. Estimated spend and balance multiply this PC's token counts by published prices and are not a bill.","credits.loading":"Loading API credits…","credits.loadFailed":"Could not load API credits: {reason}","credits.wallet.hive":"Hive","credits.scope.hive":"This PC's records","credits.since":"since {date}","credits.sinceDefault":"last 30 days","credits.total":"Total","credits.spent":"Est. spent","credits.remaining":"Est. left","credits.meterLabel":"{wallet} credit used","credits.usedPct":"{pct}% used","credits.enterPrompt":"Enter the total and start date to see an estimated balance.","credits.enter":"Enter credit","credits.edit":"Edit","credits.formLabel":"{wallet} credit","credits.totalUsd":"Total (USD)","credits.startDate":"Start date","credits.save":"Save","credits.saving":"Saving…","credits.cancel":"Cancel","credits.clear":"Remove","credits.saveFailed":"Not saved: {reason}","credits.invalid.total":"Enter the total as a number.","credits.error.invalid_total":"the total must be a number above 0","credits.error.invalid_start_date":"check the start date","credits.error.start_date_in_future":"the start date is in the future","credits.error.session_scan_failed":"session records could not be read","credits.error.session_scan_partial":"some session records could not be read, so the spent amount is a minimum","credits.error.internal":"an unexpected error occurred","credits.error.settings_unreadable":"the credit settings file could not be read, so it was not overwritten","credits.walletError":"Usage not read: {reason}","credits.settingsError":"The credit settings file could not be read. Enter the credits again.","credits.tokens":"in {input} \xb7 out {output}","credits.cacheTokens":"cache {cache}","credits.requests":"{count} calls","credits.priceUnknown":"price unknown","credits.purpose.session":"Chat \xb7 agents","credits.purpose.memory":"Memory","credits.purpose.korean-reply-translation":"Reply translation","credits.wallet.anthropic":"Anthropic API","credits.billingLink":"Actual balance","credits.billingLinkLabel":"See the actual {wallet} balance on its billing page (opens in a new tab)","credits.scope.anthropic":"This PC's records","credits.anthropic.note":"Counts only API-key responses with recorded tokens; excludes subscription (OAuth) requests and failed attempts without tokens. Amounts are estimates at published prices, not a bill or balance.","credits.anthropic.noCoverage":"No requests in this window have a recorded credential kind, so API-key usage is unknown.","credits.anthropic.coverageSince":"First recorded credential in window: {date} (this PC may not have recorded every later request)","credits.anthropic.none":"No recorded API-key requests in this window.","credits.anthropic.oauthExcluded":"Subscription (OAuth) excluded","credits.anthropic.unattributedExcluded":"Unrecorded credential excluded","credits.category.input":"Input","credits.category.output":"Output","credits.category.cacheRead":"Cache read","credits.category.cacheWrite":"Cache write","credits.balance.label":"Billing-page balance","credits.balance.source":"Manual record","credits.balance.observed":"Checked {time}","credits.balance.age.now":"Just now","credits.balance.age.minutes":"{count}m ago","credits.balance.age.hours":"{count}h ago","credits.balance.age.days":"{count}d ago","credits.balance.none":"No recorded balance","credits.balance.record":"Record balance","credits.balance.edit":"Edit balance","credits.balance.formLabel":"{wallet} billing-page balance","credits.balance.amount":"Balance (USD)","credits.balance.observedAt":"Checked at","credits.balance.observedAtHint":"When you saw the balance on the billing page.","credits.invalid.amount":"Enter a valid balance number.","credits.invalid.observedAt":"Enter a valid time.","credits.error.invalid_balance":"the balance must be 0 or more","credits.error.invalid_observed_at":"check the time","credits.error.observed_at_in_future":"the time is later than now","credits.error.routes_unreadable":"the settings file could not be read, so the APIs in use are unknown","credits.wallet.exa":"Exa","credits.wallet.typesafe":"TypeSafe Jev","credits.route.hive":"Assigned to model roles (memory, skim, etc.)","credits.route.exa":"Default web search path","credits.route.typesafe":"Default quick judgement (Jev) path","credits.route.anthropic":"API key fallback when the subscription's weekly allowance runs out","credits.evidence.lastPaidUse":"Last paid use on this PC: {time}","credits.evidence.unverified":"Some session logs could not be read, so recent paid use is unconfirmed.","memoryTrace.refresh":"Refresh","memoryTrace.noSession":"Select a session to see how it looked up memories.","memoryTrace.loading":"Reading the session log…","memoryTrace.error":"Could not load the memory trace. {error}","memoryTrace.retry":"Load again","memoryTrace.empty":"This session has no memory or doc-map records.","memoryTrace.requests":"{count} requests with records","memoryTrace.requestsLabel":"Requests","memoryTrace.requestHeading":"Request #{index}","memoryTrace.noPreview":"(no text)","memoryTrace.flowLabel":"Request flow","memoryTrace.stageRecall":"Recalled","memoryTrace.stageJev":"JEV check","memoryTrace.stageDocmap":"Map candidates","memoryTrace.stageDocs":"Docs opened","memoryTrace.stageLessons":"Pre-edit lessons","memoryTrace.stageSaved":"Saved","memoryTrace.stageEmpty":"This step did not happen in this request.","memoryTrace.openedSummary":"{opened} opened \xb7 {skipped} not opened","memoryTrace.opened":"Opened","memoryTrace.candidateOnly":"Candidate only","memoryTrace.fromMap":"Map candidate","memoryTrace.lines":"Lines {lines}","memoryTrace.autoRecall":"Recalled before the request","memoryTrace.explicitRecall":"Looked up during the work","memoryTrace.query":"Query","memoryTrace.noResults":"No memories came back.","memoryTrace.noMemoryText":"This log keeps no text for this memory.","memoryTrace.jevUnknown":"{count} undecided","memoryTrace.jevUnrelated":"{count} unrelated","memoryTrace.lessonFor":"Memories shown before editing","memoryTrace.savedAuto":"Auto-saved","memoryTrace.graphLabel":"Link graph","memoryTrace.graphScope":"Graph scope","memoryTrace.scopeRequest":"This request","memoryTrace.scopeSession":"Whole session","memoryTrace.legendRequest":"Request","memoryTrace.legendMemory":"Memory","memoryTrace.legendDoc":"Map doc","memoryTrace.legendFile":"Edited file","memoryTrace.graphEmpty":"Nothing is linked in this scope.","memoryTrace.nodeLabel":"{kind}: {label}, {count} links","memoryTrace.edgeRecalled":"Recalled","memoryTrace.edgeLesson":"Pre-edit lesson","memoryTrace.verdictLegend":"JEV verdict","memoryTrace.verdictApply":"Applies","memoryTrace.verdictExcepted":"Condition not met or exception","memoryTrace.verdictConflict":"Conflicts with the request","memoryTrace.verdictUnconfirmed":"Condition unconfirmed","memoryTrace.verdictUnlisted":"Unrelated or undecided","memoryTrace.graphHint":"Point at or focus a node to read its full text here.","memoryTrace.legendDocEdited":"Opened and edited","memoryTrace.noticeHarness":"Harness","memoryTrace.noticeResume":"Auto-resume"}}),l({id:"ko",label:"한국어",messages:i});var d=r(2730);let u="pi-locale",p=(0,a.createContext)(null);function h({children:e}){let[t,r]=(0,a.useState)("en"),[i,l]=(0,a.useState)(!1),m=(0,a.useMemo)(()=>c().map(e=>o.get(e)).filter(e=>!!e),[]),f=(0,a.useMemo)(()=>Object.fromEntries(c().flatMap(e=>{let t=o.get(e);return t?[[e,t.messages]]:[]})),[]);(0,a.useEffect)(()=>{let e=function(){var e;let t=null;try{t=window.localStorage.getItem(u)}catch{}let r=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}return"ko"}(r)}();r(e),document.documentElement.lang=e,l(!0)},[]);let g=(0,a.useCallback)(e=>{if(o.get(e)){r(e),document.documentElement.lang=e;try{window.localStorage.setItem(u,e)}catch{}}},[]),x=(0,a.useCallback)((e,r)=>(0,d.u0)(t,e,f,r),[t,f]),v=(0,a.useMemo)(()=>({locale:i?t:"en",setLocale:g,t:x,supportedLocales:m}),[i,t,g,x,m]);return(0,n.jsx)(p.Provider,{value:v,children:e})}function m(){let e=(0,a.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,6805,8774,7330,2545,1637,8441,3794,7358],()=>e(e.s=80455)),_N_E=e.O()}]);
|