cuelo 0.10.243 → 0.10.244
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 +52 -52
- 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 +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- 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 +1 -1
- 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/api/upkeep/morning/route.js +2 -2
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +4 -4
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/page.js +3 -3
- 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 +2 -2
- package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
- package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
- 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 +52 -52
- 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-2908269df5be376f.js → layout-b381c051dda8c032.js} +1 -1
- package/.next/static/chunks/app/{page-168ad3b3cab09086.js → page-a80fa1bc8b845b28.js} +3 -3
- package/.next/trace +112 -112
- package/.next/trace-build +1 -1
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
- package/package.json +1 -1
- /package/.next/static/{3fIFbOJr8oF3E_09qjSEx → 9TdKLHX_BY0-ukeQUIt7F}/_buildManifest.js +0 -0
- /package/.next/static/{3fIFbOJr8oF3E_09qjSEx → 9TdKLHX_BY0-ukeQUIt7F}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
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,n)=>{"use strict";function r(e,t,n,i={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,i)}n.d(t,{u0:()=>r})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21040:e=>{e.exports={view:"RoutineView_view__4busO",topbar:"RoutineView_topbar__YPacL",back:"RoutineView_back__ac5Vn",body:"RoutineView_body__01N2Q",crumb:"RoutineView_crumb__K1_0X",link:"RoutineView_link__whmc9",head:"RoutineView_head__WBrda",headActions:"RoutineView_headActions__KqC_W",sub:"RoutineView_sub__mh018",facts:"RoutineView_facts__Yyns3",strong:"RoutineView_strong__x6Fhg",subNote:"RoutineView_subNote__tAUYO",mono:"RoutineView_mono__ms2qU",button:"RoutineView_button__sbfYZ",tabs:"RoutineView_tabs__iPnSQ",field:"RoutineView_field__B4jvA",badge:"RoutineView_badge__uMNRL",table:"RoutineView_table__3ihqX",title:"RoutineView_title__WPF5j",no:"RoutineView_no__Ck2vM",emptyCell:"RoutineView_emptyCell__o5V_C",empty:"RoutineView_empty__FoRja",foot:"RoutineView_foot__EmDj9",sync:"RoutineView_sync__Fek1M",notice:"RoutineView_notice__VvzFH",postHead:"RoutineView_postHead__ooMEu",postMeta:"RoutineView_postMeta___lo7j",postBody:"RoutineView_postBody__nwcmb",form:"RoutineView_form__SZrKX",row:"RoutineView_row__YLKM0",rowLabel:"RoutineView_rowLabel__wAaNU",narrow:"RoutineView_narrow__EazoW",hint:"RoutineView_hint__R9fMv",days:"RoutineView_days__lm_q_",check:"RoutineView_check__gT_Aa",formActions:"RoutineView_formActions__A9Djj",danger:"RoutineView_danger__Xi84r",error:"RoutineView_error__JNoxw",panel:"RoutineView_panel__jkMFt",panelList:"RoutineView_panelList__JrArr",count:"RoutineView_count__GICfE",wide:"RoutineView_wide__bJkXf",rowSchedule:"RoutineView_rowSchedule__Co8RM",visuallyHidden:"RoutineView_visuallyHidden__M_RPw",inline:"RoutineView_inline__ZaYAe",chips:"RoutineView_chips__hnVXc",chipRemove:"RoutineView_chipRemove__wNru7",host:"RoutineView_host__SV_7k"}},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"}},34241:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>y7});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),o=n(81886),l=n(68890),c=n(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 n,r=f(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=f(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,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[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let n=null;for(let[r,i]of Object.entries(t.opened))(e.opened[r]??-1/0)>=i||((n??={...e.opened})[r]=i);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function R(e,t,n){let r=Math.max(n,M(t)??0);return(e.opened[t.id]??-1/0)>=r?e:{since:e.since,opened:{...e.opened,[t.id]:r}}}let E=new Set;function $(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function 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 P(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=L(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function A(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(L(e.key),e.order);let r=[...e],i=new Set(e.map(L));for(let e of t){let t=L(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(L(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let _=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function F(e){let t=e.match(_);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var z=n(84183);let W=`(max-width: ${p.navigator-1}px)`;function O(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=O("(max-width: 640px)"),H=O(W);function U(){return!1}function B(){return(0,i.useSyncExternalStore)(D.subscribe,D.getSnapshot,U)}var q=n(47650);async function V(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function K(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function G(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function J({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,z.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await V(e),n=t.path??e??"/";d(n),p(t.parentPath??null),m(!0===t.upToDrives),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),C()},[C]);let N=f.trim()!==c,T=!!c&&!N&&!n,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,q.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!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,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value: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,r.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,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(G,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(K,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!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(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Z=n(21443),Y=n.n(Z);async function X(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function Q({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,z.s)(),o=(0,i.useRef)(null),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,T]=(0,i.useState)(null),[I,M]=(0,i.useState)(!1),[R,E]=(0,i.useState)(50),$=p?.device?.state==="pending",L=n||S,P=(0,i.useCallback)(async()=>{w(!0),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 A(){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 _(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,i.useEffect)(()=>{c(!0),P()},[P]),(0,i.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,i.useEffect)(()=>{let e;if(!$||d)return;let t=!1,n=async()=>{try{let e=await X("/api/github/projects");if(t)return;if(h(e),e.connected)return void await P();if(e.device?.state!=="pending")return}catch(e){t||T(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[$,d,P]),!l)return null;if(d)return(0,r.jsx)(J,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let F=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),W=N??a??p?.device?.error;return(0,q.createPortal)((0,r.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),L||e()},children:(0,r.jsxs)("form",{onSubmit:_,className:Y().form,children:[(0,r.jsxs)("header",{className:Y().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:Y().sources,children:[(0,r.jsx)("span",{className:Y().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:L,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:Y().body,children:[(0,r.jsxs)("section",{className:Y().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:y||L,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:y||k||$||L,children:k||$?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),$&&(0,r.jsxs)("div",{className:Y().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:Y().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.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,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Y().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:Y().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:L}),y?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:Y().list,children:F.slice(0,R).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":v===e.fullName,disabled:L,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:Y().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:Y().repoDescription,children:e.description})]})},e.fullName))}),!F.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),F.length>R&&(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:Y().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:L,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),W&&(0,r.jsxs)("div",{className:Y().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:W}),(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:L,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:Y().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:Y().footer,children:[(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:L,children:s("i18n.cancel")}),(0,r.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:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var et=n(2730);let en={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 er(){let{locale:e}=(0,z.s)();return{tt:(0,i.useCallback)((t,n)=>(0,et.u0)(e,t,en,n),[e]),locale:e}}let ei={en:{issueLabel:"GitHub issue (optional)",issuePlaceholder:"#123 or GitHub issue URL",issueStart:"Start issue session",issueBusy:"Starting…",fallbackBase:"Fetch failed; started from local {branch}"},ko:{issueLabel:"GitHub 이슈 (선택)",issuePlaceholder:"#123 또는 GitHub 이슈 URL",issueStart:"이슈 세션 시작",issueBusy:"시작 중…",fallbackBase:"가져오기 실패; 로컬 {branch}에서 시작됨"},zh:{issueLabel:"GitHub Issue(可选)",issuePlaceholder:"#123 或 GitHub Issue URL",issueStart:"开始 Issue 会话",issueBusy:"正在启动…",fallbackBase:"拉取失败;已从本地 {branch} 启动"}},ea={en:"The subdirectory {path} is not in this worktree; opened its root instead",ko:"이 워크트리에 하위 디렉터리 {path}이(가) 없어 루트 디렉터리를 대신 열었습니다",zh:"此工作树中不存在子目录 {path},已改为打开其根目录"};function es(e,t){if(t)try{sessionStorage.setItem(`cuelo:worktree:${e}`,JSON.stringify(t))}catch{}}let eo="omp-web:unread-session-ids",el="omp-web:pinned-session-ids",ec="omp-web:removed-projects";function ed(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 eu(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function ep({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function eh({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let em="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ef(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:em[Math.floor(Math.random()*em.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.243/18.20.0":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:c,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(ee,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eg(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 ex({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:m,translatorActive:f=!1,onTranslatorActiveChange:g,routinePanel:x,routineActive:v=!1,onRoutineActiveChange:b}){let y,{tt:w}=er(),{t:_,locale:F}=(0,z.s)(),W=B(),[O,D]=(0,i.useState)([]),H=(0,i.useMemo)(()=>t&&!O.some(e=>e.id===t.id)?[t,...O]:O,[O,t]),[U,q]=(0,i.useState)(!0),[V,K]=(0,i.useState)(null),[G,Z]=(0,i.useState)(null),[Y,X]=(0,i.useState)(""),[ee,et]=(0,i.useState)(!1),[en,em]=(0,i.useState)(""),[eb,ej]=(0,i.useState)("projects"),[eS,eC]=(0,i.useState)(()=>new Set),[eT,eI]=(0,i.useState)(()=>new Set),[eM,eR]=(0,i.useState)(null),[eE,e$]=(0,i.useState)(null),[eL,eP]=(0,i.useState)({version:1,projects:[]}),[eA,e_]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(!1),[eW,eO]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(null),[eU,eB]=(0,i.useState)(""),[eq,eV]=(0,i.useState)(!1),[eK,eG]=(0,i.useState)(null),[eJ,eZ]=(0,i.useState)(""),[eY,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(!1),[e8,e4]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(""),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(""),[ta,ts]=(0,i.useState)(!1),[to,tl]=(0,i.useState)(null),tc=(0,i.useRef)(null),[td,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(null),tm=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(!1),[tb,ty]=(0,i.useState)(!1),[tw,tk]=(0,i.useState)(()=>new Set),[tj,tS]=(0,i.useState)(()=>new Set),[tC,tN]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(eo);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}})()),[tT,tI]=(0,i.useState)(()=>new Set),[tM,tR]=(0,i.useState)(null),[tE,t$]=(0,i.useState)(!1),tL=(0,i.useRef)(new Set),tP=(0,i.useRef)(!1),tA=(0,i.useRef)(null);(0,i.useEffect)(()=>{tI(function(){try{let e=window.localStorage.getItem(el);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}tR(T(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=T(e.newValue,Date.now());tR(e=>e?I(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let t_=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eP(await e.json())}catch{eP({version:1,projects:[]})}finally{e_(!0)}},[]);(0,i.useEffect)(()=>{t_()},[t_,c]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ec)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await eg(n.map(e=>({key:L(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ec)}catch{}await t_()})()},[t_]);let tF=(0,i.useCallback)(async e=>{if(tv.current)throw Error("Project update in progress");tv.current=!0,eV(!0);try{await eg(e),await t_()}finally{tv.current=!1,eV(!1)}},[t_]);(0,i.useEffect)(()=>{eD&&tg.current?.select()},[eD]);let tz=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&q(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();D(r.sessions),tP.current||tk(new Set(r.runningSessionIds??[])),K(null),e||(ty(!0),tA.current&&clearTimeout(tA.current),tA.current=setTimeout(()=>ty(!1),2e3))}catch(e){K(String(e))}finally{e&&q(!1)}},[]),tW=(0,i.useCallback)(e=>{tN(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tI(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tR(t=>t&&$(t,[e])),d?.(e),tz()},[tz,d]),[tO,tD]=(0,i.useState)(null),[tH,tU]=(0,i.useState)(!1),[tB,tq]=(0,i.useState)(null),tV=(0,i.useCallback)(()=>{tH||(tD(null),tq(null))},[tH]),tK=(0,i.useCallback)(async e=>{tU(!0),tq(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(tP.current=!0,tk(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(tN(n),tI(n),tR(e=>e&&$(e,t)),t))d?.(e)}(await tz(),tU(!1),r.length>0)?tq(_("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tD(null)},[tz,d,_]),[tG,tJ]=(0,i.useState)(0),tZ=(0,i.useCallback)(()=>{tJ(e=>e+1),tz()},[tz]),tY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tY.current;tY.current=!0,tz(e,!e)},[tz,c]),(0,i.useEffect)(()=>{try{ej(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 tX=(0,i.useCallback)(e=>{ej(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==eb)return;let e=()=>{"visible"===document.visibilityState&&tz(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tz,eb]),(0,i.useEffect)(()=>{try{0===tC.size?window.localStorage.removeItem(eo):window.localStorage.setItem(eo,JSON.stringify([...tC]))}catch{}},[tC]),(0,i.useEffect)(()=>{try{0===tT.size?window.localStorage.removeItem(el):window.localStorage.setItem(el,JSON.stringify([...tT]))}catch{}},[tT]),(0,i.useEffect)(()=>{if(tM)try{var e,t,n;let r,i,a=window.localStorage;a.setItem(N,(e=a.getItem(N),t=Date.now(),i=(r=Object.entries((n=I(tM,T(e,t))).opened)).length>500?r.sort((e,t)=>t[1]-e[1]).slice(0,500):r,JSON.stringify({since:n.since,opened:Object.fromEntries(i)})))}catch{}},[tM]);let tQ=(0,i.useCallback)(e=>{tI(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;tP.current=!0,tk(new Set(r.runningSessionIds??[])),tS(new Set(r.waitingSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tL.current,n=[...t].filter(t=>!tw.has(t)&&t!==e),r=[...tw].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tN(e=>{let t=new Set(e);return tw.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!O.some(t=>t.id===e));(n.length>0||i)&&tz(!1,!0),n.length>0&&h?.(),tL.current=tw},[tw,e,O,tz,h]),(0,i.useEffect)(()=>{e&&tN(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let t0=e?H.find(t=>t.id===e)?.modified:void 0,t1=null!==tM;(0,i.useEffect)(()=>{e&&void 0!==t0&&t1&&tR(t=>t&&R(t,{id:e,modified:t0},Date.now()))},[e,t0,t1]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&X(e.home),et(!0===e.cloudProjects)}).catch(()=>{})},[]);let t2=(0,i.useRef)(!1),t8=(0,i.useCallback)(e=>{if(!e)return null;if(e8&&e8.forCwd===e||e8?.worktrees.some(t=>t.path===e))return e8.projectRoot;let t=H.find(t=>t.cwd===e);return t?.projectRoot??e},[e8,H]),t4=(0,i.useRef)(null);(0,i.useEffect)(()=>{t4.current!==G&&(t4.current=G,p?.(G,t8(G)))},[G,p,t8]);let t5=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==t5.current&&(t5.current=u,Z(u))},[u]);let[t6,t3]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!G)return void e4(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(G)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void e4(null);e4({forCwd:G,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||e4(null)}),()=>{e=!0}},[G,t6,c]),(0,i.useEffect)(()=>{if(0!==O.length&&!o&&null===G){if(s&&!t2.current){t2.current=!0;let e=O.find(e=>e.id===s);if(e){Z(e.cwd),n(e,!0);return}l?.()}if(!eA)return;let e=new Map(eL.projects.map(e=>[e.key,e])),t=A(O.length>0?P(O):[],eL.projects).filter(t=>!e.get(L(t))?.hidden);t.length>0&&Z(t[0])}},[O,G,s,o,n,l,eL,eA]);let t7=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!e1){e2(!0),e0(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void e0(n.error??_("workspace.unable"));let r=n.cwd??t,i=L(r),a=eL.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tF([{key:i,path:r,hidden:!1}])}catch{}Z(r),eX(!1)}catch{e0(_("workspace.unable"))}finally{e2(!1)}}},[tF,e1,eL.projects,_]),t9=(0,i.useCallback)(()=>{eX(!0),e0(null)},[]),ne=(0,i.useCallback)(async()=>{let e=e9.trim();if(e&&!td&&e8){tu(!0),tn(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e8.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void tn(n.error??`HTTP ${t.status}`);e7(!1),te(""),e6(!1),e4(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),Z(n.path),t3(e=>e+1)}catch(e){tn(e instanceof Error?e.message:String(e))}finally{tu(!1)}}},[e9,td,e8]),nt=(0,i.useCallback)(async(e,t)=>{if(e8&&!td){tu(!0),tn(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e8.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void th(e);tn(r.error??`HTTP ${n.status}`);return}th(null),G===e&&Z(e8.projectRoot),t3(e=>e+1)}catch(e){tn(e instanceof Error?e.message:String(e))}finally{tu(!1)}}},[e8,td,G]);(0,i.useEffect)(()=>{let e=e=>{tm.current&&!tm.current.contains(e.target)&&(e$(null),e6(!1),e7(!1),te(""),tn(null),th(null),eZ(""),eR(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let nn=(0,i.useCallback)(e=>{e.cwd&&Z(e.cwd),n(e)},[n]),nr=(0,i.useCallback)((e=G)=>{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)}`;Z(e),a?.(t,e)},[G,a]),ni=(0,i.useCallback)(async()=>{let e=e8?.projectRoot,t=tr.trim();if(!e||!t||ta)return;ts(!0),tl(null);let r=tc.current,i=r?.issue===t&&r.cwd===e?r.id:"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;tc.current={issue:t,cwd:e,id:i};try{let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,issue:t,type:"ensure_session",createRequestId:i})}),a=await r.json();if(!r.ok||!a.sessionId||!a.cwd)throw Error(a.error??`HTTP ${r.status}`);es(a.cwd,a.worktree),tc.current=null,ti(""),Z(a.cwd),t3(e=>e+1),n({id:a.sessionId,cwd:a.cwd,projectRoot:e,path:"",created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:0,firstMessage:"(no messages)",transient:!0})}catch(e){tl(e instanceof Error?e.message:String(e))}finally{ts(!1)}},[e8,tr,ta,n]),[na,ns]=(0,i.useState)(!1),[no,nl]=(0,i.useState)(null),nc=(0,i.useCallback)(async()=>{ns(!0),nl(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}`);nr(t.cwd)}catch(e){nl(_("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{ns(!1)}},[nr,_]),nd=(0,i.useCallback)(e=>{eI(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),nu=t8(G),np=null===nu?null:L(nu),nh=(0,i.useMemo)(()=>new Map(eL.projects.map(e=>[e.key,e])),[eL.projects]),nm=P(H);if(null!==nu){let e=L(nu);nm.some(t=>L(t)===e)||nm.unshift(nu)}let nf=A(nm,eL.projects),ng=nf.filter(e=>eF||!nh.get(L(e))?.hidden),nx=nf.some(e=>nh.get(L(e))?.hidden),nv=()=>{e$(null),e6(!1),e7(!1),te(""),tn(null),th(null),eZ("")},nb=async(e,t)=>{nv();try{await tF([{key:L(e),path:e,hidden:t}]),t&&np&&np===L(e)&&Z(null),t||nf.some(t=>L(t)!==L(e)&&nh.get(L(t))?.hidden)||ez(!1)}catch{}},ny=async e=>{if(tx.current){tx.current=!1,eH(null);return}let t=eU.trim();if(t===(nh.get(L(e))?.alias??""))return void eH(null);eG(null);try{await tF([{key:L(e),path:e,alias:t||null}]),eH(null)}catch{eG(_("sidebar.projectUpdateFailed"))}},nw=async(e,t)=>{if(en)return;let n=ng.indexOf(e),r=n+t;if(n<0||r<0||r>=ng.length)return;let i=new Set(ng),a=nf.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...nf],o=a[n],l=a[r];[s[o],s[l]]=[s[l],s[o]],nv();try{await tF(s.map((e,t)=>({key:L(e),path:e,order:t})))}catch{}},nk=new Map;for(let e of H){let t=e.projectRoot??e.cwd;if(!t)continue;let n=L(t),r=nk.get(n);r?r.push(e):nk.set(n,[e])}let nj=(0,i.useMemo)(()=>{let e=new Map;for(let t of H){let n=t.projectRoot??t.cwd;if(!n)continue;let r=L(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),tw.has(t.id)&&i.running++,tC.has(t.id)&&i.unread++}return e},[H,tw,tC]),nS=en.trim().toLowerCase(),nC=en.length>0,nN=ng.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=L(e),r=nh.get(n),i=r?.alias??t,a=(nk.get(n)??[]).slice().sort((e,t)=>{let n=Number(tT.has(t.id))-Number(tT.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!nS)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(nS)||t.toLowerCase().includes(nS),o=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(nS));return s||0!==o.length?[{project:e,key:n,name:i,sessions:s?a:o,hidden:r?.hidden===!0}]:[]}),nT=[],nI=[];for(let e of nN){let t=e.key===np||(nj.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?nI.push(e):nT.push(e)}let nM={running:0,unread:0};for(let e of nI){let t=nj.get(e.key);t&&(nM.running+=t.running,nM.unread+=t.unread)}let nR=nC||eW,nE=[...nT.map(e=>({kind:"project",group:e})),...nI.length>0?[{kind:"temporary"}]:[],...nR?nI.map(e=>({kind:"project",group:e})):[]],n$=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nE.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nL=(0,i.useMemo)(()=>tM?H.filter(e=>(function(e,t,n,r=E){if(e.transient||e.trial)return!1;if(r.has(e.id))return!0;if(t.has(e.id))return!1;let i=M(e);return null!==i&&i>(n.opened[e.id]??n.since)})(e,tw,tM,tj)):[],[tM,tw,H,tj]),nP=tE&&null!==tM,[nA,n_]=(0,i.useState)(null),nF=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),c=l.filter(e=>a.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(p>=o)continue;p+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=u.get(r);i?i.push(e):u.set(r,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:i,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:u.get(e)??[]});return h})(nP?H.filter(e=>e.id===nA&&!tw.has(e.id)||nL.includes(e)):H,tw,new Date,F,_("navigator.priority"),tT,_("sidebar.pinned"),nP?1/0:void 0),[nA,F,tT,nL,nP,tw,H,_]),nz=(0,i.useCallback)(e=>{n_(e.id),nn(e)},[nn]),nW=!!(e8?.isGit&&e8.isTopLevel&&G&&nu===e8.projectRoot),nO=e8?.worktrees.find(e=>e.path===G)??e8?.worktrees.find(e=>e.isMain),nD=(e8?.worktrees.length??0)>=8,nH=nD&&eJ.trim()?(e8?.worktrees??[]).filter(e=>(e.branch??eu(e.path,Y)).toLowerCase().includes(eJ.trim().toLowerCase())):e8?.worktrees??[],nU=ei[F.startsWith("ko")?"ko":F.startsWith("zh")?"zh":"en"],nB=function(e){if(e&&"u">typeof sessionStorage)try{return JSON.parse(sessionStorage.getItem(`cuelo:worktree:${e}`)??"null")??void 0}catch{return}}(G),nq=(()=>{if(!tO)return[];let e="project"===tO.kind?nk.get(L(tO.project))??[]:nF.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nV=nq.filter(e=>!tw.has(e.id)),nK=e=>{let t=new Set;for(let n of e)n.transient||tw.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nG=void 0!==m&&f,nJ=void 0!==x&&v,nZ=nG||nJ;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eY&&(0,r.jsx)(ee?Q:J,{busy:e1,error:eQ,onCancel:()=>{eX(!1),e0(null)},onSelect:e=>void t7(e)}),tO&&(0,r.jsx)(ev,{scope:tO,eligible:nV.length,runningExcluded:nq.length-nV.length,busy:tH,error:tB,onCancel:tV,onConfirm:()=>void tK(nV)}),(0,r.jsxs)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ef,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>nr(),disabled:!G,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:G?"var(--text-muted)":"var(--text-dim)",cursor:G?"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:G?_("sidebar.newSessionTitle",{path:G}):_("sidebar.selectProject"),"aria-label":G?_("sidebar.newSessionTitle",{path:G}):_("sidebar.selectProject"),onMouseEnter:e=>{G&&(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=G?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${tb?" is-success":""}`,onClick:()=>tz(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:tb?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${tb?"rgba(74,222,128,0.4)":"var(--border)"}`,color:tb?"#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=>{tb||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{tb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:_("sidebar.refresh"),children:tb?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]}),nW&&(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),ni()},style:{marginTop:8},children:[(0,r.jsx)("label",{htmlFor:"session-issue",style:{display:"block",fontSize:12,color:"var(--text-muted)"},children:nU.issueLabel}),(0,r.jsxs)("div",{style:{display:"flex",gap:4,marginTop:4},children:[(0,r.jsx)("input",{id:"session-issue",value:tr,disabled:ta,onChange:e=>{ti(e.target.value),tl(null)},placeholder:nU.issuePlaceholder,"aria-describedby":to?"session-issue-error":void 0,"aria-invalid":!!to,style:{minWidth:0,flex:1,padding:"6px 8px",fontSize:12,background:"var(--bg)",color:"var(--text)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)"}}),(0,r.jsx)("button",{type:"submit",disabled:ta||!tr.trim(),title:nU.issueStart,"aria-label":nU.issueStart,style:{minWidth:32,padding:"4px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:ta?"wait":"pointer"},children:ta?"…":"↵"})]}),ta&&(0,r.jsx)("div",{role:"status",style:{fontSize:12},children:nU.issueBusy}),to&&(0,r.jsx)("div",{id:"session-issue-error",role:"alert",style:{fontSize:12,color:"var(--danger)",overflowWrap:"anywhere"},children:to})]}),(nB||nO&&!nO.isMain)&&(0,r.jsxs)("div",{role:"status",title:G??void 0,style:{marginTop:4,fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:[nB?.branch??nO?.branch,nB?.fallback&&(0,r.jsx)("div",{children:nU.fallbackBase.replace("{branch}",nB.base)}),nB?.missingSubdirectory&&(0,r.jsx)("div",{children:ea[F.startsWith("ko")?"ko":F.startsWith("zh")?"zh":"en"].replace("{path}",nB.missingSubdirectory)})]})]}),ee&&!nZ&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:t9,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:_("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":_("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?_("sidebar.projects"):_("navigator.priority"),n=!nZ&&eb===e;return(0,r.jsx)("button",{type:"button","aria-label":_("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tX(e),nG&&g?.(!1),nJ&&b?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":_("navigator.view",{label:w("translator.tab")}),"aria-pressed":nG,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!nG),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:nG?"var(--bg-selected)":"transparent",color:nG?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nG?600:500,whiteSpace:"nowrap"},children:w("translator.tab")}),void 0!==x&&(0,r.jsx)("button",{type:"button","aria-label":_("navigator.view",{label:_("routines.tab")}),"aria-pressed":nJ,"aria-controls":"navigator-routine-panel","data-navigator-mode":"routine",onClick:()=>b?.(!nJ),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:nJ?"var(--bg-selected)":"transparent",color:nJ?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nJ?600:500,whiteSpace:"nowrap"},children:_("routines.tab")})]}),!nZ&&"projects"===eb&&(0,r.jsx)("button",{type:"button",onClick:()=>ez(e=>!e),disabled:!nx,title:_("sidebar.projectShowHidden"),"aria-label":_("sidebar.projectShowHidden"),"aria-pressed":eF,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eF?"var(--bg-selected)":"transparent",color:eF?"var(--accent)":"var(--text-dim)",cursor:nx?"pointer":"default",opacity:nx?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eF&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nZ&&"projects"===eb&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:t9,title:_("sidebar.addProject"),"aria-label":_("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,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),nG&&m,nJ&&x,!nZ&&"projects"===eb&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:en,onChange:e=>em(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),em(""),e.currentTarget.blur())},placeholder:_("sidebar.searchProjectsAndSessions"),"aria-label":_("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}})]}),!nZ&&"projects"===eb&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(U||!eA)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:_("sidebar.loading")}),V&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:V}),eK&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eK}),!U&&eA&&!V&&0===nN.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nS?_("sidebar.noMatchingProjects"):_("sidebar.noSessions")}),!U&&eA&&!V&&nE.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":nR,title:_("sidebar.temporaryProjects"),onClick:()=>eO(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:nR?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nI.length}),eN(nM,_)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===np,p=n$.has(l.toLowerCase())&&eu((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),Y)||null,h=!eT.has(s)&&!nS,m=eS.has(s),f=eD===s,g=ng.indexOf(s),x=eq||nC||g<=0,v=eq||nC||g>=ng.length-1,b=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?c:c.slice(0,5)),y=c.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:eE===s?tm:void 0,onMouseEnter:()=>eR(s),onMouseLeave:()=>eR(e=>e===s&&eE!==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,r.jsx)("button",{type:"button",onClick:()=>nd(s),title:h?_("sidebar.expandProject"):_("sidebar.collapseProject"),"aria-label":h?_("sidebar.expandProject"):_("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:tg,value:eU,onChange:e=>eB(e.target.value),onBlur:()=>void ny(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tx.current=!0,eH(null))},"aria-label":_("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,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>Z(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),eN(nj.get(o),_)]}),(0,r.jsx)("button",{type:"button",onClick:()=>nr(s),title:_("sidebar.newSessionTitle",{path:s}),"aria-label":_("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||eM===s?1:0,pointerEvents:W||eM===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>eR(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{e$(eE===s?null:s),e6(!1),e7(!1),tn(null),u||Z(s)},title:_("sidebar.projectActions"),"aria-label":_("sidebar.projectActions"),"aria-expanded":eE===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eE===s?"var(--bg-selected)":"transparent",color:u&&nO&&!nO.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:W||eM===s||eE===s?1:0,pointerEvents:W||eM===s||eE===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>eR(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(eh,{open:eE===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:[nW&&e8&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>e6(e=>!e),title:nO?_("sidebar.switchWorktreeTitle",{path:nO.path}):_("sidebar.switchWorktree"),"aria-label":_("sidebar.worktrees"),"aria-expanded":e5,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:e5?"1px solid var(--border)":"none",background:e5?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:_("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(eh,{open:e5,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:[nD&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eJ,onChange:e=>eZ(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eZ(""),e6(!1))},placeholder:_("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,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[nH.map(e=>{let t=e.path===G||e.isMain&&!e8.worktrees.some(e=>e.path===G);return tp===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void nt(e.path,!0),disabled:td,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:_("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>th(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:_("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{Z(e.path),e6(!1),tn(null),eZ("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(ep,{text:e.branch??eu(e.path,Y),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:_("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void nt(e.path,!1),disabled:td,title:_("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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nD&&0===nH.length&&eJ.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:_("sidebar.noMatchingWorktrees")})]}),e3?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:tf,value:e9,onChange:e=>{te(e.target.value),tn(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),ne()),"Escape"===e.key&&(e7(!1),te(""),tn(null))},placeholder:_("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,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void ne(),disabled:td||!e9.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:td||!e9.trim()?"not-allowed":"pointer",opacity:td||!e9.trim()?.65:1},children:td?_("sidebar.creating"):_("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e7(!1),te(""),tn(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:_("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e7(!0),tn(null),setTimeout(()=>tf.current?.focus(),0)},title:_("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:_("sidebar.newWorktree")})]}),tt&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:tt})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eq,onClick:()=>{let e;return e=nh.get(L(s))?.alias??"",void(tx.current=!1,eG(null),eB(e),eH(s),nv())},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:eq?"default":"pointer",textAlign:"left",fontSize:11,opacity:eq?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),_(nh.get(L(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:nC?_("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nw(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),_("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:nC?_("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nw(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),_("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eq,onClick:()=>void nb(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:eq?"default":"pointer",textAlign:"left",fontSize:11,opacity:eq?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),_(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nK(nk.get(o)??[])||tH,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{nv(),tq(null),tD({kind:"project",project:s,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),_("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:_("sidebar.noSessions")}),!h&&b.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:b.map(t=>(0,r.jsx)(ek,{node:t,selectedSessionId:e,runningSessionIds:tw,unreadSessionIds:tC,pinnedSessionIds:tT,onSelectSession:nn,onTogglePinnedSession:tQ,onRenamed:tz,onSessionDeleted:tW,onSessionArchived:tZ,depth:0},t.session.id))}),!h&&y&&(0,r.jsx)("button",{type:"button",onClick:()=>{eC(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?_("sidebar.showLess"):_("sidebar.showMore")})]},s)})]}),!nZ&&(0,r.jsx)(ew,{refreshKey:tG,selectedSessionId:e,onSelectSession:nn,onRestored:tZ}),!nZ&&"priority"===eb&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[U&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:_("sidebar.loading")}),V&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:V}),!U&&!V&&(y=nK(nF.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:na,onClick:()=>void nc(),title:_("sidebar.newScratchSessionTitle"),style:ed(na,W),children:_("sidebar.newScratchSession")}),nF.length>0&&!nP&&(0,r.jsx)("button",{type:"button",disabled:0===y||tH,onClick:()=>{tq(null),tD({kind:"priority"})},style:ed(0===y||tH,W),children:_("sidebar.clearPriorityList")})]})),!U&&!V&&tM&&(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,r.jsxs)("button",{type:"button","aria-pressed":nP,"aria-label":_("navigator.resultsToCheckCount",{count:nL.length}),title:_("navigator.resultsToCheckHint"),onClick:()=>{n_(null),t$(e=>!e)},style:{...ed(!1,W),display:"inline-flex",alignItems:"center",gap:6,borderColor:nP?"var(--border-strong)":"var(--border)",background:nP?"var(--bg-selected)":"transparent",color:nP||nL.length>0?"var(--text)":"var(--text-muted)",fontWeight:nP?600:500,whiteSpace:"nowrap"},children:[_("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:nL.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nL.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nL.length})]}),nL.some(e=>!tj.has(e.id))&&(0,r.jsx)("button",{type:"button",title:_("navigator.acknowledgeResultsHint"),onClick:()=>{n_(null),tR(e=>e&&function(e,t,n){let r=e;for(let e of t)r=R(r,e,n);return r}(e,nL,Date.now()))},style:ed(!1,W),children:_("navigator.acknowledgeResults")})]}),no&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:no}),!U&&!V&&0===nF.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nP?_("navigator.resultsToCheckEmpty"):_("sidebar.noSessions")}),!U&&!V&&nF.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(ey,{session:t,selected:t.id===e,running:tw.has(t.id),waiting:tj.has(t.id),unread:tC.has(t.id),pinned:tT.has(t.id),onSelect:nP?nz:nn,onTogglePin:tQ},t.id))]},t.key))]})]})}function ev({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,z.s)(),d=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let m=(0,i.useRef)(o);return m.current=o,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function eb({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ey({session:e,selected:t,running:n,waiting:i,unread:a,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,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>o(e),title:`${d}
|
|
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,n)=>{"use strict";function r(e,t,n,i={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,i)}n.d(t,{u0:()=>r})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21040:e=>{e.exports={view:"RoutineView_view__4busO",topbar:"RoutineView_topbar__YPacL",back:"RoutineView_back__ac5Vn",body:"RoutineView_body__01N2Q",crumb:"RoutineView_crumb__K1_0X",link:"RoutineView_link__whmc9",head:"RoutineView_head__WBrda",headActions:"RoutineView_headActions__KqC_W",sub:"RoutineView_sub__mh018",facts:"RoutineView_facts__Yyns3",strong:"RoutineView_strong__x6Fhg",subNote:"RoutineView_subNote__tAUYO",mono:"RoutineView_mono__ms2qU",button:"RoutineView_button__sbfYZ",tabs:"RoutineView_tabs__iPnSQ",field:"RoutineView_field__B4jvA",badge:"RoutineView_badge__uMNRL",table:"RoutineView_table__3ihqX",title:"RoutineView_title__WPF5j",no:"RoutineView_no__Ck2vM",emptyCell:"RoutineView_emptyCell__o5V_C",empty:"RoutineView_empty__FoRja",foot:"RoutineView_foot__EmDj9",sync:"RoutineView_sync__Fek1M",notice:"RoutineView_notice__VvzFH",postHead:"RoutineView_postHead__ooMEu",postMeta:"RoutineView_postMeta___lo7j",postBody:"RoutineView_postBody__nwcmb",form:"RoutineView_form__SZrKX",row:"RoutineView_row__YLKM0",rowLabel:"RoutineView_rowLabel__wAaNU",narrow:"RoutineView_narrow__EazoW",hint:"RoutineView_hint__R9fMv",days:"RoutineView_days__lm_q_",check:"RoutineView_check__gT_Aa",formActions:"RoutineView_formActions__A9Djj",danger:"RoutineView_danger__Xi84r",error:"RoutineView_error__JNoxw",panel:"RoutineView_panel__jkMFt",panelList:"RoutineView_panelList__JrArr",count:"RoutineView_count__GICfE",wide:"RoutineView_wide__bJkXf",rowSchedule:"RoutineView_rowSchedule__Co8RM",visuallyHidden:"RoutineView_visuallyHidden__M_RPw",inline:"RoutineView_inline__ZaYAe",chips:"RoutineView_chips__hnVXc",chipRemove:"RoutineView_chipRemove__wNru7",host:"RoutineView_host__SV_7k"}},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"}},34241:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>y7});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),o=n(81886),l=n(68890),c=n(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 n,r=f(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=f(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,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[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let n=null;for(let[r,i]of Object.entries(t.opened))(e.opened[r]??-1/0)>=i||((n??={...e.opened})[r]=i);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function R(e,t,n){let r=Math.max(n,M(t)??0);return(e.opened[t.id]??-1/0)>=r?e:{since:e.since,opened:{...e.opened,[t.id]:r}}}let E=new Set;function $(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function 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 P(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=L(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function A(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(L(e.key),e.order);let r=[...e],i=new Set(e.map(L));for(let e of t){let t=L(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(L(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let _=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function F(e){let t=e.match(_);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var z=n(84183);let W=`(max-width: ${p.navigator-1}px)`;function O(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=O("(max-width: 640px)"),H=O(W);function U(){return!1}function B(){return(0,i.useSyncExternalStore)(D.subscribe,D.getSnapshot,U)}var q=n(47650);async function V(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function K(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function G(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function J({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,z.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await V(e),n=t.path??e??"/";d(n),p(t.parentPath??null),m(!0===t.upToDrives),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),C()},[C]);let N=f.trim()!==c,T=!!c&&!N&&!n,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,q.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!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,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value: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,r.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,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(G,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(K,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!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(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Z=n(21443),Y=n.n(Z);async function X(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function Q({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,z.s)(),o=(0,i.useRef)(null),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,T]=(0,i.useState)(null),[I,M]=(0,i.useState)(!1),[R,E]=(0,i.useState)(50),$=p?.device?.state==="pending",L=n||S,P=(0,i.useCallback)(async()=>{w(!0),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 A(){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 _(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,i.useEffect)(()=>{c(!0),P()},[P]),(0,i.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,i.useEffect)(()=>{let e;if(!$||d)return;let t=!1,n=async()=>{try{let e=await X("/api/github/projects");if(t)return;if(h(e),e.connected)return void await P();if(e.device?.state!=="pending")return}catch(e){t||T(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[$,d,P]),!l)return null;if(d)return(0,r.jsx)(J,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let F=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),W=N??a??p?.device?.error;return(0,q.createPortal)((0,r.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),L||e()},children:(0,r.jsxs)("form",{onSubmit:_,className:Y().form,children:[(0,r.jsxs)("header",{className:Y().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:Y().sources,children:[(0,r.jsx)("span",{className:Y().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:L,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:Y().body,children:[(0,r.jsxs)("section",{className:Y().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:y||L,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:y||k||$||L,children:k||$?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),$&&(0,r.jsxs)("div",{className:Y().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:Y().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.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,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Y().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:Y().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:L}),y?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:Y().list,children:F.slice(0,R).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":v===e.fullName,disabled:L,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:Y().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:Y().repoDescription,children:e.description})]})},e.fullName))}),!F.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),F.length>R&&(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:Y().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:L,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),W&&(0,r.jsxs)("div",{className:Y().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:W}),(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:L,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:Y().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:Y().footer,children:[(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:L,children:s("i18n.cancel")}),(0,r.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:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var et=n(2730);let en={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 er(){let{locale:e}=(0,z.s)();return{tt:(0,i.useCallback)((t,n)=>(0,et.u0)(e,t,en,n),[e]),locale:e}}let ei={en:{issueLabel:"GitHub issue (optional)",issuePlaceholder:"#123 or GitHub issue URL",issueStart:"Start issue session",issueBusy:"Starting…",fallbackBase:"Fetch failed; started from local {branch}"},ko:{issueLabel:"GitHub 이슈 (선택)",issuePlaceholder:"#123 또는 GitHub 이슈 URL",issueStart:"이슈 세션 시작",issueBusy:"시작 중…",fallbackBase:"가져오기 실패; 로컬 {branch}에서 시작됨"},zh:{issueLabel:"GitHub Issue(可选)",issuePlaceholder:"#123 或 GitHub Issue URL",issueStart:"开始 Issue 会话",issueBusy:"正在启动…",fallbackBase:"拉取失败;已从本地 {branch} 启动"}},ea={en:"The subdirectory {path} is not in this worktree; opened its root instead",ko:"이 워크트리에 하위 디렉터리 {path}이(가) 없어 루트 디렉터리를 대신 열었습니다",zh:"此工作树中不存在子目录 {path},已改为打开其根目录"};function es(e,t){if(t)try{sessionStorage.setItem(`cuelo:worktree:${e}`,JSON.stringify(t))}catch{}}let eo="omp-web:unread-session-ids",el="omp-web:pinned-session-ids",ec="omp-web:removed-projects";function ed(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 eu(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function ep({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function eh({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let em="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ef(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:em[Math.floor(Math.random()*em.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.244/18.20.0":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:c,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(ee,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eg(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 ex({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:m,translatorActive:f=!1,onTranslatorActiveChange:g,routinePanel:x,routineActive:v=!1,onRoutineActiveChange:b}){let y,{tt:w}=er(),{t:_,locale:F}=(0,z.s)(),W=B(),[O,D]=(0,i.useState)([]),H=(0,i.useMemo)(()=>t&&!O.some(e=>e.id===t.id)?[t,...O]:O,[O,t]),[U,q]=(0,i.useState)(!0),[V,K]=(0,i.useState)(null),[G,Z]=(0,i.useState)(null),[Y,X]=(0,i.useState)(""),[ee,et]=(0,i.useState)(!1),[en,em]=(0,i.useState)(""),[eb,ej]=(0,i.useState)("projects"),[eS,eC]=(0,i.useState)(()=>new Set),[eT,eI]=(0,i.useState)(()=>new Set),[eM,eR]=(0,i.useState)(null),[eE,e$]=(0,i.useState)(null),[eL,eP]=(0,i.useState)({version:1,projects:[]}),[eA,e_]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(!1),[eW,eO]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(null),[eU,eB]=(0,i.useState)(""),[eq,eV]=(0,i.useState)(!1),[eK,eG]=(0,i.useState)(null),[eJ,eZ]=(0,i.useState)(""),[eY,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(!1),[e8,e4]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(""),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(""),[ta,ts]=(0,i.useState)(!1),[to,tl]=(0,i.useState)(null),tc=(0,i.useRef)(null),[td,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(null),tm=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(!1),[tb,ty]=(0,i.useState)(!1),[tw,tk]=(0,i.useState)(()=>new Set),[tj,tS]=(0,i.useState)(()=>new Set),[tC,tN]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(eo);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}})()),[tT,tI]=(0,i.useState)(()=>new Set),[tM,tR]=(0,i.useState)(null),[tE,t$]=(0,i.useState)(!1),tL=(0,i.useRef)(new Set),tP=(0,i.useRef)(!1),tA=(0,i.useRef)(null);(0,i.useEffect)(()=>{tI(function(){try{let e=window.localStorage.getItem(el);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}tR(T(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=T(e.newValue,Date.now());tR(e=>e?I(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let t_=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eP(await e.json())}catch{eP({version:1,projects:[]})}finally{e_(!0)}},[]);(0,i.useEffect)(()=>{t_()},[t_,c]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ec)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await eg(n.map(e=>({key:L(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ec)}catch{}await t_()})()},[t_]);let tF=(0,i.useCallback)(async e=>{if(tv.current)throw Error("Project update in progress");tv.current=!0,eV(!0);try{await eg(e),await t_()}finally{tv.current=!1,eV(!1)}},[t_]);(0,i.useEffect)(()=>{eD&&tg.current?.select()},[eD]);let tz=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&q(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();D(r.sessions),tP.current||tk(new Set(r.runningSessionIds??[])),K(null),e||(ty(!0),tA.current&&clearTimeout(tA.current),tA.current=setTimeout(()=>ty(!1),2e3))}catch(e){K(String(e))}finally{e&&q(!1)}},[]),tW=(0,i.useCallback)(e=>{tN(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tI(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tR(t=>t&&$(t,[e])),d?.(e),tz()},[tz,d]),[tO,tD]=(0,i.useState)(null),[tH,tU]=(0,i.useState)(!1),[tB,tq]=(0,i.useState)(null),tV=(0,i.useCallback)(()=>{tH||(tD(null),tq(null))},[tH]),tK=(0,i.useCallback)(async e=>{tU(!0),tq(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(tP.current=!0,tk(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(tN(n),tI(n),tR(e=>e&&$(e,t)),t))d?.(e)}(await tz(),tU(!1),r.length>0)?tq(_("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tD(null)},[tz,d,_]),[tG,tJ]=(0,i.useState)(0),tZ=(0,i.useCallback)(()=>{tJ(e=>e+1),tz()},[tz]),tY=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tY.current;tY.current=!0,tz(e,!e)},[tz,c]),(0,i.useEffect)(()=>{try{ej(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 tX=(0,i.useCallback)(e=>{ej(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==eb)return;let e=()=>{"visible"===document.visibilityState&&tz(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tz,eb]),(0,i.useEffect)(()=>{try{0===tC.size?window.localStorage.removeItem(eo):window.localStorage.setItem(eo,JSON.stringify([...tC]))}catch{}},[tC]),(0,i.useEffect)(()=>{try{0===tT.size?window.localStorage.removeItem(el):window.localStorage.setItem(el,JSON.stringify([...tT]))}catch{}},[tT]),(0,i.useEffect)(()=>{if(tM)try{var e,t,n;let r,i,a=window.localStorage;a.setItem(N,(e=a.getItem(N),t=Date.now(),i=(r=Object.entries((n=I(tM,T(e,t))).opened)).length>500?r.sort((e,t)=>t[1]-e[1]).slice(0,500):r,JSON.stringify({since:n.since,opened:Object.fromEntries(i)})))}catch{}},[tM]);let tQ=(0,i.useCallback)(e=>{tI(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;tP.current=!0,tk(new Set(r.runningSessionIds??[])),tS(new Set(r.waitingSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tL.current,n=[...t].filter(t=>!tw.has(t)&&t!==e),r=[...tw].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tN(e=>{let t=new Set(e);return tw.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!O.some(t=>t.id===e));(n.length>0||i)&&tz(!1,!0),n.length>0&&h?.(),tL.current=tw},[tw,e,O,tz,h]),(0,i.useEffect)(()=>{e&&tN(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let t0=e?H.find(t=>t.id===e)?.modified:void 0,t1=null!==tM;(0,i.useEffect)(()=>{e&&void 0!==t0&&t1&&tR(t=>t&&R(t,{id:e,modified:t0},Date.now()))},[e,t0,t1]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&X(e.home),et(!0===e.cloudProjects)}).catch(()=>{})},[]);let t2=(0,i.useRef)(!1),t8=(0,i.useCallback)(e=>{if(!e)return null;if(e8&&e8.forCwd===e||e8?.worktrees.some(t=>t.path===e))return e8.projectRoot;let t=H.find(t=>t.cwd===e);return t?.projectRoot??e},[e8,H]),t4=(0,i.useRef)(null);(0,i.useEffect)(()=>{t4.current!==G&&(t4.current=G,p?.(G,t8(G)))},[G,p,t8]);let t5=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==t5.current&&(t5.current=u,Z(u))},[u]);let[t6,t3]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!G)return void e4(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(G)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void e4(null);e4({forCwd:G,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||e4(null)}),()=>{e=!0}},[G,t6,c]),(0,i.useEffect)(()=>{if(0!==O.length&&!o&&null===G){if(s&&!t2.current){t2.current=!0;let e=O.find(e=>e.id===s);if(e){Z(e.cwd),n(e,!0);return}l?.()}if(!eA)return;let e=new Map(eL.projects.map(e=>[e.key,e])),t=A(O.length>0?P(O):[],eL.projects).filter(t=>!e.get(L(t))?.hidden);t.length>0&&Z(t[0])}},[O,G,s,o,n,l,eL,eA]);let t7=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!e1){e2(!0),e0(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void e0(n.error??_("workspace.unable"));let r=n.cwd??t,i=L(r),a=eL.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tF([{key:i,path:r,hidden:!1}])}catch{}Z(r),eX(!1)}catch{e0(_("workspace.unable"))}finally{e2(!1)}}},[tF,e1,eL.projects,_]),t9=(0,i.useCallback)(()=>{eX(!0),e0(null)},[]),ne=(0,i.useCallback)(async()=>{let e=e9.trim();if(e&&!td&&e8){tu(!0),tn(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e8.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void tn(n.error??`HTTP ${t.status}`);e7(!1),te(""),e6(!1),e4(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),Z(n.path),t3(e=>e+1)}catch(e){tn(e instanceof Error?e.message:String(e))}finally{tu(!1)}}},[e9,td,e8]),nt=(0,i.useCallback)(async(e,t)=>{if(e8&&!td){tu(!0),tn(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e8.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void th(e);tn(r.error??`HTTP ${n.status}`);return}th(null),G===e&&Z(e8.projectRoot),t3(e=>e+1)}catch(e){tn(e instanceof Error?e.message:String(e))}finally{tu(!1)}}},[e8,td,G]);(0,i.useEffect)(()=>{let e=e=>{tm.current&&!tm.current.contains(e.target)&&(e$(null),e6(!1),e7(!1),te(""),tn(null),th(null),eZ(""),eR(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let nn=(0,i.useCallback)(e=>{e.cwd&&Z(e.cwd),n(e)},[n]),nr=(0,i.useCallback)((e=G)=>{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)}`;Z(e),a?.(t,e)},[G,a]),ni=(0,i.useCallback)(async()=>{let e=e8?.projectRoot,t=tr.trim();if(!e||!t||ta)return;ts(!0),tl(null);let r=tc.current,i=r?.issue===t&&r.cwd===e?r.id:"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;tc.current={issue:t,cwd:e,id:i};try{let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,issue:t,type:"ensure_session",createRequestId:i})}),a=await r.json();if(!r.ok||!a.sessionId||!a.cwd)throw Error(a.error??`HTTP ${r.status}`);es(a.cwd,a.worktree),tc.current=null,ti(""),Z(a.cwd),t3(e=>e+1),n({id:a.sessionId,cwd:a.cwd,projectRoot:e,path:"",created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:0,firstMessage:"(no messages)",transient:!0})}catch(e){tl(e instanceof Error?e.message:String(e))}finally{ts(!1)}},[e8,tr,ta,n]),[na,ns]=(0,i.useState)(!1),[no,nl]=(0,i.useState)(null),nc=(0,i.useCallback)(async()=>{ns(!0),nl(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}`);nr(t.cwd)}catch(e){nl(_("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{ns(!1)}},[nr,_]),nd=(0,i.useCallback)(e=>{eI(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),nu=t8(G),np=null===nu?null:L(nu),nh=(0,i.useMemo)(()=>new Map(eL.projects.map(e=>[e.key,e])),[eL.projects]),nm=P(H);if(null!==nu){let e=L(nu);nm.some(t=>L(t)===e)||nm.unshift(nu)}let nf=A(nm,eL.projects),ng=nf.filter(e=>eF||!nh.get(L(e))?.hidden),nx=nf.some(e=>nh.get(L(e))?.hidden),nv=()=>{e$(null),e6(!1),e7(!1),te(""),tn(null),th(null),eZ("")},nb=async(e,t)=>{nv();try{await tF([{key:L(e),path:e,hidden:t}]),t&&np&&np===L(e)&&Z(null),t||nf.some(t=>L(t)!==L(e)&&nh.get(L(t))?.hidden)||ez(!1)}catch{}},ny=async e=>{if(tx.current){tx.current=!1,eH(null);return}let t=eU.trim();if(t===(nh.get(L(e))?.alias??""))return void eH(null);eG(null);try{await tF([{key:L(e),path:e,alias:t||null}]),eH(null)}catch{eG(_("sidebar.projectUpdateFailed"))}},nw=async(e,t)=>{if(en)return;let n=ng.indexOf(e),r=n+t;if(n<0||r<0||r>=ng.length)return;let i=new Set(ng),a=nf.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...nf],o=a[n],l=a[r];[s[o],s[l]]=[s[l],s[o]],nv();try{await tF(s.map((e,t)=>({key:L(e),path:e,order:t})))}catch{}},nk=new Map;for(let e of H){let t=e.projectRoot??e.cwd;if(!t)continue;let n=L(t),r=nk.get(n);r?r.push(e):nk.set(n,[e])}let nj=(0,i.useMemo)(()=>{let e=new Map;for(let t of H){let n=t.projectRoot??t.cwd;if(!n)continue;let r=L(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),tw.has(t.id)&&i.running++,tC.has(t.id)&&i.unread++}return e},[H,tw,tC]),nS=en.trim().toLowerCase(),nC=en.length>0,nN=ng.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=L(e),r=nh.get(n),i=r?.alias??t,a=(nk.get(n)??[]).slice().sort((e,t)=>{let n=Number(tT.has(t.id))-Number(tT.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!nS)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(nS)||t.toLowerCase().includes(nS),o=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(nS));return s||0!==o.length?[{project:e,key:n,name:i,sessions:s?a:o,hidden:r?.hidden===!0}]:[]}),nT=[],nI=[];for(let e of nN){let t=e.key===np||(nj.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?nI.push(e):nT.push(e)}let nM={running:0,unread:0};for(let e of nI){let t=nj.get(e.key);t&&(nM.running+=t.running,nM.unread+=t.unread)}let nR=nC||eW,nE=[...nT.map(e=>({kind:"project",group:e})),...nI.length>0?[{kind:"temporary"}]:[],...nR?nI.map(e=>({kind:"project",group:e})):[]],n$=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nE.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nL=(0,i.useMemo)(()=>tM?H.filter(e=>(function(e,t,n,r=E){if(e.transient||e.trial)return!1;if(r.has(e.id))return!0;if(t.has(e.id))return!1;let i=M(e);return null!==i&&i>(n.opened[e.id]??n.since)})(e,tw,tM,tj)):[],[tM,tw,H,tj]),nP=tE&&null!==tM,[nA,n_]=(0,i.useState)(null),nF=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),c=l.filter(e=>a.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(p>=o)continue;p+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=u.get(r);i?i.push(e):u.set(r,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:i,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:u.get(e)??[]});return h})(nP?H.filter(e=>e.id===nA&&!tw.has(e.id)||nL.includes(e)):H,tw,new Date,F,_("navigator.priority"),tT,_("sidebar.pinned"),nP?1/0:void 0),[nA,F,tT,nL,nP,tw,H,_]),nz=(0,i.useCallback)(e=>{n_(e.id),nn(e)},[nn]),nW=!!(e8?.isGit&&e8.isTopLevel&&G&&nu===e8.projectRoot),nO=e8?.worktrees.find(e=>e.path===G)??e8?.worktrees.find(e=>e.isMain),nD=(e8?.worktrees.length??0)>=8,nH=nD&&eJ.trim()?(e8?.worktrees??[]).filter(e=>(e.branch??eu(e.path,Y)).toLowerCase().includes(eJ.trim().toLowerCase())):e8?.worktrees??[],nU=ei[F.startsWith("ko")?"ko":F.startsWith("zh")?"zh":"en"],nB=function(e){if(e&&"u">typeof sessionStorage)try{return JSON.parse(sessionStorage.getItem(`cuelo:worktree:${e}`)??"null")??void 0}catch{return}}(G),nq=(()=>{if(!tO)return[];let e="project"===tO.kind?nk.get(L(tO.project))??[]:nF.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nV=nq.filter(e=>!tw.has(e.id)),nK=e=>{let t=new Set;for(let n of e)n.transient||tw.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nG=void 0!==m&&f,nJ=void 0!==x&&v,nZ=nG||nJ;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eY&&(0,r.jsx)(ee?Q:J,{busy:e1,error:eQ,onCancel:()=>{eX(!1),e0(null)},onSelect:e=>void t7(e)}),tO&&(0,r.jsx)(ev,{scope:tO,eligible:nV.length,runningExcluded:nq.length-nV.length,busy:tH,error:tB,onCancel:tV,onConfirm:()=>void tK(nV)}),(0,r.jsxs)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ef,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>nr(),disabled:!G,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:G?"var(--text-muted)":"var(--text-dim)",cursor:G?"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:G?_("sidebar.newSessionTitle",{path:G}):_("sidebar.selectProject"),"aria-label":G?_("sidebar.newSessionTitle",{path:G}):_("sidebar.selectProject"),onMouseEnter:e=>{G&&(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=G?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${tb?" is-success":""}`,onClick:()=>tz(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:tb?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${tb?"rgba(74,222,128,0.4)":"var(--border)"}`,color:tb?"#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=>{tb||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{tb||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:_("sidebar.refresh"),children:tb?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]}),nW&&(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),ni()},style:{marginTop:8},children:[(0,r.jsx)("label",{htmlFor:"session-issue",style:{display:"block",fontSize:12,color:"var(--text-muted)"},children:nU.issueLabel}),(0,r.jsxs)("div",{style:{display:"flex",gap:4,marginTop:4},children:[(0,r.jsx)("input",{id:"session-issue",value:tr,disabled:ta,onChange:e=>{ti(e.target.value),tl(null)},placeholder:nU.issuePlaceholder,"aria-describedby":to?"session-issue-error":void 0,"aria-invalid":!!to,style:{minWidth:0,flex:1,padding:"6px 8px",fontSize:12,background:"var(--bg)",color:"var(--text)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)"}}),(0,r.jsx)("button",{type:"submit",disabled:ta||!tr.trim(),title:nU.issueStart,"aria-label":nU.issueStart,style:{minWidth:32,padding:"4px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:ta?"wait":"pointer"},children:ta?"…":"↵"})]}),ta&&(0,r.jsx)("div",{role:"status",style:{fontSize:12},children:nU.issueBusy}),to&&(0,r.jsx)("div",{id:"session-issue-error",role:"alert",style:{fontSize:12,color:"var(--danger)",overflowWrap:"anywhere"},children:to})]}),(nB||nO&&!nO.isMain)&&(0,r.jsxs)("div",{role:"status",title:G??void 0,style:{marginTop:4,fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:[nB?.branch??nO?.branch,nB?.fallback&&(0,r.jsx)("div",{children:nU.fallbackBase.replace("{branch}",nB.base)}),nB?.missingSubdirectory&&(0,r.jsx)("div",{children:ea[F.startsWith("ko")?"ko":F.startsWith("zh")?"zh":"en"].replace("{path}",nB.missingSubdirectory)})]})]}),ee&&!nZ&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:t9,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:_("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":_("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?_("sidebar.projects"):_("navigator.priority"),n=!nZ&&eb===e;return(0,r.jsx)("button",{type:"button","aria-label":_("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tX(e),nG&&g?.(!1),nJ&&b?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":_("navigator.view",{label:w("translator.tab")}),"aria-pressed":nG,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!nG),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:nG?"var(--bg-selected)":"transparent",color:nG?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nG?600:500,whiteSpace:"nowrap"},children:w("translator.tab")}),void 0!==x&&(0,r.jsx)("button",{type:"button","aria-label":_("navigator.view",{label:_("routines.tab")}),"aria-pressed":nJ,"aria-controls":"navigator-routine-panel","data-navigator-mode":"routine",onClick:()=>b?.(!nJ),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:nJ?"var(--bg-selected)":"transparent",color:nJ?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nJ?600:500,whiteSpace:"nowrap"},children:_("routines.tab")})]}),!nZ&&"projects"===eb&&(0,r.jsx)("button",{type:"button",onClick:()=>ez(e=>!e),disabled:!nx,title:_("sidebar.projectShowHidden"),"aria-label":_("sidebar.projectShowHidden"),"aria-pressed":eF,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eF?"var(--bg-selected)":"transparent",color:eF?"var(--accent)":"var(--text-dim)",cursor:nx?"pointer":"default",opacity:nx?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eF&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nZ&&"projects"===eb&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:t9,title:_("sidebar.addProject"),"aria-label":_("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,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),nG&&m,nJ&&x,!nZ&&"projects"===eb&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:en,onChange:e=>em(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),em(""),e.currentTarget.blur())},placeholder:_("sidebar.searchProjectsAndSessions"),"aria-label":_("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}})]}),!nZ&&"projects"===eb&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(U||!eA)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:_("sidebar.loading")}),V&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:V}),eK&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eK}),!U&&eA&&!V&&0===nN.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nS?_("sidebar.noMatchingProjects"):_("sidebar.noSessions")}),!U&&eA&&!V&&nE.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":nR,title:_("sidebar.temporaryProjects"),onClick:()=>eO(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:nR?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nI.length}),eN(nM,_)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===np,p=n$.has(l.toLowerCase())&&eu((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),Y)||null,h=!eT.has(s)&&!nS,m=eS.has(s),f=eD===s,g=ng.indexOf(s),x=eq||nC||g<=0,v=eq||nC||g>=ng.length-1,b=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?c:c.slice(0,5)),y=c.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:eE===s?tm:void 0,onMouseEnter:()=>eR(s),onMouseLeave:()=>eR(e=>e===s&&eE!==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,r.jsx)("button",{type:"button",onClick:()=>nd(s),title:h?_("sidebar.expandProject"):_("sidebar.collapseProject"),"aria-label":h?_("sidebar.expandProject"):_("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:tg,value:eU,onChange:e=>eB(e.target.value),onBlur:()=>void ny(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tx.current=!0,eH(null))},"aria-label":_("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,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>Z(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),eN(nj.get(o),_)]}),(0,r.jsx)("button",{type:"button",onClick:()=>nr(s),title:_("sidebar.newSessionTitle",{path:s}),"aria-label":_("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||eM===s?1:0,pointerEvents:W||eM===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>eR(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{e$(eE===s?null:s),e6(!1),e7(!1),tn(null),u||Z(s)},title:_("sidebar.projectActions"),"aria-label":_("sidebar.projectActions"),"aria-expanded":eE===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eE===s?"var(--bg-selected)":"transparent",color:u&&nO&&!nO.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:W||eM===s||eE===s?1:0,pointerEvents:W||eM===s||eE===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>eR(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(eh,{open:eE===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:[nW&&e8&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>e6(e=>!e),title:nO?_("sidebar.switchWorktreeTitle",{path:nO.path}):_("sidebar.switchWorktree"),"aria-label":_("sidebar.worktrees"),"aria-expanded":e5,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:e5?"1px solid var(--border)":"none",background:e5?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:_("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(eh,{open:e5,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:[nD&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eJ,onChange:e=>eZ(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eZ(""),e6(!1))},placeholder:_("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,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[nH.map(e=>{let t=e.path===G||e.isMain&&!e8.worktrees.some(e=>e.path===G);return tp===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void nt(e.path,!0),disabled:td,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:_("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>th(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:_("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{Z(e.path),e6(!1),tn(null),eZ("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(ep,{text:e.branch??eu(e.path,Y),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:_("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void nt(e.path,!1),disabled:td,title:_("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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nD&&0===nH.length&&eJ.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:_("sidebar.noMatchingWorktrees")})]}),e3?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:tf,value:e9,onChange:e=>{te(e.target.value),tn(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),ne()),"Escape"===e.key&&(e7(!1),te(""),tn(null))},placeholder:_("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,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void ne(),disabled:td||!e9.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:td||!e9.trim()?"not-allowed":"pointer",opacity:td||!e9.trim()?.65:1},children:td?_("sidebar.creating"):_("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e7(!1),te(""),tn(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:_("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e7(!0),tn(null),setTimeout(()=>tf.current?.focus(),0)},title:_("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:_("sidebar.newWorktree")})]}),tt&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:tt})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eq,onClick:()=>{let e;return e=nh.get(L(s))?.alias??"",void(tx.current=!1,eG(null),eB(e),eH(s),nv())},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:eq?"default":"pointer",textAlign:"left",fontSize:11,opacity:eq?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),_(nh.get(L(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:nC?_("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nw(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),_("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:nC?_("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nw(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),_("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eq,onClick:()=>void nb(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:eq?"default":"pointer",textAlign:"left",fontSize:11,opacity:eq?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),_(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nK(nk.get(o)??[])||tH,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{nv(),tq(null),tD({kind:"project",project:s,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),_("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:_("sidebar.noSessions")}),!h&&b.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:b.map(t=>(0,r.jsx)(ek,{node:t,selectedSessionId:e,runningSessionIds:tw,unreadSessionIds:tC,pinnedSessionIds:tT,onSelectSession:nn,onTogglePinnedSession:tQ,onRenamed:tz,onSessionDeleted:tW,onSessionArchived:tZ,depth:0},t.session.id))}),!h&&y&&(0,r.jsx)("button",{type:"button",onClick:()=>{eC(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?_("sidebar.showLess"):_("sidebar.showMore")})]},s)})]}),!nZ&&(0,r.jsx)(ew,{refreshKey:tG,selectedSessionId:e,onSelectSession:nn,onRestored:tZ}),!nZ&&"priority"===eb&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[U&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:_("sidebar.loading")}),V&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:V}),!U&&!V&&(y=nK(nF.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:na,onClick:()=>void nc(),title:_("sidebar.newScratchSessionTitle"),style:ed(na,W),children:_("sidebar.newScratchSession")}),nF.length>0&&!nP&&(0,r.jsx)("button",{type:"button",disabled:0===y||tH,onClick:()=>{tq(null),tD({kind:"priority"})},style:ed(0===y||tH,W),children:_("sidebar.clearPriorityList")})]})),!U&&!V&&tM&&(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,r.jsxs)("button",{type:"button","aria-pressed":nP,"aria-label":_("navigator.resultsToCheckCount",{count:nL.length}),title:_("navigator.resultsToCheckHint"),onClick:()=>{n_(null),t$(e=>!e)},style:{...ed(!1,W),display:"inline-flex",alignItems:"center",gap:6,borderColor:nP?"var(--border-strong)":"var(--border)",background:nP?"var(--bg-selected)":"transparent",color:nP||nL.length>0?"var(--text)":"var(--text-muted)",fontWeight:nP?600:500,whiteSpace:"nowrap"},children:[_("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:nL.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nL.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nL.length})]}),nL.some(e=>!tj.has(e.id))&&(0,r.jsx)("button",{type:"button",title:_("navigator.acknowledgeResultsHint"),onClick:()=>{n_(null),tR(e=>e&&function(e,t,n){let r=e;for(let e of t)r=R(r,e,n);return r}(e,nL,Date.now()))},style:ed(!1,W),children:_("navigator.acknowledgeResults")})]}),no&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:no}),!U&&!V&&0===nF.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nP?_("navigator.resultsToCheckEmpty"):_("sidebar.noSessions")}),!U&&!V&&nF.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(ey,{session:t,selected:t.id===e,running:tw.has(t.id),waiting:tj.has(t.id),unread:tC.has(t.id),pinned:tT.has(t.id),onSelect:nP?nz:nn,onTogglePin:tQ},t.id))]},t.key))]})]})}function ev({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,z.s)(),d=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let m=(0,i.useRef)(o);return m.current=o,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function eb({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ey({session:e,selected:t,running:n,waiting:i,unread:a,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,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>o(e),title:`${d}
|
|
2
2
|
${e.cwd}
|
|
3
3
|
${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:d}),i&&(0,r.jsx)(ej,{}),n&&!i&&(0,r.jsx)(eS,{}),!n&&a&&(0,r.jsx)(eC,{})]}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:u})]}),(0,r.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,r.jsx)(eb,{filled:s})})]})}function ew({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:a}){let{t:s}=(0,z.s)(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||d(n.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,i.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),a(t)}catch{}},[a]);return 0!==c.length||o?(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:o?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),s("sidebar.archived")," (",c.length,")"]}),o&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===c.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:s("sidebar.noArchivedSessions")}),c.map(e=>{let i=F(e.firstMessage)??e.firstMessage,a=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function ek({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:o,onRenamed:l,onSessionDeleted:c,onTogglePinnedSession:d,onSessionArchived:u,depth:p}){let[h,m]=(0,i.useState)(!1),f=e.children.length>0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(eT,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:a.has(e.session.id),isPinned:s.has(e.session.id),onClick:()=>o(e.session),onTogglePin:()=>d(e.session.id),onRenamed:l,onDeleted:e=>c?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:f,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),f&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ek,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:o,onTogglePinnedSession:d,onRenamed:l,onSessionDeleted:c,onSessionArchived:u,depth:p+1},e.session.id))})]})}function ej(){let{t:e}=(0,z.s)();return(0,r.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 eS(){let{t:e}=(0,z.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function eC(){let{t:e}=(0,z.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function eN(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,r.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function eT({session:e,isSelected:t,isRunning:n,isUnread:a,isPinned:s,onClick:o,onTogglePin:l,onRenamed:c,onDeleted:d,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:f}){let{t:g}=(0,z.s)(),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),T=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>T.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let I=F(e.firstMessage)??e.firstMessage,M=e.name||I.slice(0,50)||e.id.slice(0,12),R=(0,i.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]),E=(0,i.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[w,e.id,e.name,c,M]),$=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),d?.(e.id)}catch{N(!1)}}},[e.id,e.transient,d]),L=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),P=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?$():S(!0)},[$]),A=(0,i.useCallback)(e=>{e.stopPropagation(),$()},[$]),_=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),W=(0,i.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}${j?" is-confirming":""}`,onClick:j||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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:A,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick:_,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,r.jsx)("input",{ref:T,value:w,onChange:e=>k(e.target.value),onBlur:E,onKeyDown:e=>{"Enter"===e.key&&E(),"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,r.jsxs)(r.Fragment,{children:[p>0&&(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),o()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(eS,{}),!n&&a&&(0,r.jsx)(eC,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{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,r.jsx)(eb,{filled:s})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:R,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,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:P,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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let eI=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eM=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eR=/\x1B\[([0-9;]*)m/g,eE=/\x1B_pi:c\x07/g,e$=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eL=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function eP(e){return e.replace(eE,"").replace(eI,"")}function eA(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eM);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function e_(e,t){let n=eA(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eF(e){return eA(e)[0]?.char}function ez(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(eE,""),i=eP(e).trimEnd();if(t.test(i))continue;let a=e,s=eF(a);("│"===s||"┃"===s)&&" "===eF(a=e_(a,0))&&(a=e_(a,0));let o=function(e){let t=eA(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),l=o>=0?eA(a)[o]?.char:void 0;("│"===l||"┃"===l)&&(a=e_(a,o)),n.push(function(e){let t=e;for(;;){let e=eA(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(a))}for(;n.length>0&&""===eP(n[0]).trim();)n.shift();for(;n.length>0&&""===eP(n[n.length-1]).trim();)n.pop();return n.length?n:e}function eW(e){let t,n=[],r={},i=0;for(eR.lastIndex=0;null!==(t=eR.exec(e));)t.index>i&&n.push({text:e.slice(i,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=e$[r-30];else if(r>=90&&r<=97)n.color=eL[r-90];else if(r>=40&&r<=47)n.backgroundColor=e$[r-40];else if(r>=100&&r<=107)n.backgroundColor=eL[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,a,s]=[t[e+2],t[e+3],t[e+4]];[i,a,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${a}, ${s})`:n.backgroundColor=`rgb(${i}, ${a}, ${s})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return e$[e];if(e>=8&&e<16)return eL[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(n)}, ${i(r)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===r?n.color=i:n.backgroundColor=i),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&n.push({text:e.slice(i),style:r}),n}let eO={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:""},eD={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eH={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"},eU={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 eB(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eq(e){return null!==(eH[eB(e)]??null)}function eV(e){let t;return null!==("pdf"===(t=eB(e))||"docx"===t?t:null)}function eK(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eG(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 eJ(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eZ(e,t){let n=e[t];if(n?.role!=="assistant"||"error"!==n.stopReason)return!1;for(let n=t+1;n<e.length;n++){let t=e[n].role;if("user"===t)break;if("assistant"===t)return!0}return!1}function eY(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eG(e,t))}(e,t)){let e="image"===r.type||"text"===r.type&&r.text.trim().length>0?"answer":"process",t=n[n.length-1];t?.kind===e?t.blocks.push(r):n.push({kind:e,blocks:[r]})}return n}function eX(e){return e.filter(e=>"toolCall"===e.type).length}let eQ=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function e0(e){let t=0,n=0;for(let r of e)eQ.test(r)?t++:n++;return t+n/4}function e1(e){return"text"===e.type?e.text:"thinking"===e.type?e.thinking:"toolCall"===e.type?JSON.stringify(e.input??{})??"":null}function e2(e,t){if(!e)return e0(t);let n=Math.min(e.text.length,t.length),r=0;for(;r<n&&e.text.charCodeAt(r)===t.charCodeAt(r);)r++;let i=r>0?t.charCodeAt(r-1):0;return i>=55296&&i<=56319&&r--,e.tokens-e0(e.text.slice(r))+e0(t.slice(r))}function e8(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}let e4=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function e5(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let a of i)"toolCall"===a.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===n.path;if("eval"===e.toolName){let e;return e=t.content?.at(-1),e?.type==="text"&&e4.test(e.text)}return"read"===e.toolName&&"string"==typeof n.path&&eq(n.path)}(a,t.get(a.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:a.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let e6=new Map,e3=new Map,e7="[한국어 번역]\n";function e9(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function te(e){if("custom"!==e.role||"korean-reply-translation"!==e.customType)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let n="sourceTimestamp"in t&&"number"==typeof t.sourceTimestamp?t.sourceTimestamp:void 0,r="sourceHash"in t&&"string"==typeof t.sourceHash?t.sourceHash:void 0;return void 0===n&&void 0===r?null:{sourceTimestamp:n,sourceHash:r}}let tt="command",tn="autolearn-saved";function tr(e){return"custom"===e.role&&(e.customType===tt||e.customType===tn&&!1!==e.display)}function ti(e,t){let n=e[t];if(n?.role!=="custom"||"user-input-translation"!==n.customType)return -1;for(let n=t-1;n>=0;n--)if("user"===e[n].role)return n;return -1}let ta="local-command:";function ts(e){return e?.startsWith(ta)===!0}function to(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],a=[];for(let n=0;n<e.length;n++){let s=n<t.length;!(r.has(e[n])||s&&ts(t[n]))&&(i.push(e[n]),s&&a.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=a.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=a.length&&a.splice(t,0,e.entryId)}return{messages:i,entryIds:a}}function tl(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let tc={create:!0,update:!0};function td(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function tu(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let n of e)n&&"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&"string"==typeof n.text&&t.push(n.text);return t.join("\n")}function tp(e,t){if(0===e.length)return -1;if(!t)return 0;let n=-1;for(let r=0;r<e.length;r++){let i=e[r];if(i.item===t.item){if(i.k===t.k)return r;n=r}}return -1===n?0:n}function th(e){try{return decodeURIComponent(e)}catch{return e}}function tm(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tf(e){let t=tm(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,a=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){a.length>0&&".."!==a[a.length-1]?a.pop():i||n||r||a.push(e);continue}a.push(e)}let s=a.join("/");return n?s:r?`//${s}`:i?`/${s}`:s}function tg(e,t,n=t){let r,i,a,s,o;if(!e)return null;let l=e.split("#",1)[0].split("?",1)[0].trim();if(!l)return null;let c=null,d=null,u=th(l),p=u.startsWith("\\\\"),h=tm(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=th(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(c=h,d="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(c=`${tm(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let f=tf(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&n&&(r=tf(f).replace(/\/+$/,""),i=tf(n).replace(/\/+$/,""),s=(a=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(s===(o=a?i.toLowerCase():i)||s.startsWith(`${o}/`)))?null:f}function tx(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,a=i(e),s=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(a),l=a.startsWith("//");if(o||l)n=a;else if(a.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${a}`:a}else{if(!s)return null;n=`${s}/${a}`}return tf(n)}function tv(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function tb(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 ty(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tw(e,t){if(!e||"object"!=typeof e||"delete"===e.op&&!t)return null;let n=e.path??e.resolvedPath;return"string"==typeof n&&n.length>0?n:null}function tk(e,t,n=!1){let r=t.details,i=ty(e);if(i)return!n&&r&&"object"==typeof r&&"delete"===r.op?[]:[i];if(!r||"object"!=typeof r)return[];if(Array.isArray(r.perFileResults))return r.perFileResults.map(e=>tw(e,n)).filter(e=>null!==e);let a=tw(r,n);return a?[a]:[]}function tj(e,t){let n=ty(e);return(t?tk(e,t,!0):n?[n]:[]).filter(tI)}function tS(e,t,n){let r=tj(e,t);return r.length>0&&r.every(e=>tT(e,n))}let tC=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])),tN=[/^\/(?: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 tT(e,t){let n=tx(e,t),r=t?tx(t)?.replace(/\/+$/,""):void 0,i=n??e.replace(/\\/g,"/"),a=/^(?:[a-zA-Z]:\/|\/\/|\/mnt\/[a-zA-Z](?:\/|$))/.test(i)||void 0!==r&&/^(?:[a-zA-Z]:\/|\/\/)/.test(r),s=e=>a?e.toLowerCase():e,o=null===n||void 0!==r&&(s(n)===s(r)||s(n).startsWith(`${s(r)}/`));return!!function(e,t){let n=(e,n)=>void 0!==e&&(t?e.toLowerCase()===n:e===n),r=e.findIndex(e=>n(e,".omp"));if(r<0||r===e.length-1)return!1;let i=e[r+1];if(n(i,"agent")||n(i,"wt")||n(i,"profiles")&&n(e[r+3],"agent"))return!1;let a=tC.get(i.toLowerCase());return!(void 0!==a&&(t||a===i))}((null!==n&&o&&void 0!==r?n.slice(r.length):i).split("/").filter(e=>""!==e&&"."!==e),a)||!o&&tN.some(e=>e.test(i))}function tI(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tM(e,t,n){let r=new Set,i=[];for(let s of e){var a;if("toolCall"!==s.type||!(tv(a=s.toolName)||tb(a)))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of tk(s.input,e)){if(!tI(t))continue;let e=tx(t,n);!(!e||tT(t,n))&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}function tR(e){let t=[];for(let n of e){if(!n||"object"!=typeof n||!("name"in n)||!("tasks"in n))return{phases:t,malformed:!0};let{name:e,tasks:r}=n;if("string"!=typeof e||!Array.isArray(r))return{phases:t,malformed:!0};let i=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;if("string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n)return[];let r="blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0,i="dependsOn"in e&&Array.isArray(e.dependsOn)?e.dependsOn.filter(e=>"string"==typeof e):[];return[{content:t,status:n,blocker:r,...i.length>0?{dependsOn:i}:{}}]}):[];if(i.length!==r.length)return{phases:t,malformed:!0};i.length>0&&t.push({name:e,tasks:i})}return{phases:t,malformed:!1}}function tE(e){if(!Array.isArray(e))return null;let{phases:t,malformed:n}=tR(e);return n?null:t}function t$(e,t){var n;let r;if(t){let e=t.details,n=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(n))return{kind:"unknown"};let{phases:r,malformed:i}=tR(n);return i?{kind:"unknown"}:{kind:"authoritative",phases:r}}let i=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}function tL(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}function tP(e,t,n=null,r=null){return n||(function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n],i=r.trackerTodos??[];for(let e=i.length-1;e>=0;e-=1){let t=tE(i[e]);if(t)return t}if("assistant"!==r.role)continue;let a=r.content;if(Array.isArray(a))for(let e=a.length-1;e>=0;e-=1){let n=a[e];if("toolCall"!==n.type||!tL(n.toolName))continue;let r=t$(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function tA(e,t){if(!e.dependsOn?.length)return[];let n=new Set(t.flatMap(e=>e.tasks.filter(e=>"completed"===e.status).map(e=>e.content)));return e.dependsOn.filter(e=>!n.has(e))}function t_(e){let t=0,n=0,r=null,i=null,a=null;for(let s of e)for(let o of s.tasks){if("completed"===o.status){t+=1;continue}"abandoned"!==o.status&&(n+=1,tA(o,e).length>0?a||(a={phase:s,task:o}):"in_progress"===o.status?r||(r={phase:s,task:o}):"blocked"===o.status?a||(a={phase:s,task:o}):i||(i={phase:s,task:o}))}let s=r??i??a,o=t+n;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:n,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}function tF(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tz(e){return tF(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tW(e){let t=tF(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tO(e,t){if(!t)return e;let n=tF(e),r=tF(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var tD=n(65063),tH=n(7644),tU=n(32316),tB=n(88374),tq=n(63280),tV=n(94764),tK=n(63835),tG=n(54152),tJ=n(84678),tZ=n(98164);let tY={...tV.j,attributes:{...tV.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...tV.j.strip||[],"iframe","object","style","form"]};function tX(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,a=0,s=null,o=new Map;for(let e=0;e<n.length;e++){var l;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},a=0,r.push(t);continue}if(i){r.push(t);continue}let d=t.match(/<(code|pre|script|style)\b/i);if(d){let e=d[1].toLowerCase(),n=t.slice((d.index??0)+d[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(s=e),a=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){a=0,r.push(t);continue}if(a||t.includes("`")){a=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,a),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>t0(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],i=m[2].trimEnd();if(i&&!i.includes("$$")){let a=tQ(n,e+1,t,o);if(a){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<a.index;i++)r.push(t0(n[i],t));a.content&&r.push(`${t}${a.content}`),r.push(`${t}$$`),e=a.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],i=tQ(n,e+1,t,o);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let a=e+1;a<i.index;a++)r.push(t0(n[a],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((l=t,/^\s{0,3}\[[^\]]+\]:/.test(l)||/]\s*\(/.test(l)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(l)||/\b(?:https?|file|mailto):/i.test(l)||/\b[A-Za-z]:\\/.test(l)?l:l.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function tQ(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var a,s,o,l;let t=e[i];if(a=t,""===(s=n)?/^ {0,3}\$\$\s*$/.test(a):a.startsWith(s)&&/^\$\$\s*$/.test(a.slice(s.length)))return{index:i,content:"",glued:!1};if(o=t,/^ {0,3}(`{3,}|~{3,})/.test(o)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(o)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(o)||/^ {0,3}>/.test(o)||/<(code|pre|script|style)\b/i.test(o)||(l=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(l)))return r.set(n,i),null;let c=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==c)return{index:i,content:c,glued:!0}}return r.set(n,e.length),null}function t0(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let t1={singleTilde:!1},t2=[[tG.A,["yaml"]],[tJ.A,t1],tZ.A],t8=[[tG.A,["yaml"]],[tJ.A,t1],tZ.A],t4=[tq.A,[tK.A,tY],[tB.A,{throwOnError:!1,strict:!1}]],t5=[tq.A,[tK.A,tY],[tB.A,{throwOnError:!1,strict:!1}]],t6="pi-theme",t3=["light","dark","auto"],t7={preference:"auto",theme:"light"},t9="omp-theme",ne=null,nt=0,nn=new Set,nr=null,ni=!1;function na(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ns(e){return"auto"===e?na():e}let no="--omp-md-";function nl(e){let t=document.documentElement,n=ne?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let n=t.style.item(e);n.startsWith("--")&&!n.startsWith(no)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(no)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(t9,e)}catch{}}function nc(){if(nr)return nr;let e=function(){try{let e=localStorage.getItem(t6);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(t9);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=ns(e);return nl(t),nr={preference:e,theme:t}}function nd(e,t,n){if(nl(t),n)try{localStorage.setItem(t6,e)}catch{}nr={preference:e,theme:t},nn.forEach(e=>e())}function nu(){let e=nc();if("auto"!==e.preference)return;let t=na();t!==e.theme&&nd("auto",t,!1)}function np(e){return nn.add(e),nc(),ni||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",nu),window.addEventListener("focus",nu),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&nu()}),ni=!0),nu(),()=>{nn.delete(e)}}function nh(){return nc()}function nm(){return t7}async function nf(e){let t=++nt,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/theme${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Theme request failed (${r.status})`);let i=await r.json();if(t===nt){ne=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(ne))}catch{}nl(nc().theme)}}function ng(e){let t=(0,i.useSyncExternalStore)(np,nh,nm);(0,i.useEffect)(()=>{e?.syncWithOmp&&nf(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=ns(e),r=()=>{nd(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let a=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(a,window.innerWidth-a),Math.max(s,window.innerHeight-s));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${a}px ${s}px)`,`circle(${o}px at ${a}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=nc().preference,r=t3.indexOf(t),t3[(r+1)%t3.length]),e)},[n]),a=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:a,isDark:"dark"===t.theme}}function nx(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 nv={...tH.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tH.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function nb({code:e,isStreaming:t}){let{isDark:a}=ng(),{t:s}=(0,z.s)(),[o,l]=(0,i.useState)(!0),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=`${a?"dark":"light"}
|
|
4
4
|
${e}`,m=o&&!t;(0,i.useEffect)(()=>{if(!m)return;let t=!1;return d({key:h,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328)),i=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${i}`,e),await document.fonts.ready,t)return;if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:a?"dark":"default",fontFamily:i}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let s="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await r.render(s,e);t||d({key:h,status:"ready",svg:o.svg})})().catch(()=>{t||d({key:h,status:"error"})}),()=>{t=!0}},[e,h,a,m]);let f=(0,i.useMemo)(()=>(0,r.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,r.jsx)(nw,{code:e,lang:"mermaid",headerAction:f,isStreaming:t});let g=c?.key===h&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==h||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!u&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openMermaidViewer"),"aria-label":s("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),u&&(0,r.jsx)(ny,{svg:c.svg,onClose:()=>p(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),f]}),g]})}function ny({svg:e,onClose:t}){let{t:n}=(0,z.s)(),a=(0,i.useRef)(null),[s,o]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:s>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>o(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let nw=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:a}){let{isDark:s}=ng(),{t:o}=(0,z.s)(),[l,c]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{nx(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),a?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(tD.A,{language:t||"text",style:s?tH.xJ:nv,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 nk({children:e,className:t,isStreaming:n,cwd:a,onOpenFile:s}){let o=(0,i.useMemo)(()=>tX(e),[e]),l=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let a=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===a?(0,r.jsx)(nb,{code:s.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(nw,{code:s.replace(/\n$/,""),lang:a,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=s?tg(e,a):null;return i&&s?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?tg(e,a):null,s=i?`/api/files/${tz(i)}?type=read`:e;return(0,r.jsx)("img",{src:s,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[a,n,s]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(tU.oz,{remarkPlugins:t2,rehypePlugins:t4,components:l,children:o})})}function nj(e){let[t,n]=(0,i.useState)(()=>Date.now());return(0,i.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}let nS=new Map,nC=new Set;function nN(){nC.forEach(e=>e())}function nT(e){return nC.add(e),()=>{nC.delete(e)}}function nI(e,t){return e&&t?`${e}\u0000${t}`:null}function nM(e){let t=!1;for(let n of e)t=nS.delete(n)||t;t&&nN()}var nR=n(54265);let nE=(0,i.createContext)(null);function n$(e,t,n){return Math.min(n,Math.max(t,e))}function nL(e,t,n){let r=t.width>0?n.width/t.width:0,i=t.height>0?n.height/t.height:0;return{x:n$((e.x-t.left)*r,0,n.width),y:n$((e.y-t.top)*i,0,n.height)}}function nP(e){let t=n$(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let nA="#e5191f",n_="#ffffff";function nF(e){let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.toBlob(e=>e?n(e):r(Error("canvas encode failed")),"image/png"),t}function nz(e,t){let n=document.createElement("canvas");n.width=e,n.height=t;let r=n.getContext("2d");if(!r)throw Error("canvas 2d unavailable");return[n,r]}async function nW(e,t){let n=await createImageBitmap(e);try{let e={width:n.width,height:n.height},{inner:r,outer:i}=nP(e),a=Math.max(14,7*nP(e).inner),[s,o]=nz(e.width,e.height);o.drawImage(n,0,0),t.forEach((t,n)=>{let s=function(e,t){let{inner:n,outer:r}=nP(t),i=(n,r)=>{let i=n$(e.x-n,r,t.width-r),a=n$(e.y-n,r,t.height-r),s=n$(e.x+e.w+n,r,t.width-r);return{x:i,y:a,w:Math.max(0,s-i),h:Math.max(0,n$(e.y+e.h+n,r,t.height-r)-a)}};return{inner:i(n/2,n/2),outer:i(n+r/2,r/2)}}(t,e);o.lineJoin="miter",o.strokeStyle=n_,o.lineWidth=i,o.strokeRect(s.outer.x,s.outer.y,s.outer.w,s.outer.h),o.strokeStyle=nA,o.lineWidth=r,o.strokeRect(s.inner.x,s.inner.y,s.inner.w,s.inner.h);let l=String(n+1);o.font=`700 ${a}px sans-serif`;let c=Math.round(.35*a),d=Math.ceil(o.measureText(l).width)+2*c,u=Math.round(1.3*a),p=Math.min(Math.max(0,t.x-r),e.width-d),h=t.y-r-u,m=h>=0?h:Math.min(t.y,e.height-u);o.fillStyle=n_,o.fillRect(p-1,m-1,d+2,u+2),o.fillStyle=nA,o.fillRect(p,m,d,u),o.fillStyle=n_,o.textBaseline="middle",o.textAlign="center",o.fillText(l,p+d/2,m+u/2)});let l=await Promise.all(t.map(t=>{let r=function(e,t,n=.12){let r=Math.round(e.w*n),i=Math.round(e.h*n),a=n$(e.x-r,0,t.width),s=n$(e.y-i,0,t.height),o=n$(e.x+e.w+r,0,t.width);return{x:a,y:s,w:o-a,h:n$(e.y+e.h+i,0,t.height)-s}}(t,e),[i,a]=nz(r.w,r.h);return a.drawImage(n,r.x,r.y,r.w,r.h,0,0,r.w,r.h),nF(i)}));return{marked:await nF(s),crops:l}}finally{n.close()}}function nO({src:e,regions:t,max:n,onAdd:a,onNaturalSize:s,regionLabel:o}){let l=(0,i.useRef)(null),[c,d]=(0,i.useState)(null),u=(0,i.useRef)(null),[p,h]=(0,i.useState)(null),m=e=>{let t=l.current,n=u.current;return t&&n&&c?function(e,t,n,r){let i=n$(Math.min(e.x,t.x),n.left,n.left+n.width),a=n$(Math.max(e.x,t.x),n.left,n.left+n.width),s=n$(Math.min(e.y,t.y),n.top,n.top+n.height),o=n$(Math.max(e.y,t.y),n.top,n.top+n.height);if(a-i<6||o-s<6)return null;let l=nL({x:i,y:s},n,r),c=nL({x:a,y:o},n,r),d=Math.floor(l.x),u=Math.floor(l.y),p=Math.min(r.width,Math.ceil(c.x))-d,h=Math.min(r.height,Math.ceil(c.y))-u;return p>0&&h>0?{x:d,y:u,w:p,h}:null}(n.start,e,t.getBoundingClientRect(),c):null},f=(e,t)=>{if(u.current?.pointerId!==e.pointerId)return;let n=t?m({x:e.clientX,y:e.clientY}):null;u.current=null,h(null),n&&a(n)};return(0,r.jsxs)("div",{className:"tool-image-marker","data-drawing":c&&t.length<n?"true":void 0,onPointerDown:e=>{c&&!(t.length>=n)&&("mouse"!==e.pointerType||0===e.button)&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),u.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY}})},onPointerMove:e=>{u.current?.pointerId===e.pointerId&&h(m({x:e.clientX,y:e.clientY}))},onPointerUp:e=>f(e,!0),onPointerCancel:e=>f(e,!1),children:[(0,r.jsx)("img",{ref:l,className:"tool-image-full",src:e,alt:"",draggable:!1,onLoad:e=>{let t={width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight};d(t),s(t)}}),c&&t.map((e,t)=>(0,r.jsx)(nD,{region:e,natural:c,label:String(t+1),title:o(t+1)},`${t}-${e.x}-${e.y}`)),c&&p&&(0,r.jsx)(nD,{region:p,natural:c})]})}function nD({region:e,natural:t,label:n,title:i}){let a={left:e.x/t.width*100,top:e.y/t.height*100,width:e.w/t.width*100,height:e.h/t.height*100};return(0,r.jsx)("span",{className:"tool-image-region","data-draft":n?void 0:"true",role:n?"img":void 0,"aria-label":i,style:{left:`${a.left}%`,top:`${a.top}%`,width:`${a.width}%`,height:`${a.height}%`},children:n&&(0,r.jsx)("span",{className:"tool-image-region-number","aria-hidden":"true",children:n})})}function nH(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}function nU(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}let nB=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,nq=/(?:\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 nV(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let nK={hideThinkingBlock:!1},nG=new Set,nJ=nK,nZ=0;function nY(e){return nG.add(e),()=>{nG.delete(e)}}function nX(){return nJ}function nQ(){return nK}async function n0(e){let t=++nZ,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/display-settings${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Display settings request failed (${r.status})`);let i=await r.json();t!==nZ||i.hideThinkingBlock!==nJ.hideThinkingBlock&&(nJ={hideThinkingBlock:!0===i.hideThinkingBlock},nG.forEach(e=>e()))}function n1(){return(0,i.useSyncExternalStore)(nY,nX,nQ)}function n2(e){let t=new Date(e),n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}let n8=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","MITSU(미츠)","SHION(시온)","HIKARI(히카리)"],n4={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","MITSU(미츠)":"mitsu","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},n5=["approval","choice","done","failed","blocked","working"],n6={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},n3={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0},n7="/api/office-characters/",n9={voice:"/audio/completion/",sticker:"/stickers/"};function re(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function rt(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(n6,e)?e:null}function rn(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:a,ko:s}=i;if("string"!=typeof e||""===e)continue;let o=rt(a);if(null===o)continue;let l=t+e.replace(/^\/+/,""),c=n.get(o);c?c.push(l):n.set(o,[l]),"string"==typeof s&&""!==s.trim()&&r.set(l,s.trim())}return{files:n,lines:r}}function rr(e,t=n9){let n=new Map;if("object"!=typeof e||null===e)return n;let{characters:r}=e;if(!Array.isArray(r))return n;for(let e of r){if("object"!=typeof e||null===e)continue;let{id:r,clips:i,stickers:a,captions:s}=e;if("string"!=typeof r||""===r)continue;let o=rn(i,t.voice),l=rn(a,t.sticker),c=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if("object"!=typeof n||null===n)continue;let{tag:e,ko:r}=n;if("string"!=typeof r||""===r.trim())continue;let i=rt(e);if(null===i)continue;let a=t.get(i);a?a.push(r.trim()):t.set(i,[r.trim()])}return t}(s),d=new Map;for(let e of n5){let t=o.files.get(e)??[],n=new Map;for(let e of t){let t=o.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:n,captions:c.get(e)??[]})}n.set(r,d)}return n}function ri(e,t,n){let r=t&&Object.hasOwn(n4,t)?n4[t]:null;return r?e.get(r)?.get(n)??null:null}function ra(e,t,n){return e.get(t)?.get(n)??null}async function rs(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return rr(await t.json())}catch{return new Map}}function ro(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,a=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&a>=r?a+1:a]}function rl(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let n of e.content)if("text"===n.type)t.push(n.text.trim());else if("toolCall"===n.type){let e="id"in n&&"string"==typeof n.id?n.id:"";t.push(`toolCall:${n.toolCallId||e}`)}}let n="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,n,t.filter(Boolean)])}function rc(e,t,n,r){if(t&&("web6"!==t.provider||t.model!==rd))return{provider:t.provider,model:t.model,credentialId:t.credentialId};for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role)break;if("assistant"===n.role&&("web6"!==n.provider||n.model!==rd))return{provider:n.provider,model:n.model,credentialId:n.credentialId}}return{provider:n,model:r,credentialId:void 0}}let rd="ChatGPT 6PRO",ru="/api/sidecars/resource";function rp(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},n=e=>{let n=t[e];return"number"==typeof n&&Number.isFinite(n)?n:null},r=n("usedFraction");if(null!==r&&r>=1)return!0;let i=n("remainingFraction");if(null!==i&&i<=0)return!0;let a=n("used"),s=n("limit");if(null!==a&&null!==s&&a>=s)return!0;let o=n("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==a&&a>=100}let rh=[{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"}],rm={"gemini-4-argon":"HIKARI(히카리)"},rf=[{seed:3,alias:rh[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:rh[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:rh[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:rh[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:rh[2].alias,provider:"hive",model:"zai-org/glm-5.3-flash",voice:"부지런한 배달\xb7통통 튀는 보고\xb7끈질긴 재도전",summonExample:"미츠 불러와",switchExample:"미츠로 교체해"},{seed:6,alias:rh[6].alias,provider:"google-vertex",model:"gemini-4-argon",voice:"빠른 관찰\xb7톡 쏘는 한마디\xb7장난스러운 여유",summonExample:"히카리 불러와",switchExample:"히카리로 교체해"},{seed:5,alias:rh[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],rg=rf.filter(e=>null!==e.switchExample),rx={mode:"default",rosterAvailable:!1,seats:[]},rv=rx,rb=new Map,ry=new Map,rw=rf,rk=new Set,rj=null,rS=0,rC=new Map,rN=new Map,rT=null,rI=!1;function rM(e){let t="office"===e.mode?e.seats.filter(e=>!rh.some(t=>t.alias===e.alias)&&"MITSU(미츠)"!==e.seat):[];rS+=1;let n=JSON.stringify([e.mode,e.rosterAvailable,t]);if(n!==rT)for(let r of(rT=n,rv={...e,seats:t},ry=new Map([...rb=new Map(t.flatMap(e=>{let t=rh.findIndex(t=>t.alias===e.seat);return t>=0?[[t,e]]:[]}))].flatMap(([e,t])=>{let n=rh[e];return"provider"in n&&!("model"in n)?[[n.provider,{seed:e,alias:t.alias}]]:[]})),rC=new Map([...rb].flatMap(([e,t])=>{let n=rh[e];return"model"in n?[[`${n.provider}/${n.model}`,{seed:e,alias:t.alias}]]:[]})),rN=new Map(Object.entries(rm).flatMap(([e,t])=>{let n=rh.findIndex(e=>e.alias===t),r=rb.get(n);return r?[[e,{seed:n,alias:r.alias}]]:[]})),rw=0===rb.size?rf:rf.map(e=>{let t,n,r,i=rb.get(rh.findIndex(t=>t.alias===e.alias));return i?(t=i.names.findLast(e=>/[가-힣]/.test(e))??i.names[0]??i.alias.split("(",1)[0],{...e,alias:i.alias,voice:i.voice.temperament.split(/(?<=[.。])\s/,1)[0].replace(/[.。]$/,""),summonExample:`${t} 불러와`,switchExample:`${r=(n=t.charCodeAt(t.length-1)-44032)>=0&&n<=11171?n%28:0,`${t}${0===r||8===r?"로":"으로"}`} 교체해`}):e}),rk))r()}function rR(){return rv}function rE(e){return rk.add(e),()=>{rk.delete(e)}}async function r$(e=fetch){let t=rS;try{let n=await e("/api/character-mode",{cache:"no-store"});if(!n.ok)return!1;let r=await n.json();if("object"!=typeof r||null===r)return!1;if(t!==rS)return!0;let{mode:i,rosterAvailable:a,seats:s}=r;return rM({mode:"office"===i?"office":"default",rosterAvailable:!0===a,seats:Array.isArray(s)?s:[]}),!0}catch{return!1}}let rL=new WeakMap;function rP(e){let t=rL.get(e);return t||(t=rr(e.manifest,{voice:n7,sticker:n7}),rL.set(e,t)),t}function rA(e){return e?rv.seats.find(t=>t.seat===e||t.alias===e)??null:null}function r_(e){return rv.seats.find(t=>t.seat===e)?.alias??e}let rF=rh.filter(e=>!("provider"in e)).length,rz=new Map(rh.flatMap((e,t)=>"provider"in e&&!("model"in e)?[[e.provider,t]]:[])),rW=new Map(rh.flatMap((e,t)=>"model"in e?[[`${e.provider}/${e.model}`,{seed:t,alias:e.alias}]]:[])),rO=new Map(Object.entries(rm).map(([e,t])=>[e,{seed:rh.findIndex(e=>e.alias===t),alias:t}])),rD=new Map([...rz].map(([e,t])=>[e,{seed:t,alias:rh[t].alias}])),rH=new Map(Object.entries({"google-antigravity":"HIKARI(히카리)"}).map(([e,t])=>[e,rh.findIndex(e=>e.alias===t)]));function rU(e,t){if(void 0===t)return null;let n=`${e}/${t}`;return rC.get(n)??rN.get(t)??rW.get(n)??rO.get(t)??null}function rB(e){return ry.get(e)??rD.get(e)??null}function rq(e){let t=e%rh.length;return rb.get(t)?.alias??rh[t].alias}function rV(e){let t=e%rh.length;return rb.get(t)?.faceUrl??`/avatars/${rh[t].file}`}function rK(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function rG(e){return({"openai-codex":"OpenAI Codex",anthropic:"Anthropic","google-gemini":"Google Gemini","github-copilot":"GitHub Copilot","opencode-go":"OpenCode Go",devin:"Devin","b-ai":"B.AI",web6:"WEB6"})[e]??e.replace(/(^|-)(\w)/g,(e,t,n)=>`${t?" ":""}${n.toUpperCase()}`)}function rJ(e){let t=new Map;for(let n of e){if(!Number.isSafeInteger(n.oauthPosition)||n.oauthPosition<0)continue;let e=t.get(n.provider)??new Set;e.add(n.oauthPosition),t.set(n.provider,e)}return e.map(e=>{var n;let r=e.metadata?.email,i=e.metadata?.accountId,a="string"==typeof r&&r.length>0?r:"string"==typeof i?i:"",s=a.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return rK(e);let n=e.slice(t+1),r=n.lastIndexOf("."),i=r<0?n:n.slice(0,r),a=r<0?"":n.slice(r);return`${rK(e.slice(0,t))}@${0===i.length?"":`${i[0]}•••`}${a}`}(a):"",o=(n=e.provider,rz.get(n)??-1);if(o>=0)return{seed:o,alias:rq(o),masked:s,raw:a};let l=e.oauthPosition;if(!Number.isSafeInteger(l)||l<0){let n=t.get(e.provider)??new Set;for(l=0;n.has(l);)l++;n.add(l),t.set(e.provider,n)}let c=rH.get(e.provider)??-1;if(c>=0)return{seed:c,alias:`${rq(c)}${l+1}`,masked:s,raw:a};let d=l%rF,u=l<rF?rq(d):`${rq(d)}${l+1}`;return{seed:d,alias:u,masked:s,raw:a}})}class rZ extends Error{constructor(e,t,n,r){super(e,r),this.kind=t,this.status=n,this.name="ResourceClientError",this.code=r?.code,this.outcomeUnknown=r?.outcomeUnknown}}function rY(e,t){return`${ru}${e}${t?"?refresh=1":""}`}function rX(e,t,n=!1){return e instanceof rZ?e:t?new rZ("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new rZ("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new rZ(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function rQ(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function r0(e,t){let n,r=t.fetchImpl??fetch,i=new AbortController,a=!1,s=()=>i.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0}),null!=t.timeoutMs&&(n=setTimeout(()=>{a=!0,i.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,n=await r(e,{signal:i.signal});try{t=await n.json()}catch(e){throw new rZ("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",n.status,{cause:e})}let a=t&&"object"==typeof t?t:null,s="string"==typeof a?.error?a.error:null;if(!n.ok||s)throw new rZ(s??`HTTP ${n.status}`,"http",n.status,{code:"string"==typeof a?.code?a.code:void 0,outcomeUnknown:a?.outcomeUnknown===!0});return t}catch(e){throw rX(e,a,i.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",s)}}function r1(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 r2(e={}){try{let t=await r0(rY("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new rZ("사용량 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:{...t,reports:t.reports.map(r1)},error:null}}catch(t){return rQ(e.previous,rX(t,!1))}}async function r8(e,t={}){if(!e)return rQ(void 0,new rZ("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await r0(`/api/agent/${encodeURIComponent(e)}/account`,t),r=n?.state==="resolved"||n?.state==="unresolved"||n?.state==="not-running"||n?.state==="unsupported";if(!n||n.sessionId!==e||"number"!=typeof n.observedAt||!r||!Array.isArray(n.resetRecommendations))throw new rZ("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return rQ(void 0,rX(e,!1))}}async function r4(e={}){try{let t=await r0(rY("/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 rZ("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rQ(e.previous,rX(t,!1))}}async function r5(e={}){try{let t=await r0(`${ru}/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 rZ("API 크레딧 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rQ(e.previous,rX(t,!1))}}async function r6(e,t={}){await r7({wallet:"hive",value:e},t)}async function r3(e,t,n={}){await r7({kind:"balance",wallet:e,value:t},n)}async function r7(e,t){await r0(`${ru}/credits/settings`,{...t,timeoutMs:t.timeoutMs??2e4,fetchImpl:async(n,r)=>{let i=new Headers(r?.headers);return i.set("Content-Type","application/json"),(t.fetchImpl??fetch)(n,{...r,method:"POST",headers:i,body:JSON.stringify(e)})}})}async function r9(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rZ("credential id가 올바르지 않습니다.","invalid-response");let r=await r0(`${ru}/credential/${e}/${t?"enable":"disable"}`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,t)=>(n.fetchImpl??fetch)(e,{...t,method:"POST"})});if(!r||!0!==r.ok||r.credentialId!==e||!t!==r.disabled)throw new rZ("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function ie(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rZ("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new rZ("credit id가 올바르지 않습니다.","invalid-response");let r=await r0(`${ru}/credential/${e}/reset`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,r)=>{let i=new Headers(r?.headers);return i.set("Content-Type","application/json"),(n.fetchImpl??fetch)(e,{...r,method:"POST",headers:i,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!r||"boolean"!=typeof r.ok||r.credentialId!==e||r.creditId!==t||"string"!=typeof r.code||r.ok!==("reset"===r.code))throw new rZ("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function it(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let ir={faces:new Map,pins:new Map},ii=[],ia=ir,is=null,io=ii,il=new Map,ic=new Set;function id(e){let t=(ic.add(e),()=>{ic.delete(e)}),n=rE(e);return()=>{t(),n()}}function iu(e){ia=e,ic.forEach(e=>e())}function ip(e){return Number.isSafeInteger(e)&&e>0}function ih(e,t){return`${e}:${t}`}function im(e){let t=e??ii;io=t;let n=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===is)return;is=n;let r=rJ(t),i=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!ip(n))return;let a=ih(e.provider,n);i.has(a)||i.set(a,{seed:r[t].seed,alias:r[t].alias})}),iu({faces:i,pins:ia.pins})}function ig(e,t,n,r){if(!t)return null;let i=rU(t,r);if(i)return i;if(ip(n)){let e=ia.faces.get(ih(t,n));if(e)return e}let a=e?ia.pins.get(e):void 0;if(a&&a.provider===t){let e=ia.faces.get(ih(t,a.credentialId));if(e)return e}return rB(t)??("anthropic"!==t||ip(n)||a?.provider===t?null:rw.find(e=>e.provider===t&&0===e.oauthPosition)??null)}async function ix(e,t,n,r){if(!t||ip(n)||rB(t))return ig(e,t,n,r);try{let{data:n}=await r8(e);if(n?.state==="resolved"&&n.provider===t&&ip(n.credentialId)){let r=new Map(ia.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),iu({faces:ia.faces,pins:r})}}catch{}return ig(e,t,void 0,r)}function iv(e,t,n,r){let a=!!t&&!ip(n)&&!!e;return(0,i.useEffect)(()=>{a&&e&&t&&function(e,t){let n=Date.now(),r=ia.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,a=il.get(i);void 0!==a&&n-a<3e4||(il.set(i,n),r8(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!ip(i))return;let a=new Map(ia.pins);a.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),iu({faces:ia.faces,pins:a})}).catch(()=>{}))}(e,t)},[a,e,t]),(0,i.useSyncExternalStore)(id,()=>ig(e,t,n,r),()=>null)}function ib(){return(0,i.useEffect)(()=>{if(!rI){rI=!0;let e=()=>{"visible"===document.visibilityState&&r$()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e)}null===rj&&(rj=r$().then(e=>{e||(rj=null)}))},[]),(0,i.useSyncExternalStore)(rE,rR,()=>rx)}rE(()=>{is=null,im(io)});let iy={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 iw(){let{locale:e}=(0,z.s)();return{st:(0,i.useCallback)((t,n)=>(0,et.u0)(e,t,iy,n),[e]),locale:e}}function ik({seed:e,size:t,provider:n}){ib();let a=rV(e),[s,o]=(0,i.useState)(null),l=s===a,[c,d]=(0,i.useState)(!1);return l?(0,r.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:rq(e).slice(0,1)}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),d(!0)},"aria-label":rq(e),children:(0,r.jsx)("img",{className:"account-avatar",src:a,width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>o(a)})}),c&&(0,r.jsx)(ij,{seed:e,provider:n,onClose:()=>d(!1)})]})}function ij({seed:e,provider:t,onClose:n}){let{t:a}=(0,z.s)(),s=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let o=rq(e);return(0,q.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"account-avatar-dialog","aria-label":o,onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&n()},children:[(0,r.jsx)("img",{className:"account-avatar-full",src:rV(e),width:256,height:256,alt:o,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:o}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:rG(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:a("i18n.close")})]}),document.body)}function iS(e){let t,n=[],r=null,i=0,a=0,s=0,o=0,l=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){l=[],c=[];return}let e=Math.max(l.length,c.length);for(let t=0;t<e;t++){let e=l[t]?{lineNo:l[t].lineNo,text:l[t].text,type:"removed"}:d(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();r.rows.push({type:"line",left:e,right:n})}l=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(s>0||o>0)){if(d.startsWith("--- ")){u(),t=iC(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:iC(d.slice(4)),rows:[]},n.push(r);continue}}let e=d.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),a=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:d});continue}if(!r)continue;if(d.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:d});continue}let p=d[0],h=d.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:a++,text:h,type:"context"}}),s>0&&s--,o>0&&o--):"-"===p?(l.push({lineNo:i++,text:h}),s>0&&s--):"+"===p?(c.push({lineNo:a++,text:h}),o>0&&o--):""!==d&&(u(),r.rows.push({type:"hunk",text:d}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function iC(e){return e.split(" ")[0].trim()}function iN({task:e,phases:t}){let{t:n}=(0,z.s)(),i="completed"===e.status,a="abandoned"===e.status,s="in_progress"===e.status,o="blocked"===e.status,l=!t||i||a?[]:tA(e,t),c=l.length>0?n("todo.waiting",{tasks:l.join(", ")}):!t||i||a||o?null:n("todo.ready"),d=i?"✓":a?"\xd7":o?"!":s?"›":"",u=i?"is-completed":a?"is-abandoned":o?"is-blocked":s?"is-active":"is-pending";return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}${c?`; ${c}`:""}`,className:`todo-checklist-row ${u}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:d}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,o&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null,c&&(0,r.jsxs)("span",{className:`todo-checklist-readiness${l.length>0?" is-waiting":""}`,children:[" \xb7 ",c]})]})]})}let iT="/icons/catppuccin";function iI({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${iT}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${iT}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function iM({size:e=14,open:t=!1}){return(0,r.jsx)(iI,{name:t?"_folder_open":"_folder",size:e})}function iR({size:e=14}){return(0,r.jsx)(iI,{name:"_file",size:e})}let iE={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 i$(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(iI,{name:i,size:t});let a=iE[n.split(".").pop()??""];return a?(0,r.jsx)(iI,{name:a,size:t}):(0,r.jsx)(iR,{size:t})}function iL({files:e,onOpenFile:t}){let{t:n}=(0,z.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=tW(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer"},children:[i$(i,12),(0,r.jsx)("span",{children:i})]},e)})})}let iP=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function iA(e){if(!e)return null;let t=/^\s*TASK_GUARD\s*:\s*$/im.exec(e),n=e;if(t){let r=t.index+t[0].length;"\r"===e[r]&&(r+=1),"\n"===e[r]&&(r+=1);let i=r;for(;r<e.length;){let t=e.indexOf("\n",r),n=-1===t?e.length:t,a=n>r&&"\r"===e[n-1]?n-1:n;if(!iP.test(e.slice(r,a)))break;i=a,r=-1===t?e.length:t+1}let a=t[0].length-t[0].trimStart().length;n=`${e.slice(0,t.index+a)}${e.slice(i)}`}let r=[...n.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===r.length&&r[0]&&r[0]===r[0].trim()&&/[가-힣]/u.test(r[0])?r[0]:null}function i_(e){let t=e.live,n=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,r=[t?.assignment,t?.progress?.assignment,t?.task].map(iA).find(e=>null!==e)??(n?.taskTitle?.trim()||null),i=t?.progress?.lastIntent?.trim()||"",a=t?.progress?.currentTool?.trim()||"";return{title:r??"담당 업무 미확인",stage:i&&a?`${i} \xb7 ${a}`:i||(a?`${a} 실행 중`:null),explicitTitle:null!==r}}function iF(e){let t=e.live?.progress,n="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,i="string"==typeof t?.resolvedThinkingLevel?t.resolvedThinkingLevel.trim():"",a="string"==typeof r?.thinkingLevel?r.thinkingLevel.trim():"";if(n){let e=n.split("/").pop()||n;return{model:n,modelShort:i&&e.endsWith(`:${i}`)?e.slice(0,-(i.length+1)):e,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:i||a||null}}let s="string"==typeof r?.model?r.model.trim():"";return{model:s||null,modelShort:s?s.split("/").pop()||s:null,modelIsFallback:!!s&&r?.modelIsFallback===!0,effort:a||null}}class iz extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function iW(e){try{return await e.json()}catch{throw new iz("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function iO(e){return!!e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.bytes&&"number"==typeof e.modified&&(null===e.messages||"number"==typeof e.messages)&&(void 0===e.taskTitle||"string"==typeof e.taskTitle)&&"string"==typeof e.firstTask}function iD(e){return!!e&&"object"==typeof e&&"string"==typeof e.role&&("message"===e.kind||"custom"===e.kind)&&"string"==typeof e.text&&(null===e.at||"number"==typeof e.at)}function iH(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 iU(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 iB(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let n=async(t,n,r)=>{let i;try{i=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new iz(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let a=await iW(i);if(!i.ok)throw new iz("http",function(e,t){if(e&&"object"==typeof e&&"error"in e){let t=e.error;if("string"==typeof t&&t)return t}return t}(a,`HTTP ${i.status}`),i.status);return{response:i,body:a}};return{async getLiveSnapshots(e,t){let{body:r}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!r||"object"!=typeof r)throw new iz("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new iz("http",r.error);if(!0!==r.running)return{runtime:"detached",subagents:[]};let i=r.state?.subagents;if(void 0!==i&&(!Array.isArray(i)||!i.every(iH)))throw new iz("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:i??[]}},async getLiveTranscript(e,t,r,i){let{body:a}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:r}),signal:i},"live-unreachable");if(!a||"object"!=typeof a)throw new iz("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof a.error&&a.error)throw new iz("http",a.error);if(!0!==a.success||!a.data||"object"!=typeof a.data)throw new iz("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let s=a.data;if(!Array.isArray(s.entries)||!s.entries.every(iU)||"number"!=typeof s.fromByte||"number"!=typeof s.nextByte||"boolean"!=typeof s.reset)throw new iz("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:s.fromByte,nextByte:s.nextByte,reset:s.reset,entries:s.entries}},async getArchive(e,r){let i=`${t}/archive?session=${encodeURIComponent(e)}`,{body:a}=await n(i,{method:"GET",signal:r},"sidecar-unreachable");if(!a||"object"!=typeof a||"string"!=typeof a.sessionId||"string"!=typeof a.dir||"boolean"!=typeof a.found||!Array.isArray(a.subagents)||!a.subagents.every(iO))throw new iz("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:a.sessionId,dir:a.dir,found:a.found,subagents:a.subagents,...!0===a.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,r,i=400,a){let s=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(r)}&limit=${encodeURIComponent(String(i))}`,{body:o}=await n(s,{method:"GET",signal:a},"sidecar-unreachable");if(!o||"object"!=typeof o||"string"!=typeof o.sessionId||"string"!=typeof o.name||"number"!=typeof o.bytes||"boolean"!=typeof o.truncated||!Array.isArray(o.entries)||!o.entries.every(iD))throw new iz("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}let iq=["feature","maintenance","diagnostic"],iV=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function iK(e){if("string"!=typeof e)return null;let t=e.split(/\r?\n/),n=t.findIndex(e=>/^\s*TASK_GUARD\s*:\s*$/.test(e));if(n<0)return null;for(let e=n+1;e<t.length;e+=1){let n=iV.exec(t[e]);if(!n)break;if("WORK_CLASS"!==n[1])continue;let r=n[2].toLowerCase();return iq.includes(r)?r:null}return null}let iG={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function iJ(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function iZ(e){return"string"==typeof e&&e.trim()?e:null}function iY(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function iX(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 iQ(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function i0(e,t){if(t?.isError)return null;let n=iJ(e.input.tasks),r=iJ(t?.details?.progress),i=Math.max(n.length,r.length),a=[];for(let s=0;s<i;s++){let i=r.find(e=>e.index===s)??r[s],o=n[s],l=iZ(i?.id)??iZ(o?.name);l&&a.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:l,agent:iZ(i?.agent)??iZ(o?.agent),task:iZ(i?.task)??iZ(o?.task)??"",workClass:iK(o?.task)??iK(i?.task),spawned:!!t})}return a}let i1=/<task-result\b([^>]*)>/g,i2=/(\w+)="([^"]*)"/g;function i8(e,t,n){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&n.latestByAgent.get(e.agentId)===e.key)}function i4(e,t,n){var r;let i,a,s,o,l=i8(e,t,n),c=l?{key:e.key,identity:"live",live:l.assignment?l:{...l,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},d=i_(c),u=n.runs.get(e.key),p=null;l&&"unknown"!==l.status?(i=l.status,p="live"):u&&"unknown"!==u.status?(i=u.status,p="record"):i=e.spawned?"unobserved":"dispatching";let h=n.verdicts.get(e.key),m=h&&h.length>0?h[h.length-1]:null,f=m?.at??null,g=null===f?null:(r=e.key,a=n.runStartedAt.get(r)??null,s=l?.progress?.durationMs,o=l&&("pending"===l.status||"running"===l.status)&&"number"==typeof s&&l.lastUpdate>0?l.lastUpdate-s:null,null===a?o:null===o?a:Math.max(a,o)),x=null!==f&&null!==g&&g>f;return{member:e,title:d.title,explicitTitle:d.explicitTitle,stage:l?d.stage:null,model:l?iF(c):null,run:i,runSource:p,verdict:x?null:m,priorVerdict:x?m:null,runTitle:x?iA(l?.progress?.task):null,observedParallelWith:n.parallelWith.get(e.key)}}function i5(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function i6(e,t){let n=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),r=new Map,i=[];for(let e of n){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?i.push(t):r.set(e.attempt,t)}return[...i,...[...r.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}function i3(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function i7(e,t,n){let r=-1;n.forEach((e,t)=>{"user"===e.role&&(r=t)});let i=n.slice(0,r+1).flatMap(i3),a=n.slice(r+1).flatMap(i3),s=t.findIndex(e=>"user"===e.role),o=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===o?{continuing:null,atCompaction:[...i,...a]}:{continuing:{position:o,calls:a},atCompaction:i}}let i9="끊기기 전에 바깥에 영향을 주는 행동(커밋\xb7push, `git_finalize`\xb7`git_integrate`, 배포\xb7`update.sh`, CI 재실행, 이슈\xb7PR 댓글, 메시지 전송)을 하던 중이었다면 다시 하기 전에 그 결과가 이미 반영됐는지 `git log`\xb7`git status`\xb7원격 브랜치, `gh run list`, 배포 로그, 해당 페이지로 먼저 확인하고, 반영됐으면 되풀이하지 않는다. ",ae="[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+i9+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",at="[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. "+i9+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.",an="[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+i9+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",ar=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 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."]),ai={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function aa(e){return e.trim()}function as(e){return aa(e.text)||(e.images>0?"[Image]":"")}function ao(e){let t=e.filter(e=>!ai[e.stage]);if(t.length<=4)return e;let n=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!n.has(e.id))}function al(e,t){switch(t.type){case"submit":return ao([...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 ao(e.map(e=>e.id===t.id&&ai[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,i=(e,t)=>{let n=`${e}\u0000${aa(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)i("steer",e);for(let e of n)i("followUp",e);let a=!1,s=e.map(e=>{if(!ai[e.stage])return e;let t=`${e.kind}\u0000${as(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-1),e.inQueue&&"accepted"===e.stage)?e:(a=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(a=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return a?s:e}(e,t.steering,t.followUp);case"user-message":{let n=aa(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(ai[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&aa(e.text)===n&&e.images===t.images);if(!r)return e;return ao(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>ai[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=aa(t.text),i=e.find(e=>n(e)&&e.kind===t.kind&&(aa(e.text)===r||as(e)===r));return i?e.filter(e=>e!==i):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}function ac(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 ad(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}let au=["investigate","edit","check","review","commit","ci","deploy"];function ap(e,t){let n="",r=t;for(;r<e.length&&'"'!==e[r];){let t=e[r];if("\\"===t&&r+1<e.length){let i=e[r+1];"\n"!==i&&(n+='$`"\\'.includes(i)?i:t+i),r+=2}else if("$"===t&&"("===e[r+1]){let t=ah(e,r+1);n+=e.slice(r,t),r=t}else if("`"===t){let t=am(e,r+1);n+=e.slice(r,t),r=t}else n+=t,r+=1}return{text:n,end:Math.min(r+1,e.length)}}function ah(e,t){let n=e[t],r="{"===n?"}":")",i=0,a=t;for(;a<e.length;){let t=e[a];if("\\"===t)a+=2;else if("'"===t){let t=e.indexOf("'",a+1);a=t<0?e.length:t+1}else if('"'===t)a=ap(e,a+1).end;else if("`"===t)a=am(e,a+1);else{if(t===n)i+=1;else if(t===r&&0==--i)return a+1;a+=1}}return e.length}function am(e,t){let n=t;for(;n<e.length&&"`"!==e[n];)n+="\\"===e[n]?2:1;return Math.min(n+1,e.length)}function af(e){let{tokens:t,groups:n,expandingHeredoc:r}=function(e){let t=[],n=[],r=!1,i=[],a=[],s="",o=-1,l=!1,c=e=>{if(o<0)return;let n={value:s,start:o,end:e,risky:l};for(let e of(t.push(n),a.splice(0)))e.at===t.length-1&&(e.owner=n);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),n=t<0?e.length:t;s+=e.slice(d+1,n),d=n+1}else if('"'===u){o<0&&(o=d);let t=ap(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=ah(e,d+1);s+=e.slice(d,t),l=!0,d=t}else if("`"===u){o<0&&(o=d);let t=am(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 n=t[t.length-1];for(let s of("&&"!==n&&"||"!==n&&"|"!==n&&t.push(";"),d+=1,a.length=0,i.splice(0)))for(;d<e.length;){let t=e.indexOf("\n",d),n=t<0?e.length:t,i=e.slice(d,n);if(d=n+1,(s.stripTabs?i.replace(/^\t+/,""):i)===s.delimiter)break;!s.quoted&&/\$[({]|`/.test(i)&&(s.owner?s.owner.risky=!0:r=!0)}}else if("<"===u&&"<"===e[d+1]&&"<"!==e[d+2]){c(d);let n=d+2,r="-"===e[n];for(r&&(n+=1);" "===e[n]||" "===e[n];)n+=1;let s="",o=!1;for(;n<e.length&&!/[\s;&|<>()]/.test(e[n]);){let t=e[n];if("'"===t||'"'===t){o=!0;let r=e.indexOf(t,n+1),i=r<0?e.length:r;s+=e.slice(n+1,i),n=i+1}else"\\"===t&&(o=!0),s+="\\"===t?e[n+1]??"":t,n+="\\"===t?2:1}if(s){let e=t[t.length-1],n={delimiter:s,stripTabs:r,quoted:o,owner:void 0!==e&&"string"!=typeof e?e:null,at:t.length};i.push(n),n.owner||a.push(n)}d=n}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),n.push(d)):(o<0&&(o=d),("{"===u||"}"===u||"!"===u)&&(l=!0),s+=u),d+=1)}return c(e.length),{tokens:t,groups:n,expandingHeredoc:r}}(e),i=[],a=[],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 r=l[0].start,i=l[l.length-1].end,s=l.some(e=>e.risky)||n.some(e=>e>=r&&e<=i),c={words:t,text:e.slice(r,i),uncertain:s};o.commands.push(c),a.push(c)}l=[]},d=()=>{c(),o.commands.length>0&&s.pipelines.push(o),o={commands:[],negated:!1}},u=e=>{d(),s.pipelines.length>0&&i.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:i,commands:a,uncertain:n.length>0||r||t.some(e=>"string"!=typeof e&&e.risky)}}function ag(e){return e.slice(e.lastIndexOf("/")+1)}let ax={bash:!0,sh:!0,zsh:!0,dash:!0},av={sudo:!0,env:!0,command:!0,exec:!0,nice:!0,nohup:!0,time:!0,timeout:!0,setsid:!0,"systemd-run":!0},ab={"-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},ay={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},aw={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function ak(e){let t=aC(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(ax,ag(e[t]))||aj(e,t))return null;for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*c[a-zA-Z]*$/.test(e[n]))return e[n+1]??null;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return null}function aj(e,t){for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*n[a-zA-Z]*$/.test(e[n])||/^-[a-zA-Z]*o$/.test(e[n])&&"noexec"===e[n+1])return!0;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return!1}let aS={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function aC(e){let t=!1,n="";for(let r=0;r<e.length;r+=1){let i=e[r];if(!(/^[A-Za-z_]\w*=/.test(i)||!t&&Object.hasOwn(aw,i))){if(t&&(i.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(i))){if(Object.hasOwn(aS,n)&&aS[n].test(i))return -1;"command"!==n&&Object.hasOwn(ab,i)&&(r+=1);continue}if(!Object.hasOwn(av,ag(i)))return r;t=!0,n=ag(i)}}return -1}let aN=/(?:^|\/)wsl\/update\.sh$/;function aT(e,t=0){let n=ak(e);if(null!==n)return t<3&&af(n).commands.some(e=>aT(e.words,t+1));let r=aC(e);if(r<0)return!1;if(aN.test(e[r]))return!0;if(!Object.hasOwn(ax,ag(e[r]))||aj(e,r))return!1;let i=e.slice(r+1).find(e=>!e.startsWith("-"));return void 0!==i&&aN.test(i)}function aI(e){let t=aC(e),n=t<0?e:e.slice(0,t),r=n.map(ag);return r.includes("systemd-run")?!n.some(e=>Object.hasOwn(ay,e)):!!(r.includes("sudo")&&n.some(e=>"--background"===e||/^-[a-zA-Z]*b[a-zA-Z]*$/.test(e)))||r.includes("setsid")&&!n.includes("-w")&&!n.includes("--wait")}function aM(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function aR(e){if(e.every(e=>/^[A-Za-z_]\w*=/.test(e)))return!0;let[t,...n]=e;return"cd"===t?n.length<=1:"export"===t?n.every(e=>/^[A-Za-z_]\w*=/.test(e)):"set"===t&&n.every(e=>/^[-+][a-zA-Z]+$/.test(e)&&!/^-[a-zA-Z]*n/.test(e)||"pipefail"===e)}let aE={tail:!0,head:!0,cat:!0,tee:!0},a$=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,aL={bun:!0,bunx:!0,npm:!0,npx:!0,pnpm:!0,yarn:!0,node:!0,python:!0,python3:!0,deno:!0},aP={"--help":!0,"-h":!0,"--version":!0},aA=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 a_(e){let t=aC(e);if(t<0)return!1;let n=ag(e[t]);if("test"===n||"["===n||e.slice(t+1).some(e=>Object.hasOwn(aP,e)))return!1;if(a$.test(n))return!0;if(!Object.hasOwn(aL,n))return!1;if("node"===n&&function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("--test"===t)return!0;if("--"===t||!t.startsWith("-"))break;Object.hasOwn(aA,t)&&(n+=1)}return!1}(e,t+1))return!0;let r=function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("-m"===t)return e[n+1];if(/^-[a-zA-Z]*[cep]/.test(t)||/^--(?:eval|print)(?:=|$)/.test(t))break;if(!t.startsWith("-")){if("run"===t||"exec"===t||"x"===t||"dlx"===t)return e.slice(n+1).find(e=>!e.startsWith("-"));return t}}}(e,t+1);return void 0!==r&&a$.test(r)}let aF={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},az={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function aW(e){let t=aC(e);if(t<0||"git"!==ag(e[t]))return null;for(let n=t+1;n<e.length;n+=1)if(Object.hasOwn(aF,e[n]))n+=1;else if(!e[n].startsWith("-"))return{name:e[n],at:n};return null}function aO(e,t=0,n){let r=ak(e);if(null!==r)return t<3&&af(r).commands.some(e=>aO(e.words,t+1,n));let i=aW(e);if(!i||"commit"!==i.name&&"push"!==i.name||void 0!==n&&i.name!==n)return!1;let a=az[i.name];return!e.slice(i.at+1).some(e=>Object.hasOwn(a,e)||"push"===i.name&&/[nd]/.test(function(e){if(!/^-[a-zA-Z0-9]/.test(e))return"";let t="";for(let n of e.slice(1)){if("o".includes(n)||!/[a-zA-Z0-9]/.test(n))break;t+=n}return t}(e)))}function aD(e){return aR(e)||null!==aW(e)}let aH={check:({words:e})=>a_(e),commit:({words:e})=>aO(e),ci:({words:e})=>{let t=aC(e);return t>=0&&"gh"===ag(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>aT(e.words)},aU={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 aB(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 aq={"$?":!1,"${PIPESTATUS[0]}":!0};function aV(e,t){let n=a4(t);if("notRun"===n)return[];let r=n?void 0:t,i=af(e),a=[];if(i.commands.some(({words:e})=>(function e(t,n=0){let r=ak(t);return null!==r?n<3&&af(r).commands.some(t=>e(t.words,n+1)):a_(t)})(e))&&a.push("check"),i.commands.some(({words:e})=>aO(e))&&a.push("commit"),i.commands.some(({words:e})=>(function e(t,n=0){let r=ak(t);if(null!==r)return n<3&&af(r).commands.some(t=>e(t.words,n+1));let i=aC(t);return i>=0&&"gh"===ag(t[i])&&"run"===t[i+1]&&["watch","view","list"].includes(t[i+2])})(e))&&a.push("ci"),i.commands.some(aH.deploy)&&a.push("deploy"),0===a.length)return[];let s=r?nU(r):null,o=null===s?!!r?.isError:0!==s,l=a.length>1?{stages:a,failed:o}:void 0,c=r?sf(r):"";return a.map(e=>{var t;let a,d,u,p="commit"===e?aD:aR,h=function e(t,n,r=aR,i=0){let{lists:a}=t,s=[],o=t.uncertain,l=!1;return a.forEach((t,c)=>{for(let d of(t.pipelines.some(e=>e.commands.some(({words:e})=>e.some(e=>e.includes("pipefail"))))&&(l=!1),t.pipelines)){let u=!1;for(let p of d.commands){let h=i<3?ak(p.words):null,m=null===h?null:e(af(h),n,r,i+1);if(m&&m.decisive.length>0)s.push(...m.decisive);else if(n(p))s.push(p);else{let e=aC(p.words);u&&l&&e>=0&&Object.hasOwn(aE,ag(p.words[e]))||r(p.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let n=aM(e[t])?.words;return n?.[0]==="exit"&&(1===n.length||2===n.length&&"$?"===n[1])}(a,c)||(o=!0);continue}u=!0,(m?.reach==="masked"||d.negated||d.commands.length>1&&!l||t.operators.includes("||")||t.background||aI(p.words)||!function(e,t){if(t===e.length-1)return!0;let n=e[e.length-1],r=aM(n)?.words;return!!r&&"exit"===r[0]&&!n.background&&t===e.length-2&&(1===r.length||2===r.length&&"$?"===r[1])}(a,c))&&(o=!0)}}let d=aM(t)?.words;!t.background&&d?.[0]==="set"&&3===d.length&&"pipefail"===d[2]&&(/^-[a-zA-Z]*o$/.test(d[1])?l=!0:/^\+[a-zA-Z]*o$/.test(d[1])&&(l=!1))}),{reach:0===s.length?"absent":o?"masked":"carried",decisive:s}}(i,aH[e],p),m="check"===e&&h.decisive.some(({words:e})=>e.includes("--if-present")),f=r?(t=aH[e],a=new Map,d=i.lists.map(e=>(function(e){let t=e&&!e.background?aM(e)?.words:void 0;if(!t||"echo"!==t[0]||t.length<2)return null;let n=t.slice(1);if(n.some(e=>e.startsWith("-")||/^(?:\d*[<>]|&>)/.test(e)))return null;let r=n.join(" ");for(let[e,t]of Object.entries(aq)){let n=r.indexOf(e);if(n<0||r.indexOf(e,n+1)>=0)continue;let i=r.slice(0,n),a=r.slice(n+e.length);if(/[$`\\]/.test(i+a)||!/[^\s\d]/.test(i))break;return{prefix:i,suffix:a,first:t}}return null})(e)),u=c.split("\n").map(e=>e.trimEnd()),i.lists.forEach((e,n)=>{let r=d[n+1];if(!r||e.background||e.operators.includes("||"))return;let i=e.pipelines[e.pipelines.length-1],s=e.pipelines.slice(0,-1);if(i.negated||s.some(e=>e.negated||1!==e.commands.length||!p(e.commands[0].words)))return;let o=r.first||1===i.commands.length?i.commands[0]:void 0;if(!o||!t(o)||aI(o.words)||o.uncertain)return;let l=d.filter(e=>e?.prefix===r.prefix&&e.suffix===r.suffix),c=RegExp(`^${r.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(-?\\d+)${r.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,n+2).filter(e=>l.includes(e)).length-1;a.set(o,h[m])}),a):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"===n?"interrupted":r?"noExit":"noResult":"unverified"!==v?null:m?"optional":o&&l?"compound":i.uncertain?"syntax":"masked";return{stage:e,state:v,exitCode:s,labels:"check"===e?function(e){let t=[];for(let{words:n}of e){let e=aC(n);n.forEach((n,r)=>{if(r!==e||"test"!==n)for(let e of n.replace(/^-+/,"").toLowerCase().split(":")){let n=Object.hasOwn(aU,e)?aU[e]:void 0;n&&!t.includes(n)&&t.push(n)}})}return t}(h.decisive):[],...l?{compound:l}:{},...x?{evidence:x.line}:{},...b?{reason:b}:{}}})}function aK(e,t){let n=aB(e),r=null===n?void 0:aV(n,t).find(e=>"check"===e.stage);return null!==n&&r?{toolCallId:e.toolCallId,command:n,state:r.state,exitCode:r.exitCode,labels:r.labels,...r.compound?{compound:r.compound}:{},...r.reason?{reason:r.reason}:{}}:null}let aG=/\.(?:md|mdx|markdown|txt)$/i,aJ=/^docs?$/i;function aZ(e){return aG.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>aJ.test(e))}let aY={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},aX={multiedit:!0,notebookedit:!0,draft:!0},aQ={rename:!0,rename_file:!0},a0={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function a1(e){return e.split("\n")[0].trim()||void 0}let a2=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,a8=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function a4(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 a5=/\btool\.git_(?:finalize|integrate)\s*\(/,a6=/\b(?:Committed|Integrated \S+) and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,a3=/\bgit_(?:finalize|integrate) failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,a7=/\bstage["']?\s*:\s*["'](?:up-to-date|aborted)["']/,a9=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/;function se(e,t){if("string"==typeof t.commitSha&&""!==t.commitSha.trim())return t.commitSha.trim();let n=a6.exec(sf(e));return n?.[1]??n?.[2]??null}let st=/^bg_\d+$/;function sn(e){let t=e.details,n=t&&"object"==typeof t&&"async"in t?t.async:null;if(n&&"object"==typeof n&&"jobId"in n&&"string"==typeof n.jobId&&st.test(n.jobId))return n.jobId;let r=sf(e).trimStart();return r.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(r)?.[1]??null:null}function sr(e,t){let n=/Command exited with code (-?\d+)\s*$/.exec(t.trimEnd());return{jobId:e,text:t,exitCode:n?Number(n[1]):null}}function si(e){return"passed"===e||"failed"===e||"done"===e}function sa(e){let t=null;for(let n of e.values())"failed"===n.outcome&&(!t||n.order>t.order)&&(t=n);return t?.stage??null}function ss(e){return e.commandKey??JSON.stringify([e.cwd??"",e.command])}function so(e){let t=new Map;for(let n of e){if("check"!==n.stage)continue;let e=ss(n),r=t.get(e);(r?.outcome!=="failed"||si(n.outcome))&&t.set(e,n)}return[...t.values()]}function sl(e){return"compound"in e&&e.compound?.failed===!0}let sc={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function sd(e){return"stale"!==e&&(si(e)||"running"===e)}function su(e){if("ci"!==e.stage)return null;let t=af(e.command).commands.flatMap(({words:e})=>sx(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?sw(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let sp={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},sh={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},sm=/^[0-9a-f]{40}$/i;function sf(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 sg(e){let t=[];for(let n of e.split("\n")){let e,r=n.trim();if(r.startsWith("{")||r.startsWith("[")){try{e=JSON.parse(r)}catch{continue}for(let n of Array.isArray(e)?e:[e])n&&"object"==typeof n&&!Array.isArray(n)&&t.push(n)}}return t}function sx(e,t=0){let n=ak(e);if(null!==n)return t<3?af(n).commands.flatMap(e=>sx(e.words,t+1)):[];let r=aC(e);return r>=0&&"gh"===ag(e[r])?[e.slice(r+1)]:[]}function sv(e,t){for(let n=0;n<e.length;n+=1)for(let r of t){if(e[n]===r)return e[n+1]??null;if(r.startsWith("--")&&e[n].startsWith(`${r}=`))return e[n].slice(r.length+1)}return null}let sb={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function sy(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(sb,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function sw(e){let t=sy(e);return null!==t&&/^\d+$/.test(t)?t:null}let sk=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function sj(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==nU(t))return[];let n=af(e).commands.flatMap(({words:e})=>sx(e)).filter(e=>"run"===e[0]&&("list"===e[1]||"view"===e[1]));if(0===n.length)return[];let r=1===n.length?n[0]:null,i=r?.[1]==="list"?sv(r,["-c","--commit"])?.toLowerCase():void 0,a=i&&/^[0-9a-f]{7,40}$/.test(i)?i:null,s=sf(t);return a||s.includes("headSha")?sg(s).flatMap(e=>{let t="string"==typeof e.headSha?e.headSha.toLowerCase():a;if(null===t)return[];let n="string"==typeof e.url?sk.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):r?.[1]==="view"?sw(r):null,repo:(n??(r?sv(r,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:r?sv(r,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:r?sv(r,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let sS=/\b\d{9,12}\b/g,sC=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function sN(e,t){if(e?.type!=="toolCall")return[];let n=aB(e);return null===n?[]:sj(n,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(sh,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let sT="Public tree already matches; nothing to publish";function sI(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function sM(e){let t="run"===e[0]&&"list"===e[1]?sv(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(sp,t)}function sR(e,t){let n=new Map,r=[];for(let{words:i}of af(e).commands){let e=i.map(e=>/^([A-Za-z_]\w*)=([\s\S]*)$/.exec(e));if(i.length>0&&e.every(e=>null!==e)){for(let t of e){if(!t)continue;let e=/^\$\(([\s\S]*)\)$/.exec(t[2])?.[1],r=void 0===e?[]:af(e).commands.flatMap(e=>sx(e.words));n.set(t[1],1===r.length&&sM(r[0]))}continue}for(let e of sx(i)){if(sM(e)){r.push({args:e,publish:!0});continue}let i="run"===e[0]&&("watch"===e[1]||"view"===e[1])?sy(e):null,a=sI(i),s=null!==a?!0===n.get(a):null!==i&&/^\d+$/.test(i)&&t(i);r.push({args:e,publish:s})}}return r}function sE(e,t){let n=sR(e,t);return n.length>0&&n.every(({publish:e})=>e)}function s$(e,t){if(!e||!t)return!1;let[n,r]=e.length<=t.length?[e.toLowerCase(),t.toLowerCase()]:[t.toLowerCase(),e.toLowerCase()];return n.length>=7&&/^[0-9a-f]+$/.test(r)&&r.startsWith(n)}function sL(e,t,n){if(s$(e.sha,t.step.commit))return!0;let{title:r}=t.step;return!!r&&!!e.title&&!!e.repo&&!(e.order<=t.order)&&!!e.workflow&&!!Object.hasOwn(sh,e.workflow)&&[...n.publishRuns.values()].some(n=>n.order>t.order&&null!==n.sha&&s$(n.sha,t.step.commit)&&null!==n.repo&&n.repo!==e.repo)&&function(e,t){if(e===t)return!0;let n=e.endsWith("…")?e.slice(0,-1):null;return null!==n&&n.length>=20&&t.startsWith(n)}(e.title,r)}let sP={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},sA=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,s_=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) (ROLLED_BACK|ROLLBACK_FAILED|FAIL)\b/,sF=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) START old=\S* target=([0-9a-f]{7,40})\b/;function sz(e,t,n=!1,r=[],i,a=[]){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,n=[]){let r=new Map,i=new Map,a=new Map;for(let e of n)null!==e.after&&a.set(e.after,[...a.get(e.after)??[],e]);let s=(e,t)=>{for(let n of e){let e=i.get(n.jobId);e&&(i.delete(n.jobId),r.set(e.toolCallId,{...e.result,isError:!1,content:[{type:"text",text:n.text}],details:{...null===n.exitCode?{}:{exitCode:n.exitCode},backgroundJob:{jobId:n.jobId,after:t}}}))}};for(let n of Array.isArray(e)?e:[]){if(!n||"toolCall"!==n.type)continue;let e=t.get(n.toolCallId);if(e){let t="bash"===n.toolName||"eval"===n.toolName?sn(e):null;t?i.set(t,{toolCallId:n.toolCallId,result:e}):r.set(n.toolCallId,e),"wait"===n.toolName&&s(function(e){let t=e.details,n=t&&"object"==typeof t&&"jobs"in t?t.jobs:null,r=(Array.isArray(n)?n:[]).flatMap(e=>{if(!e||"object"!=typeof e||!("id"in e)||!("status"in e)||!("resultText"in e)||"string"!=typeof e.id||!st.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[{...sr(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(r.length>0)return r;let i=sf(e),a=[...i.matchAll(/^### (bg_\d+) \[\w+\] — (?:completed|failed)$/gm)];return a.map((e,t)=>{let n=(e.index??0)+e[0].length,r=i.slice(n,t+1<a.length?a[t+1].index:i.length),s=r.indexOf("\n```\n"),o=r.lastIndexOf("\n```");return sr(e[1],s>=0&&o>s?r.slice(s+5,o):"")})}(e),n.toolCallId);let a="read"===n.toolName?function(e,t){let n=e.input.path,r="string"==typeof n?/^proc:\/\/(bg_\d+)$/.exec(n)?.[1]:void 0;if(!r)return null;let[i,...a]=sf(t).split("\n");return RegExp(`^1\\|${r} \\[\\w+\\] — (?:completed|failed)\\b`).test(i)?sr(r,a.map(e=>e.replace(/^\d+\|/,"")).join("\n")):null}(n,e):null;a&&s([a],n.toolCallId)}for(let e of a.get(n.toolCallId)??[])s(function(e){let t=e.replace(/^\s*<system-notice>\s*\n?/,"").replace(/\s*<\/system-notice>\s*$/,""),n=/^Background job (bg_\d+) has (?:completed|failed)\b[^\n]*(?:\n|$)/.exec(t);if(n)return[sr(n[1],t.slice(n[0].length))];let r=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return r.flatMap((e,n)=>{if(!st.test(e[1]))return[];let i=(e.index??0)+e[0].length;return[sr(e[1],t.slice(i,n+1<r.length?r[n+1].index:t.length).replace(/^\n/,""))]})}(e.text),n.toolCallId)}return r}(g,x,Array.isArray(a)?a:[]),b=[];g.forEach((e,t)=>{let r;if(!e||"toolCall"!==e.type)return;let a=v.get(e.toolCallId);for(let s of(!function(e,t,n,r){let i=aB(t);if(null===i||!i.includes("gh"))return;let a=(t,n)=>{let i=e.publishRuns.get(t);i&&(null===n.sha||null!==i.sha)||e.publishRuns.set(t,{...n,order:i?.order??r})};for(let t of sj(i,n))e.runs.push({...t,order:r}),t.id&&t.sha&&t.workflow&&Object.hasOwn(sp,t.workflow)&&a(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==nU(t))return[];let n=af(e).commands.flatMap(({words:e})=>sx(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==n.length)return[];let r=sv(n[0],["-w","--workflow"])?.toLowerCase(),i=void 0!==r&&Object.hasOwn(sp,r),a=sv(n[0],["-R","--repo"])?.toLowerCase()??null;return sf(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let n=t.toLowerCase();if(!i&&!Object.keys(sp).some(e=>n.includes(e)))return[];let r=t.match(sS)??[];return 1===r.length?[{id:r[0],sha:sC.exec(n)?.[0]??null,repo:a}]:[]})}(i,n))a(e.id,e);for(let i of sN(t,n))e.ciHeads.push({...i,order:r});for(let t of function(e,t){let n=af(e),r=n.commands.flatMap(({words:e})=>sx(e)).filter(e=>"api"===e[0]),i=!n.uncertain&&1===n.commands.length&&1===r.length,a=t&&!t.isError&&0===nU(t)?sf(t).trim():"",s=[];for(let e of r){let t=e.slice(1).find(e=>/^\/?repos\//.test(e)),n=t?/^\/?repos\/([^/]+\/[^/]+)\/commits\/([^/?\s]+)$/.exec(t):null;if(!n)continue;let r=sv(e,["-q","--jq"]),o=null;if(i&&".sha"===r)o=a.split("\n")[0]?.trim();else if(i&&null===r&&a.startsWith("{"))try{o=JSON.parse(a.slice(0,a.lastIndexOf("}")+1)).sha}catch{}let l="string"==typeof o&&sm.test(o)?o.toLowerCase():null;s.push({repo:n[1].toLowerCase(),ref:n[2],sha:l})}return s}(i,n))e.heads.push({...t,order:r});let s=function(e,t){if(!t||t.isError||0!==nU(t)||2!==e.split(sT).length)return null;let{lists:n}=af(e),r=0;for(;r<n.length&&["set","cd"].includes(aM(n[r])?.words[0]??"");)r+=1;let i=r<n.length-1?function(e){let t=aM(e)?.words,n=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!n)return null;let r=af(n[2]),i=1===r.lists.length?aM(r.lists[0]):null,a=i?.words[0]==="gh"?sx(i.words):[];if(1!==a.length||"run"!==a[0][0]||"list"!==a[0][1])return null;let s=sv(a[0],["-c","--commit"]),o=sv(a[0],["-w","--workflow"])?.toLowerCase();return s&&sm.test(s)&&o&&Object.hasOwn(sp,o)?{name:n[1],sha:s.toLowerCase()}:null}(n[r]):null;return i&&function(e,t){if(e.background||1!==e.pipelines.length)return!1;let[n]=e.pipelines,[r,i,...a]=n.commands;if(n.negated||!i||a.length>1||"gh"!==r.words[0])return!1;let s=sx(r.words);if(1!==s.length||"run"!==s[0][0]||"view"!==s[0][1]||!s[0].includes("--log"))return!1;let o=sy(s[0]);if(sI(o)!==t)return!1;for(let e=2;e<s[0].length;e+=1){let t=s[0][e];if("-R"===t||"--repo"===t)e+=1;else if(t!==o&&"--log"!==t&&!t.startsWith("--repo=")&&!/^2>/.test(t))return!1}let[l,...c]=i.words,d=c.filter(e=>e.startsWith("-")),u=c.filter(e=>!e.startsWith("-"));if("grep"!==l||!d.every(e=>/^-[oFas]+$/.test(e))||!d.some(e=>e.includes("o"))||1!==u.length||u[0]!==sT)return!1;let[p]=a;return!p||("head"===p.words[0]||"tail"===p.words[0])&&p.words.slice(1).every(e=>/^(?:-n?\d*|\d+)$/.test(e))}(n[n.length-1],i.name)&&n.slice(r+1,-1).flatMap(e=>e.pipelines.flatMap(({commands:e})=>e)).every(({words:e})=>(function(e,t){let[n,...r]=e;if("["===n||"[["===n||"test"===n||"exit"===n||"true"===n||":"===n||"sleep"===n)return!0;if("echo"===n||"printf"===n)return r.every(e=>!/`|\$\(/.test(e)&&!/public|tree|already|matches|nothing|publish/i.test(e)&&[...e.matchAll(/\$\{?([A-Za-z_]\w*|[?])/g)].every(e=>e[1]===t||"?"===e[1]));if("gh"!==n)return!1;let i=sx(e);return 1===i.length&&"run"===i[0][0]&&"watch"===i[0][1]&&sI(sy(i[0]))===t})(e,i.name))&&sf(t).split("\n").some(e=>e.trim()===sT)?i.sha:null}(i,n);s&&e.nothingToPublish.push({sha:s,order:r})}(f,e,a,t),Array.isArray(r=function(e,t,n,r){if(!e.input||"object"!=typeof e.input||Array.isArray(e.input)||"string"!=typeof e.toolName)return null;let i=a4(t);if("notRun"===i)return null;let a={toolCallId:e.toolCallId,attempt:0},s=n&&!i?"running":"unobserved",o=aB(e);if(null!==o){var l;let n,i,c=(l=t,(i=(n=l?.details)&&"object"==typeof n&&"backgroundJob"in n?n.backgroundJob:null)&&"object"==typeof i&&"jobId"in i&&"after"in i&&"string"==typeof i.jobId&&"string"==typeof i.after?{jobId:i.jobId,after:i.after}:null);return aV(o,t).map(n=>{var i,l,d,u;let p,h;if("commit"===n.stage){let e,r,l=t?"unobserved"===n.state&&function(e,t){if(t.isError)return!1;let{commands:n}=af(e),r=sf(t),i=e=>n.some(({words:t})=>aO(t,0,e));return(!i("commit")||a2.test(r))&&(!i("push")||a8.test(r))}(o,t)?"done":a0[n.state]:s;return{...a,stage:"commit",..."done"===l?(e=(i=t)?sf(i):"",(r=a2.exec(e))?{commit:r[1],title:r[2].trim()}:{commit:a8.exec(e)?.[1]??null}):{commit:null},docsOnly:!1,outcome:l}}let m=n.evidence??(c&&null!==n.exitCode?`Command exited with code ${n.exitCode}`:void 0),f=m&&c?`${c.jobId} \xb7 ${m}`:m,g="ci"===n.stage&&"failed"===n.state&&t?function(e,t){let n=af(e).commands.flatMap(({words:e})=>sx(e)),r=n.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),i=r?sy(r):null;if(null===i||!n.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&sy(e)===i))return null;let a=sg(sf(t)).filter(e=>"completed"===e.status&&"string"==typeof e.conclusion),s=1===a.length?a[0].conclusion:null;return"string"!=typeof s||""===s||"success"===s||Object.hasOwn(sP,s)?null:s}(o,t):null,x=g?"unverified":t?n.state:s,v="check"===n.stage&&x===n.state?n.reason:void 0;return{...a,stage:n.stage,command:o,..."check"===n.stage?{cwd:(l=e.input,d=r,u=e.toolCallId,p=d?tx(d)??d:void 0,(h="string"==typeof l.cwd?l.cwd:"")?tx(h,p)??(p?tx(`${p.replace(/\/+$/,"")}/${h}`):null)??`?${u}`:p??"")}:{},exitCode:n.exitCode,labels:n.labels,outcome:x,...n.compound?{compound:n.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=i?void 0:t,u=d?.details&&"object"==typeof d.details?d.details:{};if("cross_review"===c){let t="resolve"===e.input.action?"resolve":"review";if(!d||d.isError)return{...a,stage:"review",action:t,findings:null,outcome:d?"failed":s};if("resolve"===t){if(!0===u.pass)return{...a,stage:"review",action:t,findings:0,outcome:"passed"};let e=Array.isArray(u.open)?u.open.length:null;return{...a,stage:"review",action:t,findings:e,outcome:!1===u.pass?"failed":"unobserved"}}let n=Array.isArray(u.findings)?u.findings.length:null;if(null!==n&&n>0)return{...a,stage:"review",action:t,findings:n,outcome:"failed"};let r=Array.isArray(u.reviewers)?u.reviewers:[];return!1===u.passable||r.some(e=>!e||"object"!=typeof e||!("status"in e)||"ok"!==e.status)?{...a,stage:"review",action:t,findings:n,outcome:"unverified",unusable:!0}:{...a,stage:"review",action:t,findings:n,outcome:null===n?"unobserved":"done"}}if("git_finalize"===c){let t="string"==typeof e.input.message?a1(e.input.message):void 0,n=t?{title:t}:{};if(!d)return{...a,stage:"commit",commit:null,docsOnly:!1,...n,outcome:s};let r=se(d,u),i=d.isError||!1===u.ok,o=!i&&(!0===u.ok||null!==r),l=e.input.files,c=o&&Array.isArray(l)&&l.length>0&&l.every(e=>"string"==typeof e&&aZ(e));return{...a,stage:"commit",commit:o?r:null,docsOnly:c,...n,outcome:o?"done":i?"failed":"unobserved"}}if("git_integrate"===c){if("abort"===e.input.action||"up-to-date"===u.stage)return null;if(!d)return{...a,stage:"commit",commit:null,docsOnly:!1,outcome:s};let t=se(d,u),n=d.isError||!1===u.ok,r=!n&&null!==t,i=u.files,o=r&&Array.isArray(i)&&i.length>0&&i.every(e=>"string"==typeof e&&aZ(e));return{...a,stage:"commit",commit:r?t:null,docsOnly:o,outcome:r?"done":n?"failed":"unobserved"}}if("eval"===c)return function(e,t,n){let r=function(e){if("string"==typeof e.code)return e.code;let t=e.cells;return Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"").join("\n"):""}(e.input);if(!a5.test(r))return null;let i=a9.exec(r)?.[2],a=void 0===i?void 0:a1(i.replace(/\\n/g,"\n").replace(/\\(["'`\\])/g,"$1")),s={toolCallId:e.toolCallId,attempt:0,stage:"commit",docsOnly:!1,...a?{title:a}:{}};if(!t)return{...s,commit:null,outcome:n};let o=sf(t),l=a6.exec(o),c=l?(l[1]??l[2]).toLowerCase():null;if(!c&&a7.test(o))return null;let d=a3.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(aX,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(aQ,e.input.action);if(!tv(e.toolName)&&!tb(e.toolName))return!1;let n=e.input.file_path??e.input.path;return"string"!=typeof n||/^[a-zA-Z]:[\\/]/.test(n)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(n)}(e,c))return!i&&t?.isError?null:(tv(e.toolName)||tb(e.toolName))&&tS(e.input,d,r)?{...a,stage:"investigate",outcome:i?"unobserved":t||!n?"done":"running"}:{...a,stage:"edit",outcome:d?"done":s,..."task"===c?{dispatch:!0}:{},...!function(e,t,n){if(!t||!(tv(e.toolName)||tb(e.toolName)))return!1;let r=tj(e.input,t);return r.length>0&&r.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let n=t?tx(t)??t:void 0,r=tO(tx(e,t)??e,n);if(/^[\\/]/.test(r)||/^[a-zA-Z]:[\\/]/.test(r))return!1;let i=r.split(/[\\/]/).filter(e=>""!==e&&"."!==e);return"HANDOFF.md"===i.at(-1)||"doc"===i[0]&&"history"===i[1]&&i.length>2})(e,n))}(e,d,r)?{}:{recordOnly:!0}};return Object.hasOwn(aY,c)?{...a,stage:"investigate",outcome:i?"unobserved":t||!n?"done":"running"}:null}(e,a,n,i))?r:r?[r]:[])){let n=a?void 0:x.get(e.toolCallId);"check"===s.stage&&"noResult"===s.reason&&n&&sn(n)&&(s.reason="noCompletion"),b.push({step:s,order:t})}}),s=null,o=!1,b.forEach((e,t)=>{let{step:n,order:r}=e;if("commit"===n.stage&&"done"===n.outcome&&n.commit&&(s={step:{...n,commit:n.commit},order:r},o=!1),"edit"!==n.stage||"done"!==n.outcome||n.dispatch||n.recordOnly||(o=!0),"ci"!==n.stage||!s)return;let i=s,a=af(n.command).commands.flatMap(({words:e})=>sx(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(a){let e,s=sw(a),l=e=>(f.publishRuns.get(e)?.order??1/0)<=r;if((e=sR(n.command,l).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){sE(n.command,l)||"passed"!==n.outcome&&"failed"!==n.outcome||(s&&"passed"===n.outcome&&f.watched.push({id:s,order:r}),b[t]={order:r,step:{...n,outcome:"unverified",evidence:void 0,otherRun:{kind:"publish",outcome:n.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=>sL(e,i,f))){d&&o&&"passed"===n.outcome&&(b[t]={order:r,step:{...n,stale:!0}});return}if("passed"===n.outcome||"failed"===n.outcome){let e=d.slice(0,7);b[t]={order:r,step:{...n,outcome:"unverified",evidence:`run ${s} \xb7 ${e}`,otherRun:{kind:"commit",sha:e,outcome:n.outcome}}}}return}if("unverified"!==n.outcome)return;let l=f.runs.find(e=>e.order===r&&null!==e.workflow&&Object.hasOwn(sh,e.workflow)&&sL(e,i,f));if(!l||"completed"!==l.status||"string"!=typeof l.conclusion)return;let c="success"===l.conclusion?"passed":Object.hasOwn(sP,l.conclusion)?"failed":null;c&&(b[t]={order:r,step:{...n,outcome:c,evidence:`run ${l.id??"?"} \xb7 ${l.status} ${l.conclusion}`,..."passed"===c&&o?{stale:!0}:{}}})}),b.forEach((e,t)=>{let{step:n,order:r}=e;if("deploy"!==n.stage||"unverified"!==n.outcome&&"unobserved"!==n.outcome)return;let i=function(e){let t=[],n=(e,r)=>{let i=ak(e);if(null!==i){if(r<3)for(let e of af(i).commands)n(e.words,r+1);return}if(!aT(e))return;let a=aC(e),s=aN.test(e[a])?a:e.findIndex((e,t)=>t>a&&!e.startsWith("-")),o=e[s+1];t.push(void 0!==o&&/^[0-9a-f]{7,40}$/i.test(o)?o.toLowerCase():null)};for(let{words:t}of af(e).commands)n(t,0);return 1===t.length?t[0]:null}(n.command),a=x.get(n.toolCallId);if("number"!=typeof a?.timestamp)return;let s=a.details,o=s&&"object"==typeof s&&"wallTimeMs"in s&&"number"==typeof s.wallTimeMs?s.wallTimeMs:0,l=1e3*Math.floor((a.timestamp-o)/1e3);for(let e=r;e<g.length;e+=1){let a=g[e],s=a?.type==="toolCall"?v.get(a.toolCallId):void 0;if(s)for(let e of sf(s).split("\n")){let a=e.trim().replace(/^\d+[:-](?=\d{4}-\d\d-\d\dT)/,"");if(null===i){let e=sF.exec(a);e&&Date.parse(e[1])>=l&&(i=e[2]);continue}let s=sA.exec(a);if(s&&Date.parse(s[1])>=l&&s$(s[2],i)){b[t]={order:r,step:{...n,outcome:"passed",evidence:`${s[1]} READY ${s[2].slice(0,12)}`}};return}let o=s_.exec(a);if(o&&Date.parse(o[1])>=l){b[t]={order:r,step:{...n,outcome:"failed",evidence:a.length>120?`${a.slice(0,119)}…`:a}};return}}}});let y=(e,t)=>null!==e&&(f.publishRuns.get(e)?.order??1/0)<=t;for(let{step:e,order:t}of b){let n=e;if("ci"===n.stage){let e=af(n.command).commands.flatMap(({words:e})=>sx(e)).find(e=>"run"===e[0]&&"watch"===e[1]),r=e?sw(e):null;r&&"passed"===n.outcome&&f.watched.push({id:r,order:t}),!n.compound&&sE(n.command,e=>y(e,t))&&(n={toolCallId:n.toolCallId,attempt:n.attempt,stage:"investigate",outcome:"passed"===n.outcome||"unverified"===n.outcome?"done":n.outcome})}if("edit"!==n.stage||"done"!==n.outcome||n.dispatch){if("check"===n.stage||"review"===n.stage||"ci"===n.stage){let e="check"===n.stage?`check:${ss(n)}`:n.stage,t=u.get(e);(t?.outcome!=="failed"||si(n.outcome))&&u.set(e,{stage:n.stage,outcome:n.outcome,order:l.length})}}else{let e=sa(u);e&&(c.push({from:e,attempt:d}),d+=1),u=new Map,p=l.length,n.recordOnly||(h=l.length)}n.attempt=d,m.set(n,t),l.push(n)}let w=!1;l.forEach((e,t)=>{t<("commit"===e.stage||w&&("ci"===e.stage||"deploy"===e.stage)?h:p)&&"investigate"!==e.stage&&"edit"!==e.stage&&("passed"===e.outcome||"done"===e.outcome)&&(e.stale=!0),"commit"===e.stage&&"done"===e.outcome&&(w=!0)});let k=l.filter(e=>"commit"===e.stage&&"done"===e.outcome&&e.attempt===d).at(-1),j=k?m.get(k)??-1:-1,S=k&&!k.stale&&k.commit&&sm.test(k.commit)?{sha:k.commit.toLowerCase(),order:j}:null,C=S?function(e,t,n){let r=e.watched.find(({id:n,order:r})=>{let i=e.publishRuns.get(n);return r>t.order&&i?.sha===t.sha&&i.order>t.order&&i.order<=r});if(!r)return null;let i=new Map;for(let t of e.heads)t.order>r.order&&i.set(`${t.repo}#${t.ref}`,t);let a=[...n,...e.ciHeads.filter(e=>e.order<t.order)];for(let e of i.values())if(null!==e.sha&&e.sha!==t.sha&&a.some(t=>t.repo===e.repo&&t.sha===e.sha&&t.branch===e.ref))return{kind:"publicHeadUnchanged",repo:e.repo,ref:e.ref,sha:e.sha,runId:r.id};return null}(f,S,r)??(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,n)=>{var r;let i,a=m.get(t)??-1;if("ci"!==t.stage||"unverified"!==t.outcome||a<=j||!f.nothingToPublish.some(t=>t.order===a&&t.sha===e)&&(r=t.command,!((i=af(r).commands.flatMap(({words:e})=>sx(e))).length>0&&i.every(t=>"run"===t[0]&&"list"===t[1]&&sv(t,["-c","--commit"])?.toLowerCase()===e))))return;let s={toolCallId:t.toolCallId,attempt:t.attempt,stage:"investigate",outcome:"done"};l[n]=s,m.set(s,a)})}let N=au.map(e=>{let t=l.filter(t=>t.stage===e),n="investigate"===e?t:t.filter(e=>e.attempt===d);return{stage:e,status:function(e,t){if(0===t.length)return"waiting";if("check"!==e){let e=new Set,n=null;for(let r of t){let t=r.stale?"stale":r.outcome;if("failed"!==n||si(r.outcome)){if(null!==n&&!("ci"!==r.stage||sd(t))&&!af(r.command).commands.some(({words:e})=>sx(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===n&&(su(r)?.every(t=>e.has(t))??!1);if(sd(n)||t)continue}if(n=t,"stale"===t||"passed"===r.outcome||"failed"===r.outcome)for(let t of su(r)??[])e.add(t)}}return n??"waiting"}let n="done";for(let e of so(t)){let t=e.stale?"stale":e.outcome;sc[t]>sc[n]&&(n=t)}return n}(e,n),steps:n,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),T=N[au.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[au.indexOf("ci")],R=M.steps.some(e=>(m.get(e)??1/0)>j);C&&("waiting"===M.status||("unverified"===M.status||"stale"===M.status)&&!R)?M.status="notNeeded":C=null;let E=-1;N.forEach((e,t)=>{"waiting"!==e.status&&"failed"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status&&"stale"!==e.status&&e.steps.some(e=>!e.stale&&"failed"!==e.outcome&&!sl(e))&&(E=t)});let $=null;if(n&&l.length>0)if(sa(u))$={stage:"edit",returning:!0};else if(E<0)$={stage:N.find(e=>"waiting"!==e.status)?.stage??au[0],returning:!1};else{let e=N[E].steps.at(-1);if(e?.stage==="review"&&e.unusable)$={stage:"review",returning:!1};else{let e=N.slice(E+1).find(e=>"skipped"!==e.status&&"notNeeded"!==e.status);$=e?{stage:e.stage,returning:!1}:null}}if(N.forEach((e,t)=>{t<E&&"waiting"===e.status&&(e.status="skipped")}),!n&&l.length>0){let e=!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,n){let r=e.at(-1);if(!r)return null;if(!n||n.stale)return r.stage;let i=t.filter(e=>("commit"===e.stage||"ci"===e.stage||"deploy"===e.stage)&&e.steps.length>0&&"notNeeded"!==e.status&&"skipped"!==e.status),a=i.find(e=>"commit"!==e.stage&&Object.hasOwn(sW,e.status));return a?.stage??i.at(-1)?.stage??r.stage}(l,N,k),reached:E<0?null:au[E],next:$,publication:C}}let sW={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0};function sO(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 sD(e,t,n){let r=[],i=[],a=null;for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){i.push(n);continue}if(tL(n.toolName)){let e=t$(n,t.get(n.toolCallId));"authoritative"===e.kind&&(a=e.phases);continue}let e=aK(n,t.get(n.toolCallId));e&&r.push(e)}return{checks:r,dispatchCalls:i,files:tM(e,t,n),remaining:a?sO(a):null}}function sH(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}function sU(e,t,n){let r=[],i=null;for(let a=Math.max(0,t);a<Math.min(e.length,n);a++){let t=e[a];if("assistant"===t.role)for(let e of t.content??[])"toolCall"===e.type&&(i=e.toolCallId);else if("custom"===t.role&&"async-result"===t.customType){let e="string"==typeof t.content?t.content:t.content.map(e=>"text"===e.type?e.text:"").join("\n");r.push({text:e,after:i})}}return r}function sB(e,t){var n;let r=t;for(;r>=0&&(n=e[r],n?.role==="custom"?"compaction"===n.customType:n?.role==="user"&&("steer"===ad(n)||function(e){if(e===ae||e===at||e===an||ar.has(e))return!0;let[t,n]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==n&&n.startsWith("requestId=")}(ac(n))));){let t=r-1;for(;t>=0&&"user"!==e[t].role;)t-=1;r=t}return r}function sq(e,t,n,r){let i=Math.min(e.length,r),a=new Map;for(let t=Math.max(0,n);t<i;t++){let n=e[t];"toolResult"===n.role&&a.set(n.toolCallId,t)}let s=[];for(let r=Math.max(0,n-1);r<i;r++){let i=e[r];if(r>=n&&"assistant"===i.role)for(let e of i.content??[]){if("toolCall"!==e.type||!tL(e.toolName))continue;let n=t$(e,t.get(e.toolCallId));"authoritative"===n.kind&&s.push({at:a.get(e.toolCallId)??r,phases:n.phases})}for(let e of i.trackerTodos??[]){let t=tE(e);t&&s.push({at:r+.5,phases:t})}}let o=null;for(let e of s)(!o||e.at>=o.at)&&(o=e);return o?o.phases:null}function sV(e,t,n,r=0,i=[]){for(let a=Math.max(0,r);a<Math.min(e.length,n);a++){let n=e[a];if("assistant"===n.role)for(let e of n.content??[])"toolCall"===e.type&&i.push(...sN(e,t.get(e.toolCallId)))}return i}function sK(e,t,n){let r=null,i=null;for(let a=Math.max(0,t-1);a<Math.min(e.length,n);a++){let t=e[a];for(let e of[t.timestamp,"assistant"===t.role?t.completedAt:void 0])"number"==typeof e&&Number.isFinite(e)&&((null===r||e<r)&&(r=e),(null===i||e>i)&&(i=e))}return{startedAt:r,endedAt:i}}function sG(e,t){if(0===e.length)return null;let n=[...e].sort((e,t)=>e-t),r=(n.length-1)*t,i=Math.floor(r),a=Math.ceil(r);return n[i]+(n[a]-n[i])*(r-i)}let sJ=["investigate","implement","verify","report"],sZ={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},sY={bash:!0,eval:!0};function sX(e){let t=[],n=new Map;for(let r of e)if("toolResult"===r.role&&n.set(r.toolCallId,r),"assistant"===r.role&&Array.isArray(r.content))for(let e of r.content)"toolCall"===e.type&&t.push(e);return{blocks:t,results:n}}function sQ(e,t,n,r){return!0===sZ[t]&&!tS(e.input,n.get(e.toolCallId),r)}function s0(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function s1(e){return"yield"===s0(e)&&!Array.isArray(e.input?.type)}function s2(e,t){if(0===e.length)return null;let{blocks:n,results:r}=sX(e),i=-1;n.forEach((e,t)=>{s1(e)&&(i=t)});let a=i>=0&&i===n.length-1,s=a?n.findLastIndex((e,t)=>t<i&&s1(e))+1:i+1,o={calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:a,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1},l=!1;for(let e of n.slice(s)){let n=s0(e);if(sQ(e,n,r,t))"verify"===o.phase&&(o.reedits+=1),l=!0,o.phase="implement",o.verifiedAfterEdit=!1;else if(sY[n]){if(o.phase=l?"verify":"investigate",l){o.verifiedAfterEdit=!0;let t=aK(e,r.get(e.toolCallId));t?.state==="passed"?o.checks.passed+=1:t?.state==="failed"?o.checks.failed+=1:t&&(o.checks.unknown+=1)}}else"yield"===n&&(o.phase="report",l=!1);o.calls[o.phase]+=1}return o}function s8(e,t){if(!e)return{run:null,stations:sJ.map(e=>({phase:e,state:"unobserved",calls:0}))};let n=t&&e.ended?{calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:!1,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1}:e,r=t?sJ.indexOf(n.phase):sJ.findLastIndex(e=>n.calls[e]>0),i=sJ.map((e,i)=>{let a,s=n.calls[e];return a=t&&e===n.phase?"active":s>0?"verify"!==e||n.verifiedAfterEdit?"done":"stale":i<r?"skipped":t?"waiting":"none",{phase:e,state:a,calls:s}});return{run:n,stations:i}}function s4(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function s5(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:n}}function s6(e){return"pending"===e||"running"===e}let s3=new Map;function s7(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function s9(e){return e instanceof iz&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function oe(e,{sessionId:t,client:n,enabled:r}){let[a,s]=(0,i.useState)(s3),o=(0,i.useRef)(new Map),l=(0,i.useRef)(e);l.current=e;let c=(0,i.useCallback)(()=>{let e=o.current;s(t=>{let n=!1,r=new Map;for(let[i,a]of e){let e=t.get(i),s=e&&e.entries===a.collected&&e.state===a.state?e:{state:a.state,entries:a.collected};s!==e&&(n=!0),r.set(i,s)}return r.size!==t.size&&(n=!0),n?r:t})},[]),d=e.map(e=>`${e.key}|${s7(e)}`).join("\n");return(0,i.useEffect)(()=>{if(!r)return;let e=!1,i=!1,a=null,s=o.current,d=new Set(l.current.map(e=>e.key));for(let e of[...s.keys()])d.has(e)||s.delete(e);for(let e of l.current){let t=s7(e);s.get(e.key)?.signature!==t&&s.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(r,i,a,s)=>{if(!r.archiveName){i.state={kind:"empty",source:"live",note:s};return}try{let o=await n.getArchiveTranscript(t,r.archiveName,400,a);if(e)return;0===i.collected.length&&(i.collected=o.entries.flatMap((e,t)=>{let n=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:n,message:e.message}]:e.irc?[{id:n,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),i.state=0===o.entries.length?{kind:"empty",source:"archive",note:s}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:s}}catch(n){if(e||a.aborted)return;let t=s9(n);i.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(r,i)=>{let a=s.get(r.key);if(a){if(!r.liveId)return void await u(r,a,i);try{var o,l;let s=await n.getLiveTranscript(t,r.liveId,a.nextByte,i);if(e)return;let c=(o=s.entries,l=s.fromByte,o.flatMap((e,t)=>{let n=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:n,message:s5(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:n,irc:{from:"string"==typeof t.from?t.from:void 0,message:"string"==typeof t.message?t.message:void 0}}]}return[]}));s.reset||0===s.fromByte?a.collected=c:c.length>0&&(a.collected=[...a.collected,...c]),a.nextByte=s.nextByte,a.collected.length>0?("ready-live"!==a.state.kind||a.state.entries!==a.collected)&&(a.state={kind:"ready-live",entries:a.collected}):await u(r,a,i)}catch(t){if(e||i.aborted)return;if(r.archiveName){let e=s9(t);await u(r,a,i,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=s9(t);a.state="unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message}}}}},h=async()=>{if(e||i||"u">typeof document&&"visible"!==document.visibilityState)return;i=!0;let t=new AbortController;a=t;try{for(let e of l.current)await p(e,t.signal)}finally{i=!1}e||c()};h();let m=l.current.some(e=>s6(e.status))?setInterval(()=>void h(),3e3):void 0,f=()=>{"visible"===document.visibilityState&&h()};return document.addEventListener("visibilitychange",f),()=>{e=!0,a?.abort(),clearInterval(m),document.removeEventListener("visibilitychange",f)}},[n,r,c,t,d]),a}let ot=(0,i.createContext)({ledger:iG,subagents:[],toolResults:new Map}),on="omp-web:flow-motion",or=new Set,oi=null;function oa(){if(null===oi)try{oi="paused"===window.localStorage.getItem(on)}catch{oi=!1}return oi}function os(e){return or.add(e),()=>{or.delete(e)}}function oo(){return(0,i.useSyncExternalStore)(os,oa,()=>!1)}function ol({paused:e}){let{st:t}=iw();return(0,r.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){oi=e;try{e?window.localStorage.setItem(on,"paused"):window.localStorage.removeItem(on)}catch{}for(let e of or)e()})(!e),children:t("graph.motion.pause")})}function oc(e,t,n){return n&&t.current===e.stage?"active":"waiting"===e.status?"deploy"===e.stage?"approval":"waiting":"skipped"===e.status||"notNeeded"===e.status?"skipped":"stale"===e.status?"stale":"done"===e.status||"passed"===e.status?"done":"failed"===e.status||"running"===e.status?e.status:"unverified"}function od(e){return e.stale?"stale":e.outcome}let ou=(0,r.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})});function op({look:e}){return(0,r.jsxs)("span",{className:"flow-node","aria-hidden":"true",children:[("done"===e||"stale"===e)&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:"stale"===e?"3 4":void 0,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}),"unverified"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"6",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"18",x2:"12",y2:"18.5"})]}),"failed"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"7",y1:"7",x2:"17",y2:"17"}),(0,r.jsx)("line",{x1:"17",y1:"7",x2:"7",y2:"17"})]}),"skipped"===e&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:(0,r.jsx)("line",{x1:"6",y1:"12",x2:"18",y2:"12"})})]})}function oh({outcome:e}){let t={className:"flow-check-icon",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"stale"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l4 2"})]}):"passed"===e||"done"===e?(0,r.jsx)("svg",{...t,strokeWidth:2.5,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}):"failed"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2.5,children:[(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"}),(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"})]}):"running"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0"}),(0,r.jsx)("path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0"}),(0,r.jsx)("path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7"}),(0,r.jsx)("path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8"}),(0,r.jsx)("path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69"}),(0,r.jsx)("path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8"}),(0,r.jsx)("path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69"}),(0,r.jsx)("path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7"})]}):(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,r.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}function om({step:e,st:t}){let n=t(`flow.state.${e.outcome}`);if(e.stale)n=t("passed"===e.outcome?"flow.state.stale":"flow.state.staleDone");else if("review"===e.stage&&"failed"===e.outcome&&null!==e.findings){let r=1===e.findings?"flow.state.findings.one":"flow.state.findings";n=t("resolve"===e.action?"flow.state.open":r,{count:e.findings})}else"review"===e.stage&&e.unusable?n=t("flow.state.reviewUnusable"):"review"===e.stage&&"done"===e.outcome&&(n=t("flow.state.noFindings"));return(0,r.jsxs)("span",{className:"flow-tone","data-tone":od(e),children:[n,"commit"===e.stage&&e.commit&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsxs)("span",{className:"flow-sha-tail",children:["\xb7\xa0",(0,r.jsx)("code",{className:"flow-sha",children:e.commit.slice(0,7)})]})]})]})}let of={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"},og={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 ox({step:e,label:t,st:n}){let i=sl(e),a=e.compound?.stages.map(e=>n(`flow.stage.${e}`)).join("\xb7")??"",s=e.otherRun,o=e.reason?of[e.reason]:void 0,l=i?n("flow.why.compoundConfirmed",{stages:a}):s?.kind==="unjudged"?n("flow.why.watched.unjudged",{conclusion:s.conclusion}):s?n(`flow.why.watched.${s.outcome}`):n("flow.why.exitZero"),c=i?n("flow.why.compoundMissing"):o?n(o,{label:t}):"check"===e.stage?n("flow.why.check",{label:t}):s?.kind==="commit"?n("flow.why.ciOtherRun",{sha:s.sha}):s?.kind==="publish"?n("flow.why.ciPublishRun"):s?.kind==="unjudged"?n("flow.why.ciUnjudged",{conclusion:s.conclusion}):n(`flow.why.${e.stage}`),d=e.reason?n(og[e.reason]):i?n("flow.next.compound"):null,u="unverified"===e.outcome||"unobserved"===e.outcome&&void 0!==e.reason,p=null!==e.exitCode?n("flow.exit",{code:e.exitCode}):n("failed"===e.outcome?"flow.exit.error":"running"===e.outcome?"flow.state.running":"flow.exit.none");return(0,r.jsxs)("div",{className:"flow-raw",children:[u&&(0,r.jsxs)("p",{className:"flow-why",children:["unverified"===e.outcome&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("b",{children:n("flow.why.confirmed")})," ",l,(0,r.jsx)("br",{})]}),(0,r.jsx)("b",{children:n("flow.why.missing")})," ",c,d&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("br",{}),(0,r.jsx)("b",{children:n("flow.why.next")})," ",d]})]}),e.stale&&(0,r.jsx)("p",{className:"flow-why",children:n("flow.why.stale")}),void 0===e.commandKey?(0,r.jsx)("code",{className:"flow-raw-command",children:e.command}):(0,r.jsx)("p",{className:"flow-why",children:n("flow.commandOmitted")}),(0,r.jsx)("div",{className:"flow-exit",children:p}),e.evidence&&(0,r.jsxs)("div",{className:"flow-exit",children:[n("flow.evidence")," ",(0,r.jsx)("code",{className:"flow-evidence",children:e.evidence})]})]})}function ov({steps:e,st:t,attempts:n=!1}){return(0,r.jsx)("ul",{className:"flow-checks",children:e.map(e=>{let i="check"===e.stage?e.labels.map(e=>t(`flow.label.${e}`)).join("\xb7")||t("flow.label.check"):"review"===e.stage?t("resolve"===e.action?"flow.label.resolve":"flow.label.review"):"ci"===e.stage||"deploy"===e.stage||"commit"===e.stage?t(`flow.label.${e.stage}`):t(`flow.stage.${e.stage}`),a=od(e),s=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oh,{outcome:a}),(0,r.jsx)(om,{step:e,st:t}),(0,r.jsxs)("span",{className:"flow-check-label",children:[n?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${i}`:i,sl(e)&&(0,r.jsx)("span",{className:"flow-compound",children:t("flow.compound.failed")})]})]});return"check"!==e.stage&&"ci"!==e.stage&&"deploy"!==e.stage?(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsx)("div",{className:"flow-check-head",children:s})},e.toolCallId):(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsxs)("details",{children:[(0,r.jsxs)("summary",{className:"flow-check-head",children:[s,(0,r.jsxs)("span",{className:"flow-disclose",children:[t("flow.details"),ou]})]}),(0,r.jsx)(ox,{step:e,label:i,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function ob({steps:e,st:t}){return 0===e.length?null:(0,r.jsxs)("details",{className:"flow-earlier",children:[(0,r.jsxs)("summary",{className:"flow-earlier-toggle",children:[t("flow.earlier",{count:e.length}),ou]}),(0,r.jsx)(ov,{steps:e,st:t,attempts:!0})]})}function oy({view:e,steps:t,st:n}){if(0===t.length)return null;if("check"!==e.stage)return(0,r.jsx)(ov,{steps:t,st:n});let i=so(t),a=e=>{let t=ow.indexOf(od(e));return t<0?ow.length:t},s=[...i].sort((e,t)=>a(e)-a(t)),o=t.filter(e=>!i.includes(e));return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ov,{steps:s,st:n}),o.length>0&&(0,r.jsxs)("details",{className:"flow-earlier",children:[(0,r.jsxs)("summary",{className:"flow-earlier-toggle",children:[n("flow.repeats",{count:o.length}),ou]}),(0,r.jsx)(ov,{steps:o,st:n})]})]})}let ow=["failed","unverified","unobserved","stale","running","passed"];function ok({view:e,flow:t,live:n,st:i,compact:a=!1}){if(n&&t.current===e.stage)return i("flow.state.running");if("waiting"===e.status)return i("flow.state.waiting");if("skipped"===e.status||"notNeeded"===e.status)return i(`flow.state.${e.status}`);let s=e.steps[e.steps.length-1];if("investigate"===e.stage)return i("running"===e.status?"flow.state.running":"flow.state.done");if("edit"===e.stage&&"done"===e.status)return i(t.attempt>1?"flow.state.redone":"flow.state.done");if("check"===e.stage&&!a){let t=new Map;for(let n of so(e.steps))t.set(od(n),(t.get(od(n))??0)+1);return ow.filter(e=>t.has(e)).map((e,n)=>(0,r.jsxs)("span",{children:[n>0&&" \xb7 ",(0,r.jsx)("span",{className:"flow-tone","data-tone":e,children:i(`flow.count.${e}`,{count:t.get(e)??0})})]},e))}return"check"===e.stage||"edit"===e.stage?(0,r.jsx)("span",{className:"flow-tone","data-tone":e.status,children:i(`flow.state.${e.status}`)}):(0,r.jsx)(om,{step:s,st:i})}function oj({flow:e,live:t,st:n,id:i}){let a=e.loops[e.loops.length-1],s=a?e.steps.filter(e=>e.stage===a.from):[],o=n("flow.loop.badge",{attempt:e.attempt});return(0,r.jsxs)("div",{className:"flow-chain-panel",id:i,children:[(0,r.jsxs)("div",{className:"flow-chain-wrap","data-loop":a?"":void 0,style:a?{"--loop-from":au.indexOf(a.from)}:void 0,children:[(0,r.jsx)("ol",{className:"flow-chain","aria-label":n("flow.aria"),children:e.stages.map(i=>{let a=oc(i,e,t);return(0,r.jsxs)("li",{className:"flow-link","data-state":a,"aria-current":"active"===a?"step":void 0,children:[(0,r.jsx)(op,{look:a}),(0,r.jsx)("span",{className:"flow-link-name",children:n(`flow.stage.${i.stage}`)}),(0,r.jsx)("span",{className:"flow-link-state",children:(0,r.jsx)(ok,{view:i,flow:e,live:t,st:n,compact:!0})})]},i.stage)})}),a&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flow-loop","aria-hidden":"true",children:[(0,r.jsx)("svg",{width:"22",height:"15",viewBox:"0 0 22 15",children:(0,r.jsx)("polyline",{points:"3 12 11 3 19 12",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,r.jsx)("span",{className:"flow-loop-count",children:o})]}),(0,r.jsxs)("p",{className:"flow-loop-caption",children:[(0,r.jsx)("span",{className:"flow-loop-caption-count",children:o}),n("review"===a.from?"flow.loop.findings":"flow.loop.failed",{stage:n(`flow.stage.${a.from}`),attempt:a.attempt})]})]})]}),s.length>0&&(0,r.jsx)("div",{className:"flow-chain-attempts",children:(0,r.jsx)(ov,{steps:s,st:n,attempts:!0})})]})}function oS({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:a=!0,cwd:s}){let o=(0,i.useMemo)(()=>t.filter(e=>s6(e.status)),[t]),l=r&&!!e&&o.length>0,c=oe((0,i.useMemo)(()=>o.map(e=>({key:e.id,liveId:e.id,status:e.status})),[o]),{sessionId:e??"",client:n,enabled:l&&a}),[d,u]=(0,i.useState)(null),p=o.map(e=>e.id).sort().join("\n");return(0,i.useEffect)(()=>{let t;if(!l||!e)return;let n=new AbortController,r=p.split("\n"),i=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,a=!0,s=0;async function o(){try{let t=await fetch(i,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!n.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),a=r.some(e=>!s.histories[e]))}catch{}finally{if(!n.signal.aborted){let e=a&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{n.abort(),window.clearTimeout(t)}},[p,l,e]),(0,i.useMemo)(()=>{let t=new Map;if(!l)return t;let n=d&&d.sessionId===e?d.histories:void 0;for(let e of o){let r=(a?c.get(e.id)?.entries??[]:[]).flatMap(e=>"message"in e?[e.message]:[]);t.set(e.id,{phase:function(e,t){if(0===e.length)return null;let{blocks:n,results:r}=sX(e),i="investigate",a=!1;for(let e of n){let n=s0(e);sQ(e,n,r,t)?(a=!0,i="implement"):sY[n]?i=a?"verify":"investigate":"yield"===n&&(i="report",a=!1)}return i}(r,s),trace:s2(r,s),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=tP([...e],t);if(!n)return null;let r=t_(n);return 0===r.total||null===r.percent?null:{completed:r.completed,total:r.total,percent:r.percent,activeTask:r.activeTask?.content??null}}(r),history:n?.[e.id]??null})}return t},[o,s,d,l,c,e,a])}function oC(e,t){let n=s4(t);return n?0===n.hours?e("duration.minutes",{minutes:n.minutes}):0===n.minutes?e("duration.hours",{hours:n.hours}):e("duration.hoursMinutes",{hours:n.hours,minutes:n.minutes}):e("duration.underMinute")}function oN(e,t){let n=Math.floor(t/1e3);return n<60?e("duration.seconds",{seconds:n}):n<3600?e("duration.minutesSeconds",{minutes:Math.floor(n/60),seconds:n%60}):oC(e,t)}function oT({phase:e}){let{st:t}=iw();return(0,r.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,r.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,r.jsx)("span",{"aria-hidden":"true",children:sJ.map((n,i)=>(0,r.jsxs)("span",{children:[i>0&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,r.jsx)("span",{"data-current":n===e?"":void 0,style:n===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${n}`)})]},n))})]})}let oI={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function oM(e,t){let n=t.passed+t.failed+t.unknown,i=t.failed>0?"failed":t.unknown>0?"unverified":"passed";return(0,r.jsx)("span",{className:"flow-tone","data-tone":i,children:e("subflow.checks",{passed:t.passed,total:n})})}function oR({flow:e,live:t,verdict:n,attempts:i}){let{st:a}=iw(),s=oo(),o=e.stations.findIndex(e=>"active"===e.state),l=sJ.indexOf("implement"),c=i.filter(e=>"rework"===e.verdict).length,d=n?"accepted"===n.verdict?"done":"unverified":"waiting",u=n?`${a(`verdict.${n.verdict}`)}${null!==n.attempt&&n.attempt>1?` \xb7 ${a("verdict.attempt",{attempt:n.attempt})}`:""}`:a(t?"flow.state.waiting":"verdict.none");return(0,r.jsxs)("div",{className:"subagent-flow",children:[t&&o>=0&&(0,r.jsx)(ol,{paused:s}),(0,r.jsxs)("ol",{className:"flow-graph","aria-label":a("subflow.aria"),"data-live":t?"":void 0,"data-motion":s?"paused":void 0,children:[e.stations.map((t,n)=>{let i=oI[t.state];return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":t.phase,"data-state":i,"data-loop":c>0&&n>=l?"":void 0,"aria-current":"active"===t.state?"step":void 0,style:{"--col":n+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a(`phase.${t.phase}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(op,{look:i}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:function(e,t,n){let i="verify"===t.phase&&null!==n&&n.checks.passed+n.checks.failed+n.checks.unknown>0;switch(t.state){case"active":return i&&n?(0,r.jsxs)(r.Fragment,{children:[e("flow.state.running")," \xb7 ",oM(e,n.checks)]}):e("flow.state.running");case"waiting":return e("flow.state.waiting");case"skipped":return e("flow.state.skipped");case"none":return e("detail.stageNone");case"unobserved":return e("subflow.unobserved");case"stale":return e(n&&n.checks.passed>0?"flow.state.stale":"flow.state.staleDone");case"done":if("report"===t.phase)return e("subflow.reported");if(i&&n)return oM(e,n.checks);if("implement"===t.phase&&n&&n.reedits>0)return`${e("subflow.calls",{count:t.calls})} \xb7 ${e("subflow.reedits",{count:n.reedits})}`;return e("subflow.calls",{count:t.calls})}}(a,t,e.run)})]})]})},t.phase)}),(0,r.jsx)("li",{className:"flow-graph-station","data-stage":"verdict","data-state":d,style:{"--col":sJ.length+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a("graph.join")}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(op,{look:d}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:u})]})]})}),c>0&&(0,r.jsxs)("li",{className:"flow-graph-return",style:{"--from":l+1,"--to":sJ.length+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsx)("span",{className:"flow-graph-return-text",children:a("subflow.rework",{count:c})})]})]})]})}function oE(e,t){let n=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${n} \xb7 ${t.activeTask}`:n}function o$({snapshot:e,view:t,id:n}){var i,a,s;let o,l,c,{st:d}=iw(),u=nj(5e3),p="number"!=typeof(o=e.progress?.durationMs)?null:o+(("pending"===e.status||"running"===e.status)&&e.lastUpdate>0?Math.max(0,u-e.lastUpdate):0);if(null===p)return null;let h=function(e,t){if(!e||e.rework||null===t||e.durationsSec.length<3)return null;let n=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(n.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:n.length};let r=sG(n,.5)??0;return{kind:"remaining",p25Ms:sG(n,.25)??0,medianMs:r,p75Ms:sG(n,.75)??0,samples:n.length,percent:Math.round(t/(t+r)*100)}}(t.history,p),m=(i=t.todo,!i||null===p||0===i.completed||i.completed>=i.total?null:p*(i.total-i.completed)/i.completed),f={color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},g=t.history,x=g?.rework&&null!==g.firstDispatchedAtMs?u-g.firstDispatchedAtMs:null;return(0,r.jsxs)("span",{id:n,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,r.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:d("eta.elapsed",{duration:oN(d,p)})}),g?.rework&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:d("eta.reworkHint"),children:null!==x&&x>=0?d("eta.rework",{attempt:g.attempt,duration:oN(d,x)}):d("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{title:d("eta.hint"),children:d("eta.remaining",{range:(a=h.p25Ms,s=h.p75Ms,l=s4(a),c=s4(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:oC(d,a),high:oC(d,s)})),samples:h.samples})})," \xb7 ",(0,r.jsx)("span",{style:f,children:d("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:{color:"var(--warning)"},title:d("eta.hint"),children:0===h.longerRuns?d("eta.overrun",{longest:oC(d,h.longestMs)}):d("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==m&&t.todo&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:d("eta.byTodoHint"),children:m<6e4?d("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):d("eta.byTodo",{duration:oC(d,m),completed:t.todo.completed,total:t.todo.total})})]})]})}let oL={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},oP={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function oA({maker:e,st:t}){let n=e.verdict?.verdict??"none",i=e.verdict?.attempt;return(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(oL[e.run])}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":n,children:[t(oP[n]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function o_(e,t){let n=[],r=new Map;for(let t of e)"message"in t&&("assistant"===t.message.role?n.push(...t.message.content??[]):"toolResult"===t.message.role&&r.set(t.message.toolCallId,t.message));return sD(n,r,t)}function oF(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function oz(e,t){let n=e?.state;return n?.kind!=="ready-live"?null:s2(n.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function oW({maker:e,st:t}){let n=e.runTitle??e.title;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:n,children:n}),e.priorVerdict&&!e.runTitle&&(0,r.jsx)("span",{className:"answer-dispatch-title-note",children:t("subflow.firstTitle")})]})}function oO({calls:e}){let{ledger:t,subagents:n,toolResults:a,onOpenPanel:s,sessionId:o,cwd:l,onOpenMaker:c,selectedMaker:d}=(0,i.useContext)(ot),{st:u}=iw(),{t:p}=(0,z.s)(),[h,m]=(0,i.useState)(!1),f=(0,i.useId)(),g=(0,i.useMemo)(()=>iB(),[]),x=(0,i.useMemo)(()=>e.flatMap(e=>i0(e,a.get(e.toolCallId))??[]).map(e=>i4(e,n,t)),[e,a,n,t]),v=(0,i.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=i8(e.member,n,t);return r?[r]:[]}),[x,n,t]),b=oS({sessionId:o,snapshots:v,client:g,enabled:!0,transcripts:h,cwd:l}),y=(0,i.useMemo)(()=>new Map(x.flatMap(e=>{let t=i5(e.member,n);return t?[[e.member.key,t]]:[]})),[x,n]),w=(0,i.useMemo)(()=>h?[...y].filter(([,e])=>!s6(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:oF(t)})):[],[y,h]),k=oe(w,{sessionId:o??"",client:g,enabled:h&&!!o&&w.length>0}),j=d?.origin?x.find(e=>e.member.key===d.origin):void 0,S=j?.run,C=j?.verdict??null;if((0,i.useEffect)(()=>{if(!d||!c||!S)return;let e=d.status;e&&e.run===S&&e.verdict?.order===C?.order||c({...d,status:{run:S,verdict:C}},!1)},[c,d,S,C]),0===x.length)return null;let N=0,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,r.jsxs)("section",{className:"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":h,"aria-controls":f,title:u(h?"dispatch.collapse":"dispatch.expand"),onClick:()=>m(e=>!e),children:[(0,r.jsx)("span",{className:"answer-dispatch-heading",children:u("dispatch.title",{count:x.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:u("dispatch.tally",{running:N,done:T,accepted:I})}),(0,r.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,r.jsx)("ul",{className:"answer-dispatch-list",id:f,"aria-label":h?p("dispatchLane.label"):void 0,children:x.map(e=>{var n;let i,a="pending"===e.run||"running"===e.run,s=a?v.find(t=>t.id===e.member.agentId):void 0,o=s?b.get(s.id):void 0,p=y.get(e.member.key),m=e.member.key===d?.origin,f=a&&"live"===e.runSource,g=h?s8(f?o?.trace??null:oz(k.get(e.member.key),l),f):null,x=h?i6(e.member,t):[];return(0,r.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":m?"":void 0,children:[h?(0,r.jsx)(oD,{maker:e,phase:f&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,n){if(!t)return{kind:"unobserved"};if(s6(t.status))return{kind:"running"};let r=e?.state;if(!r||"loading"===r.kind)return{kind:"loading"};if("ready-live"===r.kind){let{checks:e}=o_(r.entries,n);return{kind:"counted",passed:e.filter(e=>"passed"===e.state).length,total:e.length}}return"empty"===r.kind&&"live"===r.source?{kind:"counted",passed:0,total:0}:{kind:"unobserved"}}(k.get(e.member.key),p,l),onOpen:p&&c?()=>c({key:`live:${p.id}`,toolCallId:e.member.toolCallId,origin:e.member.key,status:{run:e.run,verdict:e.verdict}}):null}):(0,r.jsxs)("div",{className:"answer-dispatch-line",children:[(0,r.jsx)(oW,{maker:e,st:u}),(0,r.jsx)(oA,{maker:e,st:u})]}),g&&(0,r.jsx)(oR,{flow:g,live:f,verdict:e.verdict,attempts:x}),h&&(0,r.jsx)(oU,{attempts:x}),s&&o&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[o.todo?`${oE(u,o.todo)} \xb7 `:null,(0,r.jsx)(o$,{snapshot:s,view:o})]}),h&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[a&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??u("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.model")}),(0,r.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${u("detail.fallback")}`:""}`:u("detail.modelNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${u("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("subflow.prior")}),(0,r.jsx)("dd",{children:(i=null!==(n=e.priorVerdict).attempt&&n.attempt>1?` \xb7 ${u("verdict.attempt",{attempt:n.attempt})}`:"",`${u(oP[n.verdict])}${i}${n.reason?` \xb7 ${n.reason}`:""}`)})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u(e.runTitle?"subflow.firstTitle":"subflow.runTitle")}),(0,r.jsx)("dd",{children:e.runTitle?e.title:u("detail.stageNone")})]}),e.verdict?.reason&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),h&&s&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:u("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:u("detail.openProcess")})]})]})}function oD({maker:e,phase:t,checks:n,onOpen:i}){let{st:a}=iw(),{t:s}=(0,z.s)(),o=e.verdict?.verdict??"none",l=a(oL[e.run]),c="running"===n.kind?null:"counted"===n.kind?s("dispatchLane.checks",{passed:n.passed,total:n.total}):s("loading"===n.kind?"dispatchLane.checksLoading":"dispatchLane.checksUnobserved");return(0,r.jsxs)("div",{className:"answer-dispatch-line is-lane",children:[(0,r.jsx)(oW,{maker:e,st:a}),(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?s("dispatchLane.runPhase",{run:l,phase:t}):l}),c&&(0,r.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===n.kind&&n.passed<n.total?"failed":n.kind,children:c}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsx)("span",{className:"answer-status-verdict","data-verdict":o,children:a(oP[o])})]}),i?(0,r.jsx)("button",{type:"button",className:"answer-link answer-dispatch-open","aria-label":s("dispatchLane.openLabel",{title:e.title}),onClick:i,children:s("dispatchLane.open")}):(0,r.jsx)("span",{className:"answer-dispatch-unavailable",title:s("makerDetail.unavailable"),children:s("dispatchLane.unavailable")})]})}function oH({maker:e}){let{ledger:t,subagents:n,sessionId:a,cwd:s}=(0,i.useContext)(ot),o=(0,i.useMemo)(()=>iB(),[]),l="pending"===e.run||"running"===e.run,c=l&&"live"===e.runSource,d=l?i8(e.member,n,t):void 0,u=oS({sessionId:a,snapshots:(0,i.useMemo)(()=>d?[d]:[],[d]),client:o,enabled:!0,transcripts:!0,cwd:s}),p=i5(e.member,n),h=(0,i.useMemo)(()=>p&&!s6(p.status)?[{key:e.member.key,liveId:p.id,status:p.status,archiveName:oF(p)}]:[],[p,e.member.key]),m=oe(h,{sessionId:a??"",client:o,enabled:!!a&&h.length>0}),f=d?u.get(d.id):void 0,g=s8(c?f?.trace??null:oz(m.get(e.member.key),s),c),x=i6(e.member,t);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oR,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,r.jsx)(oU,{attempts:x})]})}function oU({attempts:e}){let{t}=(0,z.s)();return e.length<2?null:(0,r.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":t("dispatchLane.label"),children:e.map((e,n)=>(0,r.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[n>0&&(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→ "}),null===e.attempt?t("dispatchLane.attemptUnknown"):t("dispatchLane.attempt",{attempt:e.attempt})," ",t(`dispatchLane.verdict.${e.verdict}`)]},`${e.attempt??"n"}-${n}`))})}let oB={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},oq={html:0,document:1,image:2},oV=/\.(?:md|mdx|markdown|txt)$/i;function oK(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function oG(e,t,n){return"investigate"!==e.stage&&("edit"===e.stage?n>0||e.earlier.length>0:e.steps.length>0||e.earlier.length>0||"ci"===e.stage&&null!==t.publication)}function oJ({entry:e,st:t}){let n="running"===e.maker.run||"pending"===e.maker.run||"dispatching"===e.maker.run;return e.bar&&null!==e.durationMs?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"flow-graph-track","aria-hidden":"true",children:(0,r.jsx)("span",{className:"flow-graph-bar",style:{left:oK(e.bar.offset),width:oK(e.bar.width)}})}),(0,r.jsx)("span",{className:"flow-graph-time",children:oN(t,e.durationMs)})]}):(0,r.jsx)("span",{className:"flow-graph-time-missing",children:t(n?"summary.time.running":"summary.time.unobserved")})}function oZ({entry:e,together:t,batch:n=!1,st:i}){let a=e.maker.member.workClass;return(0,r.jsxs)("span",{className:"flow-graph-maker-tags",children:[(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":a?void 0:"",children:i(`graph.kind.${a??"unknown"}`)}),n&&e.batchSize>1&&(0,r.jsx)("span",{className:"flow-graph-chip",children:i("graph.parallel.batch")}),t&&(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":"unknown"===e.concurrency?"":void 0,"data-concurrency":e.concurrency,children:i(`graph.concurrency.${e.concurrency}`)})]})}function oY({selectable:e,selected:t,detailId:n,onSelect:i,className:a,children:s,style:o}){return e?(0,r.jsx)("button",{type:"button",className:a,style:o,"aria-pressed":t,"aria-controls":n,onClick:i,children:s}):(0,r.jsx)("div",{className:a,style:o,children:s})}function oX({summary:e,makers:t,timings:n,live:a=!1,onOpenFile:s}){let o,l,c,{subagents:d,onOpenMaker:u}=(0,i.useContext)(ot),{st:p}=iw(),h=(0,i.useId)(),{flow:m}=e,f=(0,i.useMemo)(()=>(function(e,t,n,r){let i=function(e,t){let n=t.map(e=>null!==e.startedAt&&null!==e.durationMs?{start:e.startedAt,end:e.startedAt+e.durationMs}:null),r=e.startedAt,i=e.endedAt;for(let e of n)e&&((null===r||e.start<r)&&(r=e.start),(null===i||e.end>i)&&(i=e.end));let a=null!==r&&null!==i?i-r:0;return n.map(e=>e?a<=0||null===r?{offset:0,width:1}:{offset:(e.start-r)/a,width:(e.end-e.start)/a}:null)}(n,t),a=e.map(e=>"live"===e.runSource&&"running"===e.run),s=new Map;for(let t of e)s.set(t.member.toolCallId,(s.get(t.member.toolCallId)??0)+1);let o=e.map((n,r)=>{let o="unknown";for(let t=0;t<e.length;t+=1)if(t!==r&&(a[r]&&a[t]||n.observedParallelWith?.has(e[t].member.key))){o="overlapped";break}return{maker:n,bar:i[r],durationMs:t[r]?.durationMs??null,concurrency:o,batchSize:s.get(n.member.toolCallId)??1,liveRunning:a[r]}});return{makers:o,parallel:o.some(e=>"overlapped"===e.concurrency)?"observed":o.some(e=>e.batchSize>1)?"batch":"none",files:r.filter(e=>!oV.test(e.filePath)),docs:r.filter(e=>oV.test(e.filePath))}})(t,n,e.span,e.files),[t,n,e.span,e.files]),[g,x]=(0,i.useState)(void 0),v=oo(),b=e.files.length,y=a&&m.current?m.stages.find(e=>e.stage===m.current):void 0,w=void 0===g?y&&oG(y,m,b)?`stage:${y.stage}`:(o=m.stages.filter(e=>oG(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?au.indexOf(k.from):-1,S=au.indexOf("edit"),C=y?au.indexOf(y.stage):-1,N=f.makers.some(e=>e.liveRunning),T=f.files.length>0||f.docs.length>0,I=(0,i.useMemo)(()=>a?[]:function(e,t,n,r){let i=au.indexOf("edit"),a=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,s=[],o=n,l=e=>{let t=au.indexOf(e.stage);o&&t>i&&(s.push("branch"),o=!1),s.push(e.stage),o&&t===i&&(s.push("branch"),o=!1)},c=t[t.length-1];if(c){let t=au.indexOf(c.from);for(let n of e)au.indexOf(n.stage)<=t&&(a(n)||n.earlier.length>0||n.stage===c.from)&&l(n);for(let t of(o&&(s.push("branch"),o=!1),s.push("return"),e))au.indexOf(t.stage)>=i&&a(t)&&l(t)}else for(let t of e)a(t)&&l(t);return o&&s.push("branch"),r&&s.push("outputs"),s}(m.stages,m.loops,f.makers.length>0,T),[a,m.stages,m.loops,f.makers.length,T]),[M,R]=(0,i.useState)(null),E=null!==M&&M<I.length?M:null;(0,i.useEffect)(()=>{if(null===E)return;let e=window.setTimeout(()=>R(E+1<I.length?E+1:null),800);return()=>window.clearTimeout(e)},[E,I.length]);let $=e=>{if(null!==E&&I.includes(e))return I[E]===e?"now":I.slice(0,E).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 P=1===L.size&&L.has("accepted"),A=m.stages[S+1],_=A?oc(A,m,a):"skipped",F=f.makers.length>0&&(0,r.jsxs)("li",{className:"flow-graph-branch","data-loop":k&&j>S?"":void 0,"data-merge":"skipped"===_||"waiting"===_||"approval"===_?"quiet":void 0,"data-beat":$("branch"),children:[(0,r.jsxs)("p",{className:"flow-graph-branch-head",children:[(0,r.jsx)("span",{children:p(1===f.makers.length?"graph.branch.one":"graph.branch",{count:f.makers.length})}),"none"!==f.parallel&&(0,r.jsx)("span",{className:"flow-graph-chip","data-parallel":f.parallel,children:p(`graph.parallel.${f.parallel}`)})]}),(0,r.jsx)("ul",{className:"flow-graph-lanes",children:f.makers.map(e=>{let t=`maker:${e.maker.member.key}`;return(0,r.jsx)("li",{className:"flow-graph-lane","data-run":e.maker.run,"data-live":e.liveRunning?"":void 0,children:(0,r.jsxs)(oY,{selectable:!0,selected:w===t,detailId:h,onSelect:()=>x(w===t?null:t),className:"flow-graph-maker",children:[(0,r.jsx)("span",{className:"flow-graph-maker-name",title:e.maker.title,children:e.maker.title}),(0,r.jsx)(oZ,{entry:e,together:f.makers.length>1,st:p}),(0,r.jsx)("span",{className:"flow-graph-maker-time",children:(0,r.jsx)(oJ,{entry:e,st:p})}),(0,r.jsx)(oA,{maker:e.maker,st:p})]})},e.maker.member.key)})}),(0,r.jsxs)("p",{className:"flow-graph-join","data-state":P?"done":"unverified",children:[(0,r.jsx)(op,{look:P?"done":"unverified"}),(0,r.jsx)("span",{className:"flow-graph-join-label",children:p("graph.join")}),(0,r.jsx)("span",{className:"flow-graph-join-counts",children:["accepted","rework","held","none"].filter(e=>L.has(e)).map(e=>(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":e,children:[p(oP[e])," ",L.get(e)]},e))})]})]},"branch"),z=k&&(0,r.jsxs)("li",{className:"flow-graph-return","data-beat":$("return"),style:{"--from":S+1,"--to":j+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsxs)("span",{className:"flow-graph-return-text",children:[(0,r.jsx)("b",{children:p("flow.loop.badge",{attempt: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 n=oc(e,m,a),i=`stage:${e.stage}`,s=e.steps.some(sl);return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":e.stage,"data-state":n,"data-again":e.earlier.length>0?"":void 0,"data-loop":k&&t>=S&&t<j?"":void 0,"data-beat":$(e.stage),"aria-current":"active"===n?"step":void 0,style:{"--col":t+1},children:(0,r.jsxs)(oY,{selectable:oG(e,m,b),selected:w===i,detailId:h,onSelect:()=>x(i),className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:p(`flow.stage.${e.stage}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(op,{look:n}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:(0,r.jsx)(ok,{view:e,flow:m,live:a,st:p})})]}),s&&(0,r.jsx)("span",{className:"flow-compound",children:p("flow.compound.failed")})]})},e.stage)}),O=[];W.forEach((e,t)=>{O.push(e),t===S&&F&&O.push(F),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 n="ci"===t.stage&&null!==m.publication&&"notNeeded"===t.status,i="edit"===t.stage||n?[]:t.steps;D=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:p(`flow.stage.${t.stage}`)}),"ci"===t.stage&&m.publication&&(0,r.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,r.jsx)(iL,{files:e.files,onOpenFile:s}),(0,r.jsx)(oy,{view:t,steps:i,st:p}),(0,r.jsx)(ob,{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=i5(e.maker.member,d);D=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,r.jsx)(oZ,{entry:e,together:f.makers.length>1,batch:!0,st:p}),(0,r.jsx)("p",{className:"flow-graph-detail-line",children:(0,r.jsx)(oA,{maker:e.maker,st:p})}),(0,r.jsx)("div",{className:"flow-graph-maker-time",children:(0,r.jsx)(oJ,{entry:e,st:p})}),(0,r.jsx)(oH,{maker:e.maker}),t&&u?(0,r.jsx)("button",{type:"button",className:"flow-graph-open",onClick:()=>u({key:`live:${t.id}`,toolCallId:e.maker.member.toolCallId,origin:e.maker.member.key,status:{run:e.maker.run,verdict:e.maker.verdict}}),children:p("graph.maker.open")}):(0,r.jsx)("p",{className:"flow-graph-note",children:p("graph.maker.unavailable")})]})}}else("files"===w||"docs"===w)&&(D=(0,r.jsxs)(r.Fragment,{children:[(0,r.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,r.jsx)(iL,{files:"files"===w?f.files:f.docs,onOpenFile:s})]}));return(0,r.jsxs)("section",{className:"flow-section",children:[(0,r.jsxs)("div",{className:"flow-graph-head",children:[(0,r.jsx)("h4",{className:"flow-heading",children:p("flow.heading")}),(C>=0||N)&&(0,r.jsx)(ol,{paused:v}),I.length>1&&(0,r.jsx)("button",{type:"button",className:"flow-graph-replay",onClick:()=>R(null===E?0:null),children:p(null===E?"graph.replay":"graph.replay.stop")})]}),(0,r.jsx)("div",{className:"flow-graph-frame",children:(0,r.jsxs)("ol",{className:"flow-graph","aria-label":p("flow.aria"),"data-live":a?"":void 0,"data-motion":v?"paused":void 0,"data-replay":null===E?void 0:"",children:[O,T&&(0,r.jsxs)("li",{className:"flow-graph-outputs","data-beat":$("outputs"),children:[(0,r.jsx)("span",{className:"flow-graph-outputs-label",children:p("graph.outputs")}),f.files.length>0&&(0,r.jsx)(oY,{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,r.jsx)(oY,{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,r.jsx)("div",{className:"flow-graph-detail",id:h,role:"region","aria-label":p("graph.detail.aria"),children:D})]})}function oQ(e,t,n){let r=new URLSearchParams({type:t});return n&&r.set("sessionId",n),`/api/files/${tz(e)}?${r}`}function o0(e,t){let[n,r]=(0,i.useState)({kind:"loading"});return(0,i.useEffect)(()=>{let n=new AbortController;return r({kind:"loading"}),fetch(e,{method:"head"===t?"HEAD":"GET",cache:"no-store",signal:n.signal}).then(async e=>{if(!e.ok)return null;if("head"===t)return"";if("text"===t)return e.text();let n=await e.json();return"string"==typeof n.content?n.content:null}).then(e=>{n.signal.aborted||r(null===e?{kind:"failed"}:{kind:"ready",content:e})}).catch(()=>{n.signal.aborted||r({kind:"failed"})}),()=>n.abort()},[e,t]),n}function o1({messageKey:e}){let{st:t}=iw();return(0,r.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function o2({deliverable:e,sessionId:t,title:n}){let{filePath:i,kind:a}=e;if("image"===a){let e=oQ(i,"read",t);return(0,r.jsx)(o6,{src:e,title:n},e)}if("html"===a){let e=oQ(i,"read",t);return(0,r.jsx)(o8,{url:e,title:n},e)}if(i.toLowerCase().endsWith(".pdf")){let e=oQ(i,"read",t);return(0,r.jsx)(o4,{url:e,title:n},e)}let s=oQ(i,"preview",t);return(0,r.jsx)(o5,{url:s,title:n},s)}function o8({url:e,title:t}){let n=o0(e,"json");return"ready"!==n.kind?(0,r.jsx)(o1,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-scripts",title:t,scrolling:"no",inert:!0})}function o4({url:e,title:t}){let n=o0(e,"head");return"ready"!==n.kind?(0,r.jsx)(o1,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",src:`${e}#toolbar=0&view=FitH`,title:t,inert:!0})}function o5({url:e,title:t}){let n=o0(e,"text");return"ready"!==n.kind?(0,r.jsx)(o1,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-same-origin",title:t,inert:!0})}function o6({src:e,title:t}){let[n,a]=(0,i.useState)("loading");return"failed"===n?(0,r.jsx)(o1,{messageKey:"result.previewFailed"}):(0,r.jsxs)(r.Fragment,{children:["loading"===n?(0,r.jsx)(o1,{messageKey:"result.previewLoading"}):null,(0,r.jsx)("img",{className:"answer-result-media","data-fit":"contain",src:e,alt:t,draggable:!1,hidden:"loading"===n,onLoad:()=>a("ready"),onError:()=>a("failed")})]})}function o3({deliverables:e,onOpenFile:t}){let{sessionId:n}=(0,i.useContext)(ot),{st:a}=iw(),[o,l]=function(){let e=(0,i.useRef)(null),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{let r=e.current;if(!r||t)return;if("u"<typeof IntersectionObserver)return void n(!0);let i=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n(!0)},{rootMargin:"200px 0px"});return i.observe(r),()=>i.disconnect()},[t]),[e,t]}(),[c,...d]=e;if(!c)return null;let u=tW(c.filePath),p=a("result.previewTitle",{name:u}),h=t?()=>t(c.filePath):void 0;return(0,r.jsxs)("section",{className:"answer-result","aria-label":a("result.label"),children:[(0,r.jsxs)("div",{ref:o,className:"answer-result-frame","data-kind":c.kind,children:[l&&(0,r.jsx)(o2,{deliverable:c,sessionId:n,title:p}),h&&(0,r.jsx)("button",{type:"button",className:"answer-result-cover",tabIndex:-1,"aria-hidden":"true",onClick:h})]}),(0,r.jsxs)("div",{className:"answer-result-bar",children:[(0,r.jsxs)("span",{className:"answer-result-title",children:[(0,r.jsx)("span",{className:"answer-result-kind",children:a("html"===c.kind?"result.kind.html":"image"===c.kind?"result.kind.image":c.filePath.toLowerCase().endsWith(".pdf")?"result.kind.pdf":"result.kind.document")}),(0,r.jsx)("span",{className:"answer-result-name",title:c.filePath,children:u})]}),h&&(0,r.jsx)(s.r,{className:"answer-result-open",variant:"neutralSolid",size:"medium",onClick:h,"aria-label":a("result.openNamed",{name:u}),children:a("result.open")})]}),d.length>0&&(0,r.jsxs)("div",{className:"answer-result-more",children:[(0,r.jsx)("span",{className:"answer-result-more-label",children:a("result.more",{count:d.length})}),(0,r.jsx)(iL,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}function o7({summary:e,live:t=!1,onOpenFile:n}){let{ledger:a,subagents:s,toolResults:o}=(0,i.useContext)(ot),{st:l}=iw(),c=(0,i.useMemo)(()=>t?[]:function(e){let t=[];for(let n of e){if(function(e){let t=e.toLowerCase().replace(/\\/g,"/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e];if(Object.hasOwn(oB,n)||n.startsWith(".next")||"doc"===n&&"history"===t[e+1])return!0}return!1}(n.filePath))continue;let e=function(e){let t=eB(e);return"html"===t||"htm"===t?"html":eV(e)?"document":eq(e)?"image":null}(n.filePath);e&&t.push({filePath:n.filePath,kind:e})}return t.map((e,t)=>({deliverable:e,index:t})).sort((e,t)=>oq[e.deliverable.kind]-oq[t.deliverable.kind]||e.index-t.index).map(({deliverable:e})=>e)}(e.files),[t,e.files]),[d,u]=(0,i.useState)(null),p=d??(e.latest&&0===c.length),h=(0,i.useId)(),m=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>i0(e,o.get(e.toolCallId))??[]).map(e=>i4(e,s,a)),[e.dispatchCalls,o,s,a]),f=(0,i.useMemo)(()=>m.map(e=>({startedAt:a.spawnedAt.get(e.member.key)??null,durationMs:a.durations.get(e.member.key)??null})),[m,a]),{flow:g,remaining:x}=e,v=so(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,r.jsxs)("div",{className:"answer-summary","data-open":p?"":void 0,"data-live":t?"":void 0,"data-result":c.length>0?"":void 0,children:[c.length>0&&(0,r.jsx)(o3,{deliverables:c,onOpenFile:n}),(0,r.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":p,"aria-controls":h,title:l(p?"summary.collapse":"summary.expand"),onClick:()=>u(!p),children:[(0,r.jsx)("span",{className:"answer-summary-text","data-unverified":N?"":void 0,children:C.join(" \xb7 ")}),(0,r.jsx)("svg",{className:"answer-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),p&&(0,r.jsxs)("div",{className:"answer-summary-body",id:h,children:[g.steps.length>0&&(0,r.jsx)(oX,{summary:e,makers:m,timings:f,live:t,onOpenFile:n}),x&&(0,r.jsxs)("section",{className:"flow-remaining",children:[(0,r.jsx)("h4",{className:"flow-heading",children:l("summary.heading.remaining")}),0===x.length?(0,r.jsx)("p",{className:"answer-summary-empty",children:l("summary.todo.none")}):(0,r.jsx)("ul",{className:"flow-remaining-list",children:x.map((e,t)=>(0,r.jsxs)("li",{className:"answer-remaining","data-status":e.status,title:e.phase||void 0,children:[(0,r.jsx)("span",{className:"answer-remaining-status",children:l(`summary.todo.${e.status}`)}),(0,r.jsx)("span",{className:"answer-remaining-text",children:e.content}),e.blocker&&(0,r.jsx)("span",{className:"answer-remaining-blocker",children:l("summary.todo.blocker",{blocker:e.blocker})})]},`${e.phase}#${t}`))})]})]})]})}let o9=/^att_[0-9a-f]{32}$/,le=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function lt(e){return"string"==typeof e&&o9.test(e)}function ln(e){return"string"==typeof e&&le.test(e)}class lr extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let li={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},la={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},ls={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function lo(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let n=t.lastIndexOf(".");if(n>0&&la[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&ls[r]?"text":null}let ll={".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 lc(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?ll[t.slice(n)]:void 0;if(r)return r;let i=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return i?.startsWith("audio/")?i:null}function ld(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function lu(e){if(!Array.isArray(e))return[];let t=[],n=0,r=0;for(let i of e){if(i&&"object"==typeof i&&"string"==typeof i.name&&i.name.length>0&&("text/markdown"===i.mimeType||"text/plain"===i.mimeType||"application/pdf"===i.mimeType)&&"number"==typeof i.size&&Number.isSafeInteger(i.size)&&i.size>=0&&i.size<=8388608&&"string"==typeof i.text&&i.text.length<=12e4){if(t.length>=3)break;!(n+i.size>0x1000000)&&(r+i.text.length>24e4||(t.push({name:i.name,mimeType:i.mimeType,size:i.size,text:i.text,...lt(i.attachmentId)?{attachmentId:i.attachmentId}:{}}),n+=i.size,r+=i.text.length))}}return t}async function lp(e){let t,n=lo(e);if(!n)throw new lr("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new lr("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await lk(e);else{try{t=await e.text()}catch(e){throw new lr("read_failed",e instanceof Error?e.message:String(e))}lj(t)}return{name:e.name,mimeType:li[n],size:e.size,text:t}}function lh(e,t){let n=lu(t);if(0===n.length)return e;let r={userMessageLength:e.length,documents:n.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,textLength:r.length}))},i=`${lS}${JSON.stringify(r)}${lC}
|
|
@@ -17,7 +17,7 @@ ${t}`)),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(()=>new Set);if((0,i.use
|
|
|
17
17
|
${t}`,r=e6.get(n);if(void 0!==r)return Promise.resolve(r);let i=e3.get(n);if(i)return i;let a=fetch(e8(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),r=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return e6.set(n,r),r}).catch(()=>0).finally(()=>e3.delete(n));return e3.set(n,a),a})(e,t).then(e=>{n&&s(e)}),()=>{n=!1}},[a,e,t]),!a)return null;let u=Array.from({length:a},(e,t)=>t).filter(e=>!c.has(e));return 0===u.length?null:(0,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(i=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>l(i),children:(0,r.jsx)("img",{src:e8(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(i))})},i)),null!==o&&(0,r.jsx)(lq,{src:e8(e,t,o),fileName:`screen-${t.slice(-8)}-${o+1}`,onClose:()=>l(null)})]})}let lB={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function lq({src:e,fileName:t,onClose:n}){let{t:a}=(0,z.s)(),o=(0,i.useContext)(nE),l=(0,i.useRef)(null),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)([]),[f,g]=(0,i.useState)(null),x=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=l.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{x.current?.abort(),document.body.style.overflow=t,e.open&&e.close()}},[]);let v=()=>{x.current?.abort(),n()},b=async()=>{let r,i;if(!o)return void p(a("toolImage.noComposer"));x.current?.abort();let s=new AbortController;x.current=s,d(!0),p(null);try{let n=await fetch(e,{signal:s.signal});if(!n.ok)throw Error(`HTTP ${n.status}`);let o=await n.blob(),l=lB[o.type];if(!l)throw Error(`unsupported ${o.type}`);if(0!==h.length&&f){let e=await nW(o,h);r=[new File([e.marked],`${t}-marked.png`,{type:"image/png"}),...e.crops.map((e,n)=>new File([e],`${t}-region-${n+1}.png`,{type:"image/png"}))];let n=1===h.length?"1":`1~${h.length}`;i=[a("toolImage.locatorIntro",{range:n}),...h.map((e,t)=>a("toolImage.locatorRegion",{n:t+1,x:e.x,y:e.y,w:e.w,h:e.h,width:f.width,height:f.height}))].join("\n")+"\n"}else r=[new File([o],`${t}.${l}`,{type:o.type})]}catch{if(s.signal.aborted)return;d(!1),p(a("toolImage.loadFailed"));return}if(!s.signal.aborted&&l.current?.open){if(!o(r,i)){d(!1),p(a("toolImage.noComposer"));return}n()}};return(0,q.createPortal)((0,r.jsxs)("dialog",{ref:l,className:"tool-image-dialog","aria-label":a("toolImage.dialogLabel"),onCancel:e=>{e.preventDefault(),v()},onClick:e=>{e.target===e.currentTarget&&v()},children:[(0,r.jsx)(nO,{src:e,regions:h,max:9,onAdd:e=>m(t=>t.length<9?[...t,e]:t),onNaturalSize:g,regionLabel:e=>a("toolImage.regionLabel",{n:e})}),u?(0,r.jsx)("p",{role:"alert",className:"tool-image-error",children:u}):(0,r.jsx)("p",{className:"tool-image-hint","data-hidden":h.length>0&&h.length<9?"true":void 0,children:h.length>=9?a("toolImage.markLimit",{count:9}):a("toolImage.markHint")}),(0,r.jsxs)("div",{className:"tool-image-actions",children:[(0,r.jsx)(s.r,{variant:"neutralSolid",size:"medium",loading:c,onClick:()=>void b(),title:a("toolImage.requestEditHint"),children:a("toolImage.requestEdit")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",disabled:0===h.length,onClick:()=>m([]),children:a("toolImage.clearMarks")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",onClick:v,children:a("i18n.close")})]})]}),document.body)}function lV({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(lE,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function lK({block:e,duration:t,sessionId:n,entryId:a,blockIndex:s}){let{t:o}=(0,z.s)(),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){c(null),u(!1),h(null);return}let t=!1;return n&&a?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=lR.get(r);if(i)return lR.delete(r),lR.set(r,i),i;let a=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw lR.delete(r),e});if(lR.set(r,a),lR.size>100){let e=lR.keys().next().value;e&&lR.delete(e)}return a})(n,a,s).then(e=>{t||c(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(o("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,s,a,n,o]);let m=e.deferred?l:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":o("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:d?(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,r.jsx)(nk,{className:"markdown-thinking-body",children:m}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&f&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function lG({block:e,result:t,duration:n,runStartedAt:a,sessionId:s}){var o;let l,{t:c}=(0,z.s)(),d=(0,i.useId)(),[u]=(0,i.useState)(()=>Date.now()),[p,h]=(0,i.useState)(null),m=(o=t?null:nI(s,e.toolCallId),(0,i.useSyncExternalStore)(nT,()=>o?nS.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 n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let i="string"==typeof n.diff?n.diff:null;return i?{text:i}:null}(t):null,y=x?"unknown"===(l=t$(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?nU(t):null,C=t?t.isError||null!==S&&0!==S?"failed":"done":"running",N="failed"===C,T=p??N;if(x&&y)return(0,r.jsx)(l1,{phases:y});let I=v&&"string"==typeof e.input.command?e.input.command:"",M=function(e,t,n){let r,i=t.html;if(!("ask"===(r=e.trim().toLowerCase())||r.endsWith(".ask")||r.endsWith("_ask"))||"string"!=typeof i)return null;let a="object"==typeof n&&null!==n?n:{},s=[];if(Array.isArray(a.answers))for(let e of a.answers)"string"==typeof e?.question&&"string"==typeof e.answer&&s.push({question:e.question,answer:e.answer});let o=!0===a.timedOut,l=s[0]?.question||i.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),R=null!==M&&M.rows.length>0?M:null,E=!!(y||b||R),$=v?I.split(/\r?\n/,1)[0]??"":M?.target??function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.length)return"";let i=e.toolName.toLowerCase();if(t=i,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(-120);if("file_path"in n)return String(n.file_path).slice(-120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let a=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==a)return String(a).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,y),L=!v&&/^\S+$/.test($)&&/[\\/]/.test($),P=w?c("toolRun.diffStats",{added:w.added,removed:w.removed}):"";return(0,r.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,r.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,r.jsx)(lQ,{toolName:e.toolName}),(0,r.jsx)("span",{className:"tool-call-name",children:v?"bash":e.toolName}),v&&f.includes("(local)")&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"}),(0,r.jsx)("span",{className:`tool-call-target${L?" is-path":""}`,title:v?I:$,children:L?(0,r.jsx)("bdi",{dir:"ltr",children:$}):$}),w&&(0,r.jsxs)("span",{className:"tool-call-diffstats",title:P,"aria-label":P,children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",w.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",w.removed]})]}),(0,r.jsx)(lZ,{state:C,duration:n,exitCode:S,startedAt:a??u}),(0,r.jsx)("svg",{className:"tool-call-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:T?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),"running"===C&&m&&(0,r.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,r.jsx)("div",{id:d,className:"tool-call-body",children:v?(0,r.jsx)(l2,{command:I,output:k??"",pending:!t,isError:N}):(0,r.jsxs)(r.Fragment,{children:[b&&(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(l8,{diff:b})}),t&&N&&(0,r.jsx)(l7,{text:k??"",isEmpty:j,isError:!0}),R&&!N&&(0,r.jsx)(lJ,{summary:R}),!E&&(0,r.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:g}),t&&!E&&!N&&(0,r.jsx)(l7,{text:k??"",isEmpty:j,isError:!1})]})})]})}function lJ({summary:e}){let{t}=(0,z.s)();return(0,r.jsxs)("div",{className:"tool-call-ask",style:{padding:"8px 10px"},children:[(0,r.jsx)("dl",{style:{margin:0,display:"grid",gap:8},children:e.rows.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("dt",{style:{color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflowWrap:"anywhere"},children:e.question}),(0,r.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,r.jsx)("p",{style:{margin:"8px 0 0",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:t("toolRun.askTimedOut")})]})}function lZ({state:e,duration:t,exitCode:n,startedAt:i}){let{t:a}=(0,z.s)();return"running"===e?(0,r.jsx)(lY,{startedAt:i}):(0,r.jsxs)(r.Fragment,{children:[void 0!==t&&(0,r.jsxs)("span",{className:"tool-run-duration",children:[t,"s"]}),"failed"===e&&(0,r.jsxs)("span",{className:"tool-run-failed",children:[(0,r.jsx)(nR.E,{tone:"critical",variant:"weak",size:"medium",children:a("toolRun.failed")}),null!==n&&(0,r.jsx)("span",{className:"tool-run-exit",children:a("toolRun.exitCode",{code:n})})]})]})}function lY({startedAt:e}){let{t}=(0,z.s)(),n=nj(500)-e;return n<400?null:(0,r.jsxs)("span",{className:"tool-run-running",children:[t("toolRun.running"),(0,r.jsxs)("span",{className:"tool-run-duration",children:[Math.floor(n/1e3),"s"]})]})}function lX(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function lQ({toolName:e}){let t,n=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||lX(t,"edit")?"edit":lX(t,"read")||lX(t,"cat")?"read":lX(t,"write")||lX(t,"save")?"write":lX(t,"glob")||lX(t,"find")?"glob":lX(t,"grep")||lX(t,"search")?"grep":lX(t,"bash")||lX(t,"shell")||lX(t,"exec")?"bash":lX(t,"todo")?"todo":lX(t,"eval")?"eval":lX(t,"task")||lX(t,"agent")?"task":lX(t,"browser")||lX(t,"web_search")||lX(t,"fetch")?"browser":lX(t,"image")||lX(t,"inspect_image")?"image":"generic";return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:"var(--text-muted)"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)(l0,{kind:n})})})}function l0({kind:e}){switch(e){case"read":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,r.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,r.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,r.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,r.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,r.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,r.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,r.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,r.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,r.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,r.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,r.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,r.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function l1({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),n=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,r.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,r.jsxs)("div",{className:"todo-checklist-header",children:[(0,r.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,r.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,r.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),n>0&&n<t&&(0,r.jsxs)("span",{className:"todo-checklist-progress",children:[n,"/",t]})]}),(0,r.jsx)("div",{className:"todo-checklist-body",children:e.map((t,n)=>(0,r.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,r.jsx)(iN,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function l2({command:e,output:t,pending:n,isError:i}){let{isDark:a}=ng(),{t:s}=(0,z.s)(),o=ez(t.split(/\r?\n/)),l=1===o.length&&""===o[0]?[]:o;return(0,r.jsxs)("div",{className:`shell-output-preview${i?" is-error":""}`,children:[(0,r.jsxs)("div",{className:"shell-command-line",children:[(0,r.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,r.jsx)(tD.A,{className:"shell-command-code",language:"bash",style:a?tH.xJ:tH.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsx)("div",{className:"shell-output-divider",children:(0,r.jsx)("span",{className:"shell-output-label",children:"Output"})}),(0,r.jsxs)("div",{className:"shell-output-body",children:[0===l.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:s("i18n.noOutput")}),l.map((e,t)=>{let n=eP(e).trimStart(),a=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${a}`.trim(),children:[eW(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},t):(0,r.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)})]})]})]})}function l8({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(l4,{text:e.text})})}function l4({text:e}){let{t}=(0,z.s)(),n=(0,i.useMemo)(()=>iS(e),[e]);if(!n)return(0,r.jsx)(l3,{text:e});let a=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[a&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(l5,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(l5,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(l6,{cell:e.left,side:"left"}),(0,r.jsx)(l6,{cell:e.right,side:"right"})]},t))})]},n))})}function l5({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function l6({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:a,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function l3({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"var(--success-soft)":"removed"===n?"var(--danger-soft)":"hunk"===n?"var(--accent-soft)":"transparent",borderLeft:"added"===n?"3px solid var(--success)":"removed"===n?"3px solid var(--danger)":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"var(--success)":"removed"===n?"var(--danger)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function l7({text:e,isEmpty:t,isError:n}){let{t:i}=(0,z.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--danger-line)":"var(--success-line)"}`,background:n?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?i("i18n.noOutput"):e})})}function l9({message:e}){let{t}=(0,z.s)(),n=cr(e.content),a=(0,i.useMemo)(()=>{let e,t,r,i,a;return e=[],t=[],r=n.match(nq),i=r?.[1]??"",a=r?.index===void 0?n:n.slice(0,r.index),i.replace(nB,(n,r,i)=>{let a=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...a):t.push(...a),""}),{body:a.trim(),readFiles:e,modifiedFiles:t}},[n]),s=lA(e.timestamp),o=e.details&&"object"==typeof e.details&&"tokensBefore"in e.details&&"number"==typeof e.details.tokensBefore&&e.details.tokensBefore>0?e.details.tokensBefore:null;return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==o&&(0,r.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:nV(o)})}),s&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),a.body?(0,r.jsx)(nk,{className:"markdown-compaction-message",children:a.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(ce,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function ce({readFiles:e,modifiedFiles:t}){let{t:n}=(0,z.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(ct,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(ct,{title:n("i18n.readFiles"),files:e})]})}function ct({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function cn({message:e,cwd:t,onOpenFile:n}){var a;let s,{t:o}=(0,z.s)(),l=!1===e.display,[c,d]=(0,i.useState)(!l),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=cr(e.content),g="string"==typeof(a=e.content)?[]:a.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=lA(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),c?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=ci(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,r.jsx)(nk,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(s=f.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":o("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,r.jsx)("button",{className:"message-meta-action",onClick:()=>{nx(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,r.jsx)("button",{onClick:()=>{l?d(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(l?c?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(l&&c||!l&&u)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function cr(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function ci(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 ca({message:e,sessionId:t}){let[n,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(null),d=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===n,m=n??e.output;async function f(){if(p){o(!0),c(null);try{let e=await fetch(p),t=await e.json();t.success?a(t.data?.output??""):c(t.error??"failed")}catch(e){c(String(e))}finally{o(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=d?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:m?[{type:"text",text:m}]:[],isError:u,details:void 0!==e.exitCode?{exitCode:e.exitCode}:void 0,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(lG,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:f,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),l&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",l,")"]})]})]})}n(21340);let cs="cuelo-chat-search",co="cuelo-chat-search-active";function cl(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 cc({open:e,onClose:t,containerRef:n,index:a,renderedStart:s,renderedEnd:o,contentKey:l,onReveal:c,onProgrammaticScroll:d,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[m,f]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)({index:-1,total:0}),y=(0,i.useDeferredValue)(m),w=e?y.trim().toLowerCase():"",k=(0,i.useRef)(g);k.current=g;let j=(0,i.useRef)([]),S=(0,i.useRef)({key:null,needle:"",rendered:!1});(0,i.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,i.useEffect)(()=>()=>{cl(cs,[]),cl(co,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){cl(cs,[]),cl(co,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),i=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let a=(e.textContent??"").toLowerCase(),s=n.get(i);s||(s=[],n.set(i,s));for(let n=a.indexOf(t);-1!==n;n=a.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),s.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,i){let a=[];if(!t)return a;for(let s=0;s<e.length;s++){let o=s>=r&&s<i?n.get(s)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[s],t);for(let e=0;e<o;e++)a.push({item:s,k:e})}return a}(a,w,n,s,o);j.current=r;let i=tp(r,k.current);b(e=>e.index===i&&e.total===r.length?e:{index:i,total:r.length});let l=[];for(let t of e.values())for(let e of t)l.push(e);if(cl(cs,l),i<0){cl(co,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=s&&u.item<o,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){cl(co,[]),f&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(cl(co,g?[g]:[]),f)if(d(),g){let e,n;e=g.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,a,s,o,l,g,n,c,d]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=tp(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,r.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsx)("input",{ref:h,type:"search",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,r.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,r.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}function cd({questions:e,containerRef:t,layoutKey:n,onJump:a,label:s}){let o=(0,i.useRef)(null),[l,c]=(0,i.useState)(-1),[d,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=d&&e.length>=2;(0,i.useEffect)(()=>{let n=t.current;if(!n||!p)return;let r=0,i=null,a=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,a=0,s=i.length-1,o=i.length-1;for(;a<=s;){let e=a+s>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(o=e,s=e-1):a=e+1}let l=o>=0?Number(i[o].dataset.chatItem):-1,d=-1;for(let t of e){if(t.item>l)break;d=t.item}c(d)},s=()=>{r||(r=requestAnimationFrame(a))};return r=requestAnimationFrame(a),n.addEventListener("scroll",s,{passive:!0}),()=>{n.removeEventListener("scroll",s),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,i.useEffect)(()=>{let e=o.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let n=t.offsetTop-e.scrollTop;(n<0||n+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[l]);let h=e.length,m=(0,i.useCallback)((e,t)=>{let n="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===n)return;e.preventDefault();let r=Math.max(0,Math.min(h-1,n));o.current?.querySelectorAll("button")[r]?.focus()},[h]);if(!p)return null;let f=e.some(e=>e.item===l)?l:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,r.jsx)("div",{ref:o,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(cu,{question:e,position:t,count:h,active:e.item===l,focusable:e.item===f,onJump:a,onMoveFocus:m},e.item))})})}let cu=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:a,onJump:s,onMoveFocus:o}){let l=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,r.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:a?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${l}`,title:l,onClick:()=>s(e.item),onKeyDown:e=>o(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function cp({label:e,tone:t,children:n}){return(0,r.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"run-status-label",children:e}),(0,r.jsx)("span",{className:"run-status-text",children:n})]})}let ch={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function cm({compaction:e,t}){let[n,a]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;a(Date.now());let t=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((n-e.startedAt)/1e3)),o=e.reason&&!0===ch[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(cp,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),o?` \xb7 ${o}`:""]})}function cf({onDismiss:e,t}){return(0,r.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,r.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,r.jsxs)("span",{className:"interrupted-run-text",children:[(0,r.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,r.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,r.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}var cg=n(39092),cx=n.n(cg);let cv=["01","02","03"];function cb(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),0x1000193);return(t>>>0)/0x100000000}function cy(e,t,n){if(e&&"streaming"!==t){let r=rA(e);if(r){let e="failed"===t?"failed":"done",i=ro(ra(rP(r),r.id,e)?.stickers??[],null,()=>cb(n));return i?{src:i,alt:n6[e]}:null}}if(!e||"streaming"===t||!n8.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),a=ro(cv.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>cb(n));return a?{src:a,alt:n6[r]}:null}let cw=new Map,ck=(0,i.createContext)(cw);function cj({utterances:e,children:t}){return(0,r.jsx)(ck.Provider,{value:e,children:t})}function cS({turnIndex:e,turnEntryId:t,sessionId:n,cwd:a,onOpenFile:s}){let o=(0,i.useContext)(ck).get(e);return o&&0!==o.length?(0,r.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:o.map(e=>(0,r.jsx)(cC,{utterance:e,sessionId:n,cwd:a,onOpenFile:s},e.key))}):null}function cC({utterance:e,sessionId:t,cwd:n,onOpenFile:a}){let s=iv(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId,e.model),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),u=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=u.current;e&&!o&&d(e.scrollHeight>e.clientHeight+1)},[e.text,o]);let p=e.text.trim().length>0,h=e.label?.trim(),m=s?.alias??h??rG(e.provider),f=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==f?`작업 \xb7 ${h}`:null,x=cy(s?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...s?{minHeight:40}:null},children:[s&&(0,r.jsx)(ik,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(nk,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:a,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(c||o)&&(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:o?"접기":"더보기"}),x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-e0a9ca790f024efb inline-utterance-sticker"}),(0,r.jsx)(cx(),{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 cN=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function cT(e,t,n,r){if("string"!=typeof n)return[];let i=cN.exec(n),a=i?.[1],s=i?.[2];return a&&s?[{toolCallId:e,...t?{name:t}:{},alias:a,model:s,batchSize:r}]:[]}function cI(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[]){if("toolCall"!==n.type||"task"!==n.toolName)continue;let e=n.input,r=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...cT(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let i of e.tasks)!i||"object"!=typeof i||Array.isArray(i)||t.push(...cT(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function cM(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[])"toolCall"===n.type&&"task"===n.toolName&&t.push(n.toolCallId);return t}let cR=/^agent:\/\/([^/?#]+)\/?$/i;function cE(e,t){if(!e||"assistant"!==e.role)return[];let n=[];for(let r of e.content??[]){if("toolCall"!==r.type||"write"!==r.toolName)continue;let e=r.input,i="string"==typeof e.path?cR.exec(e.path):null,a=i?.[1],s=e.content;if(!a||"string"!=typeof s)continue;let o=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:a,message:s,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return n}function c$(e,t,n){for(let r of["string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",t?.model.trim()??""]){let e=r.indexOf("/");if(e>0&&r.slice(0,e)===n)return r.slice(e+1).trim()||void 0}}let cL=["greeting","utterance","message","text"],cP=function(e){let t=(0,i.useMemo)(()=>iB(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let a of n.subagents){if(t.has(a.name))continue;let n=[...i].reverse().find(e=>e.name===a.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},a="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,s="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==a||void 0!==s)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==a?{resolvedModel:a,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),i}(a,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),a="string"==typeof t.task?cN.exec(t.task):null,s=a?.[1],o=a?.[2],l=i.find(e=>e.name===t.id)??(s&&o?r.requests.find(e=>e.alias===s&&e.model===o):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!l)return[];let c=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:r.turnIndex,summon:l,sends:c}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),a=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),s=oe(a,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&a.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:a}=e,s="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",o="failed"===s,l=a?.model.split("/",1)[0]?.trim()||void 0,c=o&&l?l:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=r.indexOf("/");if(i>0)return r.slice(0,i);let a=t?.model.trim()??"",s=a.indexOf("/");return s>0?a.slice(0,s):n?.trim()||void 0}(i,a,n),d=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,n)=>{var r;let f;if("irc"in t){let{from:n,message:r,truncated:a}=t.irc;if(a||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let a=e.sends[t];if(a.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(a.send,i.id)&&a.send.from===n){h=a.turnIndex,m=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||c;if(!g||o&&l&&g!==l)return;let x=((f=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let n of e.content??[]){if("toolCall"!==n.type||"yield"!==n.toolName)continue;let e=n.input.data,r="";if("string"==typeof e)r=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...cL]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let i=r.trim();i.length>0&&(t=i)}return t}(r))||(o?t.message.errorMessage?.trim()??"":"");if(0===x.length)return;let v=t.message.model||c$(i,a,g);p.push({key:`${i.id}:${n}`,turnIndex:h,speakerId:u,provider:g,...v?{model:v}:{},credentialId:t.message.credentialId,accountSessionId:null,label:o&&a?a.alias:d,text:x,status:s})}),0===p.length&&"settled"!==s&&c){let e=o?i.progress?.retryFailure?.errorMessage?.trim():void 0,t=c$(i,a,c);p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:c,...t?{model:t}:{},accountSessionId:null,label:o&&a?a.alias:d,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[r,s,e.sessionProvider])},cA="web6",c_=[],cF=[],cz=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let a=`${t}?sessionId=${encodeURIComponent(i)}`,s=await e(a,{signal:r});if(!s.ok)throw Error(`HTTP ${s.status}`);let o=await s.json(),l=o&&"object"==typeof o&&"consults"in o?o.consults:null;if(!Array.isArray(l))throw Error("consults 배열이 아니다");return l.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:a,text:s,error:o}=e;return{sessionId:t,startedAt:n,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof a&&""!==a?a:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof o&&""!==o?o:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(cF),a=(0,i.useRef)(""),s=e.sessionId??"",o=s.length>0;return(0,i.useEffect)(()=>{if(!o){a.current="",r(cF);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(s,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===a.current)return;a.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,o,s]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return c_;let r=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if("user"!==r.role)continue;let i=r.timestamp;"number"==typeof i&&Number.isFinite(i)&&t.push({index:n,openedAt:i})}return t}(t);if(0===r.length)return c_;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let a=t.error??"";0!==a.trim().length&&i.push({key:`${cA}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${cA}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return i.length>0?i:c_})(n,e.messages,s),[n,e.messages,s])},cW="lab:";function cO(e){return e.startsWith(cW)?e.slice(cW.length).split(":",1)[0]||null:null}let cD={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function cH(e){return e.multi&&e.options.length>1}function cU(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 cB(e,t){let n={};for(let[t,r]of e.hidden)cG(n,t,r);return e.fields.forEach((e,r)=>{let i=t[r];if(!e.name||!i)return;let a=function(e,t){if("text"===e.kind){var n,r,i="text"===t.kind?t.text:"";if(("number"===e.type||"range"===e.type)&&""!==i.trim()){let e=Number(i);if(Number.isFinite(e))return e}return i}if("choice"===t.kind){let i,a;return n=new Set(t.checked),r=t.otherOn?t.other:void 0,i=e.other?r?.trim():void 0,a=e.options.flatMap((e,t)=>n.has(t)&&!e.disabled?[e.value]:[]),cH(e)?i?[...a,i]:a:i||a[0]}}(e,i);void 0!==a&&cG(n,e.name,a)}),n}function cq(e,t){let n={};for(let r of e.fields){if(!r.name||cJ(n,r.name))continue;let e=function(e,t){if("choice"===e.kind){let n=void 0===t||Array.isArray(t)&&0===t.length;if(!e.required||!n)return;return cH(e)?{code:"selectAtLeastOne"}:{code:"required"}}let n=void 0===t?"":String(t);if(""===n.trim())return e.required?{code:"required"}:void 0;if("number"===e.type||"range"===e.type){let t=Number(n);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&&n.length<e.minLength?{code:"minLength",value:e.minLength}:void 0!==e.maxLength&&n.length>e.maxLength?{code:"maxLength",value:e.maxLength}:"email"!==e.type||/^[^\s@]+@[^\s@]+$/.test(n)?"url"!==e.type||URL.canParse(n)?e.pattern&&(function(e){try{return RegExp(`^(?:${e})$`,"v")}catch{return}})(e.pattern)?.test(n)===!1?{code:"pattern",pattern:e.pattern.length>40?`${e.pattern.slice(0,39)}…`:e.pattern}:void 0:{code:"url"}:{code:"email"}}(r,cJ(t,r.name));e&&cG(n,r.name,e)}return n}function cV(e){return e.map(e=>e.text).join("")}function cK(e,t,n){if(!e.multi)return{...t,checked:[n],otherOn:!1};let r=t.checked.includes(n)?t.checked.filter(e=>e!==n):[...t.checked,n].sort((e,t)=>e-t);return{...t,checked:r}}function cG(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function cJ(e,t){return Object.hasOwn(e,t)?e[t]:void 0}let cZ={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},cY={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)"},cX={minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"};function cQ({spans:e}){return(0,r.jsx)(r.Fragment,{children:e.map((e,t)=>{let n=[];return(e.text.split("\n").forEach((e,t)=>{t>0&&n.push((0,r.jsx)("br",{},`br-${t}`)),n.push(e)}),"code"===e.style)?(0,r.jsx)("code",{style:{padding:"0 4px",borderRadius:4,background:"var(--bg-subtle)",fontFamily:"var(--font-mono)",fontSize:"0.92em"},children:n},t):"strong"===e.style?(0,r.jsx)("strong",{style:{fontWeight:600},children:n},t):"em"===e.style?(0,r.jsx)("em",{children:n},t):(0,r.jsx)("span",{children:n},t)})})}function c0({src:e,alt:t}){let{t:n}=(0,z.s)(),[a,s]=(0,i.useState)(!1);return!e||a?(0,r.jsx)("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",overflowWrap:"anywhere"},children:t||n("chat.formImageUnavailable")}):(0,r.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 c1({block:e,id:t}){let n={margin:0,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.55,overflowWrap:"anywhere"};switch(e.kind){case"text":return(0,r.jsx)("p",{id:t,style:{...n,fontWeight:e.heading?600:400},children:(0,r.jsx)(cQ,{spans:e.spans})});case"list":{let t=e.ordered?"ol":"ul";return(0,r.jsx)(t,{style:{...n,paddingInlineStart:22},children:e.items.map((e,t)=>(0,r.jsx)("li",{children:(0,r.jsx)(cQ,{spans:e})},t))})}case"pre":return(0,r.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,r.jsx)("div",{tabIndex:0,style:{maxWidth:"100%",overflowX:"auto",border:"1px solid var(--hairline)",borderRadius:"var(--radius-control)"},children:(0,r.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)("tbody",{children:e.rows.map((t,n)=>(0,r.jsx)("tr",{children:t.map((t,i)=>{let a=n<e.headerRows?"th":"td";return(0,r.jsx)(a,{scope:n<e.headerRows?"col":void 0,style:{padding:"6px 10px",borderBottom:"1px solid var(--hairline)",color:n<e.headerRows?"var(--text-muted)":"var(--text)",fontWeight:n<e.headerRows?600:400,textAlign:"left",verticalAlign:"top",minWidth:72},children:(0,r.jsx)(cQ,{spans:t})},i)})},n))})})});case"image":return(0,r.jsx)(c0,{src:e.src,alt:e.alt})}}function c2({field:e,id:t,index:n,error:i,children:a,hasLabel:s}){let{t:o}=(0,z.s)();return(0,r.jsxs)("div",{"data-field":n,style:{display:"grid",gap:6,minWidth:0},children:[(s||e.required)&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[s&&(0,r.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,r.jsx)(cQ,{spans:e.label})}),e.required&&(0,r.jsx)("span",{style:{marginLeft:s?0:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:o("chat.formRequired")})]}),a,i&&(0,r.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,r.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,r.jsx)("circle",{cx:"7",cy:"7",r:"5.5"}),(0,r.jsx)("path",{d:"M7 4v3.4M7 9.6v.1"})]}),(0,r.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}`)}}(i,o)})]})]})}function c8({field:e,id:t,index:n,state:a,error:s,captionId:o,fallbackName:l,onChange:c}){let{t:d}=(0,z.s)(),u=(0,i.useRef)(null);if("choice"!==a.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,r.jsx)(c2,{field:e,id:t,index:n,error:s,hasLabel:p,children:(0,r.jsx)("select",{id:t,...h,value:String(a.checked[0]??""),onChange:t=>c(n,cK(e,a,Number(t.target.value))),style:{...cY,height:36},children:e.options.map((e,t)=>(0,r.jsx)("option",{value:t,disabled:e.disabled,children:cV(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,r.jsx)(c2,{field:e,id:t,index:n,error:s,hasLabel:p,children:(0,r.jsxs)("div",{role:e.multi?"group":"radiogroup",...h,style:{display:"grid",gap:4},children:[e.options.map((t,i)=>{let s=a.checked.includes(i);return(0,r.jsxs)("label",{style:f(s,t.disabled),children:[(0,r.jsx)("input",{type:m,name:x,checked:s,disabled:t.disabled,"aria-required":!!e.required&&!e.multi||void 0,onChange:()=>c(n,cK(e,a,i)),style:g}),(0,r.jsx)("span",{children:(0,r.jsx)(cQ,{spans:t.label})})]},i)}),e.other&&(0,r.jsxs)("div",{style:{display:"grid",gap:6},children:[(0,r.jsxs)("label",{style:f(a.otherOn,!1),children:[(0,r.jsx)("input",{type:m,name:x,checked:a.otherOn,onChange:()=>{c(n,e.multi?{...a,otherOn:!a.otherOn}:{...a,checked:[],otherOn:!0}),a.otherOn&&e.multi||u.current?.focus()},style:g}),(0,r.jsx)("span",{children:d("chat.formOther")})]}),(0,r.jsx)("input",{ref:u,type:"text",value:a.other,"aria-label":d("chat.formOther"),placeholder:d("chat.formOtherPlaceholder"),onChange:t=>{var r;let i;return c(n,(i=""!==(r=t.target.value).trim(),{...a,other:r,otherOn:!!i||a.otherOn,checked:i&&!e.multi?[]:a.checked}))},style:{...cY,height:36,width:"calc(100% - 35px)",marginInlineStart:35}})]})]})})}function c4({field:e,id:t,index:n,state:i,error:a,captionId:s,fallbackName:o,onChange:l}){if("text"!==i.kind)return null;let c=e.label.length>0,d=Object.hasOwn(cZ,e.type)?e.type:"text",u={id:t,value:i.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":!!a||void 0,"aria-describedby":a?`${t}-error`:void 0},p=a?"1px solid var(--danger)":cY.border;return(0,r.jsx)(c2,{field:e,id:t,index:n,error:a,hasLabel:c,children:e.multiline?(0,r.jsx)("textarea",{...u,rows:Math.max(2,e.rows),onChange:e=>l(n,{kind:"text",text:e.target.value}),style:{...cY,padding:"8px 10px",border:p,lineHeight:1.5,resize:"vertical"}}):(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.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(n,{kind:"text",text:e.target.value}),style:{...cY,height:"color"===d?40:36,border:p,..."range"===d?{padding:0}:{},fontVariantNumeric:"tabular-nums"}}),"range"===d&&(0,r.jsx)("output",{htmlFor:t,style:{minWidth:32,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:i.text})]})})}function c5({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,z.s)(),o=(0,i.useId)(),l=e.form,[c,d]=(0,i.useState)(()=>l.fields.map(cU)),u=(0,i.useRef)(c),[p,h]=(0,i.useState)(!1),m=(0,i.useRef)(null),f=(0,i.useRef)(n);f.current=n;let g=(0,i.useRef)(e);g.current=e;let x=a?.status==="sending",v=(0,i.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=cD){let n,r=-1/0,i=!1,a=()=>{i&&t.clearTimeout(n),i=!1,r=t.now(),e()};return{notify(){let e=1e3-(t.now()-r);e<=0?a():i||(i=!0,n=t.setTimeout(a,e))},cancel(){i&&t.clearTimeout(n),i=!1}}}(()=>{var n,r;let i=g.current;t+=1,f.current?.(i,(n=t,r=cB(i.form,u.current),`activity:form:v2:${e}:${n}:${JSON.stringify(r)}`))})}(0,i.useEffect)(()=>()=>v.current?.cancel(),[]);let b=(0,i.useCallback)((e,t)=>{let n=u.current.slice();n[e]=t,u.current=n,d(n),g.current.timeout&&f.current&&v.current?.notify()},[]),y=cB(l,c),w=p?cq(l,y):{},k=Object.keys(w).length>0,j=()=>{if(x)return;let n=cB(l,u.current),r=cq(l,n);if(Object.keys(r).length>0){h(!0);let e=l.fields.findIndex(e=>""!==e.name&&void 0!==cJ(r,e.name));m.current?.querySelector(`[data-field="${e}"] input, [data-field="${e}"] select, [data-field="${e}"] textarea`)?.focus();return}t(e,{value:JSON.stringify(n)})};return(0,r.jsxs)("div",{"data-ask-form":"",style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentFormHint")}),e.timeout?(0,r.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,r.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,r.jsx)("div",{style:{display:"grid",gap:20,minWidth:0},children:l.sections.map((e,t)=>{let n,i=cV(e.title);return(0,r.jsxs)("section",{"aria-labelledby":i?`${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:[i&&(0,r.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,r.jsx)(cQ,{spans:e.title})}),e.blocks.map((e,a)=>{var s;let d;if("field"!==e.kind){let i=`${o}-s${t}b${a}`;return n="text"===e.kind?i:void 0,(0,r.jsx)(c1,{block:e,id:i},a)}let u=l.fields[e.index],h=n;n=void 0;let m=(s=e.index,d=l.fields[s],{id:`${o}-f${s}`,index:s,state:c[s],error:p&&d.name?cJ(w,d.name):void 0,captionId:h,fallbackName:i||d.name,onChange:b});return"choice"===u.kind?(0,r.jsx)(c8,{...m,field:u},a):(0,r.jsx)(c4,{...m,field:u},a)})]},t)})})}),(0,r.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,r.jsx)("p",{role:"alert",style:{margin:0,marginRight:"auto",color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.formInvalid")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:cX,children:s("chat.cancel")}),(0,r.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 c6={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},c3={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function c7({rows:e,removeLabel:t,onRemove:n}){let a,{st:s}=iw(),[o,l]=(0,i.useState)(!1),{rows:c,hidden:d}=(a=Math.max(0,e.length-4),o||0===a?{rows:e,hidden:a}:{rows:e.slice(a),hidden:a}),u=e.length>4;return(0,i.useEffect)(()=>{u||l(!1)},[u]),(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":o,onClick:()=>l(e=>!e),children:o?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:d})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:c.map(e=>{let i=lm(e.text),a=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?s(1===e.images?"delivery.images.one":"delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,r.jsx)("span",{className:"answer-delivery-kind",children:s(c6[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:s(c3[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${a}`,onClick:()=>n(e.kind,e.text),children:(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}async function c9(e,t){let n=await fetch(e,{cache:"no-store",...t}),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}let de=(0,i.forwardRef)(function({value:e,token:t,cwd:n,sessionTitle:a,style:s,maxHeight:o,onReplace:l,onClose:c},d){let{t:u}=(0,z.s)(),[p,h]=(0,i.useState)([]),[m,f]=(0,i.useState)(!0),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(-1),S=(0,i.useRef)([]),C=t.query.toLowerCase(),N=p.filter(e=>`${e.title}
|
|
18
18
|
${e.body}`.toLowerCase().includes(C)),T=e.slice(0,t.start)+e.slice(t.end),I=!!T.trim(),M=N.length+ +!!I,R=(0,i.useCallback)(async()=>{h((await c9("/api/saved-prompts")).prompts)},[]);(0,i.useEffect)(()=>{let e=!1;return c9("/api/saved-prompts").then(t=>{e||h(t.prompts)}).catch(t=>{e||b(String(t.message??t))}).finally(()=>{e||f(!1)}),()=>{e=!0}},[]),(0,i.useEffect)(()=>{j(N.length>0?0:-1),w(null)},[C,p,N.length,I]),(0,i.useEffect)(()=>{S.current[k]?.scrollIntoView({block:"nearest"})},[k]);let E=r=>{var i,s;let o=new Date,c=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`,d=(i=r.body,s={project_name:n?.replace(/[\\/]+$/,"").split(/[\\/]/).pop(),cwd:n,session_name:a,date:c},i.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)},$=async()=>{if(!g&&I){x(!0),b(null);try{await c9("/api/saved-prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:T})}),l(e,T,t.start,!0),await R()}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 c9(`/api/saved-prompts/${encodeURIComponent(e)}`,{method:"DELETE"}),h(t=>t.filter(t=>t.id!==e)),w(null),await R()}catch(e){b(e instanceof Error?e.message:String(e))}finally{x(!1)}}};(0,i.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]?E(N[k]):$()),!0;"Enter"===e.key&&c()}return!1}}));let P=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,r.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,r.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,r.jsxs)("div",{style:{overflowY:"auto",minHeight:0,padding:4},children:[!m&&0===N.length&&(0,r.jsx)("div",{style:{padding:8,fontSize:12,color:"var(--text-dim)"},children:u("savedPrompts.empty")}),N.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[(0,r.jsxs)("button",{type:"button",ref:e=>{S.current[t]=e},disabled:g,"data-saved-prompt-id":e.id,onClick:()=>E(e),onMouseEnter:()=>j(t),style:P(t===k),children:[(0,r.jsx)("span",{style:{display:"block",overflowWrap:"anywhere"},children:e.title}),(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:e.body.replace(/\s+/g," ")})]}),(0,r.jsx)("button",{type:"button",disabled:g,"data-delete-prompt":e.id,"aria-label":`${u("savedPrompts.delete")}: ${e.title}`,onClick:()=>void L(e.id),style:{...P(!1),width:"auto",flexShrink:0,color:"var(--danger, var(--text))"},children:u(y===e.id?"savedPrompts.confirmDelete":"savedPrompts.delete")}),y===e.id&&(0,r.jsx)("button",{type:"button",onClick:()=>w(null),style:{...P(!1),width:"auto",flexShrink:0},children:u("savedPrompts.cancel")})]},e.id)),I&&(0,r.jsx)("button",{type:"button","data-save-current-prompt":"",disabled:g||m,ref:e=>{S.current[N.length]=e},onClick:()=>void $(),onMouseEnter:()=>j(N.length),style:P(k===N.length),children:u("savedPrompts.save")})]}),v&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 10px",fontSize:12,color:"var(--danger, var(--text))",overflowWrap:"anywhere"},children:u("savedPrompts.error",{error:v})}),(0,r.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")})]})}),dt=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),dn=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function dr({soundEnabled:e,onToggle:t}){let n=e?"완료음 끄기":"완료음 켜기";return(0,r.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:n,"aria-label":n,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?dt:dn})})})}let di=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),da=["normal","slow"],ds={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function dl(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(a),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},a=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}function dc(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let dd={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},du=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),dp=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function dh({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:a}=(0,z.s)(),s=function(e,t,n){let{locale:r}=(0,z.s)(),[a,s]=(0,i.useState)("idle"),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,i.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,y.current?.close(),y.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let n=b.current;b.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,i.useCallback)((e,t)=>{l(e),d(t??null),j("error")},[j]),C=(0,i.useCallback)(async()=>{let i,a=k.current+1;k.current=a,l(null),d(null),g(!0),s("connecting");let o=e;if(!o&&t){try{o=await t()}catch{o=void 0}if(k.current!==a)return}if(!o){k.current===a&&(g(!1),S("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===a&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==a){for(let e of i.getTracks())e.stop();return}v.current=i;try{let e,t,l=new RTCPeerConnection;for(let e of(x.current=l,i.getTracks()))l.addTrack(e,i);let c=document.createElement("audio");if(c.autoplay=!0,b.current=c,l.ontrack=e=>{let[t]=e.streams;t&&(c.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await dl(l),k.current!==a)return;let d=l.localDescription?.sdp;if(!d)throw Error("The browser produced no offer SDP.");let u=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,sdp:d,locale:r})}),h=await u.json().catch(()=>({})),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===a&&(g(!1),S(dc(u.status,e),t));return}if(k.current!==a)return void fetch(`/api/live/call/${encodeURIComponent(m)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:f}),k.current!==a){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===a){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;if("string"!=typeof t.state||(r=t.state,!0!==ds[r]))return;"closed"===t.state?j("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&n&&Promise.resolve().then(()=>n(o)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&di.test(e)&&j("idle")}return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},v.onerror=()=>{k.current===a&&w.current&&S("failed")},s("live")}catch(e){k.current===a&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===a&&g(!1)}},[e,t,n,r,S,j]),N=(0,i.useCallback)(()=>{if("idle"===a||"closed"===a||"error"===a){f||C();return}j("idle")},[f,a,C,j]);return(0,i.useEffect)(()=>()=>j("closed"),[j]),{state:a,failure:o,detail:c,transcript:u,supported:h,toggle:N}}(e,t,n),o="connecting"===s.state||"live"===s.state||"working"===s.state,l="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,c=a(o?"chat.liveStop":"chat.liveStart"),d=!1===s.supported?dd.unsupported:s.failure?dd[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,r.jsxs)("div",{role:"group","aria-label":a("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[d&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:a(d)}),l&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a(l)}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":o,title:p?a(p):c,"aria-label":p?a(p):c,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o?dp:du})})]})}let dm={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 df({sessionId:e}){let{t}=(0,z.s)(),[n,a]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void a(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let s=Array.isArray(i.handles)?i.handles:[],o=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==o,a(o)}catch{}},s=async()=>{await i(),t||(n=window.setTimeout(()=>void s(),r?5e3:3e4))};return s(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:dm,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}let dg=new Map,dx="ompweb-drafts-for-reload-v1",dv=!1,db=new Map,dy=new Map,dw="\0stale",dk=new Map,dj=0,dS=new Map,dC=new Map,dN=new Map,dT=new Map,dI=new Map,dM=(e,t,n)=>lw(e,t,n.length?{sentAttachmentIds:n}:{}),dR=null,dE=!1;function d$(){if(dv||"u"<typeof sessionStorage)return;dv=!0;let e=sessionStorage.getItem(dx);if(e){sessionStorage.removeItem(dx);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)&&(dg.set(e[0],dP(t)),"string"==typeof t.draftId&&t.draftId&&(db.set(e[0],t.draftId),dy.set(t.draftId,dw)),dU(e[0]))}}catch{}}}function dL(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(dx,JSON.stringify([...dg.entries()].map(([e,t])=>{let n=db.get(e);return[e,n?{...dP(t),draftId:n}:dP(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function dP(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function dA(e){return!e.value&&0===e.images.length&&0===e.documents.length}function d_(e){d$();let t=dg.get(e);return t?dP(t):null}function dF(e,t){d$(),dA(t)?dg.delete(e):dg.set(e,dP(t)),dU(e)}function dz(e){dg.delete(e),dU(e)}function dW(e,t,n,r,i,a=[]){let s=[...t??[],...r].filter(nH).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=lu([...i??[],...a]);return{value:e.trim()?n.trim()?`${e}
|
|
19
19
|
|
|
20
|
-
${n}`:e:n,images:s,documents:o}}function dO(e,t,n){if(e===t)return n?dP(n):d_(t);let r=d_(e),i=n&&!dA(n)?dP(n):r??(n?dP(n):null),a=d_(t),s=db.get(e);if(db.delete(e),s&&!db.has(t)&&db.set(t,s),dz(e),!i)return a;let o=a?dW(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return dF(t,o),dP(o)}function dD(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function dH(e){d$();let t=db.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),db.set(e,t)),t}function dU(e){let t=dD(dg.get(e)?.documents),n=t.length?dH(e):db.get(e);for(let[e,n]of dC){for(let e of t)n.delete(e);0===n.size&&dC.delete(e)}let r=`${n??""}|${t.join(",")}`;dT.get(e)!==r&&(0!==t.length||n?dT.set(e,r):dT.delete(e),dZ())}async function dB(e){let t=dH(e);dS.set(t,(dS.get(t)??0)+1),await dI.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(dS.get(t)??1)-1;if(r>0?dS.set(t,r):dS.delete(t),e){let n=dC.get(t)??new Set;n.add(e),dC.set(t,n)}dy.set(t,dw),dZ()}}}function dq(e,t){let n=dN.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&dN.delete(e),[...n].sort()}async function dV(){if(!dM)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of db)t(n,dD(dg.get(e)?.documents));for(let{draftId:e,ids:n}of dk.values())t(e,n);for(let[e,n]of dC)t(e,n);for(let e of dy.keys())t(e,[]);for(let e of dN.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dS.has(e))return!1;let n=dy.get(e);return dq(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=dS.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=dq(r,i),a=dM(r,i,e).then(()=>{0===i.length?dy.delete(r):dy.set(r,i.join(","));let t=dN.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&dN.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});dI.set(r,a),await a,dI.get(r)===a&&dI.delete(r)}n?function(){if(dJ)return;dJ=!0;let e=setTimeout(()=>{dJ=!1,dZ()},dG);"object"==typeof e&&"unref"in e&&e.unref(),dG=Math.min(2*dG,6e4)}():dG=dK}let dK=5e3,dG=5e3,dJ=!1;function dZ(){if(dM){if(dR){dE=!0;return}dR=Promise.resolve().then(dV).finally(()=>{dR=null,dE&&(dE=!1,dZ())})}}let dY=Math.floor(Number.MAX_SAFE_INTEGER/1048576),dX=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function dQ(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=dY}async function d0(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!dQ(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:dQ((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:dX.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:dX.autoCleanupEnabled,orphanGraceDays:7}}async function d1(e={}){return d0(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function d2(e){return d0(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function d8(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function d4(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function d5(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function d6(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function d3(e,t,n){let r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`;return`${a}${s} `}let d7="omp-web:model-picks";function d9(){try{let e=JSON.parse(window.localStorage.getItem(d7)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function ue(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*s)),c=Math.max(0,e-a-s),d=Math.max(0,n-t-a-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=r||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(r,h?u:p))}}function ut(e,t,n){return Math.min(e*t,n)}function un(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,i.useState)({side:c??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),d=ue(i.top,i.bottom,n,ut(n,r,a),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,s,o,l,c,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var ur=n(14755);let ui="omp-web:model-roles-expanded";async function ua(e,t,n,r,i,a,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...ub,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(a&&(!c||"builtin"===c.source))return i(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return i(`/${o} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function us(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t||"fallback"===t}let uo=["off","default","full"],ul={off:"none",default:"default",full:"full"},uc=ur.IN.join(" \xb7 "),ud=ur.C1.filter(e=>!ur.IN.includes(e)).join(" \xb7 ");function uu(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let up=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),uh=0,um={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function uf(e,t){return up.compare(e.name||e.modelId,t.name||t.modelId)||up.compare(e.provider,t.provider)||up.compare(e.modelId,t.modelId)}let ug=["auto","off","minimal","low","medium","high","xhigh","max"],ux=["low","medium","high","xhigh"],uv={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},ub=[{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"}],uy=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uw={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},uk={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function uj(e,t,n){let r=e.name.toLowerCase(),i=uS(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function uS(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uC(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uN(e){return{data:e.data,mimeType:e.mimeType}}function uT(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uI(e){return(e??[]).filter(nH).slice(0,10).map(uT)}let uM=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uR="\n\nTranscript of the audio ";function uE(e){return lu(e).map(e=>{let t=lv(e),n="audio"===t&&e.attachmentId&&!e.text.includes(uR)?uM.exec(e.text):null;return{...e,id:++uh,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function u$({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function uL(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class uP extends Error{constructor(e,t,n,r,i=null){super(e),this.code=t,this.completedParts=n,this.parts=r,this.offer=i}}let uA="composer:unkeyed";async function u_(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;let r="number"==typeof n.completedParts?n.completedParts:null,i="number"==typeof n.parts?n.parts:null,a="fallback_confirmation_required"===n.code&&"string"==typeof n.fallbackToken&&"string"==typeof n.notice&&null!==r&&null!==i?{token:n.fallbackToken,notice:n.notice,completedParts:r,parts:i}:null;throw new uP("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,r,i,a)}function uF(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 uz(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function uW({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function uO({error:e}){return e?(0,r.jsx)(uW,{tone:"error",title:"Model error",body:e}):null}function uD({warnings:e}){return e&&0!==e.length?(0,r.jsx)(uW,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uH=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange: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:R=!1,thinkingCeiling:E,onThinkingLevelChange:$,availableThinkingLevels:L,thinkingLevelMap:P,fastMode:A=null,fastModeBusy:_=!1,onFastModeToggle:F,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:en,onEnsureSession:er,onLiveTranscriptPersisted:ei},ea){let es,eo,el,ec,ed,eu,ep,eh,em,ef,{t:eg}=(0,z.s)();ib();let{st:ex}=iw(),ev=O.some(e=>e.removable),eb=B(),[ey,ew]=(0,i.useState)(()=>Q?d_(Q)?.value??"":""),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(null),[eN,eT]=(0,i.useState)(""),[eI,eM]=(0,i.useState)({});(0,i.useEffect)(()=>{ek&&eM(d9())},[ek]);let[eR,eE]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(ek)try{eE("1"===window.localStorage.getItem(ui))}catch{}},[ek]);let e$=()=>{eE(e=>{let t=!e;try{window.localStorage.setItem(ui,t?"1":"0")}catch{}return t})},[eL,eP]=(0,i.useState)(!1),[eA,e_]=(0,i.useState)(null),[eF,ez]=(0,i.useState)(!1),[eW,eO]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(null),[eU,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(()=>Q?uI(d_(Q)?.images):[]),[eK,eG]=(0,i.useState)(()=>Q?uE(d_(Q)?.documents):[]),[eJ,eZ]=(0,i.useState)(null),eY=(0,i.useMemo)(()=>eK.filter(e=>"ready"===e.status),[eK]),eX=eK.some(e=>"ready"!==e.status||us(e)),eQ=eK.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uR))),e0=ey.trimStart(),e1=0===eq.length&&0===eK.length&&e0.startsWith("!"),e2=e1&&e0.startsWith("!!"),[e8,e4]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(0),[e3,e7]=(0,i.useState)(null),e9=e3?.value===ey&&e3.draftKey===Q?e3.token:null,[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(!1),ti=(0,i.useRef)(null),[ta,ts]=(0,i.useState)(null),[to,tl]=(0,i.useState)(!1),[tc,td]=(0,i.useState)(0),[tu,tp]=(0,i.useState)(!1),[th,tm]=(0,i.useState)(0),[tf,tg]=(0,i.useState)(null),[tx,tv]=(0,i.useState)(!1),[tb,ty]=(0,i.useState)(null),[tw,tk]=(0,i.useState)(null),tj=ee&&tw?.cwd===ee?tw.values:{},tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tN=(0,i.useRef)(null),tT=(0,i.useRef)(null),tI=(0,i.useRef)(null),tM=(0,i.useRef)(null),tR=(0,i.useRef)(null),tE=(0,i.useRef)(null),t$=(0,i.useRef)(null),tL=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(!1),t_=(0,i.useRef)(0),tF=(0,i.useRef)(!1),tz=(0,i.useRef)([]),tW=(0,i.useRef)([]),tO=(0,i.useRef)([]),tD=(0,i.useRef)(null),tH=(0,i.useRef)(null),tU=(0,i.useRef)(Q),tB=(0,i.useRef)(ey),tq=(0,i.useRef)(eq),tV=(0,i.useRef)(0),tK=(0,i.useRef)(eK);tB.current=ey,tq.current=eq,tK.current=eK,(0,i.useImperativeHandle)(ea,()=>({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,n,r=tS.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ey,tq.current.length,tV.current,tK.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lm(t)?.message??t),a=uI("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return nH(r)?[r]:[]})),s=uE((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lm(n)?.documents??[]));tB.current=i,tq.current=a,tK.current=s,ew(i),ts(null),tp(!1),eV(e=>(e.forEach(uz),a)),eG(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tU.current!==e)return void dO(e,t);let n={value:tB.current,images:tq.current.map(uN),documents:tK.current.filter(e=>"ready"===e.status).map(u$)},r=dO(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tU.current=t,i)return;let a=uI(r.images),s=uL(uE(r.documents),tK.current),o=r.value;tB.current=o,tq.current=a,tK.current=s,ew(o),eV(e=>(e.forEach(uz),a)),eG(s),ts(null),tp(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tU.current,a=r??i,s=a===i,o=!s&&a?d_(a):null,l=dW(e,t,s?tB.current:o?.value??"",s?tq.current.map(uN):o?.images??[],n,s?tK.current.filter(e=>"ready"===e.status).map(u$):o?.documents??[]);if(a&&dF(a,l),!s)return;let c=t?.length?[...uI(t).slice(0,Math.max(0,10-tq.current.length)),...tq.current].slice(0,10):tq.current,d=uL(uE(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 n=Math.max(0,10-e.length),r=uI(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tq.current=i,i}),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 n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",o=i+s+e+a;tB.current=o,ew(o),ts(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){t9(e)}}));let tG=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tq.current.length-tV.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eZ(eg("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:lf(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eZ(eg("chat.attachImageLimit",{count:10})),i.length){tV.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eV(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(uz);let r=[...t,...n];return tq.current=r,r})}finally{tV.current-=i.length}}},[eg]),tJ=(0,i.useCallback)(async e=>{for(let t of e){let e=lo(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:lf(8388608)}));continue}if(tK.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eZ(eg("chat.attachTotalTooLarge",{limit:lf(0x1000000)}));continue}let n={id:++uh,name:t.name,mimeType:li[e],size:t.size,text:"",status:"extracting"},r=[...tK.current,n];tK.current=r,eG(r);try{let e=await lp(t);if(tK.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new lr("text_too_large","Total extracted text exceeds 240000 characters");let r=tK.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tK.current=r,eG(r)}catch(i){let e=tK.current.some(e=>e.id===n.id),r=tK.current.filter(e=>e.id!==n.id);if(tK.current=r,eG(r),!e)continue;i instanceof lr?"text_too_large"===i.code?eZ(eg("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eZ(eg("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eZ(eg("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.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,i.useCallback)((e,t)=>{if(!tK.current.some(t=>t.id===e))return!1;let n=t?tK.current.map(n=>n.id===e?t:n):tK.current.filter(t=>t.id!==e);return tK.current=n,eG(n),!0},[]),tY=(0,i.useCallback)((e,t)=>{if(!tK.current.some(t=>t.attachmentId===e))return!1;let n=tK.current.map(n=>n.attachmentId===e?t(n):n);return tK.current=n,eG(n),!0},[]),tX=(0,i.useCallback)((e,t,n)=>{if(!e||e===tU.current)return;let r=d_(e);r?.documents.some(e=>e.attachmentId===t)&&dF(e,{...r,documents:uE(r.documents).map(e=>e.attachmentId===t?n(e):e).map(u$)})},[]),tQ=(0,i.useRef)(new Map),t0=(0,i.useRef)(new Map),t1=(0,i.useRef)(new Set),t2=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=lb({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),t8=(0,i.useCallback)(e=>e instanceof uP&&"media_tool_unavailable"===e.code?eg("chat.transcribeToolMissing"):e instanceof uP&&"fallback_confirmation_expired"===e.code?eg("chat.transcribeFallbackExpired"):e instanceof uP&&"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,i.useCallback)(async(e,t)=>{let n=tU.current,r=tK.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;t0.current.get(e)?.abort();let a=new AbortController;t0.current.set(e,a),tY(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await u_(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:a.signal}));if("string"!=typeof r.transcript)throw new uP("Invalid transcription result",null,null,null);let i=r.transcript;tY(e,e=>t2(e,i,tK.current)??{...e,transcription:{state:"failed",error:eg("chat.transcribeTooLong")}})||tX(n,e,e=>t2(e,i,[])??e)}catch(r){if(a.signal.aborted)return void tY(e,e=>({...e,transcription:{state:"skipped"}}));if(r instanceof uP&&"confirmation_required"===r.code)return void t5.current?.(e);let t=r instanceof uP?r.offer:null;if(t){let n={state:"fallback",reason:r instanceof Error?r.message:"",...t};tY(e,e=>({...e,transcription:n}))||uF(e,t.token);return}let n=t8(r);tY(e,e=>({...e,transcription:{state:"failed",error:n}}))}finally{t0.current.get(e)===a&&t0.current.delete(e)}},[eg,t8,tY,tX,t2]),t5=(0,i.useRef)(null),t6=(0,i.useCallback)(async e=>{let t;t0.current.get(e)?.abort();let n=new AbortController;t0.current.set(e,n),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 uP("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await u_(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tY(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=t8(t);tY(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t0.current.get(e)===n&&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,i.useCallback)(e=>{let t=t0.current.get(e);if(t)return void t.abort();let n=tK.current.find(t=>t.attachmentId===e)?.transcription;n?.state==="fallback"&&uF(e,n.token),tY(e,e=>({...e,transcription:{state:"skipped"}}))},[tY]),t7=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++uh,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tK.current,i];tK.current=a,eG(a);let s=(e,t)=>{let n=tK.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?ld("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?ld("utf-16be",t.subarray(2)):t.includes(0)?null:ld("utf-8",t)??ld("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tZ(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await d1().catch(()=>dX)).uploadLimitMb),r.size>n){tZ(i.id,null)&&eZ(eg("chat.attachStoredTooLarge",{name:r.name,limit:lf(n)}));continue}let o={...i,stored:t,status:"uploading",size:0};if(!tZ(i.id,o))continue;let l=tU.current??uA,c=await dB(l),d=null,u=new AbortController;tQ.current.set(i.id,u);try{if(t1.current.has(i.id))continue;let e=await ly(r,{sessionId:en,draftId:c.draftId,signal:u.signal}),n=tK.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=lb({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tZ(i.id,null)&&eZ(eg("chat.attachTotalTooLarge",{limit:lf(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tZ(i.id,h))d=e.id;else if(!t1.current.has(i.id)&&l!==tU.current){let t=d_(l)??{value:"",images:[],documents:[]};dF(l,{...t,documents:[...t.documents,u$(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tZ(i.id,null)&&eZ(eg("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tQ.current.delete(i.id),c.end(d)}d&&"audio"===t&&tK.current.some(e=>e.attachmentId===d)&&t6(d)}},[tZ,t6,en,eg]),t9=(0,i.useCallback)(async e=>{eZ(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==lo(a)?n.push(a):lc(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tG(t),tJ(n.filter(e=>e.size<=8388608)),t7(r,"audio"),t7([...i,...a],"file")])},[tJ,t7,tG]),ne=(0,i.useCallback)(e=>{eV(t=>{let n=[...t],[r]=n.splice(e,1);return r&&uz(r),tq.current=n,n})},[]),nt=(0,i.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"&&uF(t.attachmentId,t.transcription.token);var n=t.attachmentId;for(let[e,t]of dC)t.delete(n)&&(0===t.size&&dC.delete(e),dZ())}let r=tK.current.filter(t=>t.id!==e);tK.current=r,eG(r)},[]),nn=(0,i.useCallback)(()=>{tq.current=[],eV(e=>(e.forEach(uz),[]))},[]),nr=(0,i.useCallback)(()=>{tK.current=[],eG([])},[]),ni=(0,i.useCallback)(()=>{tB.current="",ew(""),ts(null),e7(null),tt(!1),tp(!1),Q&&dz(Q),tU.current&&tU.current!==Q&&dz(tU.current),nn(),nr(),eZ(null),tS.current&&(tS.current.style.height="auto")},[nr,nn,Q]);(0,i.useEffect)(()=>{Q&&tU.current===Q&&dF(Q,{value:ey,images:eq.map(uN),documents:eY.map(u$)})},[eq,Q,eY,ey]),(0,i.useEffect)(()=>{let e=tU.current;if(e===Q)return;e&&dF(e,{value:tB.current,images:tq.current.map(uN),documents:tK.current.filter(e=>"ready"===e.status).map(u$)});let t=Q?d_(Q):null;tU.current=Q;let n=t?.value??"",r=uI(t?.images),i=uE(t?.documents);tB.current=n,tq.current=r,tK.current=i,ew(n),ts(null),tp(!1),eV(e=>(e.forEach(uz),r)),eG(i)},[Q]),(0,i.useEffect)(()=>{let e=tS.current;e&&(e.style.height="auto",ey&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ey]),(0,i.useEffect)(()=>()=>{tq.current.forEach(uz)},[]);let na=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=dD(t);if(0===n.length)return()=>{};let r=++dj;return dk.set(r,{draftId:dH(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=dk.get(r);if(t){if(dk.delete(r),"accepted"===e){let e=dN.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);dN.set(t.draftId,e)}dZ()}}}(tU.current??uA,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),ns=(0,i.useCallback)(async()=>{let t=ey.trim(),n=e0.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eq.length&&!eY.length||o||eX)return;Y?.();let i=eq.length?eq:void 0,a=eY.length?eY:void 0;if(r.startsWith("/")){await ua(r,q,G,t=>na(a,()=>e(t,i,a)),eZ,!!(i||a),K)&&ni();return}ni(),na(a,()=>e(r,i,a))},[ey,e0,eq,eY,eX,o,G,q,K,e,ni,Y,na]),no=!e0.startsWith("/")||e0.startsWith("//")||/\s/.test(e0.slice(1))?null:e0.slice(1).toLowerCase(),nl=(()=>{if(null===no)return[];let e=[...o?[]:ub,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=uS(e,eg).toLowerCase();return t.includes(no)||n.includes(no)}).sort((e,t)=>{let n=uj(e,no,eg)-uj(t,no,eg);return 0!==n?n:uk[e.source]-uk[t.source]||up.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:nc,groups:nd}=(es=0,{commands:(eo=uy.map(e=>{let t=nl.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!uC(e,tj)),...t.filter(e=>uC(e,tj))]:t;return{source:e,items:n.map(e=>({command:e,index:es++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:eo}),nu=1===nl.length?eg(no?"chat.match":"chat.command"):eg(no?"chat.matches":"chat.commands",{count:nl.length}),np=!!ey.trim(),nh=!eX&&(np||eq.length>0||eY.length>0),nm=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=Math.max(0,Math.min(e.length,t)),r=/(?:^|\s)(\/\/[^\s]*)$/.exec(e.slice(0,n));if(!r)return null;let i=n-r[1].length,a=/^\S*/.exec(e.slice(n))[0];return{start:i,end:n+a.length,query:e.slice(i+2,n)}}(e,t??e.length);if(e7(n?{value:e,draftKey:Q,token:n}:null),tr(!1),!ee)return void ts(null);let r=t??e.length;ts(d8(e.slice(0,r)))},[ee,Q]),nf=ta?.query??null,ng=i.useMemo(()=>null!==nf&&tf&&tf.cwd===ee?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:d5(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:d5(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||d4(e.entry.path)-d4(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tf.entries,nf):[],[nf,tf,ee]),nx=!!(nf&&tf?.truncated&&tf.cwd===ee);(0,i.useEffect)(()=>{if(!nx||!ee||!nf)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(nf)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ty({cwd:ee,query:nf,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nx,nf,ee]);let nv=nx&&null!==tb&&tb.cwd===ee&&tb.query===nf,nb=nv?tb.matches:ng,ny=null===ta?null:`${ta.start}:${+!!ta.quoted}:${ta.query}`;(0,i.useEffect)(()=>{if(null===ny){tl(!1),td(0);return}tl(!0),td(0)},[ny]);let nw=null!==ta,nk=un(tL,tu,{viewportFraction:.44,cap:360}),nj=un(tL,e8,{viewportFraction:.56,cap:460}),nS=un(tL,to,{viewportFraction:.48,cap:400}),nC=un(tL,te,{viewportFraction:.48,cap:400}),nN=e9?`${e9.start}:${e9.end}:${e9.query}`:null;(0,i.useEffect)(()=>{tt(null!==nN)},[nN]);let nT=(0,i.useCallback)((e,t,n,r=!1)=>{tB.current===e&&tU.current===Q&&(tB.current=t,ew(t),e7(null),tt(!1),tr(r),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(n,n),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[Q]);(0,i.useEffect)(()=>{if(!nw||!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 n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>d4(e.path)-d4(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tD.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tD.current=null}).finally(()=>{tH.current=null,tv(!1)}))},[nw,ee]);let nI=(0,i.useCallback)(e=>{if(!ta)return;let t=tS.current,n=t?.selectionStart??ey.length,r=ey.slice(0,ta.start),i=ey.slice(n);ta.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,ta.quoted),s=r+a.text+i,o=r.length+a.cursorOffset;ew(s),ts(d8(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`)})},[ta,ey]);(0,i.useEffect)(()=>{tc>=nb.length&&td(Math.max(0,nb.length-1))},[nb.length,tc]),(0,i.useEffect)(()=>{tW.current.length=nb.length},[nb.length]),(0,i.useEffect)(()=>{to&&tW.current[tc]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tc,to]),(0,i.useEffect)(()=>{th>=D.length&&tm(Math.max(0,D.length-1))},[D.length,th]),(0,i.useEffect)(()=>{tO.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{tu&&tO.current[th]?.scrollIntoView({block:"nearest",inline:"nearest"})},[th,tu]);let nM=(0,i.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`)})},[]),nR=(0,i.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`)})},[]),nE=(0,i.useCallback)(async e=>{let t=ey.trim(),r=e0.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eX||!i&&0===eq.length&&0===eY.length?null:{message:i,images:eq.length?eq:void 0,documents:eY.length?eY:void 0};if(!s)return;Y?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await ua(i,q,G,e=>{if(!X)throw Error("Cannot queue this command while the session is busy.");na(s.documents,()=>X(e,o,s.images,s.documents))},eZ,!!(s.images?.length||s.documents?.length),K)&&ni();return}ni(),"steer"===e&&n?na(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&na(s.documents,()=>a(s.message,s.images,s.documents))},[ey,e0,eq,eY,eX,q,K,G,X,n,a,ni,Y,na]),n$=(0,i.useCallback)(e=>{let t=nc.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 n=tz.current[e5];if(!n)return"down"===e?Math.min(t,e5+1):Math.max(0,e5-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===e5)continue;let t=tz.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-a;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<o&&(s=n,o=c)}return s>=0?s:"down"===e?Math.min(t,e5+1):Math.max(0,e5-1)},[nc.length,e5]),nL=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-t_.current<100,s=tA.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&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(),nM(D[th]);return}}if(!(te&&e9&&!s&&ti.current?.handleKeyDown(e))){if(e8&&null!==no){if("ArrowDown"===e.key){e.preventDefault(),e6(n$("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e6(n$("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e6(n$("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e6(n$("left"));return}if("Escape"===e.key){e.preventDefault(),e4(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nc[e5]){e.preventDefault(),nR(nc[e5]);return}}if(to&&null!==ta&&!s){if("ArrowDown"===e.key){e.preventDefault(),td(e=>Math.min(Math.max(0,nb.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)&&nb[tc]){e.preventDefault(),nI(nb[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&&(n||a)?nE(n?"steer":"followup"):ns())}},[o,n,a,t,e8,no,nc,e5,nR,nE,ns,n$,to,ta,nb,tc,nI,tu,D,th,nM,ey,te,e9]),nP=(0,i.useCallback)(()=>{let e=tS.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nA=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),t9(t))},[t9]);(0,i.useEffect)(()=>{if(null===no){e4(!1),e6(0),tF.current=!1;return}e4(!0),e6(0),!tF.current&&K&&(tF.current=!0,Promise.resolve(K()).catch(()=>{tF.current=!1}))},[no,K]),(0,i.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 n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tk({cwd:ee,values:n})}).catch(()=>{e||tk({cwd:ee,values:{}})}),()=>{e=!0}},[e8,ee]),(0,i.useEffect)(()=>{e5>=nc.length&&e6(Math.max(0,nc.length-1))},[nc.length,e5]),(0,i.useEffect)(()=>{tz.current.length=nc.length},[nc.length]),(0,i.useEffect)(()=>{e8&&tz.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e8]);let n_=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(uf):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(uf),nF=g??null,nz=rg.find(e=>e.alias===nF)?.provider??null,nW=nz?n_.filter(e=>e.provider===nz):n_,nO=(el=eN.trim().toLocaleLowerCase())?nW.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(el)):nW,nD=nW.length>8,nU=[];for(let e of nO){let t=nU.find(t=>t.provider===e.provider);t?t.options.push(e):nU.push({provider:e.provider,options:[e]})}let nB=nz?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nq=l?nB.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,nK=eN.trim()?[]:nW.map((e,t)=>{var n,r;return{option:e,order:t,count:eI[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nG=(e,t,n)=>{let i=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ej(!1),eT(""),!i||c){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(d9(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(d7,JSON.stringify(r))}catch{}eM(r),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eg("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nJ=l?n_.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,nZ=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nY=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eg("chat.compacted")} ${nV(S.tokensBefore)} -> ${nV(S.estimatedTokensAfter)} tokens (${eg("chat.tokensSaved",{saved:nV(nZ)})})`:null,nX=e=>{let t=P?.[e];return null!=t&&t!==e?t:null},nQ="auto"===(ec=T??"auto")?E?`auto ≤ ${nX(E)??E}`:"auto":P?P[ec]??ec:ec,n0=(T??"auto")==="auto"&&I&&"auto"!==I?P?.[I]??I:null,n1=$&&n0?eg("chat.currentReasoning",{level:n0}):null,n2=e=>!L||L.includes(e),n8=[{level:"auto",ceiling:null},...ux.filter(n2).map(e=>({level:"auto",ceiling:e})),...ug.filter(e=>"auto"!==e&&n2(e)).map(e=>({level:e,ceiling:null}))],n4=Object.entries(ul).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.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)&&eP(!1),tM.current&&!tM.current.contains(e.target)&&ez(!1),tR.current&&!tR.current.contains(e.target)&&eO(!1),tE.current&&!tE.current.contains(e.target)&&eB(!1),!t$.current||t$.current.contains(e.target)||tS.current?.contains(e.target)||tp(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eb||eB(!1)},[eb]);let n5=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eq.length||eK.length?" is-active":""}`,onClick:()=>tP.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,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),n6=f&&rg.length>0?(0,r.jsxs)("div",{ref:tT,style:{position:"relative",flexShrink:+!!eb,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eb?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e_({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eP(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eP(!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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eb?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eg("chat.mainPreset")})]}),eL&&eA&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=ue(eA.top,eA.bottom,e,ut(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eA.top+6}:{top:eA.bottom+6},a=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eA.left,width:"max-content",minWidth:eA.width};return(0,r.jsx)("div",{ref:tI,role:"menu","aria-label":eg("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eP(!1),tT.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:rg.map(e=>{let t=e.alias===nF;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eP(!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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:rV(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:r_(e.alias)}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,n3=$?(0,r.jsxs)("div",{ref:tR,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.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(""),eP(!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:nQ}),"aria-label":eg("chat.changeReasoning",{level:nQ}),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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eb?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nQ})]}),eW&&eD&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=ue(eD.top,eD.bottom,e,ut(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eD.top+6}:{top:eD.bottom+6},a=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eD.left,width:"max-content",minWidth:Math.max(180,eD.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eg("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eO(!1),tR.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:n8.map(({level:e,ceiling:t})=>{let n=(T??"auto")===e&&("auto"!==e||(E??null)===t),i=t??e,a="auto"===e&&null===t?null:nX(i),s=t?`auto ≤ ${a??t}`:a??e,o=t?eg("chat.thinkingAutoCapped",{level:a??t}):eg(uv[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eO(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,n7=F?(ed=_?eg("chat.fastModeBusy"):null===A?eg("chat.fastModeUnknown"):A.active?eg("chat.fastModeActive"):A.enabled?eg("chat.fastModeInactive"):eg("chat.fastModeOff"),eu=_||o||b,ep=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:F,disabled:eu,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":_||void 0,title:ed,"aria-label":ed,style:{flexShrink:0,opacity:o?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:ep&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,n9=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nE("steer"),disabled:!nh,title:eX?eg("chat.attachExtractingWait"):eg("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nh?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nh?"var(--warning)":"var(--text-dim)",cursor:nh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eg("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nE("followup"),disabled:!nh,title:eX?eg("chat.attachExtractingWait"):eg("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nh?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nh?"var(--accent-hover)":"var(--text-dim)",cursor:nh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eg("chat.followUp")]})]}),re=void 0!==Z?(0,r.jsx)(dr,{soundEnabled:J??!0,onToggle:Z}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tP,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t9(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(uO,{error:p}),(0,r.jsx)(uD,{warnings:h}),O.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ex("delivery.title",{count:O.length})}),H&&ev&&(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eg("chat.recall")]})]}),(0,r.jsx)(c7,{rows:O,removeLabel:eg("chat.queueRemove"),onRemove:U?(e,t)=>U("steer"===e?"steering":"followUp",t):void 0})]}),W&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eg("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),nY&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nY]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eJ&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eJ}),(0,r.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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eq.length>0||eK.length>0)&&(0,r.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,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eg("chat.removeImage",{index:t+1}),onClick:()=>ne(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eK.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||us(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):i$(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eg("chat.attachKindAudio"):"file"===e.stored?eg("chat.attachKindFile"):um[e.mimeType]," \xb7 ",lf(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,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eg("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>nt(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,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eQ.length>0&&(0,r.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,n,i,a,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"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?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,r.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[l.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeUsageNotice")})]}),l?.state==="fallback"&&(0,r.jsxs)(r.Fragment,{children:[l.reason&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.reason}),l.completedParts>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:eg("chat.transcribeFallbackProgress",{done:l.completedParts,total:l.parts})}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeFallbackUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{confirmed:!0}),children:eg("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),l?.state==="fallback"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{fallbackToken:l.token,approve:!0}),children:eg("chat.transcribeFallbackStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,r.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,r.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,r.jsxs)("div",{ref:tL,style:{position:"relative",minWidth:0},children:[tu&&D.length>0&&(0,r.jsxs)("div",{ref:t$,style:{position:"absolute",left:0,right:0,...uu(nk.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nk.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nk.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===th;return(0,r.jsxs)("button",{ref:e=>{tO.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nM(e)},onMouseEnter:()=>tm(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),tn&&(0,r.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:eg("savedPrompts.saved")}),te&&e9&&(0,r.jsx)(de,{ref:ti,value:ey,token:e9,cwd:ee,sessionTitle:et,style:uu(nC.side),maxHeight:nC.maxHeight,onReplace:nT,onClose:()=>tt(!1)}),e8&&null!==no&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uu(nj.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nj.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:V?eg("chat.loadingCommands"):eg("chat.slashCommands",{label:nu})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nj.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==nl.length?nd.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eg(uw[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===e5,i=uC(e,tj);return(0,r.jsxs)("button",{ref:e=>{tz.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nR(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 ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eg("chat.dormant")})]}),uS(e,eg)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uS(e,eg)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eg("chat.noCommands")})})]}),to&&null!==ta&&(eh=tx&&(!tf||tf.cwd!==ee),em=1===nb.length?eg("chat.match"):eg("chat.matches",{count:nb.length}),ef=tf?.truncated&&!nv?ta.query?eg("chat.searchingAll"):eg("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uu(nS.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nS.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:eh?eg("chat.loadingFiles"):eg("chat.files",{label:em,hint:ef})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nS.maxHeight-34),overflowY:"auto",padding:4},children:eh||0!==nb.length?nb.map((e,t)=>{let n=t===tc,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tW.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nI(e)},onMouseEnter:()=>td(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(iM,{size:14}):i$(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:nx&&!nv?eg("chat.searching"):eg("chat.noMatchingFiles")})})]})),(0,r.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&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tS,"aria-controls":te?"saved-prompt-menu":void 0,value:ey,onChange:e=>{tB.current=e.target.value,ew(e.target.value),tp(!1),nm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nm(t.value,t.selectionStart)},onKeyDown:nL,onCompositionStart:()=>{tA.current=!0},onCompositionEnd:e=>{tA.current=!1,t_.current=Date.now();let t=e.currentTarget;nm(t.value,t.selectionStart)},onInput:nP,onPaste:nA,placeholder:o&&(n||a)?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,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:n9}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:ns,disabled:!nh,"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:nh?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nh?"var(--accent-hover)":"var(--text-dim)",cursor:nh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eb?null:eg("chat.send")]})]})]}),e1&&(0,r.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,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.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)&&n5,!eb&&n6,!(eb&&o)&&(n_.length>0||nJ||p)&&m&&(0,r.jsxs)("div",{ref:tC,style:{position:"relative",flex:eb?"1 1 0%":void 0,width:eb?0:void 0,minWidth:44*!!eb},children:[(0,r.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":n_.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nJ??(n_.length>0?"Select model":"No models")})]}),ek&&eS&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=ue(eS.top,eS.bottom,e,ut(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eS.top+6}:{top:eS.bottom+6},a=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eS.left,width:"max-content",minWidth:eS.width};return(0,r.jsxs)("div",{ref:tN,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nD&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nK.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eg("chat.frequentModels")}),nK.map(({option:e,count:t})=>nG(e,"frequent",t))]}),nB.length>0&&!eN.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nK.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eR,"aria-controls":"model-role-rows",onClick:e$,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eR?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:eg("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nB.length}),nq&&(0,r.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:nq.tag??nq.role.toUpperCase()}),nq.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eR,children:nB.map(e=>{let t=nq?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ej(!1),eT(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:"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,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eg("chat.allModels")})]}),0===nU.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eN.trim()?eg("chat.noMatchingModels"):"No available models"}):nU.map((e,t)=>(0,r.jsxs)("div",{children:[nU.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nG(e,"all"))]},e.provider))]})]})})()]}),eb&&o&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:n9}),!eb&&n3,!eb&&n7,!eb&&n1&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:n1}),!eb&&null!==M&&(0,r.jsx)("span",{title:eg(R?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:eg(R?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,r.jsx)(df,{sessionId:en})]}),(0,r.jsxs)("div",{ref:tE,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,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title: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,r.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,r.jsxs)(r.Fragment,{children:[o&&n5,n6,n3,n7]}),!o&&N&&(0,r.jsxs)("div",{ref:tM,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eF?" is-active":""}`,onClick:()=>!o&&ez(e=>!e),disabled:o,title:eg("chat.changeToolPreset")+`: ${n4}`,"aria-label":eg("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eF?"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=eF?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:n4})]}),eF&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:uo.map(e=>{let t=ul[e],n=(C??"default")===t,i="off"===e?eg("chat.noTools"):"default"===e?eg("chat.builtInTools",{tools:uc}):eg("chat.allBuiltInTools",{tools:`${uc} + ${ud}`});return(0,r.jsxs)("button",{onClick:()=>{ez(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!o&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eg("chat.stopCompaction"):eg("chat.compactContext"),"aria-label":k?eg("chat.stopCompaction"):eg("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compact")})]})})}),eb&&re,eU&&(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title: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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eb?null:eg("chat.stop")]}),(0,r.jsx)(dh,{sessionId:en,onEnsureSession:er,onTranscriptPersisted:ei}),!eb&&re]})]})]})]})});function uU({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),n=eP(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eW(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function uB({phases:e,flow:t,busy:n}){let{t:a}=(0,z.s)(),{st:s}=iw(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=(0,i.useId)(),m=e??[],{currentPhase:f,activeTask:g,remaining:x,completed:v,total:b,percent:y}=t_(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,s);if(0===b&&null===j)return null;let S=b>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:j}),b>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!j&&f&&(0,r.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:S?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:S?a("todo.progressDone",{percent:y??0,completed:v,total:b}):a("todo.progress",{percent:y??0,completed:v,total:b,remaining:x})})]}),k&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,r.jsx)(oj,{flow:t,live:n,st:s,id:h}),o&&b>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(iN,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function uq(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uV(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 uK(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}class uG extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function uJ(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new uG(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let uZ="ompweb-update-client-id",uY="ompweb-update-resume-intent-v2",uX="ompweb-update-return-v1",uQ="cuelo-restart-return-v1",u0="ompweb-update-failure-return-v1",u1="ompweb:update-wake";function u2(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function u8(){let e=sessionStorage.getItem(uZ);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(uZ,t),t}function u4(){sessionStorage.removeItem(uY)}function u5(){let e=sessionStorage.getItem(uX);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 u6(e){let t=u5();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(uX,JSON.stringify(n))}catch{}return n}async function u3(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:u8(),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 u7(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let n=await t.json().catch(()=>null);!function(e){let t=u5();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(uX,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u4();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(u1,{detail:{sessionId:e.sessionId}}))}async function u9(e){let t=function(e){let t=sessionStorage.getItem(u0);if(!t)return null;sessionStorage.removeItem(u0);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(u4(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(u1,{detail:{sessionId:e.sessionId}})),"failed"):(await u7(e),"resumed")}function pe(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function pt(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 pn(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function pr(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function pi(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function pa(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker||(t.dependsOn?.length??0)!==(n.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==n.dependsOn?.[t]))return!1}}return!0}function ps(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function po(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!ts(r??void 0))return{message:e[n],entryId:r}}return null}let pl=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class pc 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 pd(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pu(e){return new Promise(t=>setTimeout(t,e))}function pp(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ph(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:pp(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:pp(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=pp(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function pm(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 pf(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(pm).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function pg(e){return"user"===e.role?`user:${pf(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 px(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 pv(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function pb(e){nM(e),e.clear()}function py(e,t,n){for(let r of n??[]){let n=nI(t,r);n&&e.add(n)}}function pw(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let pk=!1,pj={width:0,height:0},pS=new Set,pC=null;function pN(){let e=window.visualViewport,t=pw();pj.width!==window.innerWidth?pj={width:window.innerWidth,height:window.innerHeight}:t||(pj.height=Math.max(pj.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:pj.height});if(n!==pk)for(let e of(pk=n,pS))e()}function pT(e){if(pS.add(e),!pC){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,pN()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),pN(),pC=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{pS.delete(e),0===pS.size&&pC&&(pC(),pC=null)}}function pI(){return(0,i.useSyncExternalStore)(pT,()=>pk,()=>!1)}let pM={count:50,end:null};function pR(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function pE(e,t,n){let{startIndex:r,endIndex:i}=pR(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function p$({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:n6[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(cx(),{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 pL(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=(lm(t)?.message??t).trim();return n.length>0?n:null}function pP(e){return`omp-cues:${e}`}function pA(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(pP(e),JSON.stringify(n.slice(-200)))}catch{}}let p_=[];function pF(e){return`omp-web:interrupted-dismissed:${e}`}let pz=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent: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,i.useEffect)(()=>{T({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:f})},[T,x,e,t,n,a,s,f]);let R=(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n=0;n<e.length;n++){let r=ti(e,n);r>=0&&t.set(r,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 n=t.indexOf("\n\n");return n<0?t:t.slice(n+2)}(e[n]))}return t})(e),[e]),E=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[o.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(o.blocks?i.get(o.idx):void 0)??o.afterMainIndex??-1),l=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=td(i.action);if(!0===tc[e]){let t={kind:"skill",action:e,name:td(i.name)};n(JSON.stringify(t),t)}continue}let a=td(i.memory),s=i.skill,o=s?{action:td(s.action),name:td(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:o}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...o?{skill:o}:{}})}}(o.blocks??e.content??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:tn,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,N]),$=(0,i.useMemo)(()=>{let r=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(r=t.idx);return function(e,t,n,r,i,a,s=[]){let o=function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&sB(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:sB(t,n),s=new Map;for(let[n,o]of(e.forEach((e,n)=>{"answer"===e.kind&&s.set(sB(t,e.anchorIdx),n)}),s)){if(n===a)continue;let e=i.find(e=>e>n);r.set(o,{from:n+1,to:e??t.length})}return r}(e,t,n),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,n]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(sV(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let i=n.to-1;for(;i>=n.from&&ts(s[i]);)i-=1;if(s[i]!==a.throughEntryId)continue;let o=sH(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sq(t,r,n.from,n.to);c.set(e,{...a.summary,...p?{remaining:sO(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,i,a=[]){let s=sH(e,n,r),o=sq(e,t,n,r);return{...sD(s,t,i),remaining:o?sO(o):null,span:sK(e,n,r),flow:sz(s,t,!1,a,i,sU(e,n,r))}}(t,r,n.from,n.to,i,d),latest:e===l})}return c}(g,e,r,n,s,y,t)},[g,e,n,s,l,y,t]),L=w>0,P=k<g.length,A=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&ts(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(l_,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:o,entryId:t[i],onFork:l||c||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary,inputTranslation:"user"===x.role?R.get(i):void 0,recoveredError:eZ(e,i)},`${y}-view-${i}`)},_=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[L&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((a,l)=>{let c=w+l,d=b?.position===c?(0,r.jsx)(oO,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<m}).map(e=>(0,r.jsx)(p$,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),y=h!==u,k=E.get(c),j=k?(0,r.jsx)(l_,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=y?(0,r.jsx)(cS,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:o}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[d,_(c,A(a.idx)),j,S,x]},`message-${a.idx}`);let C=tM(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[d,_(c,A(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=eK(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:$.get(c)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&k===g.length&&(0,r.jsx)(oO,{calls:b.calls}),P&&(0,r.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function pW({session:e,newSessionCwd:t,initialSessionData:a,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:R,onAttentionChange:E,soundEnabled:$=!0,onSoundToggle:L,playCueSound:P=async()=>({sticker:null,text:null}),preloadCueSound:A,unlockAudio:_,jumpRequest:F=null,onJumpHandled:W}){var O,D;let H,U,V,{t:K}=(0,z.s)(),G=pI(),J=B(),Z=(0,i.useRef)(P);Z.current=P;let Y=(0,i.useRef)(null),X=(0,i.useRef)(A);X.current=A;let[Q,et]=(0,i.useState)([]),en=(0,i.useRef)(Q);en.current=Q;let er=(0,i.useRef)(0),ei=(0,i.useRef)([]),ea=(0,i.useRef)([]),eo=(0,i.useRef)(null),el=(0,i.useRef)(0),ec=(0,i.useRef)(-1),ed=(0,i.useRef)(-1),eu=(0,i.useCallback)(()=>{let e=eo.current?.current;return e?{sessionId:e,turn:el.current}:null},[]),ep=(0,i.useCallback)(e=>eo.current?.current===e.sessionId&&el.current===e.turn,[]),eh=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;er.current=Math.max(er.current+1,Date.now());let i={id:er.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};et(e=>{let t=[...e,a];return null!==a.anchorEntryId&&pA(n.sessionId,t),t})},[]),em=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ep(n)&&("working"!==t||ed.current!==n.turn);i()&&Z.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&eh(e,t,n,r)}).catch(()=>{})},[ep,eh]),ef=(0,i.useCallback)(async(e,t,n,r)=>{let i=(await ix(e,t,n,r))?.alias??null;return i&&X.current?.(i),i},[]),eg=(0,i.useCallback)((e,t,n,r,i)=>{let a=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=rl(e[n]),a=0;for(let t=r;t<=n;t++)rl(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(ei.current,ea.current);ef(t.sessionId,n,r,i).then(n=>{em(n,e,t,a)})},[em,ef]),[ex,ev]=(0,i.useState)(0),eb=(0,i.useRef)([]),ey=(0,i.useCallback)(e=>{if(el.current+=1,null!==re(e.outcome)){let t=e.sessionId;eb.current.push({completion:e,trigger:t?{sessionId:t,turn:el.current}:null}),ev(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eb.current.splice(0)){let n=re(e.outcome),r="neutral"===n?null:n;t?eg(r,t,e.provider,e.credentialId,e.model):Z.current(null,r).catch(()=>{})}},[ex,eg]);let ew=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ek,error:ej,messages:eS,entryIds:eC,streamState:eN,agentRunning:eT,bashRunning:eI,pendingBash:eM,modelNames:eR,modelList:eE,modelError:e$,modelScopeWarnings:eL,modelThinkingLevels:eA,modelThinkingLevelMaps:e_,modelRoles:eF,toolPreset:ez,thinkingLevel:eW,effectiveThinkingLevel:eO,thinkingCeiling:eD,fastMode:eH,fastModeBusy:eU,handleFastModeToggle:eB,retryInfo:eq,contextUsage:eV,forkingEntryId:eG,isCompacting:eQ,compaction:e0,compactError:e8,compactResult:e4,displayModel:e6,modelSwitching:e3,sessionStats:tn,runStateKnown:tc,compactedWork:td,slashCommands:tp,slashCommandsLoading:th,deliveryRows:tm,subagents:tf,todoPhases:tg,notices:tx,extensionDialog:tv,extensionResponse:tb,extensionCustomUi:ty,extensionStatuses:tw,extensionWidgets:tk,respondToExtensionUi:tj,sendExtensionCustomInput:tS,isAutoModelSelection:tC,agentPhase:tN,isNew:tT,autoFollowPaused:tI,resumeAutoFollow:tM,pauseAutoFollow:tR,goalStatus:tE,sessionIdRef:t$,messagesEndRef:tL,scrollContainerRef:tA,handleSend:t_,handleAbort:tF,handleFork:tz,handleNavigate:tO,handleModelChange:tD,handleRoleModelChange:tH,handleMainPresetChange:tU,newSessionAccount:tB,handleCompact:tq,handleSteer:tV,handleFollowUp:tK,handlePromptWithStreamingBehavior:tG,handleAbortCompaction:tJ,handleRecallQueue:tZ,handleRemoveQueuedMessage:tY,handleBuiltinSlashCommand:tX,handleToolPresetChange:tQ,handleThinkingLevelChange:t0,loadSlashCommands:t1,ensureNewSession:t2,refreshLiveTranscript:t8}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[N,T]=(0,i.useState)(f?.context.entryIds??[]),[I,M]=(0,i.useState)(f?.context.compactedWork??null),[R,E]=(0,i.useReducer)(pt,{isStreaming:!1,streamingMessage:null}),[$,L]=(0,i.useState)(!1),[P,A]=(0,i.useState)(!1),[_,F]=(0,i.useState)(null),[z,W]=(0,i.useState)({}),[O,D]=(0,i.useState)([]),[H,U]=(0,i.useState)(null),[B,q]=(0,i.useState)([]),[V,K]=(0,i.useState)({}),[G,J]=(0,i.useState)({}),[Z,Y]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[eo,el]=(0,i.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ec,ed]=(0,i.useState)(),[eu,ep]=(0,i.useState)(null),[eh,em]=(0,i.useState)(null),[ef,eg]=(0,i.useState)(!1),ex=(0,i.useRef)(0),ev=(0,i.useRef)(0),eb=(0,i.useRef)(""),[ey,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(f?.contextUsage??null),[eS,eC]=(0,i.useState)(null),[eN,eT]=(0,i.useState)(null),[eI,eM]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(null),[e$,eL]=(0,i.useState)(!1),[eA,e_]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(null),[eW,eO]=(0,i.useState)(null),[eD,eH]=(0,i.useState)(null),eU=(0,i.useRef)(null),[eB,eq]=(0,i.useState)(!1),[eV,eK]=(0,i.useState)(null),[eG,eJ]=(0,i.useState)([]),[eZ,eY]=(0,i.useState)(!1),[eX,eQ]=(0,i.useReducer)(ph,{visible:[],pending:[]}),[e0,e1]=(0,i.useState)(null),[e2,e8]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(null),e6=(0,i.useRef)(null),[e3,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)([]),[tn,tr]=(0,i.useState)([]),[ti,tl]=(0,i.useState)({steering:[],followUp:[]}),[tc,td]=(0,i.useState)([]),[tu,tp]=(0,i.useReducer)(al,[]),th=(0,i.useRef)(0);(0,i.useEffect)(()=>{tp({type:"queue",steering:ti.steering,followUp:ti.followUp})},[ti]),(0,i.useEffect)(()=>{$||tp({type:"idle"})},[$]),(0,i.useEffect)(()=>{tp({type:"reset"})},[t?.id]);let tm=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${as(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${aa(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(tu,ti),[tu,ti]),[tf,tg]=(0,i.useState)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(0),tj=(0,i.useRef)(!1),tS=(0,i.useRef)(t?.id??null),tC=(0,i.useRef)(f?.leafId??null),tN=(0,i.useRef)(S),tT=(0,i.useRef)(N);tN.current=S,tT.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tM=(0,i.useRef)(!1),tR=(0,i.useRef)(new Set);(0,i.useEffect)(()=>()=>pb(tR.current),[]);let tE=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),tL=(0,i.useRef)(-1),tP=(0,i.useRef)("unknown"),tA=(0,i.useRef)(null),t_=(0,i.useRef)(null),tF=(0,i.useRef)(0),tz=(0,i.useRef)(!1),tW=(0,i.useRef)(0),tO=(0,i.useRef)(null),tD=(0,i.useRef)(null),tH=(0,i.useRef)(null),tU=(0,i.useRef)(!1),tB=(0,i.useRef)(!0),[tq,tV]=(0,i.useState)(!1),[tK,tG]=(0,i.useState)(null),tJ=(0,i.useRef)(void 0),tZ=(0,i.useRef)(0),tY=(0,i.useRef)(null),tX=(0,i.useRef)(0),tQ=(0,i.useRef)(()=>{}),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t8=(0,i.useRef)(null),t4=(0,i.useRef)(!1),t5=(0,i.useRef)(null),t6=(0,i.useRef)(null),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(null),ne=(0,i.useRef)(0),nt=(0,i.useRef)(null),nn=(0,i.useRef)(null),nr=(0,i.useRef)(!1);nr.current=e.transitioning??!1;let ni=(0,i.useRef)(Date.now()),na=(0,i.useRef)(0),ns=(0,i.useRef)(0),no=(0,i.useRef)(null),nl=(0,i.useRef)(!1),nc=(0,i.useRef)(Promise.resolve()),nd=e.setToolPreset??ea,nu=eI??g?.context.model??eR??null,np=m?X??en:nu,nh=(0,i.useMemo)(()=>{if(e0)return{...e0,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,n+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tS.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ek?{contextUsage:ek}:{}}},[S,e0,ek,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nm=(0,i.useRef)(0),nf=(0,i.useCallback)((e,t)=>{e&&tS.current===e&&Array.isArray(t)&&(nm.current+=1,tg(n=>n?.sid===e&&pa(n.phases,t)?n:{sid:e,phases:t}))},[]),ng=(0,i.useCallback)((e,t,n)=>{tS.current===e&&nm.current===n&&Array.isArray(t)&&tg(n=>n?.sid===e&&pa(n.phases,t)?n:{sid:e,phases:t})},[]),nx=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tN.current):e;tN.current=t,C(t)},[]),nv=(0,i.useCallback)(e=>{tT.current=e,T(e)},[]),nb=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nx([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tS.current!==e)return null;x(a),j(a.leafId),tC.current=a.leafId??null;let s=to(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nx(s.messages),nv(s.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null),eM(e=>nl.current?e:null),w(null);let o=!n&&t9.current===e;if(o||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),ep(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!n){if(o)try{let t=ne.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tS.current===e){let r=await n.json();tS.current===e&&ne.current===t&&(r.state?.thinkingLevel!==void 0?(el(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(t9.current=null,el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nm.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tS.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ej(i.contextUsage??null),void 0!==i.systemPrompt&&eC(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t9.current=e,el(i.configuredThinkingLevel??i.thinkingLevel),ed(i.thinkingLevel)),void 0!==i.thinkingCeiling&&ep(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&te(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&tr(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(pn(i.queuedMessages)),void 0!==i.subagents&&td(e=>pe(e,i.subagents??[])),ng(e,i.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[ng,nv,nx]),ny=(0,i.useCallback)(e=>{let t=nc.current.then(async()=>{tS.current===e&&await nb(e)});return nc.current=t.catch(()=>{}),t},[nb]),nw=(0,i.useCallback)(async(e,t)=>{let n=++ev.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ev.current!==n||tS.current!==e)return;tC.current=t;let o=to(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nx(o.messages),nv(o.entryIds),M(s.context.compactedWork??null),ej(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nv,nx]),nk=(0,i.useCallback)(async e=>{try{let t=await uJ(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));nd(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[nd]),nj=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tS.current;if(!m||!r||!n||t4.current)return;let i=t5.current??r;t4.current=!0,l?.({id:n,path:"",cwd:i,...i!==r?{projectRoot:r}:{},name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0})},[m,r,l]),nC=(0,i.useCallback)(async()=>{if(t2.current)return t2.current;let e=tS.current;if(e&&nn.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t6.current,n=t7.current,i=t3.current;e&&eE(e);let a={cwd:r,type:"ensure_session",toolNames:(0,ur.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),o=t8.current,l=o?.body===s?o.createRequestId:pd();t8.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:l})});if(!c.ok)throw Error((await c.json().catch(()=>({}))).error??`HTTP ${c.status}`);let d=await c.json();t8.current=null,t=d.sessionId,tS.current=t,t5.current=d.cwd??r??null,t5.current&&es(t5.current,d.worktree),null!==nt.current&&(nn.current=t),d.model&&t6.current===e&&(eE(d.model),e||er(d.model)),d.thinkingLevel&&t7.current===n&&(el(d.configuredThinkingLevel??d.thinkingLevel),ed(d.thinkingLevel))}for(;nn.current===t;){let e=nt.current;await uJ(t,{type:"set_thinking_ceiling",ceiling:e}),nt.current===e&&nn.current===t&&(nn.current=null)}return t})();t2.current=t;try{return await t}finally{t2.current=null}},[m,r,ei]),nT=(0,i.useCallback)(async()=>{let e=tS.current??await nC();if(!e)return eJ([]),[];eY(!0);try{let t=await uJ(e,{type:"get_commands"}),n=t?.commands??[];return eJ(n),n}catch(e){return console.error("Failed to load slash commands:",e),eJ([]),[]}finally{eY(!1)}},[nC]),nR=(0,i.useCallback)(()=>{tk.current+=1,tj.current=!1,tw.current&&(clearTimeout(tw.current),tw.current=null)},[]),nE=(0,i.useCallback)(()=>{tx.current?.close(),tx.current=null,tv.current=null,tb.current=null},[]),n$=(0,i.useCallback)(()=>{ty.current?.close(),ty.current=null},[]),nL=(0,i.useCallback)(e=>{n$();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);ty.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tO.current?.(n):"agent_start"===n.type&&tD.current?.(e)}catch{}}},[n$]),nP=(0,i.useCallback)(e=>{nE();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tx.current=t,tv.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tb.current?.source===t&&(tb.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tO.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tx.current===t&&(tM.current||tj.current))){tx.current=null,tv.current=null,tb.current=null;let t=tk.current;setTimeout(()=>{t===tk.current&&!tx.current&&(tM.current||tj.current)&&nP(e)},1e3)}}});return tb.current={source:t,promise:n,pending:!0},n},[nE]),nA=(0,i.useCallback)(async e=>{let t=tx.current;if(t&&tv.current===e){if(t.readyState===EventSource.OPEN)return;let e=tb.current;if(e?.source===t&&e.pending&&(await e.promise,tx.current===t&&t.readyState===EventSource.OPEN))return}let n=await nP(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tx.current===n.source&&(tx.current=null),tv.current===e&&(tv.current=null),tb.current?.source===n.source&&(tb.current=null),n.source.close(),new pc(n.status)},[nP]),n_=(0,i.useCallback)(async(e,t)=>{let n=e6.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tS.current,i=e=>{e6.current=e,e5(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await uJ(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e8(t=>t?.id===e.id?null:t)},[]),nF=(0,i.useCallback)(async(e,t)=>{let n=tS.current;if(n)try{await uJ(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nz=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eQ({type:"add",notice:{id:e.id??pd(),message:t,type:e.type??"info"}})},[]),nW=(0,i.useCallback)(e=>{let t={role:"custom",customType:tt,content:eP(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tS.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tT.current.slice(0,tN.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!ts(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${ta}${n.seq}`,baseEntryId:a,message:t});let s=to(tN.current,tT.current,n.outputs);nx(s.messages),nv(s.entryIds)},[nx,nv]),nO=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e8(e=>e?.id===t.id?null:e),e6.current?.id===t.id&&(e6.current=null,e5(null));return}switch(uV(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":e8(t);break;case"notify":nz({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tr(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e7(e=>t.closed?e?.id===t.id?null:e:t)}},[nz,o,e.chatInputRef]),nD=(0,i.useCallback)(()=>{let e=tM.current;return tM.current=!1,L(!1),eK(null),pb(tR.current),ew(null),E({type:"end"}),e},[]),nH=(0,i.useCallback)(()=>{tP.current="unknown",tA.current=null;let e=po(tN.current,tT.current);t_.current=e?{entryId:e.entryId,key:pg(e.message)}:null,tF.current+=1},[]),nU=(0,i.useCallback)(()=>{let e=tP.current,t=tA.current;if("unknown"===e){let n=po(tN.current,tT.current),r=n?.message,i=t_.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:pg(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=ps(r),t??={provider:r.provider,...r.model?{model:r.model}:{},...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tS.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nB=(0,i.useCallback)(e=>{let t=nU();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tF.current;e.catch(()=>void 0).then(()=>{let e=tS.current===t.sessionId&&tF.current===n;s?.(e?nU():t)})},[s,nU]),nq=(0,i.useCallback)((e,t)=>tL.current!==e&&(tL.current=e,nB(t),!0),[nB]),nV=(0,i.useCallback)(e=>{nR(),tj.current=!0;let t=tk.current,n=async()=>{if(t===tk.current&&tS.current===e&&tj.current)try{let r=nm.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tk.current||tS.current!==e||!tj.current)return;let s=a.state;if(td(e=>pe(e,s?.subagents??[])),ng(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tj.current=!1,tw.current=null,tE.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tM.current=!0,L(!0),eK(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){e_(!0),eH(pi(s)),tw.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){tw.current=setTimeout(()=>void n(),1e3);return}tj.current=!1,tw.current=null,nE()}catch{if(t!==tk.current||tS.current!==e||!tj.current)return;tw.current=setTimeout(()=>void n(),600)}};tw.current=setTimeout(()=>void n(),3e4)},[ng,nR,nE]),nK=(0,i.useCallback)(async(e=tS.current,t=na.current)=>{if(na.current===t)try{e&&await nb(e)}finally{if(na.current!==t)return;let n=t$.current,r=tE.current;t$.current=!1,tE.current=!1,no.current=null;let i=nD();n?nq(t):r&&i&&nB(),e&&nV(e)}},[nb,nB,nq,nV,nD]),nG=(0,i.useCallback)(async(e,t)=>{await pu(800);let n=Date.now();for(;tM.current&&Date.now()-n<2e4;){if(void 0!==t&&na.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nK(e,t)}}catch{}await pu(600)}},[nK]),nJ=(0,i.useCallback)(async e=>{let t=tW.current+1;for(tW.current=t;tz.current&&tW.current===t&&tS.current===e;){await pu(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nb(e),tW.current!==t||tS.current!==e)return;tz.current=!1,A(!1),F(null);return}catch{}}},[nb]),nZ=(0,i.useCallback)(async e=>{if(!tM.current)return;let t=na.current;try{let n=nm.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(na.current!==t)return;let a=i.state;if(e_(a?.isCompacting??!1),eH(pi(a)),tl(pn(a?.queuedMessages)),a?.contextUsage!==void 0&&ej(a.contextUsage??null),td(e=>pe(e,a?.subagents??[])),ng(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tM.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&te(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&tr(a.extensionWidgets??[])),await nK(e,t)}catch{}},[ng,nK]),nY=(0,i.useCallback)(async e=>{let t=await nb(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tS.current===e&&!tM.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tE.current=!!n.isStreaming,t$.current=!!n.isPromptRunning,tM.current=!0,L(!0),eK(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),py(tR.current,e,n.pendingToolCalls),nP(e),!n.isStreaming&&n.isPromptRunning&&nG(e),!0)},[nP,nb,nG]),nX=(0,i.useCallback)(async(e,t=na.current)=>{let n=ns.current+1;ns.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==ns.current||tS.current!==e||na.current!==t)return;i.state?.contextUsage!==void 0&&ej(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eA){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eA]),(0,i.useEffect)(()=>{if(!$&&!eA)return;let e=()=>{let e=tS.current;e&&nX(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[$,eA,nX]),(0,i.useEffect)(()=>{if(!$)return;let e=()=>{let e=tS.current;e&&nZ(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[$,nZ]),(0,i.useEffect)(()=>{if($)return;let e=()=>{let e=tS.current;e&&!tM.current&&nY(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tS.current,n=e.detail?.sessionId;t&&n===t&&!tM.current&&nY(t).then(e=>{e||tS.current!==t||tM.current||nb(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(u1,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(u1,n)}},[$,nY,nb]),tD.current=e=>{if(tS.current!==e||tM.current||tx.current||tH.current)return;let t=nY(e).then(async t=>{t||tS.current!==e||tM.current||await nb(e)}).catch(()=>{}).finally(()=>{tH.current===t&&(tH.current=null)});tH.current=t},(0,i.useEffect)(()=>{tM.current=$},[$]),tO.current=(0,i.useCallback)(e=>{var t;switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=pg(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=pg(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=pg(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tS.current,tC.current,tN.current,tT.current);if(!t)break;tC.current=t.entryId;let n=to(t.messages,t.entryIds,tI.current.sessionId===tS.current?tI.current.outputs:[]);nx(n.messages),nv(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tM.current;nR(),e&&nH(),tE.current=!0,tM.current=!0,L(!0),eK({kind:"waiting_model"}),E({type:"start"});break}case"agent_end":if(!tM.current)break;if(eK(null),pb(tR.current),ew(null),E({type:"end"}),tS.current){nb(tS.current);let e=nm.current;fetch(`/api/agent/${encodeURIComponent(tS.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ej(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&te(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&tr(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>pe(e,t.state?.subagents??[])),tS.current&&ng(tS.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tG(t.state.goal??null),tl(pn(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tG(e.status??null);break;case"agent_settled":{let e=tE.current;if(tE.current=!1,!e||t$.current)break;let t=tS.current,n=nD();e_(!1);let r=t?nb(t):void 0;t&&nV(t),n&&nB(r);break}case"prompt_done":{let e=na.current,t=t$.current;t$.current=!1,no.current=null;let n=tL.current!==e;if(!t&&!n)break;let r=tS.current;nq(e,r?nb(r):void 0),!tE.current&&(nD(),r&&nV(r))}break;case"prompt_error":tP.current="failed",nz({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tP.current="failed",nz({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tM.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&E({type:"update",message:s5(t)}),eK(null);break}case"message_end":{if(!tM.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}:{}},tP.current=ps(t)),t&&"user"===t.role){let e=s5(t),n=pf(e),r=no.current;no.current=null,nx(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&pf(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tp({type:"user-message",kind:ad(e),text:ac(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nx(e=>[...e,s5(t)]);let n=tS.current;n&&nX(n),E({type:"reset"}),eK(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tS.current,n=e.thinkingLevel;t&&void 0!==n&&(t9.current=t,ne.current+=1,el(e.configured??n),ed(n));break}case"todo_changed":nf(tS.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,i=nI(tS.current,t);i&&tR.current.add(i),eK(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_update":{let n=nI(tS.current,"string"==typeof e.toolCallId?e.toolCallId:null);n&&tR.current.has(n)&&"string"==typeof e.text&&(t=e.text,nS.get(n)!==t&&(nS.set(n,t),nN()));break}case"tool_execution_end":{let t=e.toolCallId,n=nI(tS.current,t);n&&tR.current.delete(n)&&nM([n]),eK(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";td(n=>{let r=n.find(e=>e.id===t.id);return pe(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};td(e=>pe(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};td(e=>pe(e,[r]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ew({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ew(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}e_(!0),ez(null),eO(null);break;case"auto_compaction_end":case"compaction_end":if(e_(!1),e.errorMessage)ez(e.errorMessage),eO(null);else if(!e.aborted){eO(px(e.result,e.reason??"auto"));let t=tS.current;t&&(nb(t),nX(t))}break;case"extension_ui_request":nO(e)}},[nz,nf,ng,nR,nO,nb,nB,nq,nX,nH,nV,nD,nv,nx]);let nQ=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tM.current||tz.current||nl.current)return"unknown";let o=lh(n,a??[]),l=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tJ.current?.(t,e),"accepted"):"unknown"}nH();let c=na.current+1;nR(),t$.current=!0;let d=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...o.trim()?[{type:"text",text:o}]:[],...d]:o,timestamp:Date.now()};nx(e=>[...e,u]),no.current=pf(u),na.current=c,tM.current=!0,L(!0),eK(l?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),tQ.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1,g="unknown";try{if(m&&r){let e=tS.current??await t2.current,t=await nC();t&&(h=t,X&&(eE(X),e&&await uJ(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nA(t),f=!0,await uJ(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),nj(1,n),g="accepted")}else t&&(h=t.id,await nA(t.id),f=!0,await uJ(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&nG(h,c),g}catch(o){console.error("Failed to send message:",o);let r=o instanceof uG&&"update_draining"===o.code&&!1===o.accepted;if(!(!f||o instanceof uG&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return nG(h,c),"unknown";t$.current=!1,tM.current=!1,nE();let s=no.current;return s&&nx(e=>{let t=e[e.length-1];return t?.role==="user"&&pf(t)===s?e.slice(0,-1):e}),nz({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,pv(i),a,t?.id??h??void 0),no.current=null,L(!1),eK(null),E({type:"end"}),"returned"}},[m,r,X,t,nC,nA,nj,nG,nz,nR,nE,e.chatInputRef,nH,nx]);tJ.current=(0,i.useCallback)(async(n,r)=>{if(tM.current||tz.current)return;let i=`${r?"!!":"!"}${n}`;tz.current=!0,tQ.current(!0),F({command:n,excludeFromContext:r}),A(!0);try{let e=tS.current??t?.id??await nC();if(!e)throw Error("Unable to create a session for the shell command");await uJ(e,{type:"bash",command:n,excludeFromContext:r}),await nb(e),nj(1,i)}catch(t){console.error("Failed to execute shell command:",t),nz({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tz.current=!1,F(null),A(!1)}},[nz,nC,nb,e.chatInputRef,nj,t]);let n0=(0,i.useCallback)(async()=>{let e=tS.current;if(e){if(tz.current){try{await uJ(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uJ(e,{type:"abort"}),tP.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),n1=(0,i.useCallback)(async e=>{if(tz.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tS.current;if(!t)return{forked:!1,error:"No active session to fork"};eT(e??null);try{let{cancelled:n,newSessionId:r}=await uJ(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eT(null)}},[c]),n2=(0,i.useCallback)(async e=>{if(tz.current)return;let t=tS.current;t&&(uJ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nw(t,e))},[nw]),n8=(0,i.useCallback)(async e=>{if(tz.current)return;j(e);let t=tS.current;t&&(await nw(t,e),e&&uJ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nw]),n4=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t6.current?.provider===e;t6.current=n,r||(t3.current=null,et(null)),Q(n),eE(n);let i=tS.current??await t2.current;if(!i)return;try{await uJ(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tS.current;if(n&&!nl.current){nl.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await uJ(n,{type:"set_model",provider:e,modelId:t}),nl.current=!1,await nb(n)}catch(e){console.error("Failed to set model:",e),nl.current=!1,eM(eI),nz({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nb(n)}finally{nl.current=!1,eL(!1)}}},[nz,eI,m,nb,Q]),n5=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(nl.current)return!1;nl.current=!0,eL(!0);let e=t6.current,a=t3.current,s=t7.current;try{t6.current=t,t3.current=n??null,t7.current="auto";let e=tS.current??await t2.current;return e&&await uJ(e,r),Q(t),et(n??null),eE(t),el("auto"),ed(void 0),e&&await nb(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t6.current=e,t3.current=a,t7.current=s,nz({type:"error",message:i(n)});let t=tS.current;return t&&await nb(t),!1}finally{nl.current=!1,eL(!1)}}let a=tS.current;if(!a||nl.current)return!1;nl.current=!0,eM(t),eL(!0);try{return await uJ(a,r),await nb(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eI),nz({type:"error",message:i(e)}),await nb(a),!1}finally{nl.current=!1,eL(!1)}},[nz,eI,ec,m,nb,Q,eo]),n6=(0,i.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t7.current=t??null,el(t??"auto"),ed(void 0),t6.current=e,t3.current=null,et(null),Q(e),eE(e)}let r=tS.current??(m?await t2.current:null);if(r)try{await uJ(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,Q]),n3=(0,i.useCallback)(async()=>{let e=tS.current;if(e&&!eA){eU.current="manual",e_(!0),ez(null),eO(null);try{let t=await uJ(e,{type:"compact"});eO(px(t,"manual")),await nb(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eO(null)}finally{e_(!1)}}},[eA,nb]),n7=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();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&&!tS.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t7.current&&el(t??"auto")}},[m,r,t?.cwd]),n9=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await nC(),s=e=>(e.handled&&(e.error?nz({type:"error",message:e.error}):"openSessionStats"!==e.action&&nz({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eA)return s({handled:!0,error:"No active session to compact"});eU.current="manual",e_(!0),ez(null),eO(null);let e=await uJ(a,{type:"compact",...i?{customInstructions:i}:{}});return eO(px(e,"manual")),await nb(a,!0)&&nj(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await uJ(a,{type:"reload"}),await Promise.all([nb(a,!1,!0),nk(a),nT(),n7()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await uJ(a,{type:"set_session_name",name:i}),await nb(a)&&nj(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await uJ(a,{type:"get_session_stats"});return e&&e1(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await uJ(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await n1();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await uJ(a,{type:"goal",args:i});if(tG(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nW(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nz({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tM.current||tz.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tM.current=!0,L(!0),eK({kind:"running_command"});try{await nA(a);let e=await uJ(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nb(a,!0)&&nj(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tM.current=!1,L(!1),eK(null),tS.current===a&&nV(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await uJ(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nW(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&e_(!1)}},[nz,nW,nA,nC,n1,eA,n7,nb,nT,nk,nj,h,nV]),re=(0,i.useCallback)(async(t,n,r)=>{let i=tS.current;if(!i)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r),"returned";let a=lh(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++th.current;tp({type:"submit",id:o,kind:"steer",text:a,images:s?.length??0});try{return await uJ(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tp({type:"ack",id:o}),"accepted"}catch(a){return tp({type:"fail",id:o}),console.error("Failed to steer:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r,i),"returned"}},[nz,e.chatInputRef]),rt=(0,i.useCallback)(async(t,n,r,i)=>{let a=tS.current;if(!a)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(r),i),"returned";let s=lh(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++th.current;tp({type:"submit",id:l,kind:n,text:s,images:o?.length??0});try{return await uJ(a,{type:"prompt",message:s,streamingBehavior:n,...o?.length?{images:o}:{}}),tp({type:"ack",id:l}),"accepted"}catch(n){return tp({type:"fail",id:l}),console.error("Failed to queue prompt:",n),nz({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(r),i,a),"returned"}},[nz,e.chatInputRef]),rn=(0,i.useCallback)(async(t,n,r)=>{let i=tS.current;if(!i)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r),"returned";let a=lh(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++th.current;tp({type:"submit",id:o,kind:"followUp",text:a,images:s?.length??0});try{return await uJ(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tp({type:"ack",id:o}),"accepted"}catch(a){return tp({type:"fail",id:o}),console.error("Failed to follow up:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r,i),"returned"}},[nz,e.chatInputRef]),rr=(0,i.useCallback)(async()=>{let e=tS.current;if(e)try{await uJ(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),ri=(0,i.useCallback)(async()=>{let t=tS.current;if(t)try{var n;let r=await uJ(t,{type:"clear_queue"});tp({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nz({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nz]),ra=(0,i.useCallback)(async(e,t)=>{let n=tS.current;if(n)try{let r=await uJ(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tp({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nz({type:"error",message:"Failed to remove queued message"})}},[nz]),rs=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==eu;el(e),ep(n),m&&(!tS.current||nn.current===tS.current)&&(t7.current=e,nt.current=n),ed(void 0);let i=tS.current??await t2.current;if(i)try{nn.current===i?await nC():r&&await uJ(i,{type:"set_thinking_ceiling",ceiling:n}),await uJ(i,{type:"set_thinking_level",level:e}),await nb(i)}catch(e){console.error("Failed to set thinking level:",e),nz({type:"error",message:"Failed to set thinking level"}),await nb(i)}},[m,nb,nz,eu,nC]);eb.current=np?`${np.provider}/${np.modelId}`:"";let ro=e=>e?`${e}|${eb.current}`:null,rl=t?.id??tS.current,rc=ro(rl),rd=eh&&eh.key===rc?eh.value:null;(0,i.useEffect)(()=>{let e=++ex.current;rc&&rl&&!$&&!e$&&fetch(`/api/agent/${encodeURIComponent(rl)}`).then(e=>e.json()).then(t=>{ex.current===e&&ro(tS.current)===rc&&em({key:rc,value:(t.running?pr(t.state):void 0)??null})}).catch(()=>{})},[rc,$,e$]);let ru=(0,i.useCallback)(async()=>{let e=tS.current??await nC(),t=ro(tS.current);if(!e||!t)return;let n=++ex.current,r=()=>ex.current===n&&ro(tS.current)===t,i=e=>{r()&&em({key:t,value:e})};eg(!0);try{let n=eh?.key===t?eh.value?.enabled:void 0;if(void 0===n){let t=pr(await uJ(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await uJ(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nz({type:"error",message:t instanceof Error?t.message:String(t)});try{i(pr(await uJ(e,{type:"get_state"}))??null)}catch{i(null)}}finally{eg(!1)}},[nC,eh,nz]),rp=(0,i.useCallback)(async e=>{let t=(0,ur.xG)(e);nd(e);let n=tS.current??await t2.current;if(n)try{await uJ(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[nd]),rh=(0,i.useCallback)(e=>{tB.current=e,tV(t=>!e===t?t:!e)},[]);tQ.current=e=>{tY.current=null,rh(e)};let rm=(0,i.useCallback)((e="smooth")=>{tX.current=Date.now()+700,t0.current?.scrollIntoView({behavior:e})},[]),rf=(0,i.useCallback)(()=>{tZ.current=0,tY.current=null,rh(!0),rm("smooth")},[rm,rh]),rg=(0,i.useCallback)(()=>{tZ.current=0,tY.current=null,rh(!1)},[rh]),rx=(0,i.useCallback)(()=>{if(!tY.current)return;tY.current=null;let e=t1.current;e&&rh(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[rh]),rv=(0,i.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(tY.current)return void rx();rg();let e=t1.current;return void(tY.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}rx(),e instanceof KeyboardEvent&&(!pl.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tZ.current=Date.now()+1200)},[rx,rg]),rb=(0,i.useCallback)(()=>{let e=t1.current;if(!e)return;let t=tY.current;if(null!==t){let n=t.top;t.moved||=e.scrollTop!==n,t.top=e.scrollTop;return}if(!tM.current&&!tz.current)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight,r=Date.now()<=tZ.current;if(!(!r&&Date.now()<tX.current)){if(n<=72)return void rh(!0);r&&rh(!1)}},[rh]);return(0,i.useEffect)(()=>(tS.current=t?.id??null,tI.current.sessionId!==tS.current&&(tI.current={sessionId:tS.current,outputs:[],seq:0}),t&&nb(t.id,!f,!0,f).then(e=>{if(tS.current!==t.id)return;nL(t.id),e?.running&&(nk(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tE.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tM.current=!0,L(!0),eK(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),py(tR.current,t.id,e.state.pendingToolCalls),nP(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nG(t.id)),e.state?.isBashRunning&&(tz.current=!0,A(!0),nJ(t.id)),(e.state?.subagents?.length??0)>0&&nP(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&e_(n.isCompacting),eH(pi(n)),void 0!==n.contextUsage&&ej(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t9.current=t.id,el(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&ep(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&te(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&tr(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(pn(n.queuedMessages)),void 0!==n.subagents&&td(e=>pe(e,n.subagents??[])),void 0!==n.goal&&tG(n.goal??null)),e&&eq(!0)}),()=>{tW.current+=1,nR(),nE(),n$()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,n8)},[g?.tree,k,n8,u]),(0,i.useEffect)(()=>{let e=e=>{let t=tY.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t1.current?.contains(e.target))?rx():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",rv),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",rv)}},[rx,rv]),(0,i.useEffect)(()=>{let e=t1.current;if(!e)return;let t=()=>{tY.current?.moved&&rx()};return e.addEventListener("pointerdown",rv,{passive:!0}),e.addEventListener("wheel",rv,{passive:!0}),e.addEventListener("touchstart",rv,{passive:!0}),e.addEventListener("scroll",rb,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",rv),e.removeEventListener("wheel",rv),e.removeEventListener("touchstart",rv),e.removeEventListener("scroll",rb),e.removeEventListener("scrollend",t)}},[S.length,v,rx,rb,rv]),(0,i.useEffect)(()=>{if(nr.current||!$&&!P||!tB.current)return;let e=t1.current;if(!e)return;let t=requestAnimationFrame(()=>{tB.current&&(tX.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[$,P,S.length,R.streamingMessage,eV,_,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tU.current){tU.current=!0,rm("instant");return}if(!nr.current&&tB.current){let e=Date.now()-ni.current<1500;rm(tM.current||tz.current||e?"instant":"smooth")}}},[S.length,$,P,rm,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n7(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n7,d]),(0,i.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eO(null),6e3);return()=>clearTimeout(e)},[eW]),(0,i.useEffect)(()=>{if(0===eX.visible.length)return;let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eQ({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eX.visible[0])return;let t=setTimeout(()=>{eQ({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eX.visible]),(0,i.useEffect)(()=>{e1(null)},[S.length,ek?.tokens,ek?.percent,ek?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:R,agentRunning:$,modelNames:z,modelList:O,modelError:H,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ei,thinkingLevel:eo,effectiveThinkingLevel:ec,thinkingCeiling:eu,retryInfo:ey,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:eA,compaction:eD,compactError:eF,compactResult:eW,currentModel:nu,displayModel:np,modelSwitching:e$,sessionStats:nh,runStateKnown:eB,slashCommands:eG,slashCommandsLoading:eZ,queuedMessages:ti,deliveryRows:tm,subagents:tc,todoPhases:tf&&tf.sid===tS.current?tf.phases:null,compactedWork:I,notices:eX.visible,extensionDialog:e2,extensionResponse:e4,extensionCustomUi:e3,extensionStatuses:e9,extensionWidgets:tn,respondToExtensionUi:n_,sendExtensionCustomInput:nF,isAutoModelSelection:m&&null===X,agentPhase:eV,isNew:m,autoFollowPaused:tq,resumeAutoFollow:rf,pauseAutoFollow:rg,goalStatus:tK,sessionIdRef:tS,eventSourceRef:tx,messagesEndRef:t0,scrollContainerRef:t1,handleSend:nQ,handleAbort:n0,handleFork:n1,handleNavigate:n2,handleModelChange:n4,handleRoleModelChange:n6,handleMainPresetChange:n5,newSessionAccount:ee,handleCompact:n3,handleSteer:re,handleFollowUp:rn,handlePromptWithStreamingBehavior:rt,handleAbortCompaction:rr,handleRecallQueue:ri,handleRemoveQueuedMessage:ra,handleBuiltinSlashCommand:n9,handleToolPresetChange:rp,handleThinkingLevelChange:rs,fastMode:rd,fastModeBusy:ef,handleFastModeToggle:ru,loadTools:nk,loadSlashCommands:nT,ensureNewSession:nC,refreshLiveTranscript:ny,setActiveLeafId:j,setData:x,setMessages:C,dispatch:E,setAgentRunning:L,setForkingEntryId:eT,bashRunning:P,pendingBash:_,handleAgentEventRef:tO}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ey,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),t4=(0,i.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=te(i);if(!a||"custom"!==i.role)continue;t??=[...e];let s=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&s.push(t);continue}let i=n.get(t);void 0===i&&(i=function(e){let t=e9(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,i)),i===a.sourceHash&&s.push(t)}s.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===a.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[r]={...i,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(e7)?{kind:"translated",text:n.slice(e7.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(i,e9(o.content??[]))}}return t??e})(eS),[eS]),t5=iv(e?.id,e6?.provider,void 0,e6?.modelId),t6=t5?.alias;(0,i.useEffect)(()=>{t6&&X.current?.(t6)},[t6]);let t3=(0,i.useMemo)(()=>{if(!e6)return null;let e=tT?tB:rg.find(e=>e.alias===t5?.alias)?.oauthPosition;return rg.find(t=>t.provider===e6.provider&&(void 0===t.oauthPosition?null===t5||t5.seed===t.seed:t.oauthPosition===e))?.alias??null},[e6,tT,tB,t5]),t7=eT||eI,t9=e?.id;ei.current=t4,ea.current=eC,eo.current=t$;let ne=(0,i.useRef)(!0);ne.current=!tI;let nt=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eT&&!nt.current&&(el.current+=1),nt.current=eT},[eT]),(0,i.useEffect)(()=>()=>{el.current+=1},[]),(0,i.useEffect)(()=>{et(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(pP(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[]}}(t9),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t9)])},[t9]),(0,i.useEffect)(()=>{let e=t$.current;e&&en.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(rl(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,t4,eC);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(pA(e,r),r):t})},[t4,eC,t$]);let nn=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=t$.current,t=nn.current;if(nn.current=e?{sessionId:e,entryIds:eC}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===rd&&r.push(t[a])}return r}(t.entryIds,eC,t4),r=eu();if(0===n.length||!r)return;let i=ig(e,"web6",void 0)?.alias??null;for(let e of n)en.current.some(t=>t.anchorEntryId===e)||em(i,"done",r,{kind:"entry",entryId:e})},[eC,t4,t$,eu,em]);let nr=eT&&tN?.kind==="running_tools"&&tN.tools.length>0&&tN.tools.every(e=>"wait"===e.name),ni=ek||s,{hideThinkingBlock:na}=(O=t??e?.cwd??null,H=n1(),(0,i.useEffect)(()=>{n0(O).catch(()=>{})},[O]),H),ns=(0,i.useMemo)(()=>({hideThinking:na}),[na]);(0,i.useEffect)(()=>{var e;if(!tv||Y.current===tv.id)return;Y.current=tv.id;let t=eu();if(!t)return;ed.current=t.turn;let n=eN.streamingMessage?.role==="assistant"?eN.streamingMessage:null,r=rc(ei.current,n,e6?.provider,e6?.modelId);eg("select"===(e=tv.method)||"ask"===e||"form"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tv,eN.streamingMessage,e6?.provider,e6?.modelId,eu,eg]),(0,i.useEffect)(()=>(v=t7?tF:null,()=>void(v=null)),[t7,tF]),(0,i.useEffect)(()=>{M?.(t7)},[M,t7]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{R?.(nr)},[nr,R]),(0,i.useEffect)(()=>()=>R?.(!1),[R]),(0,i.useEffect)(()=>{E?.(null!==tv)},[E,tv]),(0,i.useEffect)(()=>()=>E?.(!1),[E]);let{main:no,process:nl}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,o=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),o=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:o});a.messageCount+=t.length,a.toolCallCount+=n},l=e5(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:a,idx:e,runIndex:n,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){o(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,r.push(i);continue}if(tr(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===te(t)&&0>ti(e,i.idx)&&o(a,[{idx:i.idx}],0);continue}let s=eY(t,n);if(eJ(t,n)&&eZ(e,i.idx)){let e=s.flatMap(e=>e.blocks);o(a,[{idx:i.idx}],eX(e)),l.collect(i.idx,e);continue}let c=!1;for(let e of s){if("answer"===e.kind){d(i.idx,e.blocks),c=!0;continue}o(a,[{idx:i.idx,blocks:e.blocks}],eX(e.blocks)),l.collect(i.idx,e.blocks)}!c&&eJ(t,n)&&d(i.idx,[])}return u(),{main:r,process:i}})(t4,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(tl(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!tl(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!tl(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,o=[],l=0,c=0,d=e5(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(n),precedingBlocks:o}),o=[]};for(let l=t+1;l<n;l++){let n=e[l];if("assistant"!==n.role){if(null!==te(n)||ti(e,l)>=0)continue;if(tr(n)){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:l});continue}let c=eY(n,r);if(eJ(n,r)&&eZ(e,l)){let e=c.flatMap(e=>e.blocks);for(let t of(a.push({idx:l}),s+=eX(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(a.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eX(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eJ(n,r)&&p(l,[])}u();let h=d.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(t4,{sessionBusy:t7,isStreaming:eN.isStreaming,hideThinking:ns.hideThinking}),ns),[t4,t7,eN.isStreaming,ns]),nc=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=i3(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=r.get(l.position);e?e.calls.push(...n):r.set(l.position,{calls:[...n],placement:o?"after":"before"})}}"user"===e.role&&(a=t),tl(e)&&(s=t)});let{continuing:o}=i7(e,t,n);if(o){let e=r.get(o.position);e?e.calls.unshift(...o.calls):r.set(o.position,{calls:o.calls,placement:"before"})}return r})(no,t4,td?.messages),[no,t4,td]),nd=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=i7(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i);return{position:-1===a?e.length:a,calls:r}})(no,t4,td?.messages),[no,t4,td]),[nu,np]=(0,i.useState)(pM),{startIndex:nh,endIndex:nm,hasLater:nf}=pR(no.length,nu),ng=null!==nu.end&&nf,nx=(0,i.useRef)(no.length);nx.current=no.length;let nv=(0,i.useRef)(null),nb=(0,i.useRef)(null),ny=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nu.end&&nu.end>=no.length&&np(e=>({count:e.count,end:null}))},[nu.end,no.length]),(0,i.useEffect)(()=>{let e=nv.current,t=tA.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(ny.current=t.scrollHeight-t.scrollTop,np(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nu,no.length,tA]),(0,i.useEffect)(()=>{if(null==ny.current)return;let e=tA.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-ny.current),ny.current=null}},[nu.count,tA]),(0,i.useEffect)(()=>{let e=nb.current,t=tA.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&np(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=pR(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nx.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nu,no.length,tA]);let[nw,nk]=(0,i.useState)(null),[nj,nC]=(0,i.useState)(0),nT=(0,i.useRef)(null),nR=(0,i.useCallback)(e=>{tR(),nT.current=e,nk(null),np(t=>pE(nx.current,e,t)),nC(e=>e+1)},[tR]);(0,i.useLayoutEffect)(()=>{let e=nT.current,t=tA.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;nT.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,nk(e)},[nj,nu,no,tA]),(0,i.useEffect)(()=>{if(null===nw)return;let e=setTimeout(()=>nk(null),1800);return()=>clearTimeout(e)},[nw]);let nE=(0,i.useCallback)(()=>{(0,q.flushSync)(()=>np(pM));let e=tA.current;e&&(e.scrollTop=e.scrollHeight)},[tA]),n$=(0,i.useCallback)(()=>{ng&&nE(),tM()},[ng,nE,tM]),nL=(0,i.useRef)(null),[nP,nA]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!F||nL.current===F.id||F.sessionId!==e?.id||ek||0===t4.length)return;nL.current=F.id,W?.(F.id);let t=eC.indexOf(F.entryId);if(t<0)return void nA(!0);let n=0;for(let e=0;e<no.length;e++){let r=no[e].idx;if(r>t||(n=e,r===t))break}nR(n)},[F,e?.id,ek,t4.length,eC,no,nR,W]),(0,i.useEffect)(()=>{if(!nP)return;let e=setTimeout(()=>nA(!1),6e3);return()=>clearTimeout(e)},[nP]);let[n_,nF]=(0,i.useState)(!1),[nz,nW]=(0,i.useState)(0),nO=(0,i.useMemo)(()=>n_?no.map(e=>(function(e,t){if("answer"===e.kind)return tu(e.blocks);let n=t[e.idx];return n&&"content"in n?tu(n.content):""})(e,t4).toLowerCase()):p_,[n_,no,t4]),nD=(0,i.useCallback)(e=>{tR(),np(t=>pE(nx.current,e,t))},[tR]),nH=(0,i.useCallback)(()=>nF(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tA.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nF(!0),nW(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tA]);let nU=(0,i.useMemo)(()=>{let e=[];return no.forEach((t,n)=>{if("message"!==t.kind)return;let r=pL(t4[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[no,t4]),nB=`${nh}:${nm}`,nq=eC.length>0?eC[eC.length-1]:null,[nV,nK]=(0,i.useState)(null),nG=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nG.current||!tc||ek||!e?.id||(nG.current=!0,t7||!nq||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(t4)||function(e){try{return window.localStorage.getItem(pF(e))}catch{return null}}(e.id)!==nq&&nK(nq))},[tc,ek,e?.id,t7,nq,t4]);let nJ=(0,i.useCallback)(()=>{e?.id&&nV&&function(e,t){try{window.localStorage.setItem(pF(e),t)}catch{}}(e.id,nV),nK(null)},[e?.id,nV]),nZ=null!==nV&&nV===nq&&!t7&&!ng,nY=tn?[tn.sessionId,tn.sessionFile??"",tn.sessionName??"",tn.userMessages,tn.assistantMessages,tn.toolCalls,tn.toolResults,tn.totalMessages,tn.tokens.input,tn.tokens.output,tn.tokens.cacheRead,tn.tokens.cacheWrite,tn.tokens.total,tn.cost??0,tn.totalActiveMs??0].join("|"):null,nX=(0,i.useRef)(tn);nX.current=tn,(0,i.useEffect)(()=>{f?.(nX.current)},[nY,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let nQ=eV?`${eV.percent??"null"}|${eV.contextWindow}|${eV.tokens??"null"}`:null,n2=(0,i.useRef)(eV);n2.current=eV,(0,i.useEffect)(()=>{x?.(n2.current)},[nQ,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(tf)},[b,tf]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{regular:n8,lab:n4}=(0,i.useMemo)(()=>(function(e){let t=[],n=[];for(let i of e){var r;((r=i.key).startsWith(cW)&&null!==cO(r)?n:t).push(i)}return{regular:t,lab:n}})(tk),[tk]),n5=e?.id??null;(0,i.useEffect)(()=>{y?.(n5,n4)},[y,n5,n4]),(0,i.useEffect)(()=>()=>{y?.(null,[])},[y]);let{isDragOver:n6,handleDragEnter:n3,handleDragOver:n7,handleDragLeave:n9,handleDrop:rt}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t7||p?.current?.addAttachments(e)},[t7,p])),rn=(0,i.useMemo)(()=>{var e;return e=td?.messages,e&&e.length>0?[...e,...t4]:t4},[td,t4]),rr=(0,i.useMemo)(()=>{let e=new Map;for(let t of rn)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rn]),ri=(0,i.useMemo)(()=>{let e,t,n,r,i,a,s,o,l,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,i=new Map,a=new Map,s=new Map,o=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},l=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=iX(e.status);if(!r||l.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;l.add(r);let s=iY(e);null!==s&&i.set(r,s)},d=(e,t,r)=>{let i=t?n.get(t):void 0,a=iY(e);i&&"number"==typeof r&&null!==a&&"running"===iX(e.status)&&s.set(i,Math.max(s.get(i)??-1/0,r-a))},rn.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rr.get(e.toolCallId);if(t)for(let i of i0(e,t)??[])n.set(i.agentId,i.key),"number"==typeof t.timestamp&&r.set(i.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(iQ(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=iZ(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:iZ(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of iJ(t.details?.jobs)){if("task"!==r.type)continue;let a=iZ(r.id);if(a&&o(a,iX(r.status),i),c(r,a),d(r,a,t.timestamp),a&&"running"===iX(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of iQ(t.content).matchAll(i1)){let t=Object.fromEntries([...e[1].matchAll(i2)].map(e=>[e[1],e[2]]));t.id&&o(t.id,iX(t.status),i)}for(let e of iJ(t.details?.jobs))"task"===e.type&&c(e,iZ(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:i,parallelWith:a,runStartedAt:s}},[rn,rr]),ra=(0,i.useMemo)(()=>({ledger:ri,subagents:tf,toolResults:rr,onOpenPanel:w,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:j,selectedMaker:S}),[ri,tf,rr,w,e?.id,e?.cwd,t,j,S]),rs=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=t4.length-1;n>=0;n-=1){let r=pL(t4[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[t4]),ro=(0,i.useMemo)(()=>tP(t4,rr,tg,td?.todoPhases??null),[t4,rr,tg,td]),ru=(0,i.useMemo)(()=>cM(eN.streamingMessage).join("|"),[eN.streamingMessage]),rp=(0,i.useMemo)(()=>JSON.stringify(cI(eN.streamingMessage)),[eN.streamingMessage]),rh=(0,i.useMemo)(()=>JSON.stringify(cE(eN.streamingMessage)),[eN.streamingMessage]),rm=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],o=new Map,l=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){l=n;continue}let i=cM(r),c=cE(r,a);if(0===i.length&&0===c.length||l<0)continue;let d=cI(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=o.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(a,e),s.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(t4,eC,ru.length>0?ru.split("|"):[],JSON.parse(rp),JSON.parse(rh)),[t4,eC,ru,rp,rh]),rf=e?.id??t$.current??void 0,rx=(U=cP(D=(0,i.useMemo)(()=>({sessionId:rf,sessionProvider:e6?.provider,turns:rm,messages:t4,subagents:tf}),[rf,e6?.provider,rm,t4,tf])),V=cz(D),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...U,...V])),[U,V])),rv=tT&&0===t4.length&&!eN.isStreaming&&!t7,rb=(0,i.useMemo)(()=>t4.filter(e=>"assistant"===e.role).length,[t4]),ry=function(e,t){let n=(0,i.useRef)(new Map),r=(0,i.useMemo)(()=>{if(!e)return n.current=new Map,0;let t=new Map,r=0;return(e.content??[]).forEach((e,i)=>{let a=e1(e);if(null===a)return;let s=e2(n.current.get(i),a);t.set(i,{text:a,tokens:s}),r+=s}),n.current=t,r},[e]),a=(0,i.useRef)(r);a.current=r;let s=null!==e,o=e?.timestamp,[l,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!s)return void c(null);let e=o??Date.now(),t=()=>{let t=(Date.now()-e)/1e3;c(t>=.5?a.current/t:0)};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[s,o,t]),s?l??0:null}(eN.streamingMessage?.role==="assistant"?eN.streamingMessage:null,rb),rw=(0,i.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("assistant"!==n.role)continue;let{usage:r,timestamp:i,completedAt:a}=n,s=r?.output??0;if(!(s<=0)&&i&&a&&!(a<=i))return s/((a-i)/1e3)}return null})(t4),[t4]),rk=e?.cwd??t??void 0,rj=e6?eA[`${e6.provider}:${e6.modelId}`]??null:null,rS=e6?e_[`${e6.provider}:${e6.modelId}`]??null:null,rC=(0,i.useRef)(null),rN=(0,i.useRef)(null),rT=(0,i.useCallback)(()=>{let e=rC.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,i.useEffect)(()=>(I?.(rT),()=>I?.(null)),[rT,I]),(0,i.useLayoutEffect)(()=>{let e=rN.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tA.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tA.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[ek,tA]);let rI=(0,i.useCallback)((...e)=>(null!==nu.end&&nE(),t_(...e)),[t_,nu.end,nE]),rM=(0,r.jsx)("div",{ref:rC,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(uH,{ref:p,sessionId:e?.id??t$.current??void 0,onEnsureSession:tT&&t?t2:void 0,onLiveTranscriptPersisted:t8,onSend:rI,onAbort:tF,onSteer:eT?tV:void 0,onFollowUp:eT?tK:void 0,onPromptWithStreamingBehavior:eT?tG:void 0,isStreaming:t7,model:e6,isAutoModelSelection:tC,modelNames:eR,modelList:eE,modelError:e$,modelScopeWarnings:eL,onModelChange:tD,onMainPresetChange:e||tT?tU:void 0,mainPresetActiveAlias:t3,modelRoles:eF,onRoleModelChange:tH,modelSwitching:e3,onCompact:e||tT?tq:void 0,onAbortCompaction:tJ,isCompacting:eQ,compactError:e8,compactResult:e4,toolPreset:ez,onToolPresetChange:e||tT?tQ:void 0,thinkingLevel:eW,effectiveThinkingLevel:eO,outputTokensPerSecond:ry??rw,outputSpeedLive:null!==ry,thinkingCeiling:eD,onThinkingLevelChange:e||tT?t0:void 0,fastMode:eH,fastModeBusy:eU,onFastModeToggle:e||tT?eB:void 0,availableThinkingLevels:rj,thinkingLevelMap:rS,retryInfo:eq,deliveryRows:tm,inputHistory:rs,onRecallQueue:tZ,onRemoveQueuedMessage:tY,slashCommands:tp,slashCommandsLoading:th,onLoadSlashCommands:t1,onBuiltinCommand:tX,soundEnabled:$,onSoundToggle:L,onAudioUnlock:_,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name})}),rR=eN.streamingMessage,rE=(0,i.useMemo)(()=>rR?eY(rR,{isStreaming:!0}):[],[rR]),r$=(0,i.useMemo)(()=>rE.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rE]),rL=(0,i.useMemo)(()=>rE.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rE]),rP=rR?.role==="assistant"?rR:null,rA=(0,i.useMemo)(()=>{let e=-1;for(let t=t4.length-1;t>=0;t-=1)if("user"===t4[t].role){e=t;break}let t=e<0?-1:sB(t4,e);return{start:t,blocks:sH(t4,t+1,t4.length),priorCiHeads:sV(t4,rr,t+1),jobNotices:sU(t4,t+1,t4.length)}},[t4,rr]),r_=(0,i.useMemo)(()=>sz(rP?[...rA.blocks,...rP.content??[]]:rA.blocks,rr,t7,rA.priorCiHeads,rk,rA.jobNotices),[rA,rP,rr,t7,rk]),rF=(0,i.useMemo)(()=>t7?{...sD(rA.blocks,rr,rk),span:sK(t4,rA.start+1,t4.length)}:null,[t7,rA,rr,rk,t4]),rz=(0,i.useMemo)(()=>rF?{...rF,flow:r_,latest:!0}:null,[rF,r_]),rW=eT&&(tN?.kind==="running_tools"||(rP?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rO=rc(t4,rP,e6?.provider,e6?.modelId),rD=rO.provider,rH=rO.model,rU=rO.credentialId;(0,i.useEffect)(()=>{if(!rW)return;let e=eu();e&&ec.current!==e.turn&&ed.current!==e.turn&&(ec.current=e.turn,eg("working",e,rD,rU,rH))},[rW,rD,rH,rU,eu,eg]);let[rB,rq]=(0,i.useState)(null),rV=(0,i.useCallback)(e=>{rq(e)},[]),rK=(0,i.useMemo)(()=>eM?{role:"bashExecution",command:eM.command,output:"",excludeFromContext:eM.excludeFromContext}:null,[eM]),rG=(0,i.useMemo)(()=>{let e=[eT&&!rR&&tN?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tN,K):null,eI&&!eM?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eT,rR,tN,eI,eM,K]);(0,i.useEffect)(()=>{if(!rB)return void C?.(null);let e=[],t=[],n=0;if(rR&&rL.length>0){let r=rB.messages.length+e.length;for(let i of(e.push(rR),rL))t.push({idx:r,blocks:i}),n+=eX(i)}if(rK&&(t.push({idx:rB.messages.length+e.length}),e.push(rK)),0===t.length)return void C?.(rG?{...rB,status:rG}:rB);let r=-1;for(let e=rB.messages.length-1;e>=0;e--)if(tl(rB.messages[e])){r=e;break}let i=rB.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),C?.({...rB,groups:i,messages:[...rB.messages,...e],status:rG})},[rB,rL,rR,rK,rG,C]),(0,i.useEffect)(()=>()=>C?.(null),[C]);let rJ=n8.filter(e=>"belowEditor"!==e.placement),rZ=n8.filter(e=>"belowEditor"===e.placement);return ej?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ej}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":ni,"data-empty-start":rv&&!T?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n3,onDragOver:n7,onDragLeave:n9,onDrop:rt,children:[ni?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,n6&&!t7&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),ty&&(0,r.jsx)(pq,{request:ty,onInput:tS}),rv&&!T?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[860px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(ee,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.243"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.20.0"]})]})]})]}),rk&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":K("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:K("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tW(rk)||rk}),(0,r.jsx)("code",{title:rk,children:rk}),(0,r.jsx)("p",{children:K("chat.emptyProjectHint")})]}),k&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:k,children:K("chat.openSessionList")})]}),(0,r.jsx)(pH,{notices:tx,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[T&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:T}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!T,style:{display:T?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(cc,{open:n_,onClose:nH,containerRef:tA,index:nO,renderedStart:nh,renderedEnd:nm,contentKey:t4,onReveal:nD,onProgrammaticScroll:tR,focusRequest:nz,t:K}),nP&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,r.jsx)(pH,{notices:tx,floating:!0,align:"right"})]})}),(0,r.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,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(pD,{widgets:rJ}),(0,r.jsxs)(ot.Provider,{value:ra,children:[(0,r.jsx)(cj,{utterances:rx,children:(0,r.jsx)(pz,{messages:t4,entryIds:eC,toolResultsMap:rr,modelNames:eR,messageCwd:rk,onOpenFile:N,sessionBusy:t7,isNew:tT,isStreaming:eN.isStreaming,handleFork:tz,forkingEntryId:eG,handleNavigate:tO,handleEditContent:ew,sessionId:e?.id??t$.current??void 0,main:no,dispatchSlots:nc,compactedDispatch:nd,openRequest:td?.openRequest??null,process:nl,startIndex:nh,endIndex:nm,sentinelRef:nv,laterSentinelRef:nb,flashItem:nw,t:K,cues:Q,cueFollowRef:ne,onProcessLogChange:rV})}),!ng&&eN.isStreaming&&eN.streamingMessage&&r$.length>0&&(0,r.jsx)(l_,{message:eK(eN.streamingMessage,r$),sessionId:e?.id??t$.current??void 0,isStreaming:!0,modelNames:eR,cwd:rk,onOpenFile:N}),!ng&&rz&&(0,r.jsx)(o7,{summary:rz,live:!0,onOpenFile:N})]}),nZ&&(0,r.jsx)(cf,{onDismiss:nJ,t:K}),(0,r.jsx)("div",{ref:tL})]})})}),(0,r.jsx)(cd,{questions:nU,containerRef:tA,layoutKey:nB,onJump:nR,label:K("chat.questionRail")}),(t7&&tI||ng)&&(0,r.jsxs)("button",{type:"button",onClick:n$,"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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rN,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tv&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,r.jsx)(pB,{request:tv,onRespond:tj,onActivity:(e,t)=>void tS(e,t??"activity"),delivery:tb})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(cm,{compaction:e0,t:K}),(0,r.jsx)(pO,{goal:tE,t:K}),(0,r.jsx)(pD,{widgets:rZ}),(ro||r_.steps.length>0)&&!(G&&J)&&(0,r.jsx)(uB,{phases:ro,flow:r_,busy:t7})]})}),rM,(0,r.jsx)(uU,{statuses:tw})]})]})}function pO({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nV(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nV(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function pD({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function pH({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function pU({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,z.s)(),d=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!d.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=d.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:a},children:[o?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function pB({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,z.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),m=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("form"===e.method)return(0,r.jsx)(pU,{focusKey:e.id,label:s("chat.agentQuestion"),delivery:a,children:(0,r.jsx)(c5,{request:e,onRespond:t,onActivity:n,delivery:a},e.id)});if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(pU,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{m(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let n=e.target.value;d(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(pU,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(nk,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(pU,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&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,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick: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,r.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 pq({request:e,onInput:t}){let{t:n}=(0,z.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),o=ez(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eD[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":" ":eO[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eW(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}var pV=n(40960),pK=n.n(pV);function pG({sessionId:e,refreshKey:t,compact:n}){let{t:a}=(0,z.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),h=(0,i.useRef)(e);h.current=e;let m=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e)return;let t=!1,n=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(r=>{if(t||n!==m.current)return;let i=r.running?r.state?.computerTakeover:null;l(i?{sessionId:e,state:{enabled:!0===i.enabled,available:!0===i.available}}:null),p(null)}).catch(()=>{}),()=>{t=!0}},[e,t]);let f=(0,i.useCallback)(async e=>{let t=h.current;if(t){d(!0),p(null);try{let n=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok)throw Error("shared_settings"===r.code?a("computerTakeover.shared"):r.error??n.statusText);h.current===t&&(m.current+=1,l({sessionId:t,state:{enabled:!0===r.enabled,available:!0!==r.enabled}}))}catch(e){h.current===t&&p(a("computerTakeover.failed",{error:e instanceof Error?e.message:String(e)}))}finally{d(!1)}}},[a]),g=o&&o.sessionId===e?o.state:null;if(!g||!g.enabled&&!g.available)return null;let x=g.enabled,v=x?a("computerTakeover.active"):a("computerTakeover.allow"),b=u??(x?a("computerTakeover.activeHint"):a("computerTakeover.allowHint"));return(0,r.jsxs)(s.r,{className:`workspace-header-action workspace-takeover${x?` ${pK().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,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!n)&&(0,r.jsx)("span",{children:v})]})}function pJ({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,o]=(0,i.useState)({kind:"idle"}),l=(0,i.useRef)(null),c=n.trim();(0,i.useEffect)(()=>{if(c.length<2)return void o({kind:"idle"});let e=new AbortController;o({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);o({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||o({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[c]);let d=e=>{let t=l.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),d(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var pZ=n(50640),pY=n(73620);let pX=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pQ(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let p0=["tags","categories","keywords","tag","category"];function p1({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=p0.find(t=>Array.isArray(e[t])),s=a?e[a].map(pQ).filter(Boolean):[],o=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=pQ(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var p2=n(8745);let p8=(0,i.createContext)(null),p4=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),p5=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),p6=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10 3-5 5 5 5"})}),p3=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),p7=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function p9({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:m}){let{t:f}=(0,z.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:p6})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,l&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:l})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(p2.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,r.jsxs)(p2.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(p2.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(p2.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,r.jsx)(o.In,{size:"16px",svg:p7})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":f("panel.more"),children:(0,r.jsx)(c.k.ScrollArea,{children:(0,r.jsx)(c.k.Group,{children:h.map(e=>(0,r.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(he,{}),m&&(0,r.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,r.jsx)(o.In,{size:"16px",svg:p3})})]})}function he({className:e="panel-header-button"}){let{t}=(0,z.s)(),n=(0,i.useContext)(p8);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(o.In,{size:"16px",svg:n.expanded?p5:p4})})}let ht="cuelo-html-pick",hn="cuelo-html-pick-exit";function hr(e,t){return"string"==typeof e&&e.length<=t}function hi(e){return"number"==typeof e&&Number.isFinite(e)}function ha({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:o}){let{t:l}=(0,z.s)(),c=(0,i.useRef)(null),d=(0,i.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
|
|
20
|
+
${n}`:e:n,images:s,documents:o}}function dO(e,t,n){if(e===t)return n?dP(n):d_(t);let r=d_(e),i=n&&!dA(n)?dP(n):r??(n?dP(n):null),a=d_(t),s=db.get(e);if(db.delete(e),s&&!db.has(t)&&db.set(t,s),dz(e),!i)return a;let o=a?dW(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return dF(t,o),dP(o)}function dD(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function dH(e){d$();let t=db.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),db.set(e,t)),t}function dU(e){let t=dD(dg.get(e)?.documents),n=t.length?dH(e):db.get(e);for(let[e,n]of dC){for(let e of t)n.delete(e);0===n.size&&dC.delete(e)}let r=`${n??""}|${t.join(",")}`;dT.get(e)!==r&&(0!==t.length||n?dT.set(e,r):dT.delete(e),dZ())}async function dB(e){let t=dH(e);dS.set(t,(dS.get(t)??0)+1),await dI.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(dS.get(t)??1)-1;if(r>0?dS.set(t,r):dS.delete(t),e){let n=dC.get(t)??new Set;n.add(e),dC.set(t,n)}dy.set(t,dw),dZ()}}}function dq(e,t){let n=dN.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&dN.delete(e),[...n].sort()}async function dV(){if(!dM)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of db)t(n,dD(dg.get(e)?.documents));for(let{draftId:e,ids:n}of dk.values())t(e,n);for(let[e,n]of dC)t(e,n);for(let e of dy.keys())t(e,[]);for(let e of dN.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dS.has(e))return!1;let n=dy.get(e);return dq(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=dS.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=dq(r,i),a=dM(r,i,e).then(()=>{0===i.length?dy.delete(r):dy.set(r,i.join(","));let t=dN.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&dN.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});dI.set(r,a),await a,dI.get(r)===a&&dI.delete(r)}n?function(){if(dJ)return;dJ=!0;let e=setTimeout(()=>{dJ=!1,dZ()},dG);"object"==typeof e&&"unref"in e&&e.unref(),dG=Math.min(2*dG,6e4)}():dG=dK}let dK=5e3,dG=5e3,dJ=!1;function dZ(){if(dM){if(dR){dE=!0;return}dR=Promise.resolve().then(dV).finally(()=>{dR=null,dE&&(dE=!1,dZ())})}}let dY=Math.floor(Number.MAX_SAFE_INTEGER/1048576),dX=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function dQ(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=dY}async function d0(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!dQ(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:dQ((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:dX.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:dX.autoCleanupEnabled,orphanGraceDays:7}}async function d1(e={}){return d0(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function d2(e){return d0(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function d8(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function d4(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function d5(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function d6(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function d3(e,t,n){let r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`;return`${a}${s} `}let d7="omp-web:model-picks";function d9(){try{let e=JSON.parse(window.localStorage.getItem(d7)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function ue(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*s)),c=Math.max(0,e-a-s),d=Math.max(0,n-t-a-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=r||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(r,h?u:p))}}function ut(e,t,n){return Math.min(e*t,n)}function un(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,i.useState)({side:c??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),d=ue(i.top,i.bottom,n,ut(n,r,a),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,s,o,l,c,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var ur=n(14755);let ui="omp-web:model-roles-expanded";async function ua(e,t,n,r,i,a,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...ub,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(a&&(!c||"builtin"===c.source))return i(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return i(`/${o} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function us(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t||"fallback"===t}let uo=["off","default","full"],ul={off:"none",default:"default",full:"full"},uc=ur.IN.join(" \xb7 "),ud=ur.C1.filter(e=>!ur.IN.includes(e)).join(" \xb7 ");function uu(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let up=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),uh=0,um={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function uf(e,t){return up.compare(e.name||e.modelId,t.name||t.modelId)||up.compare(e.provider,t.provider)||up.compare(e.modelId,t.modelId)}let ug=["auto","off","minimal","low","medium","high","xhigh","max"],ux=["low","medium","high","xhigh"],uv={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},ub=[{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"}],uy=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uw={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},uk={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function uj(e,t,n){let r=e.name.toLowerCase(),i=uS(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function uS(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uC(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uN(e){return{data:e.data,mimeType:e.mimeType}}function uT(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uI(e){return(e??[]).filter(nH).slice(0,10).map(uT)}let uM=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uR="\n\nTranscript of the audio ";function uE(e){return lu(e).map(e=>{let t=lv(e),n="audio"===t&&e.attachmentId&&!e.text.includes(uR)?uM.exec(e.text):null;return{...e,id:++uh,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function u$({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function uL(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class uP extends Error{constructor(e,t,n,r,i=null){super(e),this.code=t,this.completedParts=n,this.parts=r,this.offer=i}}let uA="composer:unkeyed";async function u_(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;let r="number"==typeof n.completedParts?n.completedParts:null,i="number"==typeof n.parts?n.parts:null,a="fallback_confirmation_required"===n.code&&"string"==typeof n.fallbackToken&&"string"==typeof n.notice&&null!==r&&null!==i?{token:n.fallbackToken,notice:n.notice,completedParts:r,parts:i}:null;throw new uP("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,r,i,a)}function uF(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 uz(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function uW({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function uO({error:e}){return e?(0,r.jsx)(uW,{tone:"error",title:"Model error",body:e}):null}function uD({warnings:e}){return e&&0!==e.length?(0,r.jsx)(uW,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uH=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange: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:R=!1,thinkingCeiling:E,onThinkingLevelChange:$,availableThinkingLevels:L,thinkingLevelMap:P,fastMode:A=null,fastModeBusy:_=!1,onFastModeToggle:F,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:en,onEnsureSession:er,onLiveTranscriptPersisted:ei},ea){let es,eo,el,ec,ed,eu,ep,eh,em,ef,{t:eg}=(0,z.s)();ib();let{st:ex}=iw(),ev=O.some(e=>e.removable),eb=B(),[ey,ew]=(0,i.useState)(()=>Q?d_(Q)?.value??"":""),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(null),[eN,eT]=(0,i.useState)(""),[eI,eM]=(0,i.useState)({});(0,i.useEffect)(()=>{ek&&eM(d9())},[ek]);let[eR,eE]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(ek)try{eE("1"===window.localStorage.getItem(ui))}catch{}},[ek]);let e$=()=>{eE(e=>{let t=!e;try{window.localStorage.setItem(ui,t?"1":"0")}catch{}return t})},[eL,eP]=(0,i.useState)(!1),[eA,e_]=(0,i.useState)(null),[eF,ez]=(0,i.useState)(!1),[eW,eO]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(null),[eU,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(()=>Q?uI(d_(Q)?.images):[]),[eK,eG]=(0,i.useState)(()=>Q?uE(d_(Q)?.documents):[]),[eJ,eZ]=(0,i.useState)(null),eY=(0,i.useMemo)(()=>eK.filter(e=>"ready"===e.status),[eK]),eX=eK.some(e=>"ready"!==e.status||us(e)),eQ=eK.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uR))),e0=ey.trimStart(),e1=0===eq.length&&0===eK.length&&e0.startsWith("!"),e2=e1&&e0.startsWith("!!"),[e8,e4]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(0),[e3,e7]=(0,i.useState)(null),e9=e3?.value===ey&&e3.draftKey===Q?e3.token:null,[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(!1),ti=(0,i.useRef)(null),[ta,ts]=(0,i.useState)(null),[to,tl]=(0,i.useState)(!1),[tc,td]=(0,i.useState)(0),[tu,tp]=(0,i.useState)(!1),[th,tm]=(0,i.useState)(0),[tf,tg]=(0,i.useState)(null),[tx,tv]=(0,i.useState)(!1),[tb,ty]=(0,i.useState)(null),[tw,tk]=(0,i.useState)(null),tj=ee&&tw?.cwd===ee?tw.values:{},tS=(0,i.useRef)(null),tC=(0,i.useRef)(null),tN=(0,i.useRef)(null),tT=(0,i.useRef)(null),tI=(0,i.useRef)(null),tM=(0,i.useRef)(null),tR=(0,i.useRef)(null),tE=(0,i.useRef)(null),t$=(0,i.useRef)(null),tL=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(!1),t_=(0,i.useRef)(0),tF=(0,i.useRef)(!1),tz=(0,i.useRef)([]),tW=(0,i.useRef)([]),tO=(0,i.useRef)([]),tD=(0,i.useRef)(null),tH=(0,i.useRef)(null),tU=(0,i.useRef)(Q),tB=(0,i.useRef)(ey),tq=(0,i.useRef)(eq),tV=(0,i.useRef)(0),tK=(0,i.useRef)(eK);tB.current=ey,tq.current=eq,tK.current=eK,(0,i.useImperativeHandle)(ea,()=>({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,n,r=tS.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ey,tq.current.length,tV.current,tK.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lm(t)?.message??t),a=uI("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return nH(r)?[r]:[]})),s=uE((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lm(n)?.documents??[]));tB.current=i,tq.current=a,tK.current=s,ew(i),ts(null),tp(!1),eV(e=>(e.forEach(uz),a)),eG(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tU.current!==e)return void dO(e,t);let n={value:tB.current,images:tq.current.map(uN),documents:tK.current.filter(e=>"ready"===e.status).map(u$)},r=dO(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tU.current=t,i)return;let a=uI(r.images),s=uL(uE(r.documents),tK.current),o=r.value;tB.current=o,tq.current=a,tK.current=s,ew(o),eV(e=>(e.forEach(uz),a)),eG(s),ts(null),tp(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tU.current,a=r??i,s=a===i,o=!s&&a?d_(a):null,l=dW(e,t,s?tB.current:o?.value??"",s?tq.current.map(uN):o?.images??[],n,s?tK.current.filter(e=>"ready"===e.status).map(u$):o?.documents??[]);if(a&&dF(a,l),!s)return;let c=t?.length?[...uI(t).slice(0,Math.max(0,10-tq.current.length)),...tq.current].slice(0,10):tq.current,d=uL(uE(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 n=Math.max(0,10-e.length),r=uI(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tq.current=i,i}),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 n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",o=i+s+e+a;tB.current=o,ew(o),ts(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){t9(e)}}));let tG=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tq.current.length-tV.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eZ(eg("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:lf(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eZ(eg("chat.attachImageLimit",{count:10})),i.length){tV.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eV(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(uz);let r=[...t,...n];return tq.current=r,r})}finally{tV.current-=i.length}}},[eg]),tJ=(0,i.useCallback)(async e=>{for(let t of e){let e=lo(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:lf(8388608)}));continue}if(tK.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eZ(eg("chat.attachTotalTooLarge",{limit:lf(0x1000000)}));continue}let n={id:++uh,name:t.name,mimeType:li[e],size:t.size,text:"",status:"extracting"},r=[...tK.current,n];tK.current=r,eG(r);try{let e=await lp(t);if(tK.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new lr("text_too_large","Total extracted text exceeds 240000 characters");let r=tK.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tK.current=r,eG(r)}catch(i){let e=tK.current.some(e=>e.id===n.id),r=tK.current.filter(e=>e.id!==n.id);if(tK.current=r,eG(r),!e)continue;i instanceof lr?"text_too_large"===i.code?eZ(eg("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eZ(eg("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eZ(eg("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.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,i.useCallback)((e,t)=>{if(!tK.current.some(t=>t.id===e))return!1;let n=t?tK.current.map(n=>n.id===e?t:n):tK.current.filter(t=>t.id!==e);return tK.current=n,eG(n),!0},[]),tY=(0,i.useCallback)((e,t)=>{if(!tK.current.some(t=>t.attachmentId===e))return!1;let n=tK.current.map(n=>n.attachmentId===e?t(n):n);return tK.current=n,eG(n),!0},[]),tX=(0,i.useCallback)((e,t,n)=>{if(!e||e===tU.current)return;let r=d_(e);r?.documents.some(e=>e.attachmentId===t)&&dF(e,{...r,documents:uE(r.documents).map(e=>e.attachmentId===t?n(e):e).map(u$)})},[]),tQ=(0,i.useRef)(new Map),t0=(0,i.useRef)(new Map),t1=(0,i.useRef)(new Set),t2=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=lb({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),t8=(0,i.useCallback)(e=>e instanceof uP&&"media_tool_unavailable"===e.code?eg("chat.transcribeToolMissing"):e instanceof uP&&"fallback_confirmation_expired"===e.code?eg("chat.transcribeFallbackExpired"):e instanceof uP&&"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,i.useCallback)(async(e,t)=>{let n=tU.current,r=tK.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;t0.current.get(e)?.abort();let a=new AbortController;t0.current.set(e,a),tY(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await u_(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:a.signal}));if("string"!=typeof r.transcript)throw new uP("Invalid transcription result",null,null,null);let i=r.transcript;tY(e,e=>t2(e,i,tK.current)??{...e,transcription:{state:"failed",error:eg("chat.transcribeTooLong")}})||tX(n,e,e=>t2(e,i,[])??e)}catch(r){if(a.signal.aborted)return void tY(e,e=>({...e,transcription:{state:"skipped"}}));if(r instanceof uP&&"confirmation_required"===r.code)return void t5.current?.(e);let t=r instanceof uP?r.offer:null;if(t){let n={state:"fallback",reason:r instanceof Error?r.message:"",...t};tY(e,e=>({...e,transcription:n}))||uF(e,t.token);return}let n=t8(r);tY(e,e=>({...e,transcription:{state:"failed",error:n}}))}finally{t0.current.get(e)===a&&t0.current.delete(e)}},[eg,t8,tY,tX,t2]),t5=(0,i.useRef)(null),t6=(0,i.useCallback)(async e=>{let t;t0.current.get(e)?.abort();let n=new AbortController;t0.current.set(e,n),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 uP("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await u_(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tY(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=t8(t);tY(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t0.current.get(e)===n&&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,i.useCallback)(e=>{let t=t0.current.get(e);if(t)return void t.abort();let n=tK.current.find(t=>t.attachmentId===e)?.transcription;n?.state==="fallback"&&uF(e,n.token),tY(e,e=>({...e,transcription:{state:"skipped"}}))},[tY]),t7=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++uh,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tK.current,i];tK.current=a,eG(a);let s=(e,t)=>{let n=tK.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?ld("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?ld("utf-16be",t.subarray(2)):t.includes(0)?null:ld("utf-8",t)??ld("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tZ(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await d1().catch(()=>dX)).uploadLimitMb),r.size>n){tZ(i.id,null)&&eZ(eg("chat.attachStoredTooLarge",{name:r.name,limit:lf(n)}));continue}let o={...i,stored:t,status:"uploading",size:0};if(!tZ(i.id,o))continue;let l=tU.current??uA,c=await dB(l),d=null,u=new AbortController;tQ.current.set(i.id,u);try{if(t1.current.has(i.id))continue;let e=await ly(r,{sessionId:en,draftId:c.draftId,signal:u.signal}),n=tK.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=lb({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tZ(i.id,null)&&eZ(eg("chat.attachTotalTooLarge",{limit:lf(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tZ(i.id,h))d=e.id;else if(!t1.current.has(i.id)&&l!==tU.current){let t=d_(l)??{value:"",images:[],documents:[]};dF(l,{...t,documents:[...t.documents,u$(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tZ(i.id,null)&&eZ(eg("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tQ.current.delete(i.id),c.end(d)}d&&"audio"===t&&tK.current.some(e=>e.attachmentId===d)&&t6(d)}},[tZ,t6,en,eg]),t9=(0,i.useCallback)(async e=>{eZ(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==lo(a)?n.push(a):lc(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tG(t),tJ(n.filter(e=>e.size<=8388608)),t7(r,"audio"),t7([...i,...a],"file")])},[tJ,t7,tG]),ne=(0,i.useCallback)(e=>{eV(t=>{let n=[...t],[r]=n.splice(e,1);return r&&uz(r),tq.current=n,n})},[]),nt=(0,i.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"&&uF(t.attachmentId,t.transcription.token);var n=t.attachmentId;for(let[e,t]of dC)t.delete(n)&&(0===t.size&&dC.delete(e),dZ())}let r=tK.current.filter(t=>t.id!==e);tK.current=r,eG(r)},[]),nn=(0,i.useCallback)(()=>{tq.current=[],eV(e=>(e.forEach(uz),[]))},[]),nr=(0,i.useCallback)(()=>{tK.current=[],eG([])},[]),ni=(0,i.useCallback)(()=>{tB.current="",ew(""),ts(null),e7(null),tt(!1),tp(!1),Q&&dz(Q),tU.current&&tU.current!==Q&&dz(tU.current),nn(),nr(),eZ(null),tS.current&&(tS.current.style.height="auto")},[nr,nn,Q]);(0,i.useEffect)(()=>{Q&&tU.current===Q&&dF(Q,{value:ey,images:eq.map(uN),documents:eY.map(u$)})},[eq,Q,eY,ey]),(0,i.useEffect)(()=>{let e=tU.current;if(e===Q)return;e&&dF(e,{value:tB.current,images:tq.current.map(uN),documents:tK.current.filter(e=>"ready"===e.status).map(u$)});let t=Q?d_(Q):null;tU.current=Q;let n=t?.value??"",r=uI(t?.images),i=uE(t?.documents);tB.current=n,tq.current=r,tK.current=i,ew(n),ts(null),tp(!1),eV(e=>(e.forEach(uz),r)),eG(i)},[Q]),(0,i.useEffect)(()=>{let e=tS.current;e&&(e.style.height="auto",ey&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ey]),(0,i.useEffect)(()=>()=>{tq.current.forEach(uz)},[]);let na=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=dD(t);if(0===n.length)return()=>{};let r=++dj;return dk.set(r,{draftId:dH(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=dk.get(r);if(t){if(dk.delete(r),"accepted"===e){let e=dN.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);dN.set(t.draftId,e)}dZ()}}}(tU.current??uA,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),ns=(0,i.useCallback)(async()=>{let t=ey.trim(),n=e0.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eq.length&&!eY.length||o||eX)return;Y?.();let i=eq.length?eq:void 0,a=eY.length?eY:void 0;if(r.startsWith("/")){await ua(r,q,G,t=>na(a,()=>e(t,i,a)),eZ,!!(i||a),K)&&ni();return}ni(),na(a,()=>e(r,i,a))},[ey,e0,eq,eY,eX,o,G,q,K,e,ni,Y,na]),no=!e0.startsWith("/")||e0.startsWith("//")||/\s/.test(e0.slice(1))?null:e0.slice(1).toLowerCase(),nl=(()=>{if(null===no)return[];let e=[...o?[]:ub,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=uS(e,eg).toLowerCase();return t.includes(no)||n.includes(no)}).sort((e,t)=>{let n=uj(e,no,eg)-uj(t,no,eg);return 0!==n?n:uk[e.source]-uk[t.source]||up.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:nc,groups:nd}=(es=0,{commands:(eo=uy.map(e=>{let t=nl.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!uC(e,tj)),...t.filter(e=>uC(e,tj))]:t;return{source:e,items:n.map(e=>({command:e,index:es++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:eo}),nu=1===nl.length?eg(no?"chat.match":"chat.command"):eg(no?"chat.matches":"chat.commands",{count:nl.length}),np=!!ey.trim(),nh=!eX&&(np||eq.length>0||eY.length>0),nm=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=Math.max(0,Math.min(e.length,t)),r=/(?:^|\s)(\/\/[^\s]*)$/.exec(e.slice(0,n));if(!r)return null;let i=n-r[1].length,a=/^\S*/.exec(e.slice(n))[0];return{start:i,end:n+a.length,query:e.slice(i+2,n)}}(e,t??e.length);if(e7(n?{value:e,draftKey:Q,token:n}:null),tr(!1),!ee)return void ts(null);let r=t??e.length;ts(d8(e.slice(0,r)))},[ee,Q]),nf=ta?.query??null,ng=i.useMemo(()=>null!==nf&&tf&&tf.cwd===ee?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:d5(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:d5(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||d4(e.entry.path)-d4(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tf.entries,nf):[],[nf,tf,ee]),nx=!!(nf&&tf?.truncated&&tf.cwd===ee);(0,i.useEffect)(()=>{if(!nx||!ee||!nf)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(nf)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ty({cwd:ee,query:nf,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nx,nf,ee]);let nv=nx&&null!==tb&&tb.cwd===ee&&tb.query===nf,nb=nv?tb.matches:ng,ny=null===ta?null:`${ta.start}:${+!!ta.quoted}:${ta.query}`;(0,i.useEffect)(()=>{if(null===ny){tl(!1),td(0);return}tl(!0),td(0)},[ny]);let nw=null!==ta,nk=un(tL,tu,{viewportFraction:.44,cap:360}),nj=un(tL,e8,{viewportFraction:.56,cap:460}),nS=un(tL,to,{viewportFraction:.48,cap:400}),nC=un(tL,te,{viewportFraction:.48,cap:400}),nN=e9?`${e9.start}:${e9.end}:${e9.query}`:null;(0,i.useEffect)(()=>{tt(null!==nN)},[nN]);let nT=(0,i.useCallback)((e,t,n,r=!1)=>{tB.current===e&&tU.current===Q&&(tB.current=t,ew(t),e7(null),tt(!1),tr(r),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(n,n),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[Q]);(0,i.useEffect)(()=>{if(!nw||!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 n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>d4(e.path)-d4(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tD.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tD.current=null}).finally(()=>{tH.current=null,tv(!1)}))},[nw,ee]);let nI=(0,i.useCallback)(e=>{if(!ta)return;let t=tS.current,n=t?.selectionStart??ey.length,r=ey.slice(0,ta.start),i=ey.slice(n);ta.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,ta.quoted),s=r+a.text+i,o=r.length+a.cursorOffset;ew(s),ts(d8(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`)})},[ta,ey]);(0,i.useEffect)(()=>{tc>=nb.length&&td(Math.max(0,nb.length-1))},[nb.length,tc]),(0,i.useEffect)(()=>{tW.current.length=nb.length},[nb.length]),(0,i.useEffect)(()=>{to&&tW.current[tc]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tc,to]),(0,i.useEffect)(()=>{th>=D.length&&tm(Math.max(0,D.length-1))},[D.length,th]),(0,i.useEffect)(()=>{tO.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{tu&&tO.current[th]?.scrollIntoView({block:"nearest",inline:"nearest"})},[th,tu]);let nM=(0,i.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`)})},[]),nR=(0,i.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`)})},[]),nE=(0,i.useCallback)(async e=>{let t=ey.trim(),r=e0.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eX||!i&&0===eq.length&&0===eY.length?null:{message:i,images:eq.length?eq:void 0,documents:eY.length?eY:void 0};if(!s)return;Y?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await ua(i,q,G,e=>{if(!X)throw Error("Cannot queue this command while the session is busy.");na(s.documents,()=>X(e,o,s.images,s.documents))},eZ,!!(s.images?.length||s.documents?.length),K)&&ni();return}ni(),"steer"===e&&n?na(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&na(s.documents,()=>a(s.message,s.images,s.documents))},[ey,e0,eq,eY,eX,q,K,G,X,n,a,ni,Y,na]),n$=(0,i.useCallback)(e=>{let t=nc.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 n=tz.current[e5];if(!n)return"down"===e?Math.min(t,e5+1):Math.max(0,e5-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===e5)continue;let t=tz.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-a;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<o&&(s=n,o=c)}return s>=0?s:"down"===e?Math.min(t,e5+1):Math.max(0,e5-1)},[nc.length,e5]),nL=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-t_.current<100,s=tA.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&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(),nM(D[th]);return}}if(!(te&&e9&&!s&&ti.current?.handleKeyDown(e))){if(e8&&null!==no){if("ArrowDown"===e.key){e.preventDefault(),e6(n$("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e6(n$("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e6(n$("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e6(n$("left"));return}if("Escape"===e.key){e.preventDefault(),e4(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nc[e5]){e.preventDefault(),nR(nc[e5]);return}}if(to&&null!==ta&&!s){if("ArrowDown"===e.key){e.preventDefault(),td(e=>Math.min(Math.max(0,nb.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)&&nb[tc]){e.preventDefault(),nI(nb[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&&(n||a)?nE(n?"steer":"followup"):ns())}},[o,n,a,t,e8,no,nc,e5,nR,nE,ns,n$,to,ta,nb,tc,nI,tu,D,th,nM,ey,te,e9]),nP=(0,i.useCallback)(()=>{let e=tS.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nA=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),t9(t))},[t9]);(0,i.useEffect)(()=>{if(null===no){e4(!1),e6(0),tF.current=!1;return}e4(!0),e6(0),!tF.current&&K&&(tF.current=!0,Promise.resolve(K()).catch(()=>{tF.current=!1}))},[no,K]),(0,i.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 n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tk({cwd:ee,values:n})}).catch(()=>{e||tk({cwd:ee,values:{}})}),()=>{e=!0}},[e8,ee]),(0,i.useEffect)(()=>{e5>=nc.length&&e6(Math.max(0,nc.length-1))},[nc.length,e5]),(0,i.useEffect)(()=>{tz.current.length=nc.length},[nc.length]),(0,i.useEffect)(()=>{e8&&tz.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e8]);let n_=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(uf):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(uf),nF=g??null,nz=rg.find(e=>e.alias===nF)?.provider??null,nW=nz?n_.filter(e=>e.provider===nz):n_,nO=(el=eN.trim().toLocaleLowerCase())?nW.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(el)):nW,nD=nW.length>8,nU=[];for(let e of nO){let t=nU.find(t=>t.provider===e.provider);t?t.options.push(e):nU.push({provider:e.provider,options:[e]})}let nB=nz?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nq=l?nB.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,nK=eN.trim()?[]:nW.map((e,t)=>{var n,r;return{option:e,order:t,count:eI[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nG=(e,t,n)=>{let i=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ej(!1),eT(""),!i||c){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(d9(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(d7,JSON.stringify(r))}catch{}eM(r),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eg("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nJ=l?n_.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,nZ=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nY=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eg("chat.compacted")} ${nV(S.tokensBefore)} -> ${nV(S.estimatedTokensAfter)} tokens (${eg("chat.tokensSaved",{saved:nV(nZ)})})`:null,nX=e=>{let t=P?.[e];return null!=t&&t!==e?t:null},nQ="auto"===(ec=T??"auto")?E?`auto ≤ ${nX(E)??E}`:"auto":P?P[ec]??ec:ec,n0=(T??"auto")==="auto"&&I&&"auto"!==I?P?.[I]??I:null,n1=$&&n0?eg("chat.currentReasoning",{level:n0}):null,n2=e=>!L||L.includes(e),n8=[{level:"auto",ceiling:null},...ux.filter(n2).map(e=>({level:"auto",ceiling:e})),...ug.filter(e=>"auto"!==e&&n2(e)).map(e=>({level:e,ceiling:null}))],n4=Object.entries(ul).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.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)&&eP(!1),tM.current&&!tM.current.contains(e.target)&&ez(!1),tR.current&&!tR.current.contains(e.target)&&eO(!1),tE.current&&!tE.current.contains(e.target)&&eB(!1),!t$.current||t$.current.contains(e.target)||tS.current?.contains(e.target)||tp(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eb||eB(!1)},[eb]);let n5=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eq.length||eK.length?" is-active":""}`,onClick:()=>tP.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,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),n6=f&&rg.length>0?(0,r.jsxs)("div",{ref:tT,style:{position:"relative",flexShrink:+!!eb,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eb?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e_({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eP(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eP(!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,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eb?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eg("chat.mainPreset")})]}),eL&&eA&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=ue(eA.top,eA.bottom,e,ut(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eA.top+6}:{top:eA.bottom+6},a=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eA.left,width:"max-content",minWidth:eA.width};return(0,r.jsx)("div",{ref:tI,role:"menu","aria-label":eg("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eP(!1),tT.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:rg.map(e=>{let t=e.alias===nF;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eP(!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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:rV(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:r_(e.alias)}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,n3=$?(0,r.jsxs)("div",{ref:tR,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.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(""),eP(!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:nQ}),"aria-label":eg("chat.changeReasoning",{level:nQ}),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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eb?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nQ})]}),eW&&eD&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=ue(eD.top,eD.bottom,e,ut(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eD.top+6}:{top:eD.bottom+6},a=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eD.left,width:"max-content",minWidth:Math.max(180,eD.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eg("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eO(!1),tR.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:n8.map(({level:e,ceiling:t})=>{let n=(T??"auto")===e&&("auto"!==e||(E??null)===t),i=t??e,a="auto"===e&&null===t?null:nX(i),s=t?`auto ≤ ${a??t}`:a??e,o=t?eg("chat.thinkingAutoCapped",{level:a??t}):eg(uv[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eO(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,n7=F?(ed=_?eg("chat.fastModeBusy"):null===A?eg("chat.fastModeUnknown"):A.active?eg("chat.fastModeActive"):A.enabled?eg("chat.fastModeInactive"):eg("chat.fastModeOff"),eu=_||o||b,ep=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:F,disabled:eu,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":_||void 0,title:ed,"aria-label":ed,style:{flexShrink:0,opacity:o?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:ep&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,n9=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nE("steer"),disabled:!nh,title:eX?eg("chat.attachExtractingWait"):eg("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nh?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nh?"var(--warning)":"var(--text-dim)",cursor:nh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eg("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nE("followup"),disabled:!nh,title:eX?eg("chat.attachExtractingWait"):eg("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nh?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nh?"var(--accent-hover)":"var(--text-dim)",cursor:nh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eg("chat.followUp")]})]}),re=void 0!==Z?(0,r.jsx)(dr,{soundEnabled:J??!0,onToggle:Z}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tP,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t9(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(uO,{error:p}),(0,r.jsx)(uD,{warnings:h}),O.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ex("delivery.title",{count:O.length})}),H&&ev&&(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eg("chat.recall")]})]}),(0,r.jsx)(c7,{rows:O,removeLabel:eg("chat.queueRemove"),onRemove:U?(e,t)=>U("steer"===e?"steering":"followUp",t):void 0})]}),W&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eg("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),nY&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nY]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eJ&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eJ}),(0,r.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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eq.length>0||eK.length>0)&&(0,r.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,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eg("chat.removeImage",{index:t+1}),onClick:()=>ne(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eK.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||us(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):i$(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eg("chat.attachKindAudio"):"file"===e.stored?eg("chat.attachKindFile"):um[e.mimeType]," \xb7 ",lf(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,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eg("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>nt(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,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eQ.length>0&&(0,r.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,n,i,a,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"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?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,r.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[l.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeUsageNotice")})]}),l?.state==="fallback"&&(0,r.jsxs)(r.Fragment,{children:[l.reason&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.reason}),l.completedParts>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:eg("chat.transcribeFallbackProgress",{done:l.completedParts,total:l.parts})}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeFallbackUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{confirmed:!0}),children:eg("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),l?.state==="fallback"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{fallbackToken:l.token,approve:!0}),children:eg("chat.transcribeFallbackStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,r.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,r.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,r.jsxs)("div",{ref:tL,style:{position:"relative",minWidth:0},children:[tu&&D.length>0&&(0,r.jsxs)("div",{ref:t$,style:{position:"absolute",left:0,right:0,...uu(nk.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nk.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nk.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===th;return(0,r.jsxs)("button",{ref:e=>{tO.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nM(e)},onMouseEnter:()=>tm(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),tn&&(0,r.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:eg("savedPrompts.saved")}),te&&e9&&(0,r.jsx)(de,{ref:ti,value:ey,token:e9,cwd:ee,sessionTitle:et,style:uu(nC.side),maxHeight:nC.maxHeight,onReplace:nT,onClose:()=>tt(!1)}),e8&&null!==no&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uu(nj.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nj.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:V?eg("chat.loadingCommands"):eg("chat.slashCommands",{label:nu})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nj.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==nl.length?nd.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eg(uw[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===e5,i=uC(e,tj);return(0,r.jsxs)("button",{ref:e=>{tz.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nR(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 ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eg("chat.dormant")})]}),uS(e,eg)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uS(e,eg)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eg("chat.noCommands")})})]}),to&&null!==ta&&(eh=tx&&(!tf||tf.cwd!==ee),em=1===nb.length?eg("chat.match"):eg("chat.matches",{count:nb.length}),ef=tf?.truncated&&!nv?ta.query?eg("chat.searchingAll"):eg("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uu(nS.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nS.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:eh?eg("chat.loadingFiles"):eg("chat.files",{label:em,hint:ef})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nS.maxHeight-34),overflowY:"auto",padding:4},children:eh||0!==nb.length?nb.map((e,t)=>{let n=t===tc,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tW.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nI(e)},onMouseEnter:()=>td(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(iM,{size:14}):i$(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:nx&&!nv?eg("chat.searching"):eg("chat.noMatchingFiles")})})]})),(0,r.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&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tS,"aria-controls":te?"saved-prompt-menu":void 0,value:ey,onChange:e=>{tB.current=e.target.value,ew(e.target.value),tp(!1),nm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nm(t.value,t.selectionStart)},onKeyDown:nL,onCompositionStart:()=>{tA.current=!0},onCompositionEnd:e=>{tA.current=!1,t_.current=Date.now();let t=e.currentTarget;nm(t.value,t.selectionStart)},onInput:nP,onPaste:nA,placeholder:o&&(n||a)?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,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:n9}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:ns,disabled:!nh,"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:nh?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nh?"var(--accent-hover)":"var(--text-dim)",cursor:nh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eb?null:eg("chat.send")]})]})]}),e1&&(0,r.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,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.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)&&n5,!eb&&n6,!(eb&&o)&&(n_.length>0||nJ||p)&&m&&(0,r.jsxs)("div",{ref:tC,style:{position:"relative",flex:eb?"1 1 0%":void 0,width:eb?0:void 0,minWidth:44*!!eb},children:[(0,r.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":n_.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nJ??(n_.length>0?"Select model":"No models")})]}),ek&&eS&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=ue(eS.top,eS.bottom,e,ut(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eS.top+6}:{top:eS.bottom+6},a=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eS.left,width:"max-content",minWidth:eS.width};return(0,r.jsxs)("div",{ref:tN,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nD&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.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,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nK.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eg("chat.frequentModels")}),nK.map(({option:e,count:t})=>nG(e,"frequent",t))]}),nB.length>0&&!eN.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nK.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eR,"aria-controls":"model-role-rows",onClick:e$,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eR?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:eg("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nB.length}),nq&&(0,r.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:nq.tag??nq.role.toUpperCase()}),nq.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eR,children:nB.map(e=>{let t=nq?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ej(!1),eT(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:"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,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eg("chat.allModels")})]}),0===nU.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eN.trim()?eg("chat.noMatchingModels"):"No available models"}):nU.map((e,t)=>(0,r.jsxs)("div",{children:[nU.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nG(e,"all"))]},e.provider))]})]})})()]}),eb&&o&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:n9}),!eb&&n3,!eb&&n7,!eb&&n1&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:n1}),!eb&&null!==M&&(0,r.jsx)("span",{title:eg(R?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:eg(R?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,r.jsx)(df,{sessionId:en})]}),(0,r.jsxs)("div",{ref:tE,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,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title: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,r.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,r.jsxs)(r.Fragment,{children:[o&&n5,n6,n3,n7]}),!o&&N&&(0,r.jsxs)("div",{ref:tM,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eF?" is-active":""}`,onClick:()=>!o&&ez(e=>!e),disabled:o,title:eg("chat.changeToolPreset")+`: ${n4}`,"aria-label":eg("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eF?"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=eF?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:n4})]}),eF&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:uo.map(e=>{let t=ul[e],n=(C??"default")===t,i="off"===e?eg("chat.noTools"):"default"===e?eg("chat.builtInTools",{tools:uc}):eg("chat.allBuiltInTools",{tools:`${uc} + ${ud}`});return(0,r.jsxs)("button",{onClick:()=>{ez(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!o&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eg("chat.stopCompaction"):eg("chat.compactContext"),"aria-label":k?eg("chat.stopCompaction"):eg("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compact")})]})})}),eb&&re,eU&&(0,r.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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title: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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eb?null:eg("chat.stop")]}),(0,r.jsx)(dh,{sessionId:en,onEnsureSession:er,onTranscriptPersisted:ei}),!eb&&re]})]})]})]})});function uU({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),n=eP(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eW(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function uB({phases:e,flow:t,busy:n}){let{t:a}=(0,z.s)(),{st:s}=iw(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=(0,i.useId)(),m=e??[],{currentPhase:f,activeTask:g,remaining:x,completed:v,total:b,percent:y}=t_(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,s);if(0===b&&null===j)return null;let S=b>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:j}),b>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!j&&f&&(0,r.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:S?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:S?a("todo.progressDone",{percent:y??0,completed:v,total:b}):a("todo.progress",{percent:y??0,completed:v,total:b,remaining:x})})]}),k&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,r.jsx)(oj,{flow:t,live:n,st:s,id:h}),o&&b>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(iN,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function uq(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uV(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 uK(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}class uG extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function uJ(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new uG(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let uZ="ompweb-update-client-id",uY="ompweb-update-resume-intent-v2",uX="ompweb-update-return-v1",uQ="cuelo-restart-return-v1",u0="ompweb-update-failure-return-v1",u1="ompweb:update-wake";function u2(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function u8(){let e=sessionStorage.getItem(uZ);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(uZ,t),t}function u4(){sessionStorage.removeItem(uY)}function u5(){let e=sessionStorage.getItem(uX);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 u6(e){let t=u5();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(uX,JSON.stringify(n))}catch{}return n}async function u3(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:u8(),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 u7(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let n=await t.json().catch(()=>null);!function(e){let t=u5();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(uX,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u4();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(u1,{detail:{sessionId:e.sessionId}}))}async function u9(e){let t=function(e){let t=sessionStorage.getItem(u0);if(!t)return null;sessionStorage.removeItem(u0);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(u4(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(u1,{detail:{sessionId:e.sessionId}})),"failed"):(await u7(e),"resumed")}function pe(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function pt(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 pn(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function pr(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function pi(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function pa(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker||(t.dependsOn?.length??0)!==(n.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==n.dependsOn?.[t]))return!1}}return!0}function ps(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function po(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!ts(r??void 0))return{message:e[n],entryId:r}}return null}let pl=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class pc 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 pd(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pu(e){return new Promise(t=>setTimeout(t,e))}function pp(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ph(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:pp(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:pp(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=pp(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function pm(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 pf(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(pm).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function pg(e){return"user"===e.role?`user:${pf(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 px(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 pv(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function pb(e){nM(e),e.clear()}function py(e,t,n){for(let r of n??[]){let n=nI(t,r);n&&e.add(n)}}function pw(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let pk=!1,pj={width:0,height:0},pS=new Set,pC=null;function pN(){let e=window.visualViewport,t=pw();pj.width!==window.innerWidth?pj={width:window.innerWidth,height:window.innerHeight}:t||(pj.height=Math.max(pj.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:pj.height});if(n!==pk)for(let e of(pk=n,pS))e()}function pT(e){if(pS.add(e),!pC){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,pN()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),pN(),pC=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{pS.delete(e),0===pS.size&&pC&&(pC(),pC=null)}}function pI(){return(0,i.useSyncExternalStore)(pT,()=>pk,()=>!1)}let pM={count:50,end:null};function pR(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function pE(e,t,n){let{startIndex:r,endIndex:i}=pR(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function p$({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:n6[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(cx(),{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 pL(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=(lm(t)?.message??t).trim();return n.length>0?n:null}function pP(e){return`omp-cues:${e}`}function pA(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(pP(e),JSON.stringify(n.slice(-200)))}catch{}}let p_=[];function pF(e){return`omp-web:interrupted-dismissed:${e}`}let pz=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent: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,i.useEffect)(()=>{T({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:f})},[T,x,e,t,n,a,s,f]);let R=(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n=0;n<e.length;n++){let r=ti(e,n);r>=0&&t.set(r,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 n=t.indexOf("\n\n");return n<0?t:t.slice(n+2)}(e[n]))}return t})(e),[e]),E=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[o.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(o.blocks?i.get(o.idx):void 0)??o.afterMainIndex??-1),l=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=td(i.action);if(!0===tc[e]){let t={kind:"skill",action:e,name:td(i.name)};n(JSON.stringify(t),t)}continue}let a=td(i.memory),s=i.skill,o=s?{action:td(s.action),name:td(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:o}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...o?{skill:o}:{}})}}(o.blocks??e.content??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:tn,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,N]),$=(0,i.useMemo)(()=>{let r=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(r=t.idx);return function(e,t,n,r,i,a,s=[]){let o=function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&sB(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:sB(t,n),s=new Map;for(let[n,o]of(e.forEach((e,n)=>{"answer"===e.kind&&s.set(sB(t,e.anchorIdx),n)}),s)){if(n===a)continue;let e=i.find(e=>e>n);r.set(o,{from:n+1,to:e??t.length})}return r}(e,t,n),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,n]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(sV(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let i=n.to-1;for(;i>=n.from&&ts(s[i]);)i-=1;if(s[i]!==a.throughEntryId)continue;let o=sH(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sq(t,r,n.from,n.to);c.set(e,{...a.summary,...p?{remaining:sO(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,i,a=[]){let s=sH(e,n,r),o=sq(e,t,n,r);return{...sD(s,t,i),remaining:o?sO(o):null,span:sK(e,n,r),flow:sz(s,t,!1,a,i,sU(e,n,r))}}(t,r,n.from,n.to,i,d),latest:e===l})}return c}(g,e,r,n,s,y,t)},[g,e,n,s,l,y,t]),L=w>0,P=k<g.length,A=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&ts(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(l_,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:o,entryId:t[i],onFork:l||c||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary,inputTranslation:"user"===x.role?R.get(i):void 0,recoveredError:eZ(e,i)},`${y}-view-${i}`)},_=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[L&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((a,l)=>{let c=w+l,d=b?.position===c?(0,r.jsx)(oO,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<m}).map(e=>(0,r.jsx)(p$,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),y=h!==u,k=E.get(c),j=k?(0,r.jsx)(l_,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=y?(0,r.jsx)(cS,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:o}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[d,_(c,A(a.idx)),j,S,x]},`message-${a.idx}`);let C=tM(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[d,_(c,A(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=eK(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:$.get(c)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&k===g.length&&(0,r.jsx)(oO,{calls:b.calls}),P&&(0,r.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function pW({session:e,newSessionCwd:t,initialSessionData:a,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:R,onAttentionChange:E,soundEnabled:$=!0,onSoundToggle:L,playCueSound:P=async()=>({sticker:null,text:null}),preloadCueSound:A,unlockAudio:_,jumpRequest:F=null,onJumpHandled:W}){var O,D;let H,U,V,{t:K}=(0,z.s)(),G=pI(),J=B(),Z=(0,i.useRef)(P);Z.current=P;let Y=(0,i.useRef)(null),X=(0,i.useRef)(A);X.current=A;let[Q,et]=(0,i.useState)([]),en=(0,i.useRef)(Q);en.current=Q;let er=(0,i.useRef)(0),ei=(0,i.useRef)([]),ea=(0,i.useRef)([]),eo=(0,i.useRef)(null),el=(0,i.useRef)(0),ec=(0,i.useRef)(-1),ed=(0,i.useRef)(-1),eu=(0,i.useCallback)(()=>{let e=eo.current?.current;return e?{sessionId:e,turn:el.current}:null},[]),ep=(0,i.useCallback)(e=>eo.current?.current===e.sessionId&&el.current===e.turn,[]),eh=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;er.current=Math.max(er.current+1,Date.now());let i={id:er.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};et(e=>{let t=[...e,a];return null!==a.anchorEntryId&&pA(n.sessionId,t),t})},[]),em=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ep(n)&&("working"!==t||ed.current!==n.turn);i()&&Z.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&eh(e,t,n,r)}).catch(()=>{})},[ep,eh]),ef=(0,i.useCallback)(async(e,t,n,r)=>{let i=(await ix(e,t,n,r))?.alias??null;return i&&X.current?.(i),i},[]),eg=(0,i.useCallback)((e,t,n,r,i)=>{let a=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=rl(e[n]),a=0;for(let t=r;t<=n;t++)rl(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(ei.current,ea.current);ef(t.sessionId,n,r,i).then(n=>{em(n,e,t,a)})},[em,ef]),[ex,ev]=(0,i.useState)(0),eb=(0,i.useRef)([]),ey=(0,i.useCallback)(e=>{if(el.current+=1,null!==re(e.outcome)){let t=e.sessionId;eb.current.push({completion:e,trigger:t?{sessionId:t,turn:el.current}:null}),ev(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of eb.current.splice(0)){let n=re(e.outcome),r="neutral"===n?null:n;t?eg(r,t,e.provider,e.credentialId,e.model):Z.current(null,r).catch(()=>{})}},[ex,eg]);let ew=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ek,error:ej,messages:eS,entryIds:eC,streamState:eN,agentRunning:eT,bashRunning:eI,pendingBash:eM,modelNames:eR,modelList:eE,modelError:e$,modelScopeWarnings:eL,modelThinkingLevels:eA,modelThinkingLevelMaps:e_,modelRoles:eF,toolPreset:ez,thinkingLevel:eW,effectiveThinkingLevel:eO,thinkingCeiling:eD,fastMode:eH,fastModeBusy:eU,handleFastModeToggle:eB,retryInfo:eq,contextUsage:eV,forkingEntryId:eG,isCompacting:eQ,compaction:e0,compactError:e8,compactResult:e4,displayModel:e6,modelSwitching:e3,sessionStats:tn,runStateKnown:tc,compactedWork:td,slashCommands:tp,slashCommandsLoading:th,deliveryRows:tm,subagents:tf,todoPhases:tg,notices:tx,extensionDialog:tv,extensionResponse:tb,extensionCustomUi:ty,extensionStatuses:tw,extensionWidgets:tk,respondToExtensionUi:tj,sendExtensionCustomInput:tS,isAutoModelSelection:tC,agentPhase:tN,isNew:tT,autoFollowPaused:tI,resumeAutoFollow:tM,pauseAutoFollow:tR,goalStatus:tE,sessionIdRef:t$,messagesEndRef:tL,scrollContainerRef:tA,handleSend:t_,handleAbort:tF,handleFork:tz,handleNavigate:tO,handleModelChange:tD,handleRoleModelChange:tH,handleMainPresetChange:tU,newSessionAccount:tB,handleCompact:tq,handleSteer:tV,handleFollowUp:tK,handlePromptWithStreamingBehavior:tG,handleAbortCompaction:tJ,handleRecallQueue:tZ,handleRemoveQueuedMessage:tY,handleBuiltinSlashCommand:tX,handleToolPresetChange:tQ,handleThinkingLevelChange:t0,loadSlashCommands:t1,ensureNewSession:t2,refreshLiveTranscript:t8}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[N,T]=(0,i.useState)(f?.context.entryIds??[]),[I,M]=(0,i.useState)(f?.context.compactedWork??null),[R,E]=(0,i.useReducer)(pt,{isStreaming:!1,streamingMessage:null}),[$,L]=(0,i.useState)(!1),[P,A]=(0,i.useState)(!1),[_,F]=(0,i.useState)(null),[z,W]=(0,i.useState)({}),[O,D]=(0,i.useState)([]),[H,U]=(0,i.useState)(null),[B,q]=(0,i.useState)([]),[V,K]=(0,i.useState)({}),[G,J]=(0,i.useState)({}),[Z,Y]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[eo,el]=(0,i.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ec,ed]=(0,i.useState)(),[eu,ep]=(0,i.useState)(null),[eh,em]=(0,i.useState)(null),[ef,eg]=(0,i.useState)(!1),ex=(0,i.useRef)(0),ev=(0,i.useRef)(0),eb=(0,i.useRef)(""),[ey,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(f?.contextUsage??null),[eS,eC]=(0,i.useState)(null),[eN,eT]=(0,i.useState)(null),[eI,eM]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(null),[e$,eL]=(0,i.useState)(!1),[eA,e_]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(null),[eW,eO]=(0,i.useState)(null),[eD,eH]=(0,i.useState)(null),eU=(0,i.useRef)(null),[eB,eq]=(0,i.useState)(!1),[eV,eK]=(0,i.useState)(null),[eG,eJ]=(0,i.useState)([]),[eZ,eY]=(0,i.useState)(!1),[eX,eQ]=(0,i.useReducer)(ph,{visible:[],pending:[]}),[e0,e1]=(0,i.useState)(null),[e2,e8]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(null),e6=(0,i.useRef)(null),[e3,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)([]),[tn,tr]=(0,i.useState)([]),[ti,tl]=(0,i.useState)({steering:[],followUp:[]}),[tc,td]=(0,i.useState)([]),[tu,tp]=(0,i.useReducer)(al,[]),th=(0,i.useRef)(0);(0,i.useEffect)(()=>{tp({type:"queue",steering:ti.steering,followUp:ti.followUp})},[ti]),(0,i.useEffect)(()=>{$||tp({type:"idle"})},[$]),(0,i.useEffect)(()=>{tp({type:"reset"})},[t?.id]);let tm=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${as(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${aa(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(tu,ti),[tu,ti]),[tf,tg]=(0,i.useState)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(0),tj=(0,i.useRef)(!1),tS=(0,i.useRef)(t?.id??null),tC=(0,i.useRef)(f?.leafId??null),tN=(0,i.useRef)(S),tT=(0,i.useRef)(N);tN.current=S,tT.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tM=(0,i.useRef)(!1),tR=(0,i.useRef)(new Set);(0,i.useEffect)(()=>()=>pb(tR.current),[]);let tE=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),tL=(0,i.useRef)(-1),tP=(0,i.useRef)("unknown"),tA=(0,i.useRef)(null),t_=(0,i.useRef)(null),tF=(0,i.useRef)(0),tz=(0,i.useRef)(!1),tW=(0,i.useRef)(0),tO=(0,i.useRef)(null),tD=(0,i.useRef)(null),tH=(0,i.useRef)(null),tU=(0,i.useRef)(!1),tB=(0,i.useRef)(!0),[tq,tV]=(0,i.useState)(!1),[tK,tG]=(0,i.useState)(null),tJ=(0,i.useRef)(void 0),tZ=(0,i.useRef)(0),tY=(0,i.useRef)(null),tX=(0,i.useRef)(0),tQ=(0,i.useRef)(()=>{}),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t8=(0,i.useRef)(null),t4=(0,i.useRef)(!1),t5=(0,i.useRef)(null),t6=(0,i.useRef)(null),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(null),ne=(0,i.useRef)(0),nt=(0,i.useRef)(null),nn=(0,i.useRef)(null),nr=(0,i.useRef)(!1);nr.current=e.transitioning??!1;let ni=(0,i.useRef)(Date.now()),na=(0,i.useRef)(0),ns=(0,i.useRef)(0),no=(0,i.useRef)(null),nl=(0,i.useRef)(!1),nc=(0,i.useRef)(Promise.resolve()),nd=e.setToolPreset??ea,nu=eI??g?.context.model??eR??null,np=m?X??en:nu,nh=(0,i.useMemo)(()=>{if(e0)return{...e0,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,n+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tS.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ek?{contextUsage:ek}:{}}},[S,e0,ek,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nm=(0,i.useRef)(0),nf=(0,i.useCallback)((e,t)=>{e&&tS.current===e&&Array.isArray(t)&&(nm.current+=1,tg(n=>n?.sid===e&&pa(n.phases,t)?n:{sid:e,phases:t}))},[]),ng=(0,i.useCallback)((e,t,n)=>{tS.current===e&&nm.current===n&&Array.isArray(t)&&tg(n=>n?.sid===e&&pa(n.phases,t)?n:{sid:e,phases:t})},[]),nx=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tN.current):e;tN.current=t,C(t)},[]),nv=(0,i.useCallback)(e=>{tT.current=e,T(e)},[]),nb=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nx([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tS.current!==e)return null;x(a),j(a.leafId),tC.current=a.leafId??null;let s=to(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nx(s.messages),nv(s.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null),eM(e=>nl.current?e:null),w(null);let o=!n&&t9.current===e;if(o||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),ep(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!n){if(o)try{let t=ne.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tS.current===e){let r=await n.json();tS.current===e&&ne.current===t&&(r.state?.thinkingLevel!==void 0?(el(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(t9.current=null,el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nm.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tS.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ej(i.contextUsage??null),void 0!==i.systemPrompt&&eC(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t9.current=e,el(i.configuredThinkingLevel??i.thinkingLevel),ed(i.thinkingLevel)),void 0!==i.thinkingCeiling&&ep(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&te(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&tr(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(pn(i.queuedMessages)),void 0!==i.subagents&&td(e=>pe(e,i.subagents??[])),ng(e,i.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[ng,nv,nx]),ny=(0,i.useCallback)(e=>{let t=nc.current.then(async()=>{tS.current===e&&await nb(e)});return nc.current=t.catch(()=>{}),t},[nb]),nw=(0,i.useCallback)(async(e,t)=>{let n=++ev.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ev.current!==n||tS.current!==e)return;tC.current=t;let o=to(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nx(o.messages),nv(o.entryIds),M(s.context.compactedWork??null),ej(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nv,nx]),nk=(0,i.useCallback)(async e=>{try{let t=await uJ(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));nd(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[nd]),nj=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tS.current;if(!m||!r||!n||t4.current)return;let i=t5.current??r;t4.current=!0,l?.({id:n,path:"",cwd:i,...i!==r?{projectRoot:r}:{},name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0})},[m,r,l]),nC=(0,i.useCallback)(async()=>{if(t2.current)return t2.current;let e=tS.current;if(e&&nn.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t6.current,n=t7.current,i=t3.current;e&&eE(e);let a={cwd:r,type:"ensure_session",toolNames:(0,ur.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),o=t8.current,l=o?.body===s?o.createRequestId:pd();t8.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:l})});if(!c.ok)throw Error((await c.json().catch(()=>({}))).error??`HTTP ${c.status}`);let d=await c.json();t8.current=null,t=d.sessionId,tS.current=t,t5.current=d.cwd??r??null,t5.current&&es(t5.current,d.worktree),null!==nt.current&&(nn.current=t),d.model&&t6.current===e&&(eE(d.model),e||er(d.model)),d.thinkingLevel&&t7.current===n&&(el(d.configuredThinkingLevel??d.thinkingLevel),ed(d.thinkingLevel))}for(;nn.current===t;){let e=nt.current;await uJ(t,{type:"set_thinking_ceiling",ceiling:e}),nt.current===e&&nn.current===t&&(nn.current=null)}return t})();t2.current=t;try{return await t}finally{t2.current=null}},[m,r,ei]),nT=(0,i.useCallback)(async()=>{let e=tS.current??await nC();if(!e)return eJ([]),[];eY(!0);try{let t=await uJ(e,{type:"get_commands"}),n=t?.commands??[];return eJ(n),n}catch(e){return console.error("Failed to load slash commands:",e),eJ([]),[]}finally{eY(!1)}},[nC]),nR=(0,i.useCallback)(()=>{tk.current+=1,tj.current=!1,tw.current&&(clearTimeout(tw.current),tw.current=null)},[]),nE=(0,i.useCallback)(()=>{tx.current?.close(),tx.current=null,tv.current=null,tb.current=null},[]),n$=(0,i.useCallback)(()=>{ty.current?.close(),ty.current=null},[]),nL=(0,i.useCallback)(e=>{n$();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);ty.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tO.current?.(n):"agent_start"===n.type&&tD.current?.(e)}catch{}}},[n$]),nP=(0,i.useCallback)(e=>{nE();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tx.current=t,tv.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tb.current?.source===t&&(tb.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tO.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tx.current===t&&(tM.current||tj.current))){tx.current=null,tv.current=null,tb.current=null;let t=tk.current;setTimeout(()=>{t===tk.current&&!tx.current&&(tM.current||tj.current)&&nP(e)},1e3)}}});return tb.current={source:t,promise:n,pending:!0},n},[nE]),nA=(0,i.useCallback)(async e=>{let t=tx.current;if(t&&tv.current===e){if(t.readyState===EventSource.OPEN)return;let e=tb.current;if(e?.source===t&&e.pending&&(await e.promise,tx.current===t&&t.readyState===EventSource.OPEN))return}let n=await nP(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tx.current===n.source&&(tx.current=null),tv.current===e&&(tv.current=null),tb.current?.source===n.source&&(tb.current=null),n.source.close(),new pc(n.status)},[nP]),n_=(0,i.useCallback)(async(e,t)=>{let n=e6.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tS.current,i=e=>{e6.current=e,e5(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await uJ(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e8(t=>t?.id===e.id?null:t)},[]),nF=(0,i.useCallback)(async(e,t)=>{let n=tS.current;if(n)try{await uJ(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nz=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eQ({type:"add",notice:{id:e.id??pd(),message:t,type:e.type??"info"}})},[]),nW=(0,i.useCallback)(e=>{let t={role:"custom",customType:tt,content:eP(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tS.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tT.current.slice(0,tN.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!ts(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${ta}${n.seq}`,baseEntryId:a,message:t});let s=to(tN.current,tT.current,n.outputs);nx(s.messages),nv(s.entryIds)},[nx,nv]),nO=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e8(e=>e?.id===t.id?null:e),e6.current?.id===t.id&&(e6.current=null,e5(null));return}switch(uV(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":e8(t);break;case"notify":nz({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tr(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e7(e=>t.closed?e?.id===t.id?null:e:t)}},[nz,o,e.chatInputRef]),nD=(0,i.useCallback)(()=>{let e=tM.current;return tM.current=!1,L(!1),eK(null),pb(tR.current),ew(null),E({type:"end"}),e},[]),nH=(0,i.useCallback)(()=>{tP.current="unknown",tA.current=null;let e=po(tN.current,tT.current);t_.current=e?{entryId:e.entryId,key:pg(e.message)}:null,tF.current+=1},[]),nU=(0,i.useCallback)(()=>{let e=tP.current,t=tA.current;if("unknown"===e){let n=po(tN.current,tT.current),r=n?.message,i=t_.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:pg(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=ps(r),t??={provider:r.provider,...r.model?{model:r.model}:{},...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tS.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nB=(0,i.useCallback)(e=>{let t=nU();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tF.current;e.catch(()=>void 0).then(()=>{let e=tS.current===t.sessionId&&tF.current===n;s?.(e?nU():t)})},[s,nU]),nq=(0,i.useCallback)((e,t)=>tL.current!==e&&(tL.current=e,nB(t),!0),[nB]),nV=(0,i.useCallback)(e=>{nR(),tj.current=!0;let t=tk.current,n=async()=>{if(t===tk.current&&tS.current===e&&tj.current)try{let r=nm.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tk.current||tS.current!==e||!tj.current)return;let s=a.state;if(td(e=>pe(e,s?.subagents??[])),ng(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tj.current=!1,tw.current=null,tE.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tM.current=!0,L(!0),eK(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){e_(!0),eH(pi(s)),tw.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){tw.current=setTimeout(()=>void n(),1e3);return}tj.current=!1,tw.current=null,nE()}catch{if(t!==tk.current||tS.current!==e||!tj.current)return;tw.current=setTimeout(()=>void n(),600)}};tw.current=setTimeout(()=>void n(),3e4)},[ng,nR,nE]),nK=(0,i.useCallback)(async(e=tS.current,t=na.current)=>{if(na.current===t)try{e&&await nb(e)}finally{if(na.current!==t)return;let n=t$.current,r=tE.current;t$.current=!1,tE.current=!1,no.current=null;let i=nD();n?nq(t):r&&i&&nB(),e&&nV(e)}},[nb,nB,nq,nV,nD]),nG=(0,i.useCallback)(async(e,t)=>{await pu(800);let n=Date.now();for(;tM.current&&Date.now()-n<2e4;){if(void 0!==t&&na.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nK(e,t)}}catch{}await pu(600)}},[nK]),nJ=(0,i.useCallback)(async e=>{let t=tW.current+1;for(tW.current=t;tz.current&&tW.current===t&&tS.current===e;){await pu(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nb(e),tW.current!==t||tS.current!==e)return;tz.current=!1,A(!1),F(null);return}catch{}}},[nb]),nZ=(0,i.useCallback)(async e=>{if(!tM.current)return;let t=na.current;try{let n=nm.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(na.current!==t)return;let a=i.state;if(e_(a?.isCompacting??!1),eH(pi(a)),tl(pn(a?.queuedMessages)),a?.contextUsage!==void 0&&ej(a.contextUsage??null),td(e=>pe(e,a?.subagents??[])),ng(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tM.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&te(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&tr(a.extensionWidgets??[])),await nK(e,t)}catch{}},[ng,nK]),nY=(0,i.useCallback)(async e=>{let t=await nb(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tS.current===e&&!tM.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tE.current=!!n.isStreaming,t$.current=!!n.isPromptRunning,tM.current=!0,L(!0),eK(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),py(tR.current,e,n.pendingToolCalls),nP(e),!n.isStreaming&&n.isPromptRunning&&nG(e),!0)},[nP,nb,nG]),nX=(0,i.useCallback)(async(e,t=na.current)=>{let n=ns.current+1;ns.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==ns.current||tS.current!==e||na.current!==t)return;i.state?.contextUsage!==void 0&&ej(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eA){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eA]),(0,i.useEffect)(()=>{if(!$&&!eA)return;let e=()=>{let e=tS.current;e&&nX(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[$,eA,nX]),(0,i.useEffect)(()=>{if(!$)return;let e=()=>{let e=tS.current;e&&nZ(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[$,nZ]),(0,i.useEffect)(()=>{if($)return;let e=()=>{let e=tS.current;e&&!tM.current&&nY(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tS.current,n=e.detail?.sessionId;t&&n===t&&!tM.current&&nY(t).then(e=>{e||tS.current!==t||tM.current||nb(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(u1,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(u1,n)}},[$,nY,nb]),tD.current=e=>{if(tS.current!==e||tM.current||tx.current||tH.current)return;let t=nY(e).then(async t=>{t||tS.current!==e||tM.current||await nb(e)}).catch(()=>{}).finally(()=>{tH.current===t&&(tH.current=null)});tH.current=t},(0,i.useEffect)(()=>{tM.current=$},[$]),tO.current=(0,i.useCallback)(e=>{var t;switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=pg(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=pg(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=pg(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tS.current,tC.current,tN.current,tT.current);if(!t)break;tC.current=t.entryId;let n=to(t.messages,t.entryIds,tI.current.sessionId===tS.current?tI.current.outputs:[]);nx(n.messages),nv(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tM.current;nR(),e&&nH(),tE.current=!0,tM.current=!0,L(!0),eK({kind:"waiting_model"}),E({type:"start"});break}case"agent_end":if(!tM.current)break;if(eK(null),pb(tR.current),ew(null),E({type:"end"}),tS.current){nb(tS.current);let e=nm.current;fetch(`/api/agent/${encodeURIComponent(tS.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ej(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&te(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&tr(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>pe(e,t.state?.subagents??[])),tS.current&&ng(tS.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tG(t.state.goal??null),tl(pn(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tG(e.status??null);break;case"agent_settled":{let e=tE.current;if(tE.current=!1,!e||t$.current)break;let t=tS.current,n=nD();e_(!1);let r=t?nb(t):void 0;t&&nV(t),n&&nB(r);break}case"prompt_done":{let e=na.current,t=t$.current;t$.current=!1,no.current=null;let n=tL.current!==e;if(!t&&!n)break;let r=tS.current;nq(e,r?nb(r):void 0),!tE.current&&(nD(),r&&nV(r))}break;case"prompt_error":tP.current="failed",nz({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tP.current="failed",nz({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tM.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&E({type:"update",message:s5(t)}),eK(null);break}case"message_end":{if(!tM.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}:{}},tP.current=ps(t)),t&&"user"===t.role){let e=s5(t),n=pf(e),r=no.current;no.current=null,nx(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&pf(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tp({type:"user-message",kind:ad(e),text:ac(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nx(e=>[...e,s5(t)]);let n=tS.current;n&&nX(n),E({type:"reset"}),eK(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tS.current,n=e.thinkingLevel;t&&void 0!==n&&(t9.current=t,ne.current+=1,el(e.configured??n),ed(n));break}case"todo_changed":nf(tS.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,i=nI(tS.current,t);i&&tR.current.add(i),eK(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_update":{let n=nI(tS.current,"string"==typeof e.toolCallId?e.toolCallId:null);n&&tR.current.has(n)&&"string"==typeof e.text&&(t=e.text,nS.get(n)!==t&&(nS.set(n,t),nN()));break}case"tool_execution_end":{let t=e.toolCallId,n=nI(tS.current,t);n&&tR.current.delete(n)&&nM([n]),eK(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";td(n=>{let r=n.find(e=>e.id===t.id);return pe(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};td(e=>pe(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};td(e=>pe(e,[r]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ew({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ew(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}e_(!0),ez(null),eO(null);break;case"auto_compaction_end":case"compaction_end":if(e_(!1),e.errorMessage)ez(e.errorMessage),eO(null);else if(!e.aborted){eO(px(e.result,e.reason??"auto"));let t=tS.current;t&&(nb(t),nX(t))}break;case"extension_ui_request":nO(e)}},[nz,nf,ng,nR,nO,nb,nB,nq,nX,nH,nV,nD,nv,nx]);let nQ=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tM.current||tz.current||nl.current)return"unknown";let o=lh(n,a??[]),l=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tJ.current?.(t,e),"accepted"):"unknown"}nH();let c=na.current+1;nR(),t$.current=!0;let d=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...o.trim()?[{type:"text",text:o}]:[],...d]:o,timestamp:Date.now()};nx(e=>[...e,u]),no.current=pf(u),na.current=c,tM.current=!0,L(!0),eK(l?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),tQ.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1,g="unknown";try{if(m&&r){let e=tS.current??await t2.current,t=await nC();t&&(h=t,X&&(eE(X),e&&await uJ(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nA(t),f=!0,await uJ(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),nj(1,n),g="accepted")}else t&&(h=t.id,await nA(t.id),f=!0,await uJ(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&nG(h,c),g}catch(o){console.error("Failed to send message:",o);let r=o instanceof uG&&"update_draining"===o.code&&!1===o.accepted;if(!(!f||o instanceof uG&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return nG(h,c),"unknown";t$.current=!1,tM.current=!1,nE();let s=no.current;return s&&nx(e=>{let t=e[e.length-1];return t?.role==="user"&&pf(t)===s?e.slice(0,-1):e}),nz({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,pv(i),a,t?.id??h??void 0),no.current=null,L(!1),eK(null),E({type:"end"}),"returned"}},[m,r,X,t,nC,nA,nj,nG,nz,nR,nE,e.chatInputRef,nH,nx]);tJ.current=(0,i.useCallback)(async(n,r)=>{if(tM.current||tz.current)return;let i=`${r?"!!":"!"}${n}`;tz.current=!0,tQ.current(!0),F({command:n,excludeFromContext:r}),A(!0);try{let e=tS.current??t?.id??await nC();if(!e)throw Error("Unable to create a session for the shell command");await uJ(e,{type:"bash",command:n,excludeFromContext:r}),await nb(e),nj(1,i)}catch(t){console.error("Failed to execute shell command:",t),nz({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tz.current=!1,F(null),A(!1)}},[nz,nC,nb,e.chatInputRef,nj,t]);let n0=(0,i.useCallback)(async()=>{let e=tS.current;if(e){if(tz.current){try{await uJ(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uJ(e,{type:"abort"}),tP.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),n1=(0,i.useCallback)(async e=>{if(tz.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tS.current;if(!t)return{forked:!1,error:"No active session to fork"};eT(e??null);try{let{cancelled:n,newSessionId:r}=await uJ(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eT(null)}},[c]),n2=(0,i.useCallback)(async e=>{if(tz.current)return;let t=tS.current;t&&(uJ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nw(t,e))},[nw]),n8=(0,i.useCallback)(async e=>{if(tz.current)return;j(e);let t=tS.current;t&&(await nw(t,e),e&&uJ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nw]),n4=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t6.current?.provider===e;t6.current=n,r||(t3.current=null,et(null)),Q(n),eE(n);let i=tS.current??await t2.current;if(!i)return;try{await uJ(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tS.current;if(n&&!nl.current){nl.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await uJ(n,{type:"set_model",provider:e,modelId:t}),nl.current=!1,await nb(n)}catch(e){console.error("Failed to set model:",e),nl.current=!1,eM(eI),nz({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nb(n)}finally{nl.current=!1,eL(!1)}}},[nz,eI,m,nb,Q]),n5=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(nl.current)return!1;nl.current=!0,eL(!0);let e=t6.current,a=t3.current,s=t7.current;try{t6.current=t,t3.current=n??null,t7.current="auto";let e=tS.current??await t2.current;return e&&await uJ(e,r),Q(t),et(n??null),eE(t),el("auto"),ed(void 0),e&&await nb(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t6.current=e,t3.current=a,t7.current=s,nz({type:"error",message:i(n)});let t=tS.current;return t&&await nb(t),!1}finally{nl.current=!1,eL(!1)}}let a=tS.current;if(!a||nl.current)return!1;nl.current=!0,eM(t),eL(!0);try{return await uJ(a,r),await nb(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eI),nz({type:"error",message:i(e)}),await nb(a),!1}finally{nl.current=!1,eL(!1)}},[nz,eI,ec,m,nb,Q,eo]),n6=(0,i.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t7.current=t??null,el(t??"auto"),ed(void 0),t6.current=e,t3.current=null,et(null),Q(e),eE(e)}let r=tS.current??(m?await t2.current:null);if(r)try{await uJ(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,Q]),n3=(0,i.useCallback)(async()=>{let e=tS.current;if(e&&!eA){eU.current="manual",e_(!0),ez(null),eO(null);try{let t=await uJ(e,{type:"compact"});eO(px(t,"manual")),await nb(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eO(null)}finally{e_(!1)}}},[eA,nb]),n7=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();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&&!tS.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t7.current&&el(t??"auto")}},[m,r,t?.cwd]),n9=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await nC(),s=e=>(e.handled&&(e.error?nz({type:"error",message:e.error}):"openSessionStats"!==e.action&&nz({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eA)return s({handled:!0,error:"No active session to compact"});eU.current="manual",e_(!0),ez(null),eO(null);let e=await uJ(a,{type:"compact",...i?{customInstructions:i}:{}});return eO(px(e,"manual")),await nb(a,!0)&&nj(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await uJ(a,{type:"reload"}),await Promise.all([nb(a,!1,!0),nk(a),nT(),n7()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await uJ(a,{type:"set_session_name",name:i}),await nb(a)&&nj(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await uJ(a,{type:"get_session_stats"});return e&&e1(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await uJ(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await n1();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await uJ(a,{type:"goal",args:i});if(tG(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nW(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nz({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tM.current||tz.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tM.current=!0,L(!0),eK({kind:"running_command"});try{await nA(a);let e=await uJ(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nb(a,!0)&&nj(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tM.current=!1,L(!1),eK(null),tS.current===a&&nV(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await uJ(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nW(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&e_(!1)}},[nz,nW,nA,nC,n1,eA,n7,nb,nT,nk,nj,h,nV]),re=(0,i.useCallback)(async(t,n,r)=>{let i=tS.current;if(!i)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r),"returned";let a=lh(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++th.current;tp({type:"submit",id:o,kind:"steer",text:a,images:s?.length??0});try{return await uJ(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tp({type:"ack",id:o}),"accepted"}catch(a){return tp({type:"fail",id:o}),console.error("Failed to steer:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r,i),"returned"}},[nz,e.chatInputRef]),rt=(0,i.useCallback)(async(t,n,r,i)=>{let a=tS.current;if(!a)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(r),i),"returned";let s=lh(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++th.current;tp({type:"submit",id:l,kind:n,text:s,images:o?.length??0});try{return await uJ(a,{type:"prompt",message:s,streamingBehavior:n,...o?.length?{images:o}:{}}),tp({type:"ack",id:l}),"accepted"}catch(n){return tp({type:"fail",id:l}),console.error("Failed to queue prompt:",n),nz({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(r),i,a),"returned"}},[nz,e.chatInputRef]),rn=(0,i.useCallback)(async(t,n,r)=>{let i=tS.current;if(!i)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r),"returned";let a=lh(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++th.current;tp({type:"submit",id:o,kind:"followUp",text:a,images:s?.length??0});try{return await uJ(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tp({type:"ack",id:o}),"accepted"}catch(a){return tp({type:"fail",id:o}),console.error("Failed to follow up:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,pv(n),r,i),"returned"}},[nz,e.chatInputRef]),rr=(0,i.useCallback)(async()=>{let e=tS.current;if(e)try{await uJ(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),ri=(0,i.useCallback)(async()=>{let t=tS.current;if(t)try{var n;let r=await uJ(t,{type:"clear_queue"});tp({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nz({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nz]),ra=(0,i.useCallback)(async(e,t)=>{let n=tS.current;if(n)try{let r=await uJ(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tp({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nz({type:"error",message:"Failed to remove queued message"})}},[nz]),rs=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==eu;el(e),ep(n),m&&(!tS.current||nn.current===tS.current)&&(t7.current=e,nt.current=n),ed(void 0);let i=tS.current??await t2.current;if(i)try{nn.current===i?await nC():r&&await uJ(i,{type:"set_thinking_ceiling",ceiling:n}),await uJ(i,{type:"set_thinking_level",level:e}),await nb(i)}catch(e){console.error("Failed to set thinking level:",e),nz({type:"error",message:"Failed to set thinking level"}),await nb(i)}},[m,nb,nz,eu,nC]);eb.current=np?`${np.provider}/${np.modelId}`:"";let ro=e=>e?`${e}|${eb.current}`:null,rl=t?.id??tS.current,rc=ro(rl),rd=eh&&eh.key===rc?eh.value:null;(0,i.useEffect)(()=>{let e=++ex.current;rc&&rl&&!$&&!e$&&fetch(`/api/agent/${encodeURIComponent(rl)}`).then(e=>e.json()).then(t=>{ex.current===e&&ro(tS.current)===rc&&em({key:rc,value:(t.running?pr(t.state):void 0)??null})}).catch(()=>{})},[rc,$,e$]);let ru=(0,i.useCallback)(async()=>{let e=tS.current??await nC(),t=ro(tS.current);if(!e||!t)return;let n=++ex.current,r=()=>ex.current===n&&ro(tS.current)===t,i=e=>{r()&&em({key:t,value:e})};eg(!0);try{let n=eh?.key===t?eh.value?.enabled:void 0;if(void 0===n){let t=pr(await uJ(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await uJ(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nz({type:"error",message:t instanceof Error?t.message:String(t)});try{i(pr(await uJ(e,{type:"get_state"}))??null)}catch{i(null)}}finally{eg(!1)}},[nC,eh,nz]),rp=(0,i.useCallback)(async e=>{let t=(0,ur.xG)(e);nd(e);let n=tS.current??await t2.current;if(n)try{await uJ(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[nd]),rh=(0,i.useCallback)(e=>{tB.current=e,tV(t=>!e===t?t:!e)},[]);tQ.current=e=>{tY.current=null,rh(e)};let rm=(0,i.useCallback)((e="smooth")=>{tX.current=Date.now()+700,t0.current?.scrollIntoView({behavior:e})},[]),rf=(0,i.useCallback)(()=>{tZ.current=0,tY.current=null,rh(!0),rm("smooth")},[rm,rh]),rg=(0,i.useCallback)(()=>{tZ.current=0,tY.current=null,rh(!1)},[rh]),rx=(0,i.useCallback)(()=>{if(!tY.current)return;tY.current=null;let e=t1.current;e&&rh(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[rh]),rv=(0,i.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(tY.current)return void rx();rg();let e=t1.current;return void(tY.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}rx(),e instanceof KeyboardEvent&&(!pl.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tZ.current=Date.now()+1200)},[rx,rg]),rb=(0,i.useCallback)(()=>{let e=t1.current;if(!e)return;let t=tY.current;if(null!==t){let n=t.top;t.moved||=e.scrollTop!==n,t.top=e.scrollTop;return}if(!tM.current&&!tz.current)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight,r=Date.now()<=tZ.current;if(!(!r&&Date.now()<tX.current)){if(n<=72)return void rh(!0);r&&rh(!1)}},[rh]);return(0,i.useEffect)(()=>(tS.current=t?.id??null,tI.current.sessionId!==tS.current&&(tI.current={sessionId:tS.current,outputs:[],seq:0}),t&&nb(t.id,!f,!0,f).then(e=>{if(tS.current!==t.id)return;nL(t.id),e?.running&&(nk(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tE.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tM.current=!0,L(!0),eK(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),py(tR.current,t.id,e.state.pendingToolCalls),nP(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nG(t.id)),e.state?.isBashRunning&&(tz.current=!0,A(!0),nJ(t.id)),(e.state?.subagents?.length??0)>0&&nP(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&e_(n.isCompacting),eH(pi(n)),void 0!==n.contextUsage&&ej(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t9.current=t.id,el(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&ep(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&te(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&tr(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(pn(n.queuedMessages)),void 0!==n.subagents&&td(e=>pe(e,n.subagents??[])),void 0!==n.goal&&tG(n.goal??null)),e&&eq(!0)}),()=>{tW.current+=1,nR(),nE(),n$()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,n8)},[g?.tree,k,n8,u]),(0,i.useEffect)(()=>{let e=e=>{let t=tY.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t1.current?.contains(e.target))?rx():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",rv),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",rv)}},[rx,rv]),(0,i.useEffect)(()=>{let e=t1.current;if(!e)return;let t=()=>{tY.current?.moved&&rx()};return e.addEventListener("pointerdown",rv,{passive:!0}),e.addEventListener("wheel",rv,{passive:!0}),e.addEventListener("touchstart",rv,{passive:!0}),e.addEventListener("scroll",rb,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",rv),e.removeEventListener("wheel",rv),e.removeEventListener("touchstart",rv),e.removeEventListener("scroll",rb),e.removeEventListener("scrollend",t)}},[S.length,v,rx,rb,rv]),(0,i.useEffect)(()=>{if(nr.current||!$&&!P||!tB.current)return;let e=t1.current;if(!e)return;let t=requestAnimationFrame(()=>{tB.current&&(tX.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[$,P,S.length,R.streamingMessage,eV,_,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tU.current){tU.current=!0,rm("instant");return}if(!nr.current&&tB.current){let e=Date.now()-ni.current<1500;rm(tM.current||tz.current||e?"instant":"smooth")}}},[S.length,$,P,rm,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n7(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n7,d]),(0,i.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eO(null),6e3);return()=>clearTimeout(e)},[eW]),(0,i.useEffect)(()=>{if(0===eX.visible.length)return;let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eQ({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eX.visible[0])return;let t=setTimeout(()=>{eQ({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eX.visible]),(0,i.useEffect)(()=>{e1(null)},[S.length,ek?.tokens,ek?.percent,ek?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:R,agentRunning:$,modelNames:z,modelList:O,modelError:H,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ei,thinkingLevel:eo,effectiveThinkingLevel:ec,thinkingCeiling:eu,retryInfo:ey,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:eA,compaction:eD,compactError:eF,compactResult:eW,currentModel:nu,displayModel:np,modelSwitching:e$,sessionStats:nh,runStateKnown:eB,slashCommands:eG,slashCommandsLoading:eZ,queuedMessages:ti,deliveryRows:tm,subagents:tc,todoPhases:tf&&tf.sid===tS.current?tf.phases:null,compactedWork:I,notices:eX.visible,extensionDialog:e2,extensionResponse:e4,extensionCustomUi:e3,extensionStatuses:e9,extensionWidgets:tn,respondToExtensionUi:n_,sendExtensionCustomInput:nF,isAutoModelSelection:m&&null===X,agentPhase:eV,isNew:m,autoFollowPaused:tq,resumeAutoFollow:rf,pauseAutoFollow:rg,goalStatus:tK,sessionIdRef:tS,eventSourceRef:tx,messagesEndRef:t0,scrollContainerRef:t1,handleSend:nQ,handleAbort:n0,handleFork:n1,handleNavigate:n2,handleModelChange:n4,handleRoleModelChange:n6,handleMainPresetChange:n5,newSessionAccount:ee,handleCompact:n3,handleSteer:re,handleFollowUp:rn,handlePromptWithStreamingBehavior:rt,handleAbortCompaction:rr,handleRecallQueue:ri,handleRemoveQueuedMessage:ra,handleBuiltinSlashCommand:n9,handleToolPresetChange:rp,handleThinkingLevelChange:rs,fastMode:rd,fastModeBusy:ef,handleFastModeToggle:ru,loadTools:nk,loadSlashCommands:nT,ensureNewSession:nC,refreshLiveTranscript:ny,setActiveLeafId:j,setData:x,setMessages:C,dispatch:E,setAgentRunning:L,setForkingEntryId:eT,bashRunning:P,pendingBash:_,handleAgentEventRef:tO}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ey,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),t4=(0,i.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=te(i);if(!a||"custom"!==i.role)continue;t??=[...e];let s=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&s.push(t);continue}let i=n.get(t);void 0===i&&(i=function(e){let t=e9(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,i)),i===a.sourceHash&&s.push(t)}s.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===a.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[r]={...i,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(e7)?{kind:"translated",text:n.slice(e7.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(i,e9(o.content??[]))}}return t??e})(eS),[eS]),t5=iv(e?.id,e6?.provider,void 0,e6?.modelId),t6=t5?.alias;(0,i.useEffect)(()=>{t6&&X.current?.(t6)},[t6]);let t3=(0,i.useMemo)(()=>{if(!e6)return null;let e=tT?tB:rg.find(e=>e.alias===t5?.alias)?.oauthPosition;return rg.find(t=>t.provider===e6.provider&&(void 0===t.oauthPosition?null===t5||t5.seed===t.seed:t.oauthPosition===e))?.alias??null},[e6,tT,tB,t5]),t7=eT||eI,t9=e?.id;ei.current=t4,ea.current=eC,eo.current=t$;let ne=(0,i.useRef)(!0);ne.current=!tI;let nt=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eT&&!nt.current&&(el.current+=1),nt.current=eT},[eT]),(0,i.useEffect)(()=>()=>{el.current+=1},[]),(0,i.useEffect)(()=>{et(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(pP(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[]}}(t9),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t9)])},[t9]),(0,i.useEffect)(()=>{let e=t$.current;e&&en.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(rl(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,t4,eC);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(pA(e,r),r):t})},[t4,eC,t$]);let nn=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=t$.current,t=nn.current;if(nn.current=e?{sessionId:e,entryIds:eC}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===rd&&r.push(t[a])}return r}(t.entryIds,eC,t4),r=eu();if(0===n.length||!r)return;let i=ig(e,"web6",void 0)?.alias??null;for(let e of n)en.current.some(t=>t.anchorEntryId===e)||em(i,"done",r,{kind:"entry",entryId:e})},[eC,t4,t$,eu,em]);let nr=eT&&tN?.kind==="running_tools"&&tN.tools.length>0&&tN.tools.every(e=>"wait"===e.name),ni=ek||s,{hideThinkingBlock:na}=(O=t??e?.cwd??null,H=n1(),(0,i.useEffect)(()=>{n0(O).catch(()=>{})},[O]),H),ns=(0,i.useMemo)(()=>({hideThinking:na}),[na]);(0,i.useEffect)(()=>{var e;if(!tv||Y.current===tv.id)return;Y.current=tv.id;let t=eu();if(!t)return;ed.current=t.turn;let n=eN.streamingMessage?.role==="assistant"?eN.streamingMessage:null,r=rc(ei.current,n,e6?.provider,e6?.modelId);eg("select"===(e=tv.method)||"ask"===e||"form"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tv,eN.streamingMessage,e6?.provider,e6?.modelId,eu,eg]),(0,i.useEffect)(()=>(v=t7?tF:null,()=>void(v=null)),[t7,tF]),(0,i.useEffect)(()=>{M?.(t7)},[M,t7]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{R?.(nr)},[nr,R]),(0,i.useEffect)(()=>()=>R?.(!1),[R]),(0,i.useEffect)(()=>{E?.(null!==tv)},[E,tv]),(0,i.useEffect)(()=>()=>E?.(!1),[E]);let{main:no,process:nl}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,o=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),o=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:o});a.messageCount+=t.length,a.toolCallCount+=n},l=e5(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:a,idx:e,runIndex:n,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){o(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,r.push(i);continue}if(tr(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===te(t)&&0>ti(e,i.idx)&&o(a,[{idx:i.idx}],0);continue}let s=eY(t,n);if(eJ(t,n)&&eZ(e,i.idx)){let e=s.flatMap(e=>e.blocks);o(a,[{idx:i.idx}],eX(e)),l.collect(i.idx,e);continue}let c=!1;for(let e of s){if("answer"===e.kind){d(i.idx,e.blocks),c=!0;continue}o(a,[{idx:i.idx,blocks:e.blocks}],eX(e.blocks)),l.collect(i.idx,e.blocks)}!c&&eJ(t,n)&&d(i.idx,[])}return u(),{main:r,process:i}})(t4,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(tl(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!tl(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!tl(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,o=[],l=0,c=0,d=e5(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(n),precedingBlocks:o}),o=[]};for(let l=t+1;l<n;l++){let n=e[l];if("assistant"!==n.role){if(null!==te(n)||ti(e,l)>=0)continue;if(tr(n)){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:l});continue}let c=eY(n,r);if(eJ(n,r)&&eZ(e,l)){let e=c.flatMap(e=>e.blocks);for(let t of(a.push({idx:l}),s+=eX(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(a.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eX(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eJ(n,r)&&p(l,[])}u();let h=d.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(t4,{sessionBusy:t7,isStreaming:eN.isStreaming,hideThinking:ns.hideThinking}),ns),[t4,t7,eN.isStreaming,ns]),nc=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=i3(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=r.get(l.position);e?e.calls.push(...n):r.set(l.position,{calls:[...n],placement:o?"after":"before"})}}"user"===e.role&&(a=t),tl(e)&&(s=t)});let{continuing:o}=i7(e,t,n);if(o){let e=r.get(o.position);e?e.calls.unshift(...o.calls):r.set(o.position,{calls:o.calls,placement:"before"})}return r})(no,t4,td?.messages),[no,t4,td]),nd=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=i7(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i);return{position:-1===a?e.length:a,calls:r}})(no,t4,td?.messages),[no,t4,td]),[nu,np]=(0,i.useState)(pM),{startIndex:nh,endIndex:nm,hasLater:nf}=pR(no.length,nu),ng=null!==nu.end&&nf,nx=(0,i.useRef)(no.length);nx.current=no.length;let nv=(0,i.useRef)(null),nb=(0,i.useRef)(null),ny=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nu.end&&nu.end>=no.length&&np(e=>({count:e.count,end:null}))},[nu.end,no.length]),(0,i.useEffect)(()=>{let e=nv.current,t=tA.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(ny.current=t.scrollHeight-t.scrollTop,np(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nu,no.length,tA]),(0,i.useEffect)(()=>{if(null==ny.current)return;let e=tA.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-ny.current),ny.current=null}},[nu.count,tA]),(0,i.useEffect)(()=>{let e=nb.current,t=tA.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&np(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=pR(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nx.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nu,no.length,tA]);let[nw,nk]=(0,i.useState)(null),[nj,nC]=(0,i.useState)(0),nT=(0,i.useRef)(null),nR=(0,i.useCallback)(e=>{tR(),nT.current=e,nk(null),np(t=>pE(nx.current,e,t)),nC(e=>e+1)},[tR]);(0,i.useLayoutEffect)(()=>{let e=nT.current,t=tA.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;nT.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,nk(e)},[nj,nu,no,tA]),(0,i.useEffect)(()=>{if(null===nw)return;let e=setTimeout(()=>nk(null),1800);return()=>clearTimeout(e)},[nw]);let nE=(0,i.useCallback)(()=>{(0,q.flushSync)(()=>np(pM));let e=tA.current;e&&(e.scrollTop=e.scrollHeight)},[tA]),n$=(0,i.useCallback)(()=>{ng&&nE(),tM()},[ng,nE,tM]),nL=(0,i.useRef)(null),[nP,nA]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!F||nL.current===F.id||F.sessionId!==e?.id||ek||0===t4.length)return;nL.current=F.id,W?.(F.id);let t=eC.indexOf(F.entryId);if(t<0)return void nA(!0);let n=0;for(let e=0;e<no.length;e++){let r=no[e].idx;if(r>t||(n=e,r===t))break}nR(n)},[F,e?.id,ek,t4.length,eC,no,nR,W]),(0,i.useEffect)(()=>{if(!nP)return;let e=setTimeout(()=>nA(!1),6e3);return()=>clearTimeout(e)},[nP]);let[n_,nF]=(0,i.useState)(!1),[nz,nW]=(0,i.useState)(0),nO=(0,i.useMemo)(()=>n_?no.map(e=>(function(e,t){if("answer"===e.kind)return tu(e.blocks);let n=t[e.idx];return n&&"content"in n?tu(n.content):""})(e,t4).toLowerCase()):p_,[n_,no,t4]),nD=(0,i.useCallback)(e=>{tR(),np(t=>pE(nx.current,e,t))},[tR]),nH=(0,i.useCallback)(()=>nF(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tA.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nF(!0),nW(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tA]);let nU=(0,i.useMemo)(()=>{let e=[];return no.forEach((t,n)=>{if("message"!==t.kind)return;let r=pL(t4[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[no,t4]),nB=`${nh}:${nm}`,nq=eC.length>0?eC[eC.length-1]:null,[nV,nK]=(0,i.useState)(null),nG=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nG.current||!tc||ek||!e?.id||(nG.current=!0,t7||!nq||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(t4)||function(e){try{return window.localStorage.getItem(pF(e))}catch{return null}}(e.id)!==nq&&nK(nq))},[tc,ek,e?.id,t7,nq,t4]);let nJ=(0,i.useCallback)(()=>{e?.id&&nV&&function(e,t){try{window.localStorage.setItem(pF(e),t)}catch{}}(e.id,nV),nK(null)},[e?.id,nV]),nZ=null!==nV&&nV===nq&&!t7&&!ng,nY=tn?[tn.sessionId,tn.sessionFile??"",tn.sessionName??"",tn.userMessages,tn.assistantMessages,tn.toolCalls,tn.toolResults,tn.totalMessages,tn.tokens.input,tn.tokens.output,tn.tokens.cacheRead,tn.tokens.cacheWrite,tn.tokens.total,tn.cost??0,tn.totalActiveMs??0].join("|"):null,nX=(0,i.useRef)(tn);nX.current=tn,(0,i.useEffect)(()=>{f?.(nX.current)},[nY,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let nQ=eV?`${eV.percent??"null"}|${eV.contextWindow}|${eV.tokens??"null"}`:null,n2=(0,i.useRef)(eV);n2.current=eV,(0,i.useEffect)(()=>{x?.(n2.current)},[nQ,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(tf)},[b,tf]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{regular:n8,lab:n4}=(0,i.useMemo)(()=>(function(e){let t=[],n=[];for(let i of e){var r;((r=i.key).startsWith(cW)&&null!==cO(r)?n:t).push(i)}return{regular:t,lab:n}})(tk),[tk]),n5=e?.id??null;(0,i.useEffect)(()=>{y?.(n5,n4)},[y,n5,n4]),(0,i.useEffect)(()=>()=>{y?.(null,[])},[y]);let{isDragOver:n6,handleDragEnter:n3,handleDragOver:n7,handleDragLeave:n9,handleDrop:rt}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t7||p?.current?.addAttachments(e)},[t7,p])),rn=(0,i.useMemo)(()=>{var e;return e=td?.messages,e&&e.length>0?[...e,...t4]:t4},[td,t4]),rr=(0,i.useMemo)(()=>{let e=new Map;for(let t of rn)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rn]),ri=(0,i.useMemo)(()=>{let e,t,n,r,i,a,s,o,l,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,i=new Map,a=new Map,s=new Map,o=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},l=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=iX(e.status);if(!r||l.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;l.add(r);let s=iY(e);null!==s&&i.set(r,s)},d=(e,t,r)=>{let i=t?n.get(t):void 0,a=iY(e);i&&"number"==typeof r&&null!==a&&"running"===iX(e.status)&&s.set(i,Math.max(s.get(i)??-1/0,r-a))},rn.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rr.get(e.toolCallId);if(t)for(let i of i0(e,t)??[])n.set(i.agentId,i.key),"number"==typeof t.timestamp&&r.set(i.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(iQ(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=iZ(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:iZ(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of iJ(t.details?.jobs)){if("task"!==r.type)continue;let a=iZ(r.id);if(a&&o(a,iX(r.status),i),c(r,a),d(r,a,t.timestamp),a&&"running"===iX(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of iQ(t.content).matchAll(i1)){let t=Object.fromEntries([...e[1].matchAll(i2)].map(e=>[e[1],e[2]]));t.id&&o(t.id,iX(t.status),i)}for(let e of iJ(t.details?.jobs))"task"===e.type&&c(e,iZ(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:i,parallelWith:a,runStartedAt:s}},[rn,rr]),ra=(0,i.useMemo)(()=>({ledger:ri,subagents:tf,toolResults:rr,onOpenPanel:w,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:j,selectedMaker:S}),[ri,tf,rr,w,e?.id,e?.cwd,t,j,S]),rs=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=t4.length-1;n>=0;n-=1){let r=pL(t4[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[t4]),ro=(0,i.useMemo)(()=>tP(t4,rr,tg,td?.todoPhases??null),[t4,rr,tg,td]),ru=(0,i.useMemo)(()=>cM(eN.streamingMessage).join("|"),[eN.streamingMessage]),rp=(0,i.useMemo)(()=>JSON.stringify(cI(eN.streamingMessage)),[eN.streamingMessage]),rh=(0,i.useMemo)(()=>JSON.stringify(cE(eN.streamingMessage)),[eN.streamingMessage]),rm=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],o=new Map,l=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){l=n;continue}let i=cM(r),c=cE(r,a);if(0===i.length&&0===c.length||l<0)continue;let d=cI(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=o.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(a,e),s.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(t4,eC,ru.length>0?ru.split("|"):[],JSON.parse(rp),JSON.parse(rh)),[t4,eC,ru,rp,rh]),rf=e?.id??t$.current??void 0,rx=(U=cP(D=(0,i.useMemo)(()=>({sessionId:rf,sessionProvider:e6?.provider,turns:rm,messages:t4,subagents:tf}),[rf,e6?.provider,rm,t4,tf])),V=cz(D),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...U,...V])),[U,V])),rv=tT&&0===t4.length&&!eN.isStreaming&&!t7,rb=(0,i.useMemo)(()=>t4.filter(e=>"assistant"===e.role).length,[t4]),ry=function(e,t){let n=(0,i.useRef)(new Map),r=(0,i.useMemo)(()=>{if(!e)return n.current=new Map,0;let t=new Map,r=0;return(e.content??[]).forEach((e,i)=>{let a=e1(e);if(null===a)return;let s=e2(n.current.get(i),a);t.set(i,{text:a,tokens:s}),r+=s}),n.current=t,r},[e]),a=(0,i.useRef)(r);a.current=r;let s=null!==e,o=e?.timestamp,[l,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!s)return void c(null);let e=o??Date.now(),t=()=>{let t=(Date.now()-e)/1e3;c(t>=.5?a.current/t:0)};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[s,o,t]),s?l??0:null}(eN.streamingMessage?.role==="assistant"?eN.streamingMessage:null,rb),rw=(0,i.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("assistant"!==n.role)continue;let{usage:r,timestamp:i,completedAt:a}=n,s=r?.output??0;if(!(s<=0)&&i&&a&&!(a<=i))return s/((a-i)/1e3)}return null})(t4),[t4]),rk=e?.cwd??t??void 0,rj=e6?eA[`${e6.provider}:${e6.modelId}`]??null:null,rS=e6?e_[`${e6.provider}:${e6.modelId}`]??null:null,rC=(0,i.useRef)(null),rN=(0,i.useRef)(null),rT=(0,i.useCallback)(()=>{let e=rC.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,i.useEffect)(()=>(I?.(rT),()=>I?.(null)),[rT,I]),(0,i.useLayoutEffect)(()=>{let e=rN.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tA.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tA.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[ek,tA]);let rI=(0,i.useCallback)((...e)=>(null!==nu.end&&nE(),t_(...e)),[t_,nu.end,nE]),rM=(0,r.jsx)("div",{ref:rC,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(uH,{ref:p,sessionId:e?.id??t$.current??void 0,onEnsureSession:tT&&t?t2:void 0,onLiveTranscriptPersisted:t8,onSend:rI,onAbort:tF,onSteer:eT?tV:void 0,onFollowUp:eT?tK:void 0,onPromptWithStreamingBehavior:eT?tG:void 0,isStreaming:t7,model:e6,isAutoModelSelection:tC,modelNames:eR,modelList:eE,modelError:e$,modelScopeWarnings:eL,onModelChange:tD,onMainPresetChange:e||tT?tU:void 0,mainPresetActiveAlias:t3,modelRoles:eF,onRoleModelChange:tH,modelSwitching:e3,onCompact:e||tT?tq:void 0,onAbortCompaction:tJ,isCompacting:eQ,compactError:e8,compactResult:e4,toolPreset:ez,onToolPresetChange:e||tT?tQ:void 0,thinkingLevel:eW,effectiveThinkingLevel:eO,outputTokensPerSecond:ry??rw,outputSpeedLive:null!==ry,thinkingCeiling:eD,onThinkingLevelChange:e||tT?t0:void 0,fastMode:eH,fastModeBusy:eU,onFastModeToggle:e||tT?eB:void 0,availableThinkingLevels:rj,thinkingLevelMap:rS,retryInfo:eq,deliveryRows:tm,inputHistory:rs,onRecallQueue:tZ,onRemoveQueuedMessage:tY,slashCommands:tp,slashCommandsLoading:th,onLoadSlashCommands:t1,onBuiltinCommand:tX,soundEnabled:$,onSoundToggle:L,onAudioUnlock:_,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name})}),rR=eN.streamingMessage,rE=(0,i.useMemo)(()=>rR?eY(rR,{isStreaming:!0}):[],[rR]),r$=(0,i.useMemo)(()=>rE.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rE]),rL=(0,i.useMemo)(()=>rE.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rE]),rP=rR?.role==="assistant"?rR:null,rA=(0,i.useMemo)(()=>{let e=-1;for(let t=t4.length-1;t>=0;t-=1)if("user"===t4[t].role){e=t;break}let t=e<0?-1:sB(t4,e);return{start:t,blocks:sH(t4,t+1,t4.length),priorCiHeads:sV(t4,rr,t+1),jobNotices:sU(t4,t+1,t4.length)}},[t4,rr]),r_=(0,i.useMemo)(()=>sz(rP?[...rA.blocks,...rP.content??[]]:rA.blocks,rr,t7,rA.priorCiHeads,rk,rA.jobNotices),[rA,rP,rr,t7,rk]),rF=(0,i.useMemo)(()=>t7?{...sD(rA.blocks,rr,rk),span:sK(t4,rA.start+1,t4.length)}:null,[t7,rA,rr,rk,t4]),rz=(0,i.useMemo)(()=>rF?{...rF,flow:r_,latest:!0}:null,[rF,r_]),rW=eT&&(tN?.kind==="running_tools"||(rP?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rO=rc(t4,rP,e6?.provider,e6?.modelId),rD=rO.provider,rH=rO.model,rU=rO.credentialId;(0,i.useEffect)(()=>{if(!rW)return;let e=eu();e&&ec.current!==e.turn&&ed.current!==e.turn&&(ec.current=e.turn,eg("working",e,rD,rU,rH))},[rW,rD,rH,rU,eu,eg]);let[rB,rq]=(0,i.useState)(null),rV=(0,i.useCallback)(e=>{rq(e)},[]),rK=(0,i.useMemo)(()=>eM?{role:"bashExecution",command:eM.command,output:"",excludeFromContext:eM.excludeFromContext}:null,[eM]),rG=(0,i.useMemo)(()=>{let e=[eT&&!rR&&tN?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tN,K):null,eI&&!eM?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eT,rR,tN,eI,eM,K]);(0,i.useEffect)(()=>{if(!rB)return void C?.(null);let e=[],t=[],n=0;if(rR&&rL.length>0){let r=rB.messages.length+e.length;for(let i of(e.push(rR),rL))t.push({idx:r,blocks:i}),n+=eX(i)}if(rK&&(t.push({idx:rB.messages.length+e.length}),e.push(rK)),0===t.length)return void C?.(rG?{...rB,status:rG}:rB);let r=-1;for(let e=rB.messages.length-1;e>=0;e--)if(tl(rB.messages[e])){r=e;break}let i=rB.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),C?.({...rB,groups:i,messages:[...rB.messages,...e],status:rG})},[rB,rL,rR,rK,rG,C]),(0,i.useEffect)(()=>()=>C?.(null),[C]);let rJ=n8.filter(e=>"belowEditor"!==e.placement),rZ=n8.filter(e=>"belowEditor"===e.placement);return ej?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ej}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":ni,"data-empty-start":rv&&!T?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n3,onDragOver:n7,onDragLeave:n9,onDrop:rt,children:[ni?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,n6&&!t7&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),ty&&(0,r.jsx)(pq,{request:ty,onInput:tS}),rv&&!T?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[860px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(ee,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.244"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.20.0"]})]})]})]}),rk&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":K("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:K("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tW(rk)||rk}),(0,r.jsx)("code",{title:rk,children:rk}),(0,r.jsx)("p",{children:K("chat.emptyProjectHint")})]}),k&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:k,children:K("chat.openSessionList")})]}),(0,r.jsx)(pH,{notices:tx,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[T&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:T}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!T,style:{display:T?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(cc,{open:n_,onClose:nH,containerRef:tA,index:nO,renderedStart:nh,renderedEnd:nm,contentKey:t4,onReveal:nD,onProgrammaticScroll:tR,focusRequest:nz,t:K}),nP&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,r.jsx)(pH,{notices:tx,floating:!0,align:"right"})]})}),(0,r.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,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(pD,{widgets:rJ}),(0,r.jsxs)(ot.Provider,{value:ra,children:[(0,r.jsx)(cj,{utterances:rx,children:(0,r.jsx)(pz,{messages:t4,entryIds:eC,toolResultsMap:rr,modelNames:eR,messageCwd:rk,onOpenFile:N,sessionBusy:t7,isNew:tT,isStreaming:eN.isStreaming,handleFork:tz,forkingEntryId:eG,handleNavigate:tO,handleEditContent:ew,sessionId:e?.id??t$.current??void 0,main:no,dispatchSlots:nc,compactedDispatch:nd,openRequest:td?.openRequest??null,process:nl,startIndex:nh,endIndex:nm,sentinelRef:nv,laterSentinelRef:nb,flashItem:nw,t:K,cues:Q,cueFollowRef:ne,onProcessLogChange:rV})}),!ng&&eN.isStreaming&&eN.streamingMessage&&r$.length>0&&(0,r.jsx)(l_,{message:eK(eN.streamingMessage,r$),sessionId:e?.id??t$.current??void 0,isStreaming:!0,modelNames:eR,cwd:rk,onOpenFile:N}),!ng&&rz&&(0,r.jsx)(o7,{summary:rz,live:!0,onOpenFile:N})]}),nZ&&(0,r.jsx)(cf,{onDismiss:nJ,t:K}),(0,r.jsx)("div",{ref:tL})]})})}),(0,r.jsx)(cd,{questions:nU,containerRef:tA,layoutKey:nB,onJump:nR,label:K("chat.questionRail")}),(t7&&tI||ng)&&(0,r.jsxs)("button",{type:"button",onClick:n$,"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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rN,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tv&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,r.jsx)(pB,{request:tv,onRespond:tj,onActivity:(e,t)=>void tS(e,t??"activity"),delivery:tb})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(cm,{compaction:e0,t:K}),(0,r.jsx)(pO,{goal:tE,t:K}),(0,r.jsx)(pD,{widgets:rZ}),(ro||r_.steps.length>0)&&!(G&&J)&&(0,r.jsx)(uB,{phases:ro,flow:r_,busy:t7})]})}),rM,(0,r.jsx)(uU,{statuses:tw})]})]})}function pO({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nV(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nV(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function pD({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function pH({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function pU({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,z.s)(),d=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!d.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=d.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:a},children:[o?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function pB({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,z.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),m=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("form"===e.method)return(0,r.jsx)(pU,{focusKey:e.id,label:s("chat.agentQuestion"),delivery:a,children:(0,r.jsx)(c5,{request:e,onRespond:t,onActivity:n,delivery:a},e.id)});if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(pU,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{m(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let n=e.target.value;d(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(pU,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(nk,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(pU,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&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,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick: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,r.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 pq({request:e,onInput:t}){let{t:n}=(0,z.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),o=ez(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eD[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":" ":eO[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eW(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}var pV=n(40960),pK=n.n(pV);function pG({sessionId:e,refreshKey:t,compact:n}){let{t:a}=(0,z.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),h=(0,i.useRef)(e);h.current=e;let m=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e)return;let t=!1,n=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(r=>{if(t||n!==m.current)return;let i=r.running?r.state?.computerTakeover:null;l(i?{sessionId:e,state:{enabled:!0===i.enabled,available:!0===i.available}}:null),p(null)}).catch(()=>{}),()=>{t=!0}},[e,t]);let f=(0,i.useCallback)(async e=>{let t=h.current;if(t){d(!0),p(null);try{let n=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok)throw Error("shared_settings"===r.code?a("computerTakeover.shared"):r.error??n.statusText);h.current===t&&(m.current+=1,l({sessionId:t,state:{enabled:!0===r.enabled,available:!0!==r.enabled}}))}catch(e){h.current===t&&p(a("computerTakeover.failed",{error:e instanceof Error?e.message:String(e)}))}finally{d(!1)}}},[a]),g=o&&o.sessionId===e?o.state:null;if(!g||!g.enabled&&!g.available)return null;let x=g.enabled,v=x?a("computerTakeover.active"):a("computerTakeover.allow"),b=u??(x?a("computerTakeover.activeHint"):a("computerTakeover.allowHint"));return(0,r.jsxs)(s.r,{className:`workspace-header-action workspace-takeover${x?` ${pK().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,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!n)&&(0,r.jsx)("span",{children:v})]})}function pJ({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,o]=(0,i.useState)({kind:"idle"}),l=(0,i.useRef)(null),c=n.trim();(0,i.useEffect)(()=>{if(c.length<2)return void o({kind:"idle"});let e=new AbortController;o({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);o({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||o({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[c]);let d=e=>{let t=l.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),d(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var pZ=n(50640),pY=n(73620);let pX=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pQ(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let p0=["tags","categories","keywords","tag","category"];function p1({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=p0.find(t=>Array.isArray(e[t])),s=a?e[a].map(pQ).filter(Boolean):[],o=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=pQ(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var p2=n(8745);let p8=(0,i.createContext)(null),p4=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),p5=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),p6=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10 3-5 5 5 5"})}),p3=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),p7=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function p9({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:m}){let{t:f}=(0,z.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:p6})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,l&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:l})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(p2.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,r.jsxs)(p2.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(p2.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(p2.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,r.jsx)(o.In,{size:"16px",svg:p7})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":f("panel.more"),children:(0,r.jsx)(c.k.ScrollArea,{children:(0,r.jsx)(c.k.Group,{children:h.map(e=>(0,r.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(he,{}),m&&(0,r.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,r.jsx)(o.In,{size:"16px",svg:p3})})]})}function he({className:e="panel-header-button"}){let{t}=(0,z.s)(),n=(0,i.useContext)(p8);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(o.In,{size:"16px",svg:n.expanded?p5:p4})})}let ht="cuelo-html-pick",hn="cuelo-html-pick-exit";function hr(e,t){return"string"==typeof e&&e.length<=t}function hi(e){return"number"==typeof e&&Number.isFinite(e)}function ha({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:o}){let{t:l}=(0,z.s)(),c=(0,i.useRef)(null),d=(0,i.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
|
|
21
21
|
var NONCE=${JSON.stringify(n)},TYPE=${JSON.stringify(ht)},EXIT=${JSON.stringify(hn)};
|
|
22
22
|
var host=window.parent;
|
|
23
23
|
if(document.currentScript)document.currentScript.remove();
|
|
@@ -66,7 +66,7 @@ window.addEventListener("keydown",function(e){if(e.key==="Escape"){block(e);host
|
|
|
66
66
|
})();`)}</script>`,i=-1;for(let t of e.matchAll(/<\/body>/gi))i=t.index;return i<0?e+r:e.slice(0,i)+r+e.slice(i)}(e,t)}},[n,e]),u=d.nonce,[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)(""),g=n&&m===u?p:null;return(0,i.useEffect)(()=>{if(!n)return;let e=e=>{let t=function(e,t,n,r){var i;if(!n||e!==n||!r||!t||"object"!=typeof t||t.nonce!==r)return null;if(t.type===hn)return{kind:"exit"};if(t.type!==ht)return null;let{selector:a,tag:s,id:o,classes:l,text:c,startTag:d}=t;if(!hr(a,1e3)||0===a.length||!hr(s,64)||!/^[a-z][a-z0-9-]*$/.test(s)||!hr(o,256)||!hr(c,160)||!hr(d,300)||!Array.isArray(l)||l.length>32||!l.every(e=>hr(e,128)))return null;let u=(i=t.rect)&&"object"==typeof i&&hi(i.x)&&hi(i.y)&&hi(i.w)&&hi(i.h)&&!(i.w<0)&&!(i.h<0)?{x:i.x,y:i.y,w:i.w,h:i.h}:null,p=t.viewport;return u&&p&&"object"==typeof p&&hi(p.w)&&hi(p.h)&&!(p.w<=0)&&!(p.h<=0)?{kind:"pick",element:{selector:a,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 a();h(t.element),f(u)}};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)},[u,a,n]),(0,r.jsxs)("div",{className:"html-pick-shell",children:[n&&(0,r.jsxs)("div",{className:"html-pick-bar","aria-label":l("files.pickedElement"),role:"group",children:[g?(0,r.jsxs)("p",{className:"html-pick-summary",title:`${g.selector}${g.text?`
|
|
67
67
|
${g.text}`:""}`,children:[(0,r.jsxs)("span",{className:"html-pick-tag",children:["<",g.tag,">"]}),g.text&&(0,r.jsxs)("span",{className:"html-pick-text",children:[' \xb7 "',g.text,'"']}),(0,r.jsx)("span",{className:"html-pick-selector",children:g.selector})]}):(0,r.jsx)("p",{className:"html-pick-summary html-pick-hint",children:l("files.pickElementHint")}),(0,r.jsxs)("div",{className:"html-pick-actions",children:[(0,r.jsx)(s.r,{variant:"neutralSolid",size:"small",disabled:!g,onClick:()=>g&&o(g),children:l("files.requestElementEdit")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"small",disabled:!g,onClick:()=>h(null),children:l("files.clearPick")})]})]}),(0,r.jsx)("iframe",{ref:c,className:"html-pick-frame",srcDoc:d.srcDoc,sandbox:"allow-scripts",title:t},u||"plain")]})}let hs={source:"Source",preview:"Preview",diff:"Diff"},ho={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},hl={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 hc(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function hd(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function hu(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=hd(n.startContainer),i=hd(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let a=Number(r.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(a)||!Number.isInteger(s))return null;if(a<s){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return a>s?null:{startLine:a,endLine:s}}function hp({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,a)=>{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,r.jsxs)("span",{className:"file-source-line","data-line-number":a+1,style:{display:"flex",minWidth:"100%"},children:[c&&(0,pZ.Ay)({node:c,stylesheet:t,useInlineStyles:n,key:`source-line-number-${a}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:d.map((e,r)=>(0,pZ.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${a}-${r}`}))})]},`source-line-${a}`)})}let hh=(0,i.memo)(function({content:e,language:t,isDark:n,wrapLines:i}){return(0,r.jsx)(tD.A,{className:i?"file-source-view is-wrapped":"file-source-view",language:"text"===t?"plaintext":t,style:n?tH.xJ:tH.vs,showLineNumbers:!0,lineNumberStyle:{...hl},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...ho,width:i?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:i?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(hp,{...e,wrapLines:i}),wrapLongLines:i,children:e})});function hm(e,t,n,r={}){let i=tz(e),a=new URLSearchParams({type:t});for(let[e,t]of(n&&a.set("sessionId",n),Object.entries(r)))void 0!==t&&a.set(e,String(t));return`/api/files/${i}?${a.toString()}`}let hf=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),hg=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]}),hx=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M4 4h6M4 4v6M20 4h-6M20 4v6M4 20h6M4 20v-6"}),(0,r.jsx)("path",{d:"m13 13 7 3-3 1-1 3z"})]});function hv({filePath:e,cwd:t,sourceSessionId:n,meta:i,watching:a,viewSwitch:s,actions:o=[],downloadable:l=!0}){let{t:c}=(0,z.s)(),d=tW(e),u=tO(e,t),p=u.endsWith(d)?u.slice(0,u.length-d.length).replace(/[\\/]+$/,""):"",h=c(a?"panel.liveSync":"i18n.notWatching");return(0,r.jsx)(p9,{title:d,titleTooltip:`${u}
|
|
68
68
|
${i}`,titleAdornment:null===a?void 0:(0,r.jsx)("span",{className:"panel-header-live",role:"img","aria-label":h,"data-live":a?"true":"false",title:h}),subtitle:p||void 0,subtitleKind:"path",viewSwitch:s,actions:l?[...o,{id:"download",label:c("i18n.downloadFile"),icon:hf,href:hm(e,"download",n),download:d}]:o})}function hb(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function hy({patch:e}){let t,{t:n}=(0,z.s)(),i=(t=iS(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let a=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)s.add(t);let o=[],l=0;for(;l<i.length;)if(s.has(l)){let e=[];for(;l<i.length&&s.has(l);)e.push(i[l]),l++;o.push({hidden:!1,lines:e})}else{let e=0;for(;l<i.length&&!s.has(l);)e++,l++;o.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...ho},children:o.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:hl,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:a,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function hw({filePath:e,cwd:t,sourceSessionId:n}){let[a,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)(0),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=(0,i.useRef)(null),g=tW(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{l(0),d(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(hm(e,"watch",n));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,n]);let x=hm(e,"read",n,o?{v:o}:void 0),v=null!=c?hb(c):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:n,watching:a,meta:[g||"image",u?`${u.w} \xd7 ${u.h}`:null,v].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:h?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:h}):(0,r.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 hk({filePath:e,cwd:t,sourceSessionId:n}){let[a,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)(0),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=(0,i.useRef)(null),g=tW(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{l(0),d(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(hm(e,"watch",n));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,n]);let x=hm(e,"read",n,o?{v:o}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:n,watching:a,meta:[g||"audio",null!=u?function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}(u):null,null!=c?hb(c):null].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[h&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:h}),(0,r.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 hj({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,z.s)(),[s,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(0),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eB(e),g="pdf"===f,x=g?hm(e,"read",n,l?{v:l}:void 0):hm(e,"preview",n,l?{v:l}:void 0);return(0,i.useEffect)(()=>{c(0),u(null),h(null),o(!1),m.current&&(m.current.close(),m.current=null),fetch(hm(e,"meta",n)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(hm(e,"watch",n));return m.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!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,n]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:n,watching:s,meta:["docx"===f?"docx preview":"pdf",null!=d?hb(d):null].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:tW(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function hS({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,onInsertText:o,gitRefreshKey:l,initialDisplayMode:c,viewStateStore:d,viewStateKey:u}){return eq(e)?(0,r.jsx)(hw,{filePath:e,cwd:t,sourceSessionId:n}):null!==(eU[eB(e)]??null)?(0,r.jsx)(hk,{filePath:e,cwd:t,sourceSessionId:n}):eV(e)?(0,r.jsx)(hj,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(hC,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,onInsertText:o,gitRefreshKey:l,initialDisplayMode:c,viewStateStore:d,viewStateKey:u})}function hC({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:a,onMentionLines:s,onAtMention:o,onInsertText:l,gitRefreshKey:c,initialDisplayMode:d,viewStateStore:u,viewStateKey:p}){let h,m,{isDark:f}=ng(),{t:g}=(0,z.s)(),x=p?u?.get(p):void 0,v=(0,i.useCallback)(e=>{u&&p&&u.set(p,{...u.get(p),...e})},[p,u]),b=x?.mode,[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,T]=(0,i.useState)(!0),[I,M]=(0,i.useState)(null),[R,E]=(0,i.useState)("source"),[$,L]=(0,i.useState)(!1),[P,A]=(0,i.useState)(!1),_=(0,i.useCallback)(()=>A(!1),[]),[F,W]=(0,i.useState)(!1),O=(0,i.useRef)(null),D=(0,i.useRef)(0),H=(0,i.useRef)(null),[U,B]=(0,i.useState)(null),q=(0,i.useCallback)(e=>fetch(hm(e,"read",n)).then(e=>e.json()).then(e=>e.error?(M(e.error),null):(M(null),w(e),e)).catch(e=>(M(String(e)),null)),[n]),V=(0,i.useCallback)(async e=>{let n=++D.current;if(C(!0),!t){j(null),C(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),a=await i.json();if(n!==D.current)return;j(i.ok&&a.supported&&"string"==typeof a.patch?a:null)}catch{n===D.current&&j(null)}finally{n===D.current&&C(!1)}},[t]);(0,i.useEffect)(()=>{T(!0),M(null),w(null),j(null),E("source"),L(!1),W(!1),O.current&&(O.current.close(),O.current=null),q(e).finally(()=>T(!1));let t=new EventSource(hm(e,"watch",n));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,n]),(0,i.useEffect)(()=>{V(e)},[V,e,c]),(0,i.useEffect)(()=>{let e=y?.language==="markdown"||y?.language==="html";if(b){"preview"===b&&e&&E("preview");return}e&&"diff"!==d&&E("preview")},[y?.language,d,b]);let K=k?.supported===!0&&"string"==typeof k.patch,G=K&&"deleted"===k.status;(0,i.useEffect)(()=>{K||"diff"!==R||E("source")},[R,K]),(0,i.useEffect)(()=>{G&&O.current&&(O.current.close(),O.current=null,W(!1))},[G]);let J=(0,i.useRef)(!1);(0,i.useEffect)(()=>{J.current=!1},[e]),(0,i.useEffect)(()=>{(b?"diff"===b:"diff"===d)&&K&&!J.current&&(J.current=!0,E("diff"))},[d,K,b]);let Z=(0,i.useRef)(!1);(0,i.useEffect)(()=>{Z.current=!1},[p]);let Y=x?.scrollTop;(0,i.useEffect)(()=>{if(Z.current||!y)return;if(!Y){Z.current=!0;return}if(b&&R!==b)return;let e=requestAnimationFrame(()=>{let e=H.current;e&&(e.scrollTop=Y,Z.current=!0)});return()=>cancelAnimationFrame(e)},[y,R,b,Y]);let X=(0,i.useMemo)(()=>y?.language==="markdown"?tX(y.content):"",[y]),Q=(0,i.useMemo)(()=>y?.language==="markdown"?function(e){let t=function(e){let t=pX.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,pY.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,i.useEffect)(()=>{let e=()=>{let e=H.current,t=s&&"source"===R&&e?hu(e,window.getSelection()):null;B(e=>e?.startLine===t?.startLine&&e?.endLine===t?.endLine?e:t)};if(e(),s&&"source"===R)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[y?.content,R,s]);let ee=(0,i.useCallback)(n=>{s&&n&&s(tO(e,t),n.startLine,n.endLine)},[t,e,s]);if((0,i.useEffect)(()=>{if(!s||"source"!==R)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=H.current,r=n?hu(n,window.getSelection()):null;r&&(e.preventDefault(),ee(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[R,ee,s]),N||"diff"===d&&S&&!y)return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:n,meta:g("i18n.loading"),watching:null,downloadable:!1}),(0,r.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,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:n,meta:I,watching:null,downloadable:!1}),(0,r.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",en=y?.content??"",er="html"===et,ei="markdown"===et,ea=(m=(h=tF(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===m?"/":2===m&&/^[a-zA-Z]:\//.test(h)?h.slice(0,3):h.slice(0,m),es=en.split("\n"),eo=G?"diff":R,el=G?["diff"]:["source",...er||ei?["preview"]:[],...K?["diff"]:[]],ec=G?g("files.deleted"):`${et} \xb7 ${es.length} lines \xb7 ${hb(y.size)}`,ed=er&&"preview"===eo&&!!l,eu=ed&&P;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:n,meta:ec,watching:G?null:F,downloadable:!G,viewSwitch:{label:g("i18n.fileViewMode"),value:eo,options:el.map(e=>({value:e,label:hs[e],title:"diff"===e?g("i18n.compareHead"):void 0})),onChange:e=>{E(e),A(!1),v({mode:e})}},actions:[...o||s?[{id:"mention",label:g("files.mention"),icon:(0,r.jsx)(hc,{}),onPointerDown:e=>e.preventDefault(),onClick:()=>{U&&s?ee(U):o?.(tO(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:$?g("i18n.disableWrap"):g("i18n.enableWrap"),icon:hg,pressed:$,onClick:()=>L(e=>!e)}]:[],...ed?[{id:"pick-element",label:g("files.pickElement"),icon:hx,pressed:P,onClick:()=>A(e=>!e)}]:[]]}),(0,r.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,r.jsx)(hy,{patch:k.patch}):er&&"preview"===eo?(0,r.jsx)(ha,{content:en,title:g("i18n.htmlPreview"),picking:eu,onExitPick:_,onRequestEdit:n=>{var r,i;let a;if(!l)return;let s=tO(e,t),o=function(e,t){if(!t)return null;let n=e.indexOf(t);if(n<0||e.indexOf(t,n+1)>=0)return null;let r=1;for(let t=e.indexOf("\n");t>=0&&t<n;t=e.indexOf("\n",t+1))r+=1;return r}(en,n.startTag);l((r=null===o?d6(s,!1):d3(s,o,o),i={element:e=>g("files.pickLocatorElement",{selector:e}),text:e=>g("files.pickLocatorText",{text:e}),position:e=>g("files.pickLocatorPosition",e)},a=[r.trimEnd(),i.element(n.selector)],n.text&&a.push(i.text(n.text)),a.push(i.position({x:Math.round(n.rect.x),y:Math.round(n.rect.y),w:Math.round(n.rect.w),h:Math.round(n.rect.h),vw:Math.round(n.viewport.w),vh:Math.round(n.viewport.h)})),`${a.join("\n")}
|
|
69
|
-
`))}}):ei&&"preview"===eo?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[Q?.data&&(0,r.jsx)(p1,{data:Q.data}),(0,r.jsx)(tU.oz,{remarkPlugins:t8,rehypePlugins:t5,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===i?(0,r.jsx)(nb,{code:a.replace(/\n$/,"")}):(0,r.jsx)(nw,{code:a.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let s=a?tg(e,ea,t??ea):null;return s&&a?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(s))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...a}){delete a.node;let s="string"==typeof e?tg(e,ea,t??ea):null,o=s?hm(s,"read",n):e;return(0,r.jsx)("img",{src:o,alt:i??"",loading:"lazy",...a})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:X})]}):(0,r.jsx)(hh,{content:en,language:et,isDark:f,wrapLines:$})})]})}function hN({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:a}){let{t:s,locale:o}=(0,z.s)(),[l,c]=(0,i.useState)(null);return(0,r.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===o?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,r.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),a(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:i$(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),a(e.id)},onMouseEnter:()=>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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let hT=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],hI=new Set(hT);function hM(e){return void 0!==e&&hI.has(e)}function hR(e){if(!e)return[...hT];let t=new Set(e);return hT.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function hE(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return hM(n)?n:"inherit"}function h$(e,t){let n=e.lastIndexOf(":"),r=hM(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var hL=n(98795),hP=n.n(hL);function hA(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function h_({value:e,options:t,onChange:n,disabled:a=!1,placeholder:s="Select…",searchPlaceholder:o="Search options…",noResultsLabel:l="No matching options",ariaLabel:c,className:d,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=(0,i.useRef)([]),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(0),k=(0,i.useId)(),j=t.find(t=>t.value===e),S=(0,i.useMemo)(()=>{let e=hA(v.trim());return e?t.filter(t=>hA(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,i.useEffect)(()=>{g?requestAnimationFrame(()=>m.current?.focus()):b("")},[g]),(0,i.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{g&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=un(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),T=e=>{e.disabled||(n(e.value),x(!1))},I=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${hP().root}${d?` ${d}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:hP().trigger,disabled:a,"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,r.jsx)("span",{className:j?hP().value:hP().placeholder,children:j?.label??(e||s)}),(0,r.jsx)("svg",{className:hP().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:hP().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,r.jsxs)("div",{className:hP().searchWrap,children:[(0,r.jsxs)("svg",{className:hP().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:hP().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,r.jsx)("div",{id:k,className:hP().options,role:"listbox","aria-label":c,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:hP().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>T(t),children:[(0,r.jsxs)("span",{className:hP().optionCopy,children:[(0,r.jsx)("span",{className:hP().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:hP().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:hP().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:hP().empty,children:l})})]})]})}let hF=["global","project"],hz=["implSol","implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet","crossReviewOpenAI","crossReviewAnthropic","crossReviewAdvisory","preflightAnthropic","skim","draft","ocr","interpreter"];function hW(e){return`${e.provider}/${e.id}`}function hO({cwd:e,onRolesChanged:t}){let{t:n}=(0,z.s)(),[a,s]=(0,i.useState)([]),[o,l]=(0,i.useState)([]),[c,d]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){s([]),l([]),d({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let a=await r.json();if(a.error)throw Error(a.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();s(a.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,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(a.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>a.filter(e=>!e.hidden),[a]),k=w.some(e=>hz.includes(e.role)&&!e.selector);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")}),!h&&k&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:n("roles.harnessNote")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",overflow:"hidden"},children:hF.map(e=>(0,r.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:h$(e.selector??"","inherit"),i=hE(e.selector),a=hR(c[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=hz.includes(e.role);return(0,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:"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,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),s&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:n(`roles.harness.${e.role}`)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:s&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(h_,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let n=o.find(e=>hW(e)===t),r=n?c[`${n.provider}:${n.id}`]:void 0,i=hE(e.selector),a=hR(r).includes(i)?i:"inherit";y(e.role,h$(t,a))},options:[{value:"",label:n("roles.unset")},...o.map(e=>({value:hW(e),label:`${e.name} — ${e.provider}`,searchText:hW(e)})),...t&&!o.some(e=>hW(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:a.map(a=>{let s=i===a;return(0,r.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===a?n("roles.thinkingInherit"):a,onClick:()=>{s||y(e.role,h$(t,a))},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:a},a)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function hD(e){window.open(e,"_blank","noopener,noreferrer")}var hH=n(67381),hU=n(64433),hB=n(70350),hq=n(88195),hV=n(9312),hK=n(87275),hG=n(22008),hJ=n(95476),hZ=n(35029),hY=n(14489),hX=n(78728),hQ=n(19872),h0=n(7751),h1=n(92526),h2=n(48238),h8=n(57794),h4=n(41098),h5=n(84604),h6=n(15315),h3=n(74278),h7=n(55457),h9=n(71437),me=n(29167),mt=n(97283),mn=n(34166),mr=n(33889),mi=n(85486),ma=n(74068),ms=n(83546),mo=n(83709);let ml={anthropic:{Icon:hH.A,hasColor:!1},openai:{Icon:hU.A,hasColor:!1},"openai-codex":{Icon:hU.A,hasColor:!1},google:{Icon:hB.A,hasColor:!0},"google-vertex":{Icon:hB.A,hasColor:!0},"ant-ling":{Icon:mr.A,hasColor:!0},deepseek:{Icon:hq.A,hasColor:!0},groq:{Icon:hV.A,hasColor:!1},mistral:{Icon:hK.A,hasColor:!0},moonshotai:{Icon:hG.A,hasColor:!1},"moonshotai-cn":{Icon:hG.A,hasColor:!1},moonshot:{Icon:hG.A,hasColor:!1},minimax:{Icon:hJ.A,hasColor:!0},"minimax-cn":{Icon:hJ.A,hasColor:!0},fireworks:{Icon:hZ.A,hasColor:!0},huggingface:{Icon:hY.A,hasColor:!0},cerebras:{Icon:hX.A,hasColor:!0},openrouter:{Icon:hQ.A,hasColor:!1},xai:{Icon:h0.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:h1.A,hasColor:!0},"cloudflare-workers-ai":{Icon:h1.A,hasColor:!0},"vercel-ai-gateway":{Icon:h2.A,hasColor:!1},"github-copilot":{Icon:h8.A,hasColor:!1},"amazon-bedrock":{Icon:h4.A,hasColor:!0},"azure-openai-responses":{Icon:h5.A,hasColor:!0},"kimi-coding":{Icon:h6.A,hasColor:!0},nvidia:{Icon:mi.A,hasColor:!0},opencode:{Icon:ma.A,hasColor:!1},"opencode-go":{Icon:ma.A,hasColor:!1},qwen:{Icon:h3.A,hasColor:!0},xiaomi:{Icon:ms.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:ms.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:ms.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:ms.A,hasColor:!1},zai:{Icon:mo.A,hasColor:!1},"zai-coding-cn":{Icon:mo.A,hasColor:!1},zhipu:{Icon:h7.A,hasColor:!0},cohere:{Icon:h9.A,hasColor:!0},perplexity:{Icon:me.A,hasColor:!0},together:{Icon:mt.A,hasColor:!0},grok:{Icon:mn.A,hasColor:!1}},mc=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function md({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let mu={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 mp({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...mu,fontFamily:i?"var(--font-mono)":"inherit"}})}function mh({value:e,onChange:t,placeholder:n,mono:a,onKeyDown:s,autoComplete:o="off",spellCheck:l=!1,style:c}){let[d,u]=(0,i.useState)(!1),{t:p}=(0,z.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:d?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:n,style:{...mu,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:o,spellCheck:l}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(d?"i18n.hideDetails":"i18n.showDetails"),title:p(d?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:d?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function mm({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:mu})}function mf({value:e,onChange:t,options:n,required:i}){let{t:a}=(0,z.s)();return(0,r.jsx)(h_,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${a("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function mg({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function mx({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function mv({name:e,provider:t,onChange:n,onRename:a,onDelete:s,onAddModels:o}){let{t:l}=(0,z.s)(),[c,d]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>d(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==x.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),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,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:l("i18n.provider")}),(0,r.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,r.jsxs)(md,{label:l("i18n.providerName"),children:[(0,r.jsx)(mp,{value:c,onChange:d,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,r.jsx)("button",{onClick:()=>a(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,r.jsx)(md,{label:"Base URL",children:(0,r.jsx)(mp,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(md,{label:"API Key",children:[(0,r.jsx)(mh,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(md,{label:"API",children:(0,r.jsx)(mf,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:mc,required:!0})}),(0,r.jsxs)(md,{label:"Headers",children:[(0,r.jsx)(mj,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"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,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:l("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":l("models.discoveryFilter"),style:{...mu,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked: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,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:l("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?l("models.discoveryShowing",{shown:C.length,total:S.length}):l("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(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 mb=["off","minimal","low","medium","high","xhigh","max"],my={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function mw({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:mb.map(e=>{let t=n[e],a=e in n?null===t?"null":"string":"omit",s="string"==typeof t?t:"",o=my[e],l={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:"var(--radius-control)",background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0,opacity:"null"===a?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===a?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===a?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...l,..."omit"===a?c:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...l,borderLeft:"1px solid var(--border)",..."null"===a?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:`1px solid ${"string"===a?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,s||e),style:{...l,..."string"===a?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:s,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==a&&i(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===a?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===a?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let mk={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function mj({headers:e,onChange:t}){let[n,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),s=(0,i.useRef)(n.length),o=e=>{a(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},l=(e,t)=>{o(n.map(n=>n.id===e?{...n,...t}:n))},c={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>l(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...mu,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>l(e.id,{value:t.target.value}),placeholder:"value",style:{...mu,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void o(n.filter(e=>e.id!==t))},style:c,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>a(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 mS({providerName:e,provider:t,model:n,onChange:a,onDelete:s}){let[o,l]=(0,i.useState)({phase:"idle"}),{t:c}=(0,z.s)(),[d,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>a({...n,[e]:t}),f=(()=>{if("idle"===o.phase)return null;if("testing"===o.phase)return c("i18n.testingModel");let e=[void 0!==o.latencyMs?`${o.latencyMs}ms`:null,void 0!==o.status?`HTTP ${o.status}`:null].filter(Boolean);return"success"===o.phase?[c("i18n.connected"),...e,o.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,o.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{l({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==o.phase){l({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.json();if(!r.ok||!i.ok)return void l({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});l({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,o.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===d.phase)return;let i=++p.current;u({phase:"loading"});try{let s=new URLSearchParams({q:r,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(i!==p.current)return;if(!o.ok||l.error||!l.recommendation)return void u({phase:"error",message:l.error??`HTTP ${o.status}`});let c=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},a=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],a=!0,r+=1);a&&(n.cost=i)}return{model:n,appliedCount:r}}(n,l.recommendation.preset);c.appliedCount>0&&(h.current=n,a(c.model)),u({phase:"success",recommendation:l.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[d.phase,n,a,t.baseUrl,e]),v=(()=>{if("success"!==d.phase)return null;let{recommendation:t,appliedCount:n}=d,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?c("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?c("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):c("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),b="error"===d.phase?d.message:v,y="error"===d.phase?"#ef4444":"success"===d.phase&&"unreliable"===d.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:c("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===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,r.jsxs)("button",{onClick:g,disabled:!n.id.trim()||"testing"===o.phase,title:c("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===o.phase?"#16a34a":"none",border:`1px solid ${"success"===o.phase?"#16a34a":"var(--border)"}`,borderRadius:"var(--radius-control)",color:"success"===o.phase?"#fff":n.id.trim()&&"testing"!==o.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==o.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===o.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===o.phase?c("i18n.checking"):"success"===o.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)("button",{onClick: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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(md,{label:"ID *",children:(0,r.jsx)(mp,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(md,{label:"Name",children:(0,r.jsx)(mp,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===d.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==d.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==d.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===d.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,a(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsx)(md,{label:"API override",children:(0,r.jsx)(mf,{value:n.api??"",onChange:e=>m("api",e||void 0),options:mc})}),(0,r.jsxs)(md,{label:"Headers",children:[(0,r.jsx)(mj,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(mg,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(mg,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(mg,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...mk}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(mg,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>a({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(mx,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,r.jsx)(mw,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(md,{label:"Context window (tokens)",children:(0,r.jsx)(mm,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(md,{label:"Max output tokens",children:(0,r.jsx)(mm,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(mx,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(md,{label:e,children:(0,r.jsx)(mm,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void a({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let mC={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function mN({provider:e,onRefresh:t,relogin:n}){let a=n?.onLoginSucceeded,[s,o]=(0,i.useState)({phase:"idle"}),{t:l}=(0,z.s)(),[c,d]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=void 0!==n;(0,i.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{o({phase:"idle"}),d(""),u.current?.close(),u.current=null},[e.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,i.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,d(""),o({phase:"success"}),t(),a?.())},[t,a]),x=(0,i.useCallback)(t=>{u.current?.close(),p.current=!1,o({phase:"connecting"}),d("");let n=void 0!==t,r=n?`?login=${encodeURIComponent(t)}`:"",i=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}${r}`);u.current=i,i.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:n,progress:null}),hD(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}),hD(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?(i.close(),o({phase:"error",message:t.message})):"cancelled"===t.type&&(i.close(),o({phase:"idle"}))},i.onerror=()=>{i.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,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),o({phase:"idle"}),t()},[e.id,t]),b=(0,i.useCallback)(async(t,n,r)=>{o({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})}),i=await r.json().catch(()=>({}));if(!r.ok)return void o({phase:"error",message:i.error??`Server error ${r.status}`});if(d(""),"success"===i.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,i.useCallback)(async(e,t)=>{t.trim()&&await b(e,t.trim(),"Verifying…")},[b]),w=(0,i.useCallback)(async(e,t)=>{await b(e,t,"Continuing…")},[b]),k="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:l("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:l(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),n&&(0,r.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,r.jsx)(ik,{seed:n.target.seed,size:32,provider:n.target.provider}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:l("relogin.title")}),(0,r.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[n.target.alias,n.target.masked&&(0,r.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:n.target.masked})]}),n.target.reason&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:n.target.reason})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n?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,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),"auth"===s.phase&&s.device&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:l("i18n.deviceLoginGuide")}),s.instructions&&(0,r.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===s.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":s.message}),"auth"===s.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:h,value: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,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(n?(0,r.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("relogin.done")}),n.outcome&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===n.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===n.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:l(mC[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:l("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,r.jsx)("button",{onClick:()=>{u.current?.close(),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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:m,onClick:()=>x(),style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"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,r.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&&!n&&(0,r.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 mT({provider:e,onRefresh:t}){let[n,a]=(0,i.useState)(""),[s,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,z.s)();(0,i.useEffect)(()=>{a(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){o(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(a(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{o(!1)}}},[n,e.id,t]),g=(0,i.useCallback)(async()=>{c(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{c(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,r.jsx)(md,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(mh,{value:n,onChange:a,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:s||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:"var(--radius-control)",color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:s||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":s?"i18n.saving":"i18n.save")]})]})}),d&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:d}),e.configured&&(0,r.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 mI({id:e,size:t}){let n=ml[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:"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:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}let mM={display:"flex",alignItems:"center",width:"100%",borderRadius:"var(--radius-control)",border:"none",cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},mR={padding:"6px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.04em"};function mE({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:a,onAddCustom:s,onClose:o}){let[l,c]=(0,i.useState)(""),{t:d}=(0,z.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=l.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),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,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&o()},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:u,value:l,onChange:e=>c(e.target.value),onKeyDown:e=>{"Escape"===e.key&&o()},placeholder:d("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:d("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.custom")}),f&&(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(mI,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{a(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(mI,{id:e.id,size:28})]},e.id))]})})]})})}function m$({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:a,relogin:s}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,i.useState)({providers:{}}),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[j,S]=(0,i.useState)([]),[C,N]=(0,i.useState)([]),[T,I]=(0,i.useState)(!1),M=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),R=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>N(e.providers)).catch(()=>{})},[]),E=(0,i.useCallback)(()=>{M(),R()},[M,R]);(0,i.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)),E()},[E]);let $=(0,i.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,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),P=(0,i.useCallback)((e,t)=>{d(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),k(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),A=(0,i.useCallback)(e=>{d(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),d(e=>{let t=Object.keys(e.providers??{});return k(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),_=(0,i.useCallback)(e=>{d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return k({type:"model",providerName:e,index:n}),t})},[]),F=(0,i.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],a=new Set(i.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),W=(0,i.useCallback)((e,t,n)=>{d(r=>{let i=r.providers?.[e]??{},a=[...i.models??[]];return a[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:a}}}})},[]),O=(0,i.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),k({type:"provider",name:e})},[]),D=(0,i.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),a?.(),setTimeout(()=>y(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[c,a]),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,r.jsx)(hO,{cwd:e??null,onRolesChanged:a});if("oauth"===w.type){let e=j.find(e=>e.id===w.providerId);return e?(0,r.jsx)(mN,{provider:e,onRefresh:E,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,r.jsx)(mT,{provider:e,onRefresh:E},e.id):null}if("provider"===w.type){let e=c.providers?.[w.name];return e?(0,r.jsx)(mv,{name:w.name,provider:e,onChange:e=>L(w.name,e),onRename:e=>P(w.name,e),onDelete:()=>A(w.name),onAddModels:e=>F(w.name,e)},w.name):null}let t=c.providers?.[w.providerName],n=t?.models?.[w.index];return n?(0,r.jsx)(mS,{providerName:w.providerName,provider:t,model:n,onChange:e=>W(w.providerName,w.index,e),onDelete:()=>O(w.providerName,w.index)},`${w.providerName}-${w.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},...n?{}:{role:"dialog","aria-modal":!0,"aria-label":l("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,r.jsxs)("div",{style:{width:n?"100%":o?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":o?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.jsx)("button",{onClick:t,"aria-label":l("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.jsxs)("div",{role:"group","aria-labelledby":"models-nav-roles",children:[(0,r.jsx)("div",{id:"models-nav-roles",style:mR,children:l("models.navGroupRoles")}),(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":w?.type==="roles"?"true":void 0,onClick:()=>k({type:"roles"}),style:{...mM,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,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:l("roles.title")})]})]}),(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),(U.length>0||q.length>0)&&(0,r.jsx)("div",{id:"models-nav-accounts",style:mR,children:l("models.navGroupAccounts")}),U.map(e=>{let t=w?.type==="oauth"&&w.providerId===e.id;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"oauth",providerId:e.id}),style:{...mM,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,r.jsx)(mI,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),q.map(e=>{let t=w?.type==="apikey"&&w.providerId===e.id;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"apikey",providerId:e.id}),style:{...mM,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,r.jsx)(mI,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(U.length>0||q.length>0)&&H.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),!u&&H.length>0&&(0,r.jsx)("div",{style:mR,children:l("models.navGroupCustom")}),u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):H.map(([e,t])=>{let n=w?.type==="provider"&&w.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":n?"true":void 0,onClick:()=>k({type:"provider",name:e}),style:{...mM,gap:6,padding:"7px 8px",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{let i=w?.type==="model"&&w.providerName===e&&w.index===n;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":i?"true":void 0,onClick:()=>k({type:"model",providerName:e,index:n}),style:{...mM,gap:6,padding:"5px 8px 5px 26px",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||l("i18n.newModel")}),t.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:"var(--radius-control)",flexShrink:0},children:"T"})]},n)}),(0,r.jsx)("div",{onClick:t=>{t.stopPropagation(),_(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,r.jsxs)("span",{style:{fontSize:11},children:["+ ",l("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:K??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(x??f)&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:x??f}),(0,r.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,r.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,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:b?l("i18n.saved"):h?l("i18n.saving"):l("i18n.save")})]})]})]})}),T&&(0,r.jsx)(mE,{oauthProviders:j,apiKeyProviders:C,onSelectOAuth:e=>k({type:"oauth",providerId:e}),onSelectApiKey:e=>k({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>I(!1)})]})}function mL(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function mP(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function mA(e){let t=mP(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function m_(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function mF(e){return e?e.slice(0,8):"unknown"}function mz({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,z.s)();return(0,r.jsx)("button",{onClick:n,disabled:t,title:i(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:"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,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mW({skill:e,cwd:t,onToggle:n,toggling:i,saveError:a,updateStatus:s,checkingUpdate:o,updating:l,updateError:c,onCheckUpdate:d,onUpdate:u}){let{t:p}=(0,z.s)(),h=mP(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return mL(e)}(e.filePath)}),(0,r.jsx)(mz,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),a&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:mF(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)("button",{onClick:d,disabled:o||l,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:"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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:mF(s.latestVersion)}),(o||s&&"update-available"!==s.state)&&(0,r.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,r.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,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:c})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function mO({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:a}){let{t:s}=(0,z.s)(),[o,l]=(0,i.useState)(""),[c,d]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),m(null),d([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);d(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),a()}catch(e){v(String(e))}finally{g(null)}},[a,w,e]),N="global"===w?"~/.claude/skills/":`${mL(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:s("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value: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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.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,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),c.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=f===e.package,a=e.package.indexOf("@"),o=a>-1?e.package.slice(0,a):e.package,l=a>-1?e.package.slice(a+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function mD({cwd:e,onClose:t,embedded:n=!1}){let a=B(),{t:s}=(0,z.s)(),[o,l]=(0,i.useState)([]),[c,d]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,N]=(0,i.useState)(!1),[T,I]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[E,$]=(0,i.useState)(!0),[L,P]=(0,i.useState)({}),A=(0,i.useCallback)(async()=>{d(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(l(r),$(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&P(t=>({...t,[mA(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{d(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),R(null),A()},[e]);let _=(0,i.useCallback)(async t=>{let n=(t?[t]:o.filter(e=>!!e.install)).map(m_).filter(e=>!!e);if(0!==n.length){R(null),S(e=>new Set([...e,...n])),t||N(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){R(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||N(!1)}}},[e,o]),F=(0,i.useCallback)(async t=>{if(!t.install)return;let n=m_(t);I(n),R(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await A();let a=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:a,latestVersion:a}}))}catch(e){R(e instanceof Error?e.message:String(e))}finally{I(null)}},[e,A]),W=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);l(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&P(t=>({...t,[mA(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),O=o.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":a?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":a?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mL(e)})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!E&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===o.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===mP(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===mP(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===mP(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===mP(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===mP(e)}]){let r=o.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,a=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:a?"var(--border)":"var(--accent)",boxShadow:a?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:a?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=m_(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:s("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),a=n.filter(e=>e.disableModelInvocation),o=L[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),a.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>P(t=>({...t,[e]:!o})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:o?"▾":"▸"}),s("i18n.dormant")," (",a.length,")"]}),o&&a.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:"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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(mO,{cwd:e,projectResourcesLoaded:E,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:()=>{A()}}):c?null:O?(0,r.jsx)(mW,{skill:O,cwd:e,onToggle:W,toggling:f.has(O.filePath),saveError:x,updateStatus:m_(O)?w[m_(O)]:void 0,checkingUpdate:!!m_(O)&&j.has(m_(O)),updating:T===m_(O),updateError:M,onCheckUpdate:()=>void _(O),onUpdate:()=>void F(O)},O.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.some(e=>!!e.install)&&(0,r.jsx)("button",{onClick:()=>void _(),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,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?s("i18n.update"):s("i18n.updates")]})]}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("i18n.close")})]})]})})}let mH="global";function mU(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function mB(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function mq(e){return`${e.scope}\0${e.source}`}function mV(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function mK(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function mG(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function mJ({pkg:e}){let{t}=(0,z.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function mZ({scope:e}){return(0,r.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 mY(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 mX({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,title:i,"aria-label":i,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:"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,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mQ({installDir:e,source:t,busy:n,actionError:a,onSourceChange:s,onInstall:o}){let{t:l}=(0,z.s)(),c=(0,i.useRef)(null);return(0,i.useEffect)(()=>{c.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:l("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mU(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:c,value:t,onChange:e=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=mB(t);n!==t&&(e.preventDefault(),s(n))},onBlur:e=>s(mB(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()&&!n&&o()}})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,r.jsx)("button",{type:"button",onClick:o,disabled:n||!t.trim(),style:{...mY(n||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:l(n?"i18n.installing":"i18n.install")})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:"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))})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function m0({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:a,sessionId:s,onAction:o,onReloadSession:l}){let{t:c}=(0,z.s)(),d=mq(e),u=n?.endsWith(d)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(mX,{enabled:h,loading:u||p,onToggle:()=>o(e.disabled?"enable":"disable",e),label:c(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(mZ,{scope:e.scope}),e.disabled?(0,r.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,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>o("update",e),disabled:u||p,style:mY(u||p),children:c(n===`update:${d}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:l,disabled:!s||p||u,style:mY(!s||p||u),title:c(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:c(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>o("remove",e),disabled:u||p,style:mY(u||p,!0),children:c(n===`remove:${d}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.status")}),(0,r.jsx)("div",{style:{color:mG(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:mK(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??c("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:mV(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?mU(e.installedPath):c("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mU(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:c("i18n.resolvedResources")}),(0,r.jsx)(mJ,{pkg:e})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function m1({cwd:e,sessionId:t,onClose:n,onReloaded:a,embedded:s=!1}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),T=(0,i.useMemo)(()=>c?.packages??[],[c?.packages]),I=T.find(e=>mq(e)===f)??null,M=c?.projectResourcesLoaded??!0,R=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:T.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[T]),E=(0,i.useCallback)(async()=>{p(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);d(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>mq(t)===e)?e:n.packages[0]?mq(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let $=(0,i.useCallback)(async(t,n)=>{let r=mq(n);k(`${t}:${r}`),S(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);if(d(i),"remove"===t)g(i.packages[0]?mq(i.packages[0]):null),0===i.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,i.useCallback)(async()=>{let t=mB(b).trim();if(!t)return;y(t);let n=`${mH}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,a,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:mH,cwd:e})}),o=await s.json();if(!s.ok||o.error)throw Error(o.error??`HTTP ${s.status}`);d(o);let c=(r=o.packages,a=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===mH&&e.source===i)??r.find(e=>e.scope===mH&&e.source===`npm:${a}`)??r.find(e=>e.scope===mH&&e.source.endsWith(i)));g(c?mq(c):n),v(!1),y(""),N(l("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,l]),P=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await uJ(t,{type:"reload"}),a?.(),await E(),N(l("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,a,t,l]),A=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:s?"100%":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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mU(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:l("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:o?"100%":245,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===T.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):R.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=mq(e),n=!x&&f===t;return(0,r.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:mG(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mV(e,l)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mK(e,l)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("button",{type:"button",onClick:()=>{v(!0),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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),l("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(mQ,{installDir:c?.installDir,source:b,busy:A,actionError:j,onSourceChange:y,onInstall:L}):u?null:I?(0,r.jsx)(m0,{pkg:I,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:$,onReloadSession:P},mq(I)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:c?.diagnostics.length?(0,r.jsxs)("span",{title:c.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:c.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[c.diagnostics.length," diagnostic",1===c.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:c?`${c.totals.extensions} ext \xb7 ${c.totals.skills} skills \xb7 ${c.totals.prompts} prompts \xb7 ${c.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:mY(u||null!==w),children:l("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:mY(!1),children:l("i18n.close")})]})]})})}var m2=n(13004),m8=n.n(m2);function m4(){let[e,t]=(0,i.useState)(null),[n,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,f]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),o(null),c(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);return t(i),i}catch(e){return o(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==m)return void o("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),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,i.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&c(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,i.useCallback)(async()=>{await x("clear")&&c("The stored password was removed and password access is off.")},[x]);if(!e)return(0,r.jsx)("div",{className:m8().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!d&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:m8().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,r.jsxs)("div",{className:m8().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),l&&(0,r.jsx)("div",{className:m8().reloadNotice,children:(0,r.jsx)("span",{children:l})})]}),(0,r.jsxs)("div",{className:m8().settingsBody,children:[(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:m8().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!e.configured&&!w&&(0,r.jsx)("div",{className:m8().settingDescription,children:"Set a password below before turning this on."}),s&&(0,r.jsx)("div",{className:m8().error,children:s})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("button",{type:"button",className:m8().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:d||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:m8().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("input",{className:m8().textInput,type:"password",autoComplete:"new-password",value:p,disabled:d||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:m8().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("input",{className:m8().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,r.jsxs)("div",{className:m8().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:m8().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:m8().dangerButton,disabled:d,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:m8().primaryButton,disabled:!k,onClick:()=>void v(),children:d?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:m8().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("a",{className:m8().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:m8().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,r.jsx)("div",{className:m8().settingControl})]})]})]})]})}let m5="/api/live/voices";function m6(){let{t:e}=(0,z.s)(),[t,n]=(0,i.useState)(null),[a,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)(null),c=(0,i.useCallback)(async()=>{try{let e=await fetch(m5,{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 r=da.includes(t.pace)?t.pace:"normal";n({voices:t.voices,defaultVoice:t.defaultVoice,pace:r})}catch(e){l(e instanceof Error?e.message:String(e))}},[]);(0,i.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})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let i="string"==typeof r.value?r.value:e;n(e=>e?{...e,defaultVoice:i}: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(m5,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pace:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);n(t=>t?{...t,pace:r.pace??e}:t)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(!1)}};return t?(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:m8().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:e("chat.liveVoiceSpeakerGroup")}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{className:m8().settingLabel,children:e("chat.liveVoiceCodexLabel")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.liveVoiceCodexHelp")}),o&&(0,r.jsx)("div",{className:m8().error,role:"alert",style:{overflowWrap:"anywhere"},children:o})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)(h_,{value:t.defaultVoice,disabled:a,ariaLabel:e("chat.liveVoiceCodexLabel"),options:t.voices,onChange:e=>{e!==t.defaultVoice&&d(e)}})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{className:m8().settingLabel,children:e("chat.livePaceLabel")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.livePaceHelp")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)(h_,{value:t.pace,disabled:a,ariaLabel:e("chat.livePaceLabel"),options:[{value:"normal",label:e("chat.livePaceNormal")},{value:"slow",label:e("chat.livePaceSlow")}],onChange:e=>{e!==t.pace&&da.includes(e)&&u(e)}})})]})]})})]}):(0,r.jsx)("div",{className:m8().empty,children:o?`${e("chat.liveVoiceLoadFailed")}: ${o}`:"…"})}function m3(){let{t:e}=(0,z.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[a,s]=(0,i.useState)(null),[o,l]=(0,i.useState)(""),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return d1({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,i.useCallback)(async e=>{p(!0),d(null),m(!1);try{let t=await d2(e);s(t),l(String(t.uploadLimitMb)),m(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return a?(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:m8().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:m8().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("input",{id:t,className:m8().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(a.uploadLimitMb))return;let n=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n<1){m(!1),d(e("chat.attachmentUploadLimitInvalid"));return}f({uploadLimitMb:n})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:m8().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:a.orphanGraceDays})})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("button",{type:"button",className:m8().switch,"data-on":a.autoCleanupEnabled,"aria-pressed":a.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!a.autoCleanupEnabled})})})]}),c&&(0,r.jsx)("div",{className:m8().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),h&&!c&&(0,r.jsx)("div",{className:m8().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:m8().empty,children:c?`${e("chat.attachmentSettingsLoadFailed")}: ${c}`:"…"})}function m7(){let{t:e}=(0,z.s)(),t=(0,i.useId)(),n=ib(),[a,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1);(0,i.useEffect)(()=>{r$().then(()=>s(!0))},[]);let h=(0,i.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})}),n=await t.json().catch(()=>null);if(!t.ok)throw Error("object"==typeof n&&null!==n&&"error"in n?String(n.error):`HTTP ${t.status}`);rM(n),p(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(!1)}},[]);if(!a)return(0,r.jsx)("div",{className:m8().empty,children:"…"});let m=[{mode:"default",label:e("characterMode.default")},{mode:"office",label:e("characterMode.office")}];return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:e("characterMode.title")}),(0,r.jsx)("p",{className:m8().contentDescription,children:e("characterMode.description")})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:t,className:m8().settingLabel,children:e("characterMode.label")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("characterMode.help")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("div",{className:m8().multiSelect,role:"radiogroup","aria-labelledby":t,children:m.map(e=>(0,r.jsx)("span",{className:m8().choice,"data-selected":n.mode===e.mode,children:(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":n.mode===e.mode,className:m8().choiceToggle,disabled:o,onClick:()=>{n.mode!==e.mode&&h(e.mode)},children:e.label})},e.mode))})})]}),"office"===n.mode&&!n.rosterAvailable&&(0,r.jsx)("div",{className:m8().settingDescription,role:"status",children:e("characterMode.noRoster")}),c&&(0,r.jsx)("div",{className:m8().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),u&&!c&&(0,r.jsx)("div",{className:m8().saveState,role:"status",children:e("characterMode.saved")})]})})]})}function m9({cwd:e}){let{t}=(0,z.s)(),[n,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(new Map);(0,i.useEffect)(()=>{g&&d!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[d,n,g]);let b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let i=e?`?include=${encodeURIComponent(e)}`:"",s=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),l=await s.json();if(n!==b.current||r.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,a(l.projects),o(null),c&&f({cwd:c.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;o(e instanceof Error?e.message:String(e))}finally{y.current===r&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=n?.some(e=>null!==e.pending)??!1;(0,i.useEffect)(()=>{let e;if(!S||null!==d||null!==l)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},n=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",n),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[d,l,n,S,j]);let C=(0,i.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),c(null),x(e),f(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),i=await r.json();if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);let s=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=s,a(s),"cancel"===n?f({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(n=>({...n,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!n)return(0,r.jsxs)("div",{className:m8().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,r.jsx)("button",{type:"button",className:m8().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==d;return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:m8().contentDescription,children:t("trust.settingsDescription")}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,r.jsx)("button",{type:"button",className:m8().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,r.jsx)("div",{className:m8().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[0===n.length&&(0,r.jsx)("div",{className:m8().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=d===e.cwd,a=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,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:m8().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:m8().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,r.jsx)("span",{children:(n=e.cwd).split(/[\\/]/).filter(Boolean).pop()??n}),(0,r.jsx)("span",{className:m8().settingDescription,style:{fontWeight:600},children:s})]}),(0,r.jsx)("code",{className:m8().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:m8().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,r.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,r.jsx)("div",{className:m8().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:m8().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),a&&(0,r.jsx)("div",{className:m8().settingDescription,style:{color:"var(--text)"},children:"revoke"===a.action?t("trust.confirmRevoke"):a.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:m8().saveState,children:m.text})]}),o&&(0,r.jsx)("div",{className:m8().error,role:"alert",children:o})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:m8().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:m8().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{c(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===a.action?m8().dangerButton:m8().primaryButton,disabled:N,onClick:()=>void C(e.cwd,a.action),children:"revoke"===a.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:m8().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:m8().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,r.jsx)("button",{type:"button",className:m8().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,r.jsx)("button",{type:"button",className:m8().dangerButton,disabled:N,onClick:()=>c({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let fe="cuelo-look",ft="cuelo-look-wallpaper",fn="data-cuelo-look",fr="data-cuelo-wallpaper";function fi(e){try{return localStorage.getItem(e)}catch{return null}}function fa(e,t){try{return null===t?localStorage.removeItem(e):localStorage.setItem(e,t),!0}catch{return!1}}function fs(e,t){let n=document.documentElement;e?n.setAttribute(fn,"graphite"):n.removeAttribute(fn),e&&t?n.setAttribute(fr,t):n.removeAttribute(fr)}let fo=new Set,fl=null,fc=null;function fd(){return fl??"graphite"===fi(fe)}function fu(e){let t;fl=fa(fe,e?"graphite":null)?null:e,fs(e,fc??("default"===(t=fi(ft))||"office"===t?t:null)),fo.forEach(e=>e())}function fp(e){let t="office"===e?"office":"default";fc=fa(ft,t)?null:t,fs(fd(),t)}function fh(e){return fo.add(e),()=>{fo.delete(e)}}let fm=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이다"}}}'),ff=[{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"}],fg={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),characters:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}),attachments:(0,r.jsx)("path",{d:"m21 12-8.6 8.6a5 5 0 0 1-7-7l8.5-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9"}),appearance:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function fx({kind:e}){return(0,r.jsx)("svg",{className:m8().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:fg[e]??fg.tools})}function fv({field:e,busy:t,onSave:n}){let[a,s]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let o="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:m8().textInput,type:"secret"===e.type?"password":"text",value:a,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{a!==o&&("secret"!==e.type||a.length>0)&&n(a)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function fb({field:e,busy:t,onSave:n}){let a=JSON.stringify(e.value??{},null,2),[s,o]=(0,i.useState)(a),[l,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{o(a),c(null)},[a]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:m8().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>o(e.target.value),onBlur:()=>{if(s!==a)try{n(JSON.parse(s)),c(null)}catch(e){c(e instanceof Error?e.message:String(e))}}}),l&&(0,r.jsx)("div",{className:m8().error,children:l})]})}function fy({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],a=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let a=[...i];[a[e],a[r]]=[a[r],a[e]],n(a)};return(0,r.jsx)("div",{className:m8().multiSelect,children:e.options?.map(s=>{let o=i.indexOf(s.value);return(0,r.jsxs)("span",{className:m8().choice,"data-selected":o>=0,title:s.description,children:[(0,r.jsx)("button",{type:"button",className:m8().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:s.label}),e.ordered&&o>=0&&(0,r.jsxs)("span",{className:m8().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===o,onClick:()=>a(o,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||o===i.length-1,onClick:()=>a(o,1),children:"→"})]})]},s.value)})})}function fw({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:m8().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(h_,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(fy,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(fb,{field:e,busy:t,onSave:n}):(0,r.jsx)(fv,{field:e,busy:t,onSave:n})}function fk({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:e.label}),(0,r.jsx)("div",{className:m8().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:m8().error,children:n})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)(fw,{field:e,busy:t,onSave:i})})]})}function fj({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:m8().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:m8().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:m8().themePreviewPanel,children:[(0,r.jsx)("div",{className:m8().themePreviewLine}),(0,r.jsx)("div",{className:m8().themePreviewLine})]})]})}let fS='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',fC=new Set(["hideThinkingBlock"]);function fN({cwd:e,sessionId:t,initialSection:n="models",onClose:a,onModelsChanged:s,onReloaded:o}){let[l,c]=(0,i.useState)(n),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(new Set),[y,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),{theme:N,setPreference:T}=ng(),I={enabled:(0,i.useSyncExternalStore)(fh,fd,()=>!1),setEnabled:fu},{locale:M,t:R}=(0,z.s)(),E=(0,i.useRef)(null),$=e=>"ko"===M?fm.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{let e=E.current;if(!e)return;(Array.from(e.querySelectorAll(fS)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(fS)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let P=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await nf(e),await L()):fC.has(t.path)?await n0(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,L]),A=(0,i.useMemo)(()=>new Map(d?.fields.map(e=>[e.path,e.value])??[]),[d?.fields]),_=(0,i.useMemo)(()=>d?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,A))??[],[d?.fields,A]),F=l.startsWith("settings:")?l.slice(9):null,W=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?_.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):F?_.filter(e=>e.tab===F&&("appearance"!==F||"Theme"!==e.group)):[]},[F,g,_]),O=(0,i.useCallback)(()=>{s?.(),a()},[a,s]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await uJ(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===F),U=g.trim()?`${$("Search")} \xb7 ${W.length}`:H?.label??$("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:t}),n.map(e=>(0,r.jsx)(fk,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void P(e,t)},e.path))]},t):null}),q=()=>p?(0,r.jsx)("div",{className:m8().empty,children:$("Loading omp settings…")}):m||!d?(0,r.jsx)("div",{className:m8().empty,children:m??$("Settings unavailable")}):(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:U}),(0,r.jsx)("p",{className:m8().contentDescription,children:$(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,r.jsxs)("div",{className:m8().reloadNotice,children:[(0,r.jsx)("span",{children:$("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:$(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:W.length?B(W,H?.groups??[]):(0,r.jsx)("div",{className:m8().empty,children:$("No settings match this search.")})})]});return(0,r.jsx)("div",{className:m8().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&O()},children:(0,r.jsxs)("div",{ref:E,tabIndex:-1,className:m8().window,role:"dialog","aria-modal":"true","aria-label":$("Settings"),children:[(0,r.jsxs)("aside",{className:m8().sidebar,children:[(0,r.jsxs)("div",{className:m8().brand,children:[(0,r.jsx)("div",{className:m8().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:m8().title,children:$("Settings")}),(0,r.jsx)("code",{className:m8().context,title:e??$("Global configuration"),children:e??$("Global configuration")})]}),(0,r.jsxs)("div",{className:m8().searchWrap,children:[(0,r.jsxs)("svg",{className:m8().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:m8().search,value:g,"aria-label":$("Search /settings"),placeholder:$("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:m8().nav,children:[(0,r.jsx)("div",{className:m8().navLabel,children:$("Configuration")}),ff.map(t=>{let n=t.labelKey?R(t.labelKey):$(t.label);return(0,r.jsxs)("button",{type:"button",className:m8().navButton,"data-active":!g&&l===t.id,"aria-current":g||l!==t.id?void 0:"page",disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${$("requires a project")}`:n,onClick:()=>{x(""),c(t.id)},children:[(0,r.jsx)(fx,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:m8().navLabel,children:$("OMP settings")}),d?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:m8().navButton,"data-active":!g&&F===e.id,"aria-current":g||F!==e.id?void 0:"page",onClick:()=>{x(""),c(`settings:${e.id}`)},children:[(0,r.jsx)(fx,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:m8().closeRail,children:(0,r.jsxs)("button",{type:"button",className:m8().closeButton,onClick:O,children:[(0,r.jsx)("span",{children:$("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:m8().content,children:g.trim()?q():"models"===l?(0,r.jsx)(m$,{cwd:e,embedded:!0,onClose:O,onModelsChanged:s}):"themes"===l?d?(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:$("Themes")}),(0,r.jsxs)("p",{className:m8().contentDescription,children:[$("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),$(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:m8().settingsBody,children:[(0,r.jsx)("div",{className:m8().themeGrid,children:["dark","light"].map(e=>{let t=d.fields.find(t=>t.path===`theme.${e}`),n=d.theme.palettes[e];return(0,r.jsxs)("div",{className:m8().themeCard,children:[(0,r.jsx)(fj,{mode:e,palette:n}),(0,r.jsxs)("div",{className:m8().themeCardBody,children:[(0,r.jsxs)("div",{className:m8().themeCardHeader,children:[(0,r.jsxs)("span",{className:m8().themeSlot,children:[e,$(" mapping")]}),N===e&&(0,r.jsx)("span",{className:m8().themeActive,children:$("Active on web")})]}),(0,r.jsx)(h_,{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 P(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:m8().closeButton,style:{marginTop:8},onClick:()=>T(e),children:[$("Preview "),e]})]})]},e)})}),(0,r.jsx)("section",{className:m8().group,children:(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:"settings-graphite-label",className:m8().settingLabel,children:R("theme.graphite")}),(0,r.jsx)("div",{className:m8().settingDescription,children:R("theme.graphiteHint")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("button",{type:"button",role:"switch",className:m8().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,r.jsx)("div",{className:m8().empty,children:p?$("Loading themes…"):m??$("Themes unavailable")}):"skills"===l&&e?(0,r.jsx)(mD,{cwd:e,embedded:!0,onClose:O}):"plugins"===l&&e?(0,r.jsx)(m1,{cwd:e,sessionId:t,embedded:!0,onClose:O,onReloaded:o}):"mcp"===l?(0,r.jsx)(fT,{cwd:e,sessionId:t,onReloaded:o}):"access"===l?(0,r.jsx)(m4,{}):"trust"===l?(0,r.jsx)(m9,{cwd:e}):"live-voice"===l?(0,r.jsx)(m6,{}):"attachments"===l?(0,r.jsx)(m3,{}):"characters"===l?(0,r.jsx)(m7,{}):q()})]})})}function fT({cwd:e,sessionId:t,onReloaded:n}){let[a,s]=(0,i.useState)(null),[o,l]=(0,i.useState)("user"),[c,d]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);s(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=a?"user"===o?a.user:a.project:null,j=k?.servers[c]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(t=>{if(!t)return t;let n={..."user"===o?t.user:t.project,servers:e};return"user"===o?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===c?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,servers:n})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${o}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,name:r.name,enabled:!r.enabled})}),s=await a.json();if(!a.ok||s.error)throw Error(s.error??`HTTP ${a.status}`);await w(),t&&(await uJ(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:m8().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:a?(0,r.jsxs)("div",{className:m8().mcpLayout,children:[(0,r.jsxs)("aside",{className:m8().mcpList,children:[(0,r.jsxs)("div",{className:m8().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:m8().scopeButton,"data-active":"user"===o,onClick:()=>{l("user"),d(0)},children:["User \xb7 ",a.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:m8().scopeButton,"data-active":"project"===o,disabled:!a.project,onClick:()=>{l("project"),d(0)},children:["Project \xb7 ",a.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:m8().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:m8().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${o}:${e.name}`;return(0,r.jsxs)("div",{className:m8().serverRow,"data-active":c===t,children:[(0,r.jsxs)("button",{type:"button",className:m8().serverSelect,title:e.source?.path,onClick:()=>d(t),children:[(0,r.jsx)("span",{className:m8().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:m8().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:m8().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:m8().serverToggle,"data-on":e.enabled,disabled:b===n,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:m8().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:m8().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),d(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:m8().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:m8().editorHeader,children:[(0,r.jsx)("input",{className:m8().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:m8().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==c)),d(Math.max(0,c-1)))},children:"Delete"})]}),!1===j.editable&&(0,r.jsxs)("div",{className:m8().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:m8().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:m8().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:m8().error,children:f}),(0,r.jsx)("div",{className:m8().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:m8().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:m8().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:m8().empty,children:f??"Loading MCP configuration…"})})]})}let fI="cuelo-notification-prompt-dismissed";function fM({variant:e,locale:t,permission:n,dismissed:i,request:a,dismiss:s}){let o="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||i?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":o?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:o?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,children:o?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":o?"알림 권한 안내 닫기":"Dismiss notification prompt",children:o?"닫기":"Dismiss"})]}):(0,r.jsx)(c.k.Item,{disabled:"denied"===n,onClick:"default"===n?a:void 0,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:"default"===n?o?"알림 켜기":"Enable notifications":o?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(c.k.ItemDescription,{children:o?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function fR({cwd:e,busy:t,scheduled:n,error:a,onCancel:s,onConfirm:o,onCancelSchedule:l}){let{t:c}=(0,z.s)(),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{d.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:"var(--radius-control)",cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||s()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:c(n?"trust.scheduledTitle":"trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:c(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:a})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c("trust.cancelSchedule")}),(0,r.jsx)("button",{ref:d,type:"button",onClick:s,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c(n?"trust.close":"trust.cancel")}),!n&&(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:c(t?"trust.trusting":"trust.trustProject")})]})]})})}var fE=n(55681);let f$={kind:"loading"};function fL(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":s6(e.status)?"var(--accent)":"var(--success)"}function fP(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let fA={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function f_(e){return e.lastUpdate||e.progress?.durationMs||0}let fF=(0,r.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,r.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})}),fz=[];function fW({state:e,summary:t,reason:n,onOpenFile:i}){let{st:a}=iw(),{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,r.jsxs)("div",{className:"maker-detail-outcome",children:[n&&(0,r.jsxs)("p",{className:"maker-detail-reason",children:[(0,r.jsx)("span",{children:a("detail.reason")})," ",n]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:a("summary.heading.files")}),o?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):l.length>0?(0,r.jsx)(iL,{files:l,onOpenFile:i}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noFiles")})]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:a("summary.heading.checks")}),o?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):c.length>0?(0,r.jsx)("ul",{className:"answer-summary-list",children:c.map(e=>(0,r.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,r.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,r.jsxs)("span",{className:"answer-check-result",children:[s(fO[e.state]),null!==e.exitCode?` \xb7 ${a("summary.check.exit",{code:e.exitCode})}`:null]})]},e.toolCallId))}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noChecks")})]})]})}let fO={passed:"makerDetail.checkPassed",unverified:"makerDetail.checkUnverified",failed:"makerDetail.checkFailed",unobserved:"makerDetail.checkUnobserved"};function fD({sessionId:e,sessionCwd:t,record:n,selection:a,client:s,visible:o,onBack:l,onOpenFile:c}){let{st:d}=iw(),{t:u}=(0,z.s)(),p=n?.key,h=n?.live?.id,m=n?.live?.status,f=n?.archive?.name,g=(0,i.useMemo)(()=>p?[{key:p,liveId:h,status:m,archiveName:f}]:[],[p,h,m,f]),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=oe(g,{sessionId:e,client:s,enabled:o&&g.length>0}),y=(p?b.get(p)?.state:void 0)??f$;(0,i.useEffect)(()=>{o&&v.current?.focus({preventScroll:!0})},[a.key,o]),(0,i.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:fz,k=(0,i.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,i.useMemo)(()=>"ready-live"===y.kind?o_(y.entries,t):null,[y,t]),S=n?.live?.id||n?.archive?.name||"Subagent",C=n?i_(n).title:S,N=a.status;return(0,r.jsxs)("div",{role:"region","aria-label":u("makerDetail.region",{title:S}),style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsx)(p9,{back:{label:u("subagents.back"),onClick:l},title:C,titleTooltip:n?`${C}
|
|
69
|
+
`))}}):ei&&"preview"===eo?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[Q?.data&&(0,r.jsx)(p1,{data:Q.data}),(0,r.jsx)(tU.oz,{remarkPlugins:t8,rehypePlugins:t5,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===i?(0,r.jsx)(nb,{code:a.replace(/\n$/,"")}):(0,r.jsx)(nw,{code:a.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let s=a?tg(e,ea,t??ea):null;return s&&a?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(s))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...a}){delete a.node;let s="string"==typeof e?tg(e,ea,t??ea):null,o=s?hm(s,"read",n):e;return(0,r.jsx)("img",{src:o,alt:i??"",loading:"lazy",...a})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:X})]}):(0,r.jsx)(hh,{content:en,language:et,isDark:f,wrapLines:$})})]})}function hN({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:a}){let{t:s,locale:o}=(0,z.s)(),[l,c]=(0,i.useState)(null);return(0,r.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===o?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,r.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),a(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:i$(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),a(e.id)},onMouseEnter:()=>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,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let hT=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],hI=new Set(hT);function hM(e){return void 0!==e&&hI.has(e)}function hR(e){if(!e)return[...hT];let t=new Set(e);return hT.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function hE(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return hM(n)?n:"inherit"}function h$(e,t){let n=e.lastIndexOf(":"),r=hM(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var hL=n(98795),hP=n.n(hL);function hA(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function h_({value:e,options:t,onChange:n,disabled:a=!1,placeholder:s="Select…",searchPlaceholder:o="Search options…",noResultsLabel:l="No matching options",ariaLabel:c,className:d,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=(0,i.useRef)([]),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(0),k=(0,i.useId)(),j=t.find(t=>t.value===e),S=(0,i.useMemo)(()=>{let e=hA(v.trim());return e?t.filter(t=>hA(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,i.useEffect)(()=>{g?requestAnimationFrame(()=>m.current?.focus()):b("")},[g]),(0,i.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{g&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=un(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),T=e=>{e.disabled||(n(e.value),x(!1))},I=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${hP().root}${d?` ${d}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:hP().trigger,disabled:a,"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,r.jsx)("span",{className:j?hP().value:hP().placeholder,children:j?.label??(e||s)}),(0,r.jsx)("svg",{className:hP().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:hP().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,r.jsxs)("div",{className:hP().searchWrap,children:[(0,r.jsxs)("svg",{className:hP().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:hP().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,r.jsx)("div",{id:k,className:hP().options,role:"listbox","aria-label":c,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:hP().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>T(t),children:[(0,r.jsxs)("span",{className:hP().optionCopy,children:[(0,r.jsx)("span",{className:hP().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:hP().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:hP().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:hP().empty,children:l})})]})]})}let hF=["global","project"],hz=["implSol","implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet","crossReviewOpenAI","crossReviewAnthropic","crossReviewAdvisory","preflightAnthropic","skim","draft","ocr","interpreter"];function hW(e){return`${e.provider}/${e.id}`}function hO({cwd:e,onRolesChanged:t}){let{t:n}=(0,z.s)(),[a,s]=(0,i.useState)([]),[o,l]=(0,i.useState)([]),[c,d]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){s([]),l([]),d({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let a=await r.json();if(a.error)throw Error(a.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();s(a.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,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(a.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>a.filter(e=>!e.hidden),[a]),k=w.some(e=>hz.includes(e.role)&&!e.selector);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")}),!h&&k&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:n("roles.harnessNote")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",overflow:"hidden"},children:hF.map(e=>(0,r.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:h$(e.selector??"","inherit"),i=hE(e.selector),a=hR(c[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=hz.includes(e.role);return(0,r.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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:"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,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),s&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:n(`roles.harness.${e.role}`)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:s&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(h_,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let n=o.find(e=>hW(e)===t),r=n?c[`${n.provider}:${n.id}`]:void 0,i=hE(e.selector),a=hR(r).includes(i)?i:"inherit";y(e.role,h$(t,a))},options:[{value:"",label:n("roles.unset")},...o.map(e=>({value:hW(e),label:`${e.name} — ${e.provider}`,searchText:hW(e)})),...t&&!o.some(e=>hW(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:a.map(a=>{let s=i===a;return(0,r.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===a?n("roles.thinkingInherit"):a,onClick:()=>{s||y(e.role,h$(t,a))},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:a},a)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function hD(e){window.open(e,"_blank","noopener,noreferrer")}var hH=n(67381),hU=n(64433),hB=n(70350),hq=n(88195),hV=n(9312),hK=n(87275),hG=n(22008),hJ=n(95476),hZ=n(35029),hY=n(14489),hX=n(78728),hQ=n(19872),h0=n(7751),h1=n(92526),h2=n(48238),h8=n(57794),h4=n(41098),h5=n(84604),h6=n(15315),h3=n(74278),h7=n(55457),h9=n(71437),me=n(29167),mt=n(97283),mn=n(34166),mr=n(33889),mi=n(85486),ma=n(74068),ms=n(83546),mo=n(83709);let ml={anthropic:{Icon:hH.A,hasColor:!1},openai:{Icon:hU.A,hasColor:!1},"openai-codex":{Icon:hU.A,hasColor:!1},google:{Icon:hB.A,hasColor:!0},"google-vertex":{Icon:hB.A,hasColor:!0},"ant-ling":{Icon:mr.A,hasColor:!0},deepseek:{Icon:hq.A,hasColor:!0},groq:{Icon:hV.A,hasColor:!1},mistral:{Icon:hK.A,hasColor:!0},moonshotai:{Icon:hG.A,hasColor:!1},"moonshotai-cn":{Icon:hG.A,hasColor:!1},moonshot:{Icon:hG.A,hasColor:!1},minimax:{Icon:hJ.A,hasColor:!0},"minimax-cn":{Icon:hJ.A,hasColor:!0},fireworks:{Icon:hZ.A,hasColor:!0},huggingface:{Icon:hY.A,hasColor:!0},cerebras:{Icon:hX.A,hasColor:!0},openrouter:{Icon:hQ.A,hasColor:!1},xai:{Icon:h0.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:h1.A,hasColor:!0},"cloudflare-workers-ai":{Icon:h1.A,hasColor:!0},"vercel-ai-gateway":{Icon:h2.A,hasColor:!1},"github-copilot":{Icon:h8.A,hasColor:!1},"amazon-bedrock":{Icon:h4.A,hasColor:!0},"azure-openai-responses":{Icon:h5.A,hasColor:!0},"kimi-coding":{Icon:h6.A,hasColor:!0},nvidia:{Icon:mi.A,hasColor:!0},opencode:{Icon:ma.A,hasColor:!1},"opencode-go":{Icon:ma.A,hasColor:!1},qwen:{Icon:h3.A,hasColor:!0},xiaomi:{Icon:ms.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:ms.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:ms.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:ms.A,hasColor:!1},zai:{Icon:mo.A,hasColor:!1},"zai-coding-cn":{Icon:mo.A,hasColor:!1},zhipu:{Icon:h7.A,hasColor:!0},cohere:{Icon:h9.A,hasColor:!0},perplexity:{Icon:me.A,hasColor:!0},together:{Icon:mt.A,hasColor:!0},grok:{Icon:mn.A,hasColor:!1}},mc=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function md({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let mu={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 mp({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...mu,fontFamily:i?"var(--font-mono)":"inherit"}})}function mh({value:e,onChange:t,placeholder:n,mono:a,onKeyDown:s,autoComplete:o="off",spellCheck:l=!1,style:c}){let[d,u]=(0,i.useState)(!1),{t:p}=(0,z.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:d?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:n,style:{...mu,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:o,spellCheck:l}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(d?"i18n.hideDetails":"i18n.showDetails"),title:p(d?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:d?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function mm({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:mu})}function mf({value:e,onChange:t,options:n,required:i}){let{t:a}=(0,z.s)();return(0,r.jsx)(h_,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${a("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function mg({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function mx({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function mv({name:e,provider:t,onChange:n,onRename:a,onDelete:s,onAddModels:o}){let{t:l}=(0,z.s)(),[c,d]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>d(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==x.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),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,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:l("i18n.provider")}),(0,r.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,r.jsxs)(md,{label:l("i18n.providerName"),children:[(0,r.jsx)(mp,{value:c,onChange:d,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,r.jsx)("button",{onClick:()=>a(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,r.jsx)(md,{label:"Base URL",children:(0,r.jsx)(mp,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(md,{label:"API Key",children:[(0,r.jsx)(mh,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(md,{label:"API",children:(0,r.jsx)(mf,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:mc,required:!0})}),(0,r.jsxs)(md,{label:"Headers",children:[(0,r.jsx)(mj,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"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,r.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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:l("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":l("models.discoveryFilter"),style:{...mu,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked: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,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:l("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?l("models.discoveryShowing",{shown:C.length,total:S.length}):l("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(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 mb=["off","minimal","low","medium","high","xhigh","max"],my={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function mw({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:mb.map(e=>{let t=n[e],a=e in n?null===t?"null":"string":"omit",s="string"==typeof t?t:"",o=my[e],l={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:"var(--radius-control)",background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0,opacity:"null"===a?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===a?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===a?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...l,..."omit"===a?c:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...l,borderLeft:"1px solid var(--border)",..."null"===a?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:`1px solid ${"string"===a?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,s||e),style:{...l,..."string"===a?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:s,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==a&&i(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===a?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===a?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let mk={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function mj({headers:e,onChange:t}){let[n,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),s=(0,i.useRef)(n.length),o=e=>{a(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},l=(e,t)=>{o(n.map(n=>n.id===e?{...n,...t}:n))},c={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>l(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...mu,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>l(e.id,{value:t.target.value}),placeholder:"value",style:{...mu,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void o(n.filter(e=>e.id!==t))},style:c,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>a(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 mS({providerName:e,provider:t,model:n,onChange:a,onDelete:s}){let[o,l]=(0,i.useState)({phase:"idle"}),{t:c}=(0,z.s)(),[d,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>a({...n,[e]:t}),f=(()=>{if("idle"===o.phase)return null;if("testing"===o.phase)return c("i18n.testingModel");let e=[void 0!==o.latencyMs?`${o.latencyMs}ms`:null,void 0!==o.status?`HTTP ${o.status}`:null].filter(Boolean);return"success"===o.phase?[c("i18n.connected"),...e,o.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,o.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{l({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==o.phase){l({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.json();if(!r.ok||!i.ok)return void l({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});l({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,o.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===d.phase)return;let i=++p.current;u({phase:"loading"});try{let s=new URLSearchParams({q:r,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(i!==p.current)return;if(!o.ok||l.error||!l.recommendation)return void u({phase:"error",message:l.error??`HTTP ${o.status}`});let c=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},a=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],a=!0,r+=1);a&&(n.cost=i)}return{model:n,appliedCount:r}}(n,l.recommendation.preset);c.appliedCount>0&&(h.current=n,a(c.model)),u({phase:"success",recommendation:l.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[d.phase,n,a,t.baseUrl,e]),v=(()=>{if("success"!==d.phase)return null;let{recommendation:t,appliedCount:n}=d,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?c("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?c("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):c("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),b="error"===d.phase?d.message:v,y="error"===d.phase?"#ef4444":"success"===d.phase&&"unreliable"===d.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:c("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===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,r.jsxs)("button",{onClick:g,disabled:!n.id.trim()||"testing"===o.phase,title:c("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===o.phase?"#16a34a":"none",border:`1px solid ${"success"===o.phase?"#16a34a":"var(--border)"}`,borderRadius:"var(--radius-control)",color:"success"===o.phase?"#fff":n.id.trim()&&"testing"!==o.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==o.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===o.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===o.phase?c("i18n.checking"):"success"===o.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)("button",{onClick: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,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(md,{label:"ID *",children:(0,r.jsx)(mp,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(md,{label:"Name",children:(0,r.jsx)(mp,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===d.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==d.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==d.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===d.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,a(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsx)(md,{label:"API override",children:(0,r.jsx)(mf,{value:n.api??"",onChange:e=>m("api",e||void 0),options:mc})}),(0,r.jsxs)(md,{label:"Headers",children:[(0,r.jsx)(mj,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(mg,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(mg,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(mg,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...mk}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(mg,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>a({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(mx,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,r.jsx)(mw,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(md,{label:"Context window (tokens)",children:(0,r.jsx)(mm,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(md,{label:"Max output tokens",children:(0,r.jsx)(mm,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(mx,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(md,{label:e,children:(0,r.jsx)(mm,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void a({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let mC={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function mN({provider:e,onRefresh:t,relogin:n}){let a=n?.onLoginSucceeded,[s,o]=(0,i.useState)({phase:"idle"}),{t:l}=(0,z.s)(),[c,d]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=void 0!==n;(0,i.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{o({phase:"idle"}),d(""),u.current?.close(),u.current=null},[e.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,i.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,d(""),o({phase:"success"}),t(),a?.())},[t,a]),x=(0,i.useCallback)(t=>{u.current?.close(),p.current=!1,o({phase:"connecting"}),d("");let n=void 0!==t,r=n?`?login=${encodeURIComponent(t)}`:"",i=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}${r}`);u.current=i,i.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:n,progress:null}),hD(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}),hD(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,progress:e}:{phase:"progress",message:e})}else"success"===t.type?g():"error"===t.type?(i.close(),o({phase:"error",message:t.message})):"cancelled"===t.type&&(i.close(),o({phase:"idle"}))},i.onerror=()=>{i.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,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),o({phase:"idle"}),t()},[e.id,t]),b=(0,i.useCallback)(async(t,n,r)=>{o({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})}),i=await r.json().catch(()=>({}));if(!r.ok)return void o({phase:"error",message:i.error??`Server error ${r.status}`});if(d(""),"success"===i.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,i.useCallback)(async(e,t)=>{t.trim()&&await b(e,t.trim(),"Verifying…")},[b]),w=(0,i.useCallback)(async(e,t)=>{await b(e,t,"Continuing…")},[b]),k="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:l("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:l(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),n&&(0,r.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,r.jsx)(ik,{seed:n.target.seed,size:32,provider:n.target.provider}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:l("relogin.title")}),(0,r.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[n.target.alias,n.target.masked&&(0,r.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:n.target.masked})]}),n.target.reason&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:n.target.reason})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n?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,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),"auth"===s.phase&&s.device&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:l("i18n.deviceLoginGuide")}),s.instructions&&(0,r.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,r.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,r.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,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===s.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":s.message}),"auth"===s.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:h,value: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,r.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")})]}),"auth"===s.phase&&s.progress&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:s.progress})]}),"device_code"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(n?(0,r.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("relogin.done")}),n.outcome&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===n.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===n.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:l(mC[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:l("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,r.jsx)("button",{onClick:()=>{u.current?.close(),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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:m,onClick:()=>x(),style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"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,r.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&&!n&&(0,r.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 mT({provider:e,onRefresh:t}){let[n,a]=(0,i.useState)(""),[s,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,z.s)();(0,i.useEffect)(()=>{a(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){o(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(a(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{o(!1)}}},[n,e.id,t]),g=(0,i.useCallback)(async()=>{c(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{c(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mx,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,r.jsx)(md,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(mh,{value:n,onChange:a,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:s||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:"var(--radius-control)",color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:s||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":s?"i18n.saving":"i18n.save")]})]})}),d&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:d}),e.configured&&(0,r.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 mI({id:e,size:t}){let n=ml[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:"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:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}let mM={display:"flex",alignItems:"center",width:"100%",borderRadius:"var(--radius-control)",border:"none",cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},mR={padding:"6px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.04em"};function mE({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:a,onAddCustom:s,onClose:o}){let[l,c]=(0,i.useState)(""),{t:d}=(0,z.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=l.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),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,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&o()},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:u,value:l,onChange:e=>c(e.target.value),onKeyDown:e=>{"Escape"===e.key&&o()},placeholder:d("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:d("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.custom")}),f&&(0,r.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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(mI,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{a(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(mI,{id:e.id,size:28})]},e.id))]})})]})})}function m$({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:a,relogin:s}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,i.useState)({providers:{}}),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[j,S]=(0,i.useState)([]),[C,N]=(0,i.useState)([]),[T,I]=(0,i.useState)(!1),M=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),R=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>N(e.providers)).catch(()=>{})},[]),E=(0,i.useCallback)(()=>{M(),R()},[M,R]);(0,i.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)),E()},[E]);let $=(0,i.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,i.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),P=(0,i.useCallback)((e,t)=>{d(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),k(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),A=(0,i.useCallback)(e=>{d(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),d(e=>{let t=Object.keys(e.providers??{});return k(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),_=(0,i.useCallback)(e=>{d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return k({type:"model",providerName:e,index:n}),t})},[]),F=(0,i.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],a=new Set(i.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),W=(0,i.useCallback)((e,t,n)=>{d(r=>{let i=r.providers?.[e]??{},a=[...i.models??[]];return a[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:a}}}})},[]),O=(0,i.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),k({type:"provider",name:e})},[]),D=(0,i.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),a?.(),setTimeout(()=>y(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[c,a]),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,r.jsx)(hO,{cwd:e??null,onRolesChanged:a});if("oauth"===w.type){let e=j.find(e=>e.id===w.providerId);return e?(0,r.jsx)(mN,{provider:e,onRefresh:E,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,r.jsx)(mT,{provider:e,onRefresh:E},e.id):null}if("provider"===w.type){let e=c.providers?.[w.name];return e?(0,r.jsx)(mv,{name:w.name,provider:e,onChange:e=>L(w.name,e),onRename:e=>P(w.name,e),onDelete:()=>A(w.name),onAddModels:e=>F(w.name,e)},w.name):null}let t=c.providers?.[w.providerName],n=t?.models?.[w.index];return n?(0,r.jsx)(mS,{providerName:w.providerName,provider:t,model:n,onChange:e=>W(w.providerName,w.index,e),onDelete:()=>O(w.providerName,w.index)},`${w.providerName}-${w.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},...n?{}:{role:"dialog","aria-modal":!0,"aria-label":l("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,r.jsxs)("div",{style:{width:n?"100%":o?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":o?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.jsx)("button",{onClick:t,"aria-label":l("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.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,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.jsxs)("div",{role:"group","aria-labelledby":"models-nav-roles",children:[(0,r.jsx)("div",{id:"models-nav-roles",style:mR,children:l("models.navGroupRoles")}),(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":w?.type==="roles"?"true":void 0,onClick:()=>k({type:"roles"}),style:{...mM,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,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:l("roles.title")})]})]}),(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),(U.length>0||q.length>0)&&(0,r.jsx)("div",{id:"models-nav-accounts",style:mR,children:l("models.navGroupAccounts")}),U.map(e=>{let t=w?.type==="oauth"&&w.providerId===e.id;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"oauth",providerId:e.id}),style:{...mM,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,r.jsx)(mI,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),q.map(e=>{let t=w?.type==="apikey"&&w.providerId===e.id;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"apikey",providerId:e.id}),style:{...mM,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,r.jsx)(mI,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(U.length>0||q.length>0)&&H.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),!u&&H.length>0&&(0,r.jsx)("div",{style:mR,children:l("models.navGroupCustom")}),u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):H.map(([e,t])=>{let n=w?.type==="provider"&&w.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":n?"true":void 0,onClick:()=>k({type:"provider",name:e}),style:{...mM,gap:6,padding:"7px 8px",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{let i=w?.type==="model"&&w.providerName===e&&w.index===n;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":i?"true":void 0,onClick:()=>k({type:"model",providerName:e,index:n}),style:{...mM,gap:6,padding:"5px 8px 5px 26px",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||l("i18n.newModel")}),t.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:"var(--radius-control)",flexShrink:0},children:"T"})]},n)}),(0,r.jsx)("div",{onClick:t=>{t.stopPropagation(),_(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,r.jsxs)("span",{style:{fontSize:11},children:["+ ",l("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.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,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:K??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(x??f)&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:x??f}),(0,r.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,r.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,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:b?l("i18n.saved"):h?l("i18n.saving"):l("i18n.save")})]})]})]})}),T&&(0,r.jsx)(mE,{oauthProviders:j,apiKeyProviders:C,onSelectOAuth:e=>k({type:"oauth",providerId:e}),onSelectApiKey:e=>k({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>I(!1)})]})}function mL(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function mP(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function mA(e){let t=mP(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function m_(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function mF(e){return e?e.slice(0,8):"unknown"}function mz({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,z.s)();return(0,r.jsx)("button",{onClick:n,disabled:t,title:i(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:"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,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mW({skill:e,cwd:t,onToggle:n,toggling:i,saveError:a,updateStatus:s,checkingUpdate:o,updating:l,updateError:c,onCheckUpdate:d,onUpdate:u}){let{t:p}=(0,z.s)(),h=mP(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return mL(e)}(e.filePath)}),(0,r.jsx)(mz,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),a&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:mF(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)("button",{onClick:d,disabled:o||l,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:"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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:mF(s.latestVersion)}),(o||s&&"update-available"!==s.state)&&(0,r.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,r.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,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:c})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function mO({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:a}){let{t:s}=(0,z.s)(),[o,l]=(0,i.useState)(""),[c,d]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),m(null),d([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);d(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),a()}catch(e){v(String(e))}finally{g(null)}},[a,w,e]),N="global"===w?"~/.claude/skills/":`${mL(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:s("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value: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,r.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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.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,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),c.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=f===e.package,a=e.package.indexOf("@"),o=a>-1?e.package.slice(0,a):e.package,l=a>-1?e.package.slice(a+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function mD({cwd:e,onClose:t,embedded:n=!1}){let a=B(),{t:s}=(0,z.s)(),[o,l]=(0,i.useState)([]),[c,d]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,N]=(0,i.useState)(!1),[T,I]=(0,i.useState)(null),[M,R]=(0,i.useState)(null),[E,$]=(0,i.useState)(!0),[L,P]=(0,i.useState)({}),A=(0,i.useCallback)(async()=>{d(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(l(r),$(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&P(t=>({...t,[mA(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{d(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),R(null),A()},[e]);let _=(0,i.useCallback)(async t=>{let n=(t?[t]:o.filter(e=>!!e.install)).map(m_).filter(e=>!!e);if(0!==n.length){R(null),S(e=>new Set([...e,...n])),t||N(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){R(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||N(!1)}}},[e,o]),F=(0,i.useCallback)(async t=>{if(!t.install)return;let n=m_(t);I(n),R(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await A();let a=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:a,latestVersion:a}}))}catch(e){R(e instanceof Error?e.message:String(e))}finally{I(null)}},[e,A]),W=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);l(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&P(t=>({...t,[mA(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),O=o.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":a?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":a?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mL(e)})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!E&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===o.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===mP(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===mP(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===mP(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===mP(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===mP(e)}]){let r=o.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,a=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:a?"var(--border)":"var(--accent)",boxShadow:a?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:a?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=m_(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:s("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),a=n.filter(e=>e.disableModelInvocation),o=L[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),a.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>P(t=>({...t,[e]:!o})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:o?"▾":"▸"}),s("i18n.dormant")," (",a.length,")"]}),o&&a.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:"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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(mO,{cwd:e,projectResourcesLoaded:E,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:()=>{A()}}):c?null:O?(0,r.jsx)(mW,{skill:O,cwd:e,onToggle:W,toggling:f.has(O.filePath),saveError:x,updateStatus:m_(O)?w[m_(O)]:void 0,checkingUpdate:!!m_(O)&&j.has(m_(O)),updating:T===m_(O),updateError:M,onCheckUpdate:()=>void _(O),onUpdate:()=>void F(O)},O.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.some(e=>!!e.install)&&(0,r.jsx)("button",{onClick:()=>void _(),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,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?s("i18n.update"):s("i18n.updates")]})]}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("i18n.close")})]})]})})}let mH="global";function mU(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function mB(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function mq(e){return`${e.scope}\0${e.source}`}function mV(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function mK(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function mG(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function mJ({pkg:e}){let{t}=(0,z.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function mZ({scope:e}){return(0,r.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 mY(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 mX({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,title:i,"aria-label":i,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:"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,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mQ({installDir:e,source:t,busy:n,actionError:a,onSourceChange:s,onInstall:o}){let{t:l}=(0,z.s)(),c=(0,i.useRef)(null);return(0,i.useEffect)(()=>{c.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:l("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mU(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:c,value:t,onChange:e=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=mB(t);n!==t&&(e.preventDefault(),s(n))},onBlur:e=>s(mB(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()&&!n&&o()}})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,r.jsx)("button",{type:"button",onClick:o,disabled:n||!t.trim(),style:{...mY(n||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:l(n?"i18n.installing":"i18n.install")})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:"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))})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function m0({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:a,sessionId:s,onAction:o,onReloadSession:l}){let{t:c}=(0,z.s)(),d=mq(e),u=n?.endsWith(d)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(mX,{enabled:h,loading:u||p,onToggle:()=>o(e.disabled?"enable":"disable",e),label:c(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(mZ,{scope:e.scope}),e.disabled?(0,r.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,r.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,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>o("update",e),disabled:u||p,style:mY(u||p),children:c(n===`update:${d}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:l,disabled:!s||p||u,style:mY(!s||p||u),title:c(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:c(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>o("remove",e),disabled:u||p,style:mY(u||p,!0),children:c(n===`remove:${d}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.status")}),(0,r.jsx)("div",{style:{color:mG(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:mK(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??c("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:mV(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?mU(e.installedPath):c("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mU(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:c("i18n.resolvedResources")}),(0,r.jsx)(mJ,{pkg:e})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function m1({cwd:e,sessionId:t,onClose:n,onReloaded:a,embedded:s=!1}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),T=(0,i.useMemo)(()=>c?.packages??[],[c?.packages]),I=T.find(e=>mq(e)===f)??null,M=c?.projectResourcesLoaded??!0,R=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:T.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[T]),E=(0,i.useCallback)(async()=>{p(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);d(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>mq(t)===e)?e:n.packages[0]?mq(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let $=(0,i.useCallback)(async(t,n)=>{let r=mq(n);k(`${t}:${r}`),S(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);if(d(i),"remove"===t)g(i.packages[0]?mq(i.packages[0]):null),0===i.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,i.useCallback)(async()=>{let t=mB(b).trim();if(!t)return;y(t);let n=`${mH}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,a,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:mH,cwd:e})}),o=await s.json();if(!s.ok||o.error)throw Error(o.error??`HTTP ${s.status}`);d(o);let c=(r=o.packages,a=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===mH&&e.source===i)??r.find(e=>e.scope===mH&&e.source===`npm:${a}`)??r.find(e=>e.scope===mH&&e.source.endsWith(i)));g(c?mq(c):n),v(!1),y(""),N(l("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,l]),P=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await uJ(t,{type:"reload"}),a?.(),await E(),N(l("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,a,t,l]),A=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:s?"100%":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,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mU(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:l("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:o?"100%":245,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===T.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):R.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=mq(e),n=!x&&f===t;return(0,r.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:mG(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mV(e,l)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mK(e,l)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("button",{type:"button",onClick:()=>{v(!0),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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),l("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(mQ,{installDir:c?.installDir,source:b,busy:A,actionError:j,onSourceChange:y,onInstall:L}):u?null:I?(0,r.jsx)(m0,{pkg:I,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:$,onReloadSession:P},mq(I)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:c?.diagnostics.length?(0,r.jsxs)("span",{title:c.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:c.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[c.diagnostics.length," diagnostic",1===c.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:c?`${c.totals.extensions} ext \xb7 ${c.totals.skills} skills \xb7 ${c.totals.prompts} prompts \xb7 ${c.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:mY(u||null!==w),children:l("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:mY(!1),children:l("i18n.close")})]})]})})}var m2=n(13004),m8=n.n(m2);function m4(){let[e,t]=(0,i.useState)(null),[n,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,f]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),o(null),c(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);return t(i),i}catch(e){return o(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==m)return void o("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),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,i.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&c(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,i.useCallback)(async()=>{await x("clear")&&c("The stored password was removed and password access is off.")},[x]);if(!e)return(0,r.jsx)("div",{className:m8().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!d&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:m8().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,r.jsxs)("div",{className:m8().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),l&&(0,r.jsx)("div",{className:m8().reloadNotice,children:(0,r.jsx)("span",{children:l})})]}),(0,r.jsxs)("div",{className:m8().settingsBody,children:[(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:m8().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!e.configured&&!w&&(0,r.jsx)("div",{className:m8().settingDescription,children:"Set a password below before turning this on."}),s&&(0,r.jsx)("div",{className:m8().error,children:s})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("button",{type:"button",className:m8().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:d||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:m8().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("input",{className:m8().textInput,type:"password",autoComplete:"new-password",value:p,disabled:d||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:m8().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("input",{className:m8().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,r.jsxs)("div",{className:m8().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:m8().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:m8().dangerButton,disabled:d,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:m8().primaryButton,disabled:!k,onClick:()=>void v(),children:d?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:m8().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("a",{className:m8().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:m8().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,r.jsx)("div",{className:m8().settingControl})]})]})]})]})}let m5="/api/live/voices";function m6(){let{t:e}=(0,z.s)(),[t,n]=(0,i.useState)(null),[a,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)(null),c=(0,i.useCallback)(async()=>{try{let e=await fetch(m5,{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 r=da.includes(t.pace)?t.pace:"normal";n({voices:t.voices,defaultVoice:t.defaultVoice,pace:r})}catch(e){l(e instanceof Error?e.message:String(e))}},[]);(0,i.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})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let i="string"==typeof r.value?r.value:e;n(e=>e?{...e,defaultVoice:i}: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(m5,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pace:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);n(t=>t?{...t,pace:r.pace??e}:t)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(!1)}};return t?(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:m8().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:e("chat.liveVoiceSpeakerGroup")}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{className:m8().settingLabel,children:e("chat.liveVoiceCodexLabel")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.liveVoiceCodexHelp")}),o&&(0,r.jsx)("div",{className:m8().error,role:"alert",style:{overflowWrap:"anywhere"},children:o})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)(h_,{value:t.defaultVoice,disabled:a,ariaLabel:e("chat.liveVoiceCodexLabel"),options:t.voices,onChange:e=>{e!==t.defaultVoice&&d(e)}})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{className:m8().settingLabel,children:e("chat.livePaceLabel")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.livePaceHelp")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)(h_,{value:t.pace,disabled:a,ariaLabel:e("chat.livePaceLabel"),options:[{value:"normal",label:e("chat.livePaceNormal")},{value:"slow",label:e("chat.livePaceSlow")}],onChange:e=>{e!==t.pace&&da.includes(e)&&u(e)}})})]})]})})]}):(0,r.jsx)("div",{className:m8().empty,children:o?`${e("chat.liveVoiceLoadFailed")}: ${o}`:"…"})}function m3(){let{t:e}=(0,z.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[a,s]=(0,i.useState)(null),[o,l]=(0,i.useState)(""),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return d1({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,i.useCallback)(async e=>{p(!0),d(null),m(!1);try{let t=await d2(e);s(t),l(String(t.uploadLimitMb)),m(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return a?(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:m8().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:m8().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("input",{id:t,className:m8().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(a.uploadLimitMb))return;let n=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n<1){m(!1),d(e("chat.attachmentUploadLimitInvalid"));return}f({uploadLimitMb:n})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:m8().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:a.orphanGraceDays})})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("button",{type:"button",className:m8().switch,"data-on":a.autoCleanupEnabled,"aria-pressed":a.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!a.autoCleanupEnabled})})})]}),c&&(0,r.jsx)("div",{className:m8().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),h&&!c&&(0,r.jsx)("div",{className:m8().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:m8().empty,children:c?`${e("chat.attachmentSettingsLoadFailed")}: ${c}`:"…"})}function m7(){let{t:e}=(0,z.s)(),t=(0,i.useId)(),n=ib(),[a,s]=(0,i.useState)(!1),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1);(0,i.useEffect)(()=>{r$().then(()=>s(!0))},[]);let h=(0,i.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})}),n=await t.json().catch(()=>null);if(!t.ok)throw Error("object"==typeof n&&null!==n&&"error"in n?String(n.error):`HTTP ${t.status}`);rM(n),p(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(!1)}},[]);if(!a)return(0,r.jsx)("div",{className:m8().empty,children:"…"});let m=[{mode:"default",label:e("characterMode.default")},{mode:"office",label:e("characterMode.office")}];return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:e("characterMode.title")}),(0,r.jsx)("p",{className:m8().contentDescription,children:e("characterMode.description")})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:t,className:m8().settingLabel,children:e("characterMode.label")}),(0,r.jsx)("div",{className:m8().settingDescription,children:e("characterMode.help")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("div",{className:m8().multiSelect,role:"radiogroup","aria-labelledby":t,children:m.map(e=>(0,r.jsx)("span",{className:m8().choice,"data-selected":n.mode===e.mode,children:(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":n.mode===e.mode,className:m8().choiceToggle,disabled:o,onClick:()=>{n.mode!==e.mode&&h(e.mode)},children:e.label})},e.mode))})})]}),"office"===n.mode&&!n.rosterAvailable&&(0,r.jsx)("div",{className:m8().settingDescription,role:"status",children:e("characterMode.noRoster")}),c&&(0,r.jsx)("div",{className:m8().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),u&&!c&&(0,r.jsx)("div",{className:m8().saveState,role:"status",children:e("characterMode.saved")})]})})]})}function m9({cwd:e}){let{t}=(0,z.s)(),[n,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(null),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(new Map);(0,i.useEffect)(()=>{g&&d!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[d,n,g]);let b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let i=e?`?include=${encodeURIComponent(e)}`:"",s=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),l=await s.json();if(n!==b.current||r.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,a(l.projects),o(null),c&&f({cwd:c.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;o(e instanceof Error?e.message:String(e))}finally{y.current===r&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=n?.some(e=>null!==e.pending)??!1;(0,i.useEffect)(()=>{let e;if(!S||null!==d||null!==l)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},n=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",n),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[d,l,n,S,j]);let C=(0,i.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),c(null),x(e),f(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),i=await r.json();if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);let s=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=s,a(s),"cancel"===n?f({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(n=>({...n,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!n)return(0,r.jsxs)("div",{className:m8().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,r.jsx)("button",{type:"button",className:m8().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==d;return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:m8().contentDescription,children:t("trust.settingsDescription")}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,r.jsx)("button",{type:"button",className:m8().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,r.jsx)("div",{className:m8().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:(0,r.jsxs)("section",{className:m8().group,children:[0===n.length&&(0,r.jsx)("div",{className:m8().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=d===e.cwd,a=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,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:m8().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:m8().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,r.jsx)("span",{children:(n=e.cwd).split(/[\\/]/).filter(Boolean).pop()??n}),(0,r.jsx)("span",{className:m8().settingDescription,style:{fontWeight:600},children:s})]}),(0,r.jsx)("code",{className:m8().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:m8().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,r.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,r.jsx)("div",{className:m8().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:m8().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),a&&(0,r.jsx)("div",{className:m8().settingDescription,style:{color:"var(--text)"},children:"revoke"===a.action?t("trust.confirmRevoke"):a.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:m8().saveState,children:m.text})]}),o&&(0,r.jsx)("div",{className:m8().error,role:"alert",children:o})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:m8().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:m8().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{c(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===a.action?m8().dangerButton:m8().primaryButton,disabled:N,onClick:()=>void C(e.cwd,a.action),children:"revoke"===a.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:m8().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:m8().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,r.jsx)("button",{type:"button",className:m8().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,r.jsx)("button",{type:"button",className:m8().dangerButton,disabled:N,onClick:()=>c({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let fe="cuelo-look",ft="cuelo-look-wallpaper",fn="data-cuelo-look",fr="data-cuelo-wallpaper";function fi(e){try{return localStorage.getItem(e)}catch{return null}}function fa(e,t){try{return null===t?localStorage.removeItem(e):localStorage.setItem(e,t),!0}catch{return!1}}function fs(e,t){let n=document.documentElement;e?n.setAttribute(fn,"graphite"):n.removeAttribute(fn),e&&t?n.setAttribute(fr,t):n.removeAttribute(fr)}let fo=new Set,fl=null,fc=null;function fd(){return fl??"graphite"===fi(fe)}function fu(e){let t;fl=fa(fe,e?"graphite":null)?null:e,fs(e,fc??("default"===(t=fi(ft))||"office"===t?t:null)),fo.forEach(e=>e())}function fp(e){let t="office"===e?"office":"default";fc=fa(ft,t)?null:t,fs(fd(),t)}function fh(e){return fo.add(e),()=>{fo.delete(e)}}let fm=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이다"}}}'),ff=[{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"}],fg={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),characters:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}),attachments:(0,r.jsx)("path",{d:"m21 12-8.6 8.6a5 5 0 0 1-7-7l8.5-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9"}),appearance:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function fx({kind:e}){return(0,r.jsx)("svg",{className:m8().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:fg[e]??fg.tools})}function fv({field:e,busy:t,onSave:n}){let[a,s]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let o="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:m8().textInput,type:"secret"===e.type?"password":"text",value:a,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{a!==o&&("secret"!==e.type||a.length>0)&&n(a)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function fb({field:e,busy:t,onSave:n}){let a=JSON.stringify(e.value??{},null,2),[s,o]=(0,i.useState)(a),[l,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{o(a),c(null)},[a]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:m8().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>o(e.target.value),onBlur:()=>{if(s!==a)try{n(JSON.parse(s)),c(null)}catch(e){c(e instanceof Error?e.message:String(e))}}}),l&&(0,r.jsx)("div",{className:m8().error,children:l})]})}function fy({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],a=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let a=[...i];[a[e],a[r]]=[a[r],a[e]],n(a)};return(0,r.jsx)("div",{className:m8().multiSelect,children:e.options?.map(s=>{let o=i.indexOf(s.value);return(0,r.jsxs)("span",{className:m8().choice,"data-selected":o>=0,title:s.description,children:[(0,r.jsx)("button",{type:"button",className:m8().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:s.label}),e.ordered&&o>=0&&(0,r.jsxs)("span",{className:m8().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===o,onClick:()=>a(o,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||o===i.length-1,onClick:()=>a(o,1),children:"→"})]})]},s.value)})})}function fw({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:m8().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(h_,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(fy,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(fb,{field:e,busy:t,onSave:n}):(0,r.jsx)(fv,{field:e,busy:t,onSave:n})}function fk({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:m8().settingLabel,children:e.label}),(0,r.jsx)("div",{className:m8().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:m8().error,children:n})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)(fw,{field:e,busy:t,onSave:i})})]})}function fj({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:m8().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:m8().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:m8().themePreviewPanel,children:[(0,r.jsx)("div",{className:m8().themePreviewLine}),(0,r.jsx)("div",{className:m8().themePreviewLine})]})]})}let fS='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',fC=new Set(["hideThinkingBlock"]);function fN({cwd:e,sessionId:t,initialSection:n="models",onClose:a,onModelsChanged:s,onReloaded:o}){let[l,c]=(0,i.useState)(n),[d,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(new Set),[y,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),{theme:N,setPreference:T}=ng(),I={enabled:(0,i.useSyncExternalStore)(fh,fd,()=>!1),setEnabled:fu},{locale:M,t:R}=(0,z.s)(),E=(0,i.useRef)(null),$=e=>"ko"===M?fm.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{let e=E.current;if(!e)return;(Array.from(e.querySelectorAll(fS)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(fS)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let P=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await nf(e),await L()):fC.has(t.path)?await n0(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,L]),A=(0,i.useMemo)(()=>new Map(d?.fields.map(e=>[e.path,e.value])??[]),[d?.fields]),_=(0,i.useMemo)(()=>d?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,A))??[],[d?.fields,A]),F=l.startsWith("settings:")?l.slice(9):null,W=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?_.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):F?_.filter(e=>e.tab===F&&("appearance"!==F||"Theme"!==e.group)):[]},[F,g,_]),O=(0,i.useCallback)(()=>{s?.(),a()},[a,s]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await uJ(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===F),U=g.trim()?`${$("Search")} \xb7 ${W.length}`:H?.label??$("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:m8().group,children:[(0,r.jsx)("h3",{className:m8().groupTitle,children:t}),n.map(e=>(0,r.jsx)(fk,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void P(e,t)},e.path))]},t):null}),q=()=>p?(0,r.jsx)("div",{className:m8().empty,children:$("Loading omp settings…")}):m||!d?(0,r.jsx)("div",{className:m8().empty,children:m??$("Settings unavailable")}):(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:U}),(0,r.jsx)("p",{className:m8().contentDescription,children:$(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,r.jsxs)("div",{className:m8().reloadNotice,children:[(0,r.jsx)("span",{children:$("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:$(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:W.length?B(W,H?.groups??[]):(0,r.jsx)("div",{className:m8().empty,children:$("No settings match this search.")})})]});return(0,r.jsx)("div",{className:m8().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&O()},children:(0,r.jsxs)("div",{ref:E,tabIndex:-1,className:m8().window,role:"dialog","aria-modal":"true","aria-label":$("Settings"),children:[(0,r.jsxs)("aside",{className:m8().sidebar,children:[(0,r.jsxs)("div",{className:m8().brand,children:[(0,r.jsx)("div",{className:m8().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:m8().title,children:$("Settings")}),(0,r.jsx)("code",{className:m8().context,title:e??$("Global configuration"),children:e??$("Global configuration")})]}),(0,r.jsxs)("div",{className:m8().searchWrap,children:[(0,r.jsxs)("svg",{className:m8().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:m8().search,value:g,"aria-label":$("Search /settings"),placeholder:$("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:m8().nav,children:[(0,r.jsx)("div",{className:m8().navLabel,children:$("Configuration")}),ff.map(t=>{let n=t.labelKey?R(t.labelKey):$(t.label);return(0,r.jsxs)("button",{type:"button",className:m8().navButton,"data-active":!g&&l===t.id,"aria-current":g||l!==t.id?void 0:"page",disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${$("requires a project")}`:n,onClick:()=>{x(""),c(t.id)},children:[(0,r.jsx)(fx,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:m8().navLabel,children:$("OMP settings")}),d?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:m8().navButton,"data-active":!g&&F===e.id,"aria-current":g||F!==e.id?void 0:"page",onClick:()=>{x(""),c(`settings:${e.id}`)},children:[(0,r.jsx)(fx,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:m8().closeRail,children:(0,r.jsxs)("button",{type:"button",className:m8().closeButton,onClick:O,children:[(0,r.jsx)("span",{children:$("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:m8().content,children:g.trim()?q():"models"===l?(0,r.jsx)(m$,{cwd:e,embedded:!0,onClose:O,onModelsChanged:s}):"themes"===l?d?(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:$("Themes")}),(0,r.jsxs)("p",{className:m8().contentDescription,children:[$("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),$(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:m8().settingsBody,children:[(0,r.jsx)("div",{className:m8().themeGrid,children:["dark","light"].map(e=>{let t=d.fields.find(t=>t.path===`theme.${e}`),n=d.theme.palettes[e];return(0,r.jsxs)("div",{className:m8().themeCard,children:[(0,r.jsx)(fj,{mode:e,palette:n}),(0,r.jsxs)("div",{className:m8().themeCardBody,children:[(0,r.jsxs)("div",{className:m8().themeCardHeader,children:[(0,r.jsxs)("span",{className:m8().themeSlot,children:[e,$(" mapping")]}),N===e&&(0,r.jsx)("span",{className:m8().themeActive,children:$("Active on web")})]}),(0,r.jsx)(h_,{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 P(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:m8().closeButton,style:{marginTop:8},onClick:()=>T(e),children:[$("Preview "),e]})]})]},e)})}),(0,r.jsx)("section",{className:m8().group,children:(0,r.jsxs)("div",{className:m8().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:"settings-graphite-label",className:m8().settingLabel,children:R("theme.graphite")}),(0,r.jsx)("div",{className:m8().settingDescription,children:R("theme.graphiteHint")})]}),(0,r.jsx)("div",{className:m8().settingControl,children:(0,r.jsx)("button",{type:"button",role:"switch",className:m8().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,r.jsx)("div",{className:m8().empty,children:p?$("Loading themes…"):m??$("Themes unavailable")}):"skills"===l&&e?(0,r.jsx)(mD,{cwd:e,embedded:!0,onClose:O}):"plugins"===l&&e?(0,r.jsx)(m1,{cwd:e,sessionId:t,embedded:!0,onClose:O,onReloaded:o}):"mcp"===l?(0,r.jsx)(fT,{cwd:e,sessionId:t,onReloaded:o}):"access"===l?(0,r.jsx)(m4,{}):"trust"===l?(0,r.jsx)(m9,{cwd:e}):"live-voice"===l?(0,r.jsx)(m6,{}):"attachments"===l?(0,r.jsx)(m3,{}):"characters"===l?(0,r.jsx)(m7,{}):q()})]})})}function fT({cwd:e,sessionId:t,onReloaded:n}){let[a,s]=(0,i.useState)(null),[o,l]=(0,i.useState)("user"),[c,d]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);s(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=a?"user"===o?a.user:a.project:null,j=k?.servers[c]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(t=>{if(!t)return t;let n={..."user"===o?t.user:t.project,servers:e};return"user"===o?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===c?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,servers:n})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${o}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,name:r.name,enabled:!r.enabled})}),s=await a.json();if(!a.ok||s.error)throw Error(s.error??`HTTP ${a.status}`);await w(),t&&(await uJ(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:m8().scrollContent,children:[(0,r.jsxs)("header",{className:m8().contentHeader,children:[(0,r.jsx)("h2",{className:m8().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:m8().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,r.jsx)("div",{className:m8().settingsBody,children:a?(0,r.jsxs)("div",{className:m8().mcpLayout,children:[(0,r.jsxs)("aside",{className:m8().mcpList,children:[(0,r.jsxs)("div",{className:m8().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:m8().scopeButton,"data-active":"user"===o,onClick:()=>{l("user"),d(0)},children:["User \xb7 ",a.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:m8().scopeButton,"data-active":"project"===o,disabled:!a.project,onClick:()=>{l("project"),d(0)},children:["Project \xb7 ",a.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:m8().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:m8().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${o}:${e.name}`;return(0,r.jsxs)("div",{className:m8().serverRow,"data-active":c===t,children:[(0,r.jsxs)("button",{type:"button",className:m8().serverSelect,title:e.source?.path,onClick:()=>d(t),children:[(0,r.jsx)("span",{className:m8().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:m8().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:m8().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:m8().serverToggle,"data-on":e.enabled,disabled:b===n,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:m8().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:m8().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),d(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:m8().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:m8().editorHeader,children:[(0,r.jsx)("input",{className:m8().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:m8().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==c)),d(Math.max(0,c-1)))},children:"Delete"})]}),!1===j.editable&&(0,r.jsxs)("div",{className:m8().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:m8().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:m8().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:m8().error,children:f}),(0,r.jsx)("div",{className:m8().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:m8().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:m8().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:m8().empty,children:f??"Loading MCP configuration…"})})]})}let fI="cuelo-notification-prompt-dismissed";function fM({variant:e,locale:t,permission:n,dismissed:i,request:a,dismiss:s}){let o="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||i?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":o?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:o?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,children:o?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":o?"알림 권한 안내 닫기":"Dismiss notification prompt",children:o?"닫기":"Dismiss"})]}):(0,r.jsx)(c.k.Item,{disabled:"denied"===n,onClick:"default"===n?a:void 0,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:"default"===n?o?"알림 켜기":"Enable notifications":o?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(c.k.ItemDescription,{children:o?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function fR({cwd:e,busy:t,scheduled:n,error:a,onCancel:s,onConfirm:o,onCancelSchedule:l}){let{t:c}=(0,z.s)(),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{d.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:"var(--radius-control)",cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||s()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:c(n?"trust.scheduledTitle":"trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:c(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:a})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c("trust.cancelSchedule")}),(0,r.jsx)("button",{ref:d,type:"button",onClick:s,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c(n?"trust.close":"trust.cancel")}),!n&&(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:c(t?"trust.trusting":"trust.trustProject")})]})]})})}var fE=n(55681);let f$={kind:"loading"};function fL(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":s6(e.status)?"var(--accent)":"var(--success)"}function fP(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let fA={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function f_(e){return e.lastUpdate||e.progress?.durationMs||0}let fF=(0,r.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,r.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})}),fz=[];function fW({state:e,summary:t,reason:n,onOpenFile:i}){let{st:a}=iw(),{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,r.jsxs)("div",{className:"maker-detail-outcome",children:[n&&(0,r.jsxs)("p",{className:"maker-detail-reason",children:[(0,r.jsx)("span",{children:a("detail.reason")})," ",n]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:a("summary.heading.files")}),o?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):l.length>0?(0,r.jsx)(iL,{files:l,onOpenFile:i}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noFiles")})]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:a("summary.heading.checks")}),o?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):c.length>0?(0,r.jsx)("ul",{className:"answer-summary-list",children:c.map(e=>(0,r.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,r.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,r.jsxs)("span",{className:"answer-check-result",children:[s(fO[e.state]),null!==e.exitCode?` \xb7 ${a("summary.check.exit",{code:e.exitCode})}`:null]})]},e.toolCallId))}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noChecks")})]})]})}let fO={passed:"makerDetail.checkPassed",unverified:"makerDetail.checkUnverified",failed:"makerDetail.checkFailed",unobserved:"makerDetail.checkUnobserved"};function fD({sessionId:e,sessionCwd:t,record:n,selection:a,client:s,visible:o,onBack:l,onOpenFile:c}){let{st:d}=iw(),{t:u}=(0,z.s)(),p=n?.key,h=n?.live?.id,m=n?.live?.status,f=n?.archive?.name,g=(0,i.useMemo)(()=>p?[{key:p,liveId:h,status:m,archiveName:f}]:[],[p,h,m,f]),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=oe(g,{sessionId:e,client:s,enabled:o&&g.length>0}),y=(p?b.get(p)?.state:void 0)??f$;(0,i.useEffect)(()=>{o&&v.current?.focus({preventScroll:!0})},[a.key,o]),(0,i.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:fz,k=(0,i.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,i.useMemo)(()=>"ready-live"===y.kind?o_(y.entries,t):null,[y,t]),S=n?.live?.id||n?.archive?.name||"Subagent",C=n?i_(n).title:S,N=a.status;return(0,r.jsxs)("div",{role:"region","aria-label":u("makerDetail.region",{title:S}),style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsx)(p9,{back:{label:u("subagents.back"),onClick:l},title:C,titleTooltip:n?`${C}
|
|
70
70
|
${S} \xb7 ${fP(n)}`:void 0,titleRef:v,subtitle:n?`${S} \xb7 ${fP(n)}`:void 0,state:N?(0,r.jsx)(oA,{maker:N,st:d}):n?.live&&(0,r.jsx)("span",{style:{color:fL(n.live),fontFamily:"var(--font-mono)",fontSize:11},children:n.live.status})}),!n&&(0,r.jsx)("div",{role:"status",className:"maker-detail-empty",style:{padding:24,textAlign:"center"},children:u("makerDetail.unavailable")}),n&&(0,r.jsx)(fW,{state:y,summary:j,reason:N?.verdict?.reason??null,onOpenFile:c}),n&&(0,r.jsxs)("div",{ref:x,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===y.kind&&(0,r.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,n)=>{if(!("message"in e))return[];let i=y.entries[n-1];return[(0,r.jsx)(l_,{message:e.message,toolResults:k,cwd:t,showTimestamp:!0,prevTimestamp:i&&"message"in i?i.message.timestamp:void 0},e.id)]}),"ready-archive"===y.kind&&(0,r.jsxs)(r.Fragment,{children:[y.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:y.note}),y.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),y.entries.map((e,t)=>(0,r.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,r.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===y.kind&&(0,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[y.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:y.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===y.kind&&(0,r.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,r.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 fH({record:e,view:t,onSelect:n}){let a,s,o,{st:l}=iw(),c=(0,i.useId)(),d=e.live,u=e.archive,p=i_(e),h=!!(d&&s6(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?oE(l,f.todo):"",v=d?.id||u?.name||"Subagent",b=fP(e),y=(a=e.live,(o=(s=(a?.agent||a?.progress?.agent||"").trim()).toLowerCase().split(/[-_.:/\s]+/).filter(Boolean).join(" "))?{kind:"known",agent:s,source:a?.agentSource??"bundled",label:o}:{kind:"unknown"}),w=iF(e),k=w.modelShort??"모델 미확인",j=w.effort??"추론 미확인",S="known"===y.kind?y.label:"역할 미확인";return(0,r.jsx)("div",{role:"listitem",children:(0,r.jsxs)("button",{type:"button",onClick:n,"data-identity":e.identity,"data-subagent-key":e.key,title:`${v}
|
|
71
71
|
${w.model??"모델 미확인"} \xb7 ${j}
|
|
72
72
|
${p.title}${m?`
|