cuelo 0.10.231 → 0.10.232
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 +41 -41
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +2 -2
- package/.next/required-server-files.json +2 -2
- 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/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 +2 -2
- 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 +41 -41
- 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-78992950595761ae.js → layout-8fe49107ef95bc85.js} +1 -1
- package/.next/static/chunks/app/{page-9a042d9510a4d9d1.js → page-1b2075085bff84f0.js} +2 -2
- package/.next/trace +111 -111
- package/.next/trace-build +1 -1
- package/README.md +1 -1
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +3 -3
- package/Tools/OMP_Global_Config/agent/extensions/character-voice.ts +2 -0
- package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +114 -0
- package/package.json +7 -7
- /package/.next/static/{jZwEDDQlSi7wWchdQZc49 → NVK-6kV2UVzHGTnMG9ZVq}/_buildManifest.js +0 -0
- /package/.next/static/{jZwEDDQlSi7wWchdQZc49 → NVK-6kV2UVzHGTnMG9ZVq}/_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,r)=>{"use strict";function n(e,t,r,a={}){let i=r[e]?.[t]??r.en?.[t];return void 0===i?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,r)=>{let n=t[r];return void 0===n?e:String(n)})}(i,a)}r.d(t,{u0:()=>n})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,r)=>{"use strict";r.d(t,{C1:()=>i,IN:()=>a,getPresetFromTools:()=>o,xG:()=>l});let n=[],a=["read","bash","edit","write"],i=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(i.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let r=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return r===[...a].sort().join(",")?"default":r===[...i].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...n]:"full"===e?[...i]:[...a]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},29213:e=>{e.exports={view:"PluginLabPanel_view__Sot51",toolbar:"PluginLabPanel_toolbar__co_Uq",hint:"PluginLabPanel_hint__kb7Hq",body:"PluginLabPanel_body__T_QMu",message:"PluginLabPanel_message__QbEDh",errorText:"PluginLabPanel_errorText__EI47_",list:"PluginLabPanel_list__BnAn6",card:"PluginLabPanel_card__5479R",cardHead:"PluginLabPanel_cardHead__SCiZ3",titleBlock:"PluginLabPanel_titleBlock__zfcvo",titleLine:"PluginLabPanel_titleLine__OmG7U",name:"PluginLabPanel_name__t4Ea0",id:"PluginLabPanel_id__osclH",control:"PluginLabPanel_control___gzgN",switch:"PluginLabPanel_switch__m3agg",switchLabel:"PluginLabPanel_switchLabel__DGX6y",description:"PluginLabPanel_description__PfruO",enhancement:"PluginLabPanel_enhancement__TOHjM",enhancementHead:"PluginLabPanel_enhancementHead__sgewN",enhancementDate:"PluginLabPanel_enhancementDate__4YWB1",enhancementSummary:"PluginLabPanel_enhancementSummary__srTnj",tools:"PluginLabPanel_tools__raR8s",metaLabel:"PluginLabPanel_metaLabel__LY5ak",toolList:"PluginLabPanel_toolList___rd6_",tool:"PluginLabPanel_tool___AjRR",problem:"PluginLabPanel_problem__Sx4aQ",problemLabel:"PluginLabPanel_problemLabel__rBSUT",cardActions:"PluginLabPanel_cardActions__GI_Bb",stage:"PluginLabPanel_stage__1l0FR",frame:"PluginLabPanel_frame__sP_V0",status:"PluginLabPanel_status__BYiAs",lines:"PluginLabPanel_lines__ONctT",notice:"PluginLabPanel_notice__mn_vu"}},40960:e=>{e.exports={active:"ComputerTakeoverControl_active__7430b"}},66592:e=>{e.exports={root:"TypedInterpreter_root__q_c0E",results:"TypedInterpreter_results__6j7HQ",turn:"TypedInterpreter_turn__BELhE",label:"TypedInterpreter_label__tFGb1",original:"TypedInterpreter_original__IxOOM",translation:"TypedInterpreter_translation__bR55x",composer:"TypedInterpreter_composer__IgxpT",direction:"TypedInterpreter_direction__8Chyz",field:"TypedInterpreter_field__6QmFe",submit:"TypedInterpreter_submit__tRKd5",error:"TypedInterpreter_error__h7BTN",modes:"TypedInterpreter_modes__Krr0C",toolbar:"TypedInterpreter_toolbar__L_2u0"}},80455:(e,t,r)=>{Promise.resolve().then(r.bind(r,81353)),Promise.resolve().then(r.bind(r,84183))},81353:(e,t,r)=>{"use strict";r.d(t,{AppShell:()=>yC});var n=r(95155),a=r(12115),i=r(73321),s=r(16871),o=r(81886),l=r(68890),c=r(66919);let d=["chat","process","subagents","files","resource","sidechat","efficiency","plugins","memory"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),m=Object.fromEntries(d.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let r,n=f(t.view);return{activeView:n,transientLayer:null,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"open-layer":{let r,n=f(e.activeView);return{activeView:n,transientLayer:t.layer,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"toggle-layer":{let r,n=f(e.activeView);return{activeView:n,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"close-layer":{let t,r=f(e.activeView);return{activeView:r,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==r&&t)}}case"set-deck-expanded":{let r,n=f(e.activeView);return{activeView:n,transientLayer:e.transientLayer,deckExpanded:(r=t.expanded,"chat"!==n&&r)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function T(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[r,n]of Object.entries(t.opened))"number"==typeof n&&Number.isFinite(n)&&(e[r]=n);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let r=null;for(let[n,a]of Object.entries(t.opened))(e.opened[n]??-1/0)>=a||((r??={...e.opened})[n]=a);return!r&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:r??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function E(e,t,r){let n=Math.max(r,M(t)??0);return(e.opened[t.id]??-1/0)>=n?e:{since:e.since,opened:{...e.opened,[t.id]:n}}}let $=new Set;function R(e,t){let r=null;for(let n of t)Object.hasOwn(e.opened,n)&&(r??={...e.opened},delete r[n]);return r?{since:e.since,opened:r}:e}function L(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function A(e){let t=new Map;for(let r of e){let e=r.projectRoot??r.cwd;if(!e)continue;let n=L(e),a=t.get(n);(!a||r.modified>a.modified)&&t.set(n,{project:e,modified:r.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function P(e,t){let r=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&r.set(L(e.key),e.order);let n=[...e],a=new Set(e.map(L));for(let e of t){let t=L(e.key);!t||a.has(t)||(n.push(e.path??e.key),a.add(t))}return n.map((e,t)=>({project:e,defaultIndex:t,order:r.get(L(e))})).sort((e,t)=>{let r=void 0!==e.order,n=void 0!==t.order;return r!==n?r?-1:1:r&&n&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let F=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function _(e){let t=e.match(F);if(!t)return null;let[,r,,,n]=t;return n?`/skill:${r} ${n}`:`/skill:${r}`}var z=r(84183);let W=`(max-width: ${p.navigator-1}px)`;function O(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let r=window.matchMedia(e);return r.addEventListener("change",t),()=>r.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=O("(max-width: 640px)"),H=O(W);function U(){return!1}function B(){return(0,a.useSyncExternalStore)(D.subscribe,D.getSnapshot,U)}var q=r(47650);async function V(e){let t=e?`?path=${encodeURIComponent(e)}`:"",r=await fetch(`/api/cwd/browse${t}`),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return n}function K(){return(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function G(){return(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,n.jsx)("path",{d:"M2 9h12"}),(0,n.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function J({onCancel:e,onSelect:t,busy:r=!1,error:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(""),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(""),[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)(null),[w,k]=(0,a.useState)(null),[j,S]=(0,a.useState)(!0),C=(0,a.useCallback)(async e=>{S(!0),k(null);try{let t=await V(e),r=t.path??e??"/";d(r),p(t.parentPath??null),m(!0===t.upToDrives),g(r),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,a.useEffect)(()=>{l(document.body),C()},[C]);let N=f.trim()!==c,T=!!c&&!N&&!r,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,q.createPortal)((0,n.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||r||e()},onKeyDown:t=>{"Escape"!==t.key||r||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,n.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1},children:(0,n.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,n.jsx)("button",{type:"button",onClick:e,disabled:r,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:r?"default":"pointer",opacity:r?.5:1},children:"\xd7"})]}),(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!I,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:I?"pointer":"default",opacity:I?1:.45},children:(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,n.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,n.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,n.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,n.jsx)(n.Fragment,{children:b.length>0?b.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(G,{}),(0,n.jsx)("span",{children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(K,{}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||i)&&(0,n.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??i})]}),(0,n.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:r,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:r?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!T,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:T?1:.6,cursor:T?"pointer":"default"},children:s(r?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Z=r(21443),Y=r.n(Z);async function X(e,t){let r=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),n=await r.json();if(!r.ok)throw Error(n.error||`HTTP ${r.status}`);return n}function Q({onCancel:e,onSelect:t,busy:r=!1,error:i}){let{t:s}=(0,z.s)(),o=(0,a.useRef)(null),[l,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(!1),[p,h]=(0,a.useState)(null),[m,f]=(0,a.useState)([]),[g,x]=(0,a.useState)(""),[v,b]=(0,a.useState)(""),[y,w]=(0,a.useState)(!0),[k,j]=(0,a.useState)(!1),[S,C]=(0,a.useState)(!1),[N,T]=(0,a.useState)(null),[I,M]=(0,a.useState)(!1),[E,$]=(0,a.useState)(50),R=p?.device?.state==="pending",L=r||S,A=(0,a.useCallback)(async()=>{w(!0),T(null);try{let e=await X("/api/github/projects");h(e),e.connected&&f((await X("/api/github/projects?view=repositories")).repositories)}catch(e){T(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function P(){j(!0),T(null);try{let{device:e}=await X("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){T(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function F(e){if(e.preventDefault(),v.trim()&&!L){C(!0),T(null);try{let{cwd:e}=await X("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){T(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,a.useEffect)(()=>{c(!0),A()},[A]),(0,a.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,a.useEffect)(()=>{let e;if(!R||d)return;let t=!1,r=async()=>{try{let e=await X("/api/github/projects");if(t)return;if(h(e),e.connected)return void await A();if(e.device?.state!=="pending")return}catch(e){t||T(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(r,3e3))};return e=window.setTimeout(r,1500),()=>{t=!0,clearTimeout(e)}},[R,d,A]),!l)return null;if(d)return(0,n.jsx)(J,{onCancel:()=>u(!1),onSelect:t,busy:r,error:i});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),W=N??i??p?.device?.error;return(0,q.createPortal)((0,n.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),L||e()},children:(0,n.jsxs)("form",{onSubmit:F,className:Y().form,children:[(0,n.jsxs)("header",{className:Y().header,children:[(0,n.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,n.jsx)("p",{children:s("cloudProjects.description")})]}),(0,n.jsxs)("div",{className:Y().sources,children:[(0,n.jsx)("span",{className:Y().activeSource,children:s("cloudProjects.github")}),(0,n.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:L,children:s("cloudProjects.serverFolder")})]}),(0,n.jsxs)("div",{className:Y().body,children:[(0,n.jsxs)("section",{className:Y().account,"aria-label":s("cloudProjects.account"),children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,n.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:y||L,children:s("cloudProjects.refresh")}):(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:y||k||R||L,children:k||R?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),R&&(0,n.jsxs)("div",{className:Y().login,role:"status",children:[(0,n.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:Y().codeRow,children:[(0,n.jsx)("code",{children:p.device.code}),(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>T(s("cloudProjects.copyFailure")))},children:I?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,n.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Y().loginLink,children:s("cloudProjects.openLogin")}),(0,n.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,n.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,n.jsxs)("section",{className:Y().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,n.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,n.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),$(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:L}),y?(0,n.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:Y().list,children:_.slice(0,E).map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":v===e.fullName,disabled:L,onClick:()=>b(e.fullName),children:[(0,n.jsxs)("span",{className:Y().repoHeading,children:[(0,n.jsx)("strong",{children:e.fullName}),(0,n.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,n.jsx)("span",{className:Y().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,n.jsx)("p",{children:s("cloudProjects.empty")}),_.length>E&&(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>$(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,n.jsxs)("div",{className:Y().repositoryInput,children:[(0,n.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,n.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:L,"aria-describedby":"cloud-repo-help"}),(0,n.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),W&&(0,n.jsxs)("div",{className:Y().error,role:"alert",children:[(0,n.jsx)("strong",{children:s("cloudProjects.error")}),(0,n.jsx)("p",{children:W}),(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:L,children:s("cloudProjects.refresh")})]}),S&&(0,n.jsx)("p",{role:"status",className:Y().progress,children:s("cloudProjects.openingHelp")})]}),(0,n.jsxs)("footer",{className:Y().footer,children:[(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:L,children:s("i18n.cancel")}),(0,n.jsx)("button",{type:"submit",className:Y().primary,disabled:L||!v.trim(),children:L?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function ee({label:e="CUELO",markSize:t=22,gap:r=10,style:a,labelStyle:i}){return(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:r,minWidth:0,color:"var(--text)",...a},children:[(0,n.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,n.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...i},children:e})]})}var et=r(2730);let er={ko:{"translator.modeVoice":"대화","translator.modeType":"타자","translator.source":"입력 언어","translator.swapDirection":"방향 바꾸기","translator.typeLabel":"번역할 문장","translator.typePlaceholder":"여행 중 전할 말을 입력하세요.","translator.typeSubmit":"번역","translator.typePending":"번역 중…","translator.typeError":"번역하지 못했어요. 다시 시도해 주세요.","translator.typeAuth":"Codex 로그인 상태를 확인해 주세요.","translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브가 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록","translator.mood":"분위기","translator.mood.casual":"편하게","translator.mood.polite":"정중하게","translator.mood.formal":"격식 있게","translator.mood.haggling":"흥정","translator.mood.urgent":"긴급","translator.gender":"내 성별","translator.gender.male":"남성","translator.gender.female":"여성","translator.age":"내 나이대","translator.age.20s":"20대","translator.age.30s":"30대","translator.age.40s":"40대","translator.age.50s":"50대","translator.age.60s":"60대 이상","translator.partnerGender":"상대 성별","translator.partnerAge":"상대 나이","translator.partnerAge.child":"아이","translator.partnerAge.younger":"나보다 어리거나 비슷","translator.partnerAge.older":"나보다 위","translator.partnerAge.parent":"부모님 또래","translator.partnerAge.grandparent":"조부모님 또래","translator.notSet":"선택 안 함","translator.face":"마주보기","translator.faceHint":"상대 쪽 자막을 뒤집어 마주 앉은 사람이 읽게 합니다","translator.reconnecting":"다시 연결 중…","translator.idleStopped":"한동안 대화가 없어 통역을 멈췄습니다. 다시 시작하면 앞 대화에 이어집니다.","translator.generationSkipped":"방금 말은 통역하지 못하고 넘어갔습니다. 이어서 말씀하시면 계속 통역합니다.","translator.setup":"언어\xb7상황 설정","translator.sizeDown":"글자 작게","translator.sizeUp":"글자 크게","translator.faceExit":"마주보기 끄기","translator.translating":"옮기는 중…","translator.errorStatus":"통역이 멈췄습니다","translator.translation":"통역","translator.unknownLanguage":"언어 모름","translator.jumpLatest":"최근 말로","translator.voice":"통역 음성 듣기","translator.voiceHint":"끄면 통역을 글로만 보여 줍니다. 스피커가 조용하니 마이크를 막지 않아 통역 중에 끼어든 말도 들립니다.","translator.echoGuard":"통역 음성이 나올 때 마이크 끄기","translator.echoGuardHint":"스피커로 나온 통역이 다시 통역되지 않게 합니다. 그동안 상대가 한 말은 들리지 않으니 이어폰을 쓰면 꺼 두세요.","translator.noiseSuppression":"AI 소음 제거","translator.fastDrafts":"빠른 초안 자막","translator.fastDraftsHint":"전용 번역 모델이 초안 자막을 먼저 띄우고 Codex가 곧 바로잡습니다. 켜 둔 동안 추가 요금이 들 수 있습니다.","translator.noiseSuppressionHint":"시끄러운 곳에서 마이크 소음을 줄여 통역이 말을 더 잘 알아듣게 합니다. 목소리가 뭉개지면 꺼 두세요."},en:{"translator.modeVoice":"Voice","translator.modeType":"Type","translator.source":"Input language","translator.swapDirection":"Swap direction","translator.typeLabel":"Text to translate","translator.typePlaceholder":"Type what you want to say.","translator.typeSubmit":"Translate","translator.typePending":"Translating…","translator.typeError":"Translation failed. Try again.","translator.typeAuth":"Check your Codex sign-in.","translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and Codex Live on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log","translator.mood":"Mood","translator.mood.casual":"Casual","translator.mood.polite":"Polite","translator.mood.formal":"Formal","translator.mood.haggling":"Haggling","translator.mood.urgent":"Urgent","translator.gender":"My gender","translator.gender.male":"Male","translator.gender.female":"Female","translator.age":"My age","translator.age.20s":"20s","translator.age.30s":"30s","translator.age.40s":"40s","translator.age.50s":"50s","translator.age.60s":"60+","translator.partnerGender":"Their gender","translator.partnerAge":"Their age","translator.partnerAge.child":"Child","translator.partnerAge.younger":"Younger or same age","translator.partnerAge.older":"Older than me","translator.partnerAge.parent":"My parents' age","translator.partnerAge.grandparent":"My grandparents' age","translator.notSet":"Not set","translator.face":"Face to face","translator.faceHint":"Flip the other side's captions so the person across from you can read them","translator.reconnecting":"Reconnecting…","translator.idleStopped":"Interpreting stopped after a long silence. Start again to continue the conversation.","translator.generationSkipped":"That last line couldn't be interpreted and was skipped. Keep talking; interpreting continues.","translator.setup":"Languages and setting","translator.sizeDown":"Smaller text","translator.sizeUp":"Larger text","translator.faceExit":"Leave face to face","translator.translating":"Interpreting…","translator.errorStatus":"Interpreting stopped","translator.translation":"Interpretation","translator.unknownLanguage":"Language unknown","translator.jumpLatest":"Jump to latest","translator.voice":"Play the interpretation aloud","translator.voiceHint":"Off, the interpretation is shown as text only. With the speaker silent the mic stays open, so words spoken over an interpretation are heard too.","translator.echoGuard":"Mute the mic while the interpretation plays","translator.echoGuardHint":"Keeps the speaker's interpretation from being interpreted again. Words spoken meanwhile are not heard, so turn it off with earphones.","translator.noiseSuppression":"AI noise suppression","translator.fastDrafts":"Quick draft captions","translator.fastDraftsHint":"A dedicated translation model shows a quick draft first and Codex corrects it. Extra charges may apply while this is on.","translator.noiseSuppressionHint":"Cuts background noise from the mic in a loud place so the interpreter hears you better. Turn it off if your voice sounds muffled."}};function en(){let{locale:e}=(0,z.s)();return{tt:(0,a.useCallback)((t,r)=>(0,et.u0)(e,t,er,r),[e]),locale:e}}let ea="omp-web:unread-session-ids",ei="omp-web:pinned-session-ids",es="omp-web:removed-projects";function eo(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function el(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function ec({text:e,style:t}){return(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,n.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function ed({open:e,children:t,style:r}){let[i,s]=(0,a.useState)(e),[o,l]=(0,a.useState)(e);return((0,a.useEffect)(()=>{let t,r;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),r=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),r&&clearTimeout(r)}},[e]),i)?(0,n.jsx)("div",{style:{...r,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let eu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ep(){let[e,t]=(0,a.useState)(!1),[r,i]=(0,a.useState)(!1),s=(0,a.useRef)(null),o=function(e,t){let[r,n]=(0,a.useState)(e),i=(0,a.useRef)(null),s=(0,a.useRef)(0);return(0,a.useEffect)(()=>{if(!t)return void n(e);s.current=0;let r=4*e.length,a=()=>{s.current+=1;let t=Math.floor(s.current/r*e.length);n(e.split("").map((e,r)=>" "===e?" ":r<t?e:eu[Math.floor(Math.random()*eu.length)]).join("")),s.current<r?i.current=requestAnimationFrame(a):n(e)};return i.current=requestAnimationFrame(a),()=>{i.current&&cancelAnimationFrame(i.current)}},[e,t]),r}(e?"0.10.231/18.19.0":"CUELO",r),l=(0,a.useCallback)(e=>{t(e),i(!0),setTimeout(()=>i(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,a.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,a.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,n.jsx)("button",{className:"navigator-brand",onClick:c,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,n.jsx)(ee,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eh(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function em({selectedSessionId:e,optimisticSession:t,onSelectSession:r,onNewSession:i,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:m,translatorActive:f=!1,onTranslatorActiveChange:g}){let x,{tt:v}=en(),{t:b,locale:y}=(0,z.s)(),w=B(),[F,_]=(0,a.useState)([]),W=(0,a.useMemo)(()=>t&&!F.some(e=>e.id===t.id)?[t,...F]:F,[F,t]),[O,D]=(0,a.useState)(!0),[H,U]=(0,a.useState)(null),[q,V]=(0,a.useState)(null),[K,G]=(0,a.useState)(""),[Z,Y]=(0,a.useState)(!1),[X,ee]=(0,a.useState)(""),[et,er]=(0,a.useState)("projects"),[eu,eg]=(0,a.useState)(()=>new Set),[ey,ew]=(0,a.useState)(()=>new Set),[ek,eS]=(0,a.useState)(null),[eC,eN]=(0,a.useState)(null),[eT,eI]=(0,a.useState)({version:1,projects:[]}),[eM,eE]=(0,a.useState)(!1),[e$,eR]=(0,a.useState)(!1),[eL,eA]=(0,a.useState)(!1),[eP,eF]=(0,a.useState)(null),[e_,ez]=(0,a.useState)(""),[eW,eO]=(0,a.useState)(!1),[eD,eH]=(0,a.useState)(null),[eU,eB]=(0,a.useState)(""),[eq,eV]=(0,a.useState)(!1),[eK,eG]=(0,a.useState)(null),[eJ,eZ]=(0,a.useState)(!1),[eY,eX]=(0,a.useState)(null),[eQ,e0]=(0,a.useState)(!1),[e1,e2]=(0,a.useState)(!1),[e8,e4]=(0,a.useState)(""),[e5,e6]=(0,a.useState)(null),[e3,e7]=(0,a.useState)(!1),[e9,te]=(0,a.useState)(null),tt=(0,a.useRef)(null),tr=(0,a.useRef)(null),tn=(0,a.useRef)(null),ta=(0,a.useRef)(!1),ti=(0,a.useRef)(!1),[ts,to]=(0,a.useState)(!1),[tl,tc]=(0,a.useState)(()=>new Set),[td,tu]=(0,a.useState)(()=>new Set),[tp,th]=(0,a.useState)(()=>(function(){try{let e=window.localStorage.getItem(ea);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[tm,tf]=(0,a.useState)(()=>new Set),[tg,tx]=(0,a.useState)(null),[tv,tb]=(0,a.useState)(!1),ty=(0,a.useRef)(new Set),tw=(0,a.useRef)(!1),tk=(0,a.useRef)(null);(0,a.useEffect)(()=>{tf(function(){try{let e=window.localStorage.getItem(ei);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]),(0,a.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}tx(T(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=T(e.newValue,Date.now());tx(e=>e?I(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let tj=(0,a.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eI(await e.json())}catch{eI({version:1,projects:[]})}finally{eE(!0)}},[]);(0,a.useEffect)(()=>{tj()},[tj,c]),(0,a.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(es)}catch{return}if(!e)return;let t=[];try{let r=JSON.parse(e);Array.isArray(r)&&(t=r.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let r=t.slice(e,e+500);await eh(r.map(e=>({key:L(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(es)}catch{}await tj()})()},[tj]);let tS=(0,a.useCallback)(async e=>{if(ti.current)throw Error("Project update in progress");ti.current=!0,eO(!0);try{await eh(e),await tj()}finally{ti.current=!1,eO(!1)}},[tj]);(0,a.useEffect)(()=>{eP&&tn.current?.select()},[eP]);let tC=(0,a.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();_(n.sessions),tw.current||tc(new Set(n.runningSessionIds??[])),U(null),e||(to(!0),tk.current&&clearTimeout(tk.current),tk.current=setTimeout(()=>to(!1),2e3))}catch(e){U(String(e))}finally{e&&D(!1)}},[]),tN=(0,a.useCallback)(e=>{th(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),tf(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),tx(t=>t&&R(t,[e])),d?.(e),tC()},[tC,d]),[tT,tI]=(0,a.useState)(null),[tM,tE]=(0,a.useState)(!1),[t$,tR]=(0,a.useState)(null),tL=(0,a.useCallback)(()=>{tM||(tI(null),tR(null))},[tM]),tA=(0,a.useCallback)(async e=>{tE(!0),tR(null);let t=[],r=[],n=[];for(let a of e)if(!a.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(a.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){r.push(a.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(a.id)}catch{n.push(a.name?.trim()||a.id.slice(0,8))}if(r.length>0&&(tw.current=!0,tc(e=>{if(r.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of r)t.add(e);return t})),t.length>0){let e=new Set(t),r=r=>t.some(e=>r.has(e))?new Set([...r].filter(t=>!e.has(t))):r;for(let e of(th(r),tf(r),tx(e=>e&&R(e,t)),t))d?.(e)}(await tC(),tE(!1),n.length>0)?tR(b("sidebar.clearSessionsFailed",{count:n.length,names:n.join(", ")})):r.length>0||tI(null)},[tC,d,b]),[tP,tF]=(0,a.useState)(0),t_=(0,a.useCallback)(()=>{tF(e=>e+1),tC()},[tC]),tz=(0,a.useRef)(!1);(0,a.useEffect)(()=>{let e=!tz.current;tz.current=!0,tC(e,!e)},[tC,c]),(0,a.useEffect)(()=>{try{er(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tW=(0,a.useCallback)(e=>{er(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,a.useEffect)(()=>{if("priority"!==et)return;let e=()=>{"visible"===document.visibilityState&&tC(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tC,et]),(0,a.useEffect)(()=>{try{0===tp.size?window.localStorage.removeItem(ea):window.localStorage.setItem(ea,JSON.stringify([...tp]))}catch{}},[tp]),(0,a.useEffect)(()=>{try{0===tm.size?window.localStorage.removeItem(ei):window.localStorage.setItem(ei,JSON.stringify([...tm]))}catch{}},[tm]),(0,a.useEffect)(()=>{if(tg)try{var e,t,r;let n,a,i=window.localStorage;i.setItem(N,(e=i.getItem(N),t=Date.now(),a=(n=Object.entries((r=I(tg,T(e,t))).opened)).length>500?n.sort((e,t)=>t[1]-e[1]).slice(0,500):n,JSON.stringify({since:r.since,opened:Object.fromEntries(a)})))}catch{}},[tg]);let tO=(0,a.useCallback)(e=>{tf(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]);(0,a.useEffect)(()=>{let e=!1,t=null,r=null,n=()=>{t&&clearTimeout(t),t=null},a=async()=>{if(e||"visible"!==document.visibilityState)return;let i=new AbortController;r?.abort(),r=i;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:i.signal});if(!t.ok)return;let n=await t.json();if(e||r!==i)return;tw.current=!0,tc(new Set(n.runningSessionIds??[])),tu(new Set(n.waitingSessionIds??[]))}catch{}finally{r===i&&(r=null),n(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void a(),2500))}},i=()=>{"visible"===document.visibilityState?a():(n(),r?.abort(),r=null)};return a(),document.addEventListener("visibilitychange",i),()=>{e=!0,n(),r?.abort(),document.removeEventListener("visibilitychange",i)}},[]),(0,a.useEffect)(()=>{let t=ty.current,r=[...t].filter(t=>!tl.has(t)&&t!==e),n=[...tl].filter(e=>!t.has(e));(r.length>0||n.length>0)&&th(e=>{let t=new Set(e);return tl.forEach(e=>t.delete(e)),r.forEach(e=>t.add(e)),t});let a=n.some(e=>!F.some(t=>t.id===e));(r.length>0||a)&&tC(!1,!0),r.length>0&&h?.(),ty.current=tl},[tl,e,F,tC,h]),(0,a.useEffect)(()=>{e&&th(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r})},[e]);let tD=e?W.find(t=>t.id===e)?.modified:void 0,tH=null!==tg;(0,a.useEffect)(()=>{e&&void 0!==tD&&tH&&tx(t=>t&&E(t,{id:e,modified:tD},Date.now()))},[e,tD,tH]),(0,a.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&G(e.home),Y(!0===e.cloudProjects)}).catch(()=>{})},[]);let tU=(0,a.useRef)(!1),tB=(0,a.useCallback)(e=>{if(!e)return null;if(eY&&eY.forCwd===e||eY?.worktrees.some(t=>t.path===e))return eY.projectRoot;let t=W.find(t=>t.cwd===e);return t?.projectRoot??e},[eY,W]),tq=(0,a.useRef)(null);(0,a.useEffect)(()=>{tq.current!==q&&(tq.current=q,p?.(q,tB(q)))},[q,p,tB]);let tV=(0,a.useRef)(null);(0,a.useEffect)(()=>{u&&u!==tV.current&&(tV.current=u,V(u))},[u]);let[tK,tG]=(0,a.useState)(0);(0,a.useLayoutEffect)(()=>{if(!q)return void eX(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(q)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eX(null);eX({forCwd:q,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eX(null)}),()=>{e=!0}},[q,tK,c]),(0,a.useEffect)(()=>{if(0!==F.length&&!o&&null===q){if(s&&!tU.current){tU.current=!0;let e=F.find(e=>e.id===s);if(e){V(e.cwd),r(e,!0);return}l?.()}if(!eM)return;let e=new Map(eT.projects.map(e=>[e.key,e])),t=P(F.length>0?A(F):[],eT.projects).filter(t=>!e.get(L(t))?.hidden);t.length>0&&V(t[0])}},[F,q,s,o,r,l,eT,eM]);let tJ=(0,a.useCallback)(async e=>{let t=e.trim();if(t&&!eJ){eZ(!0),eG(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await e.json().catch(()=>({}));if(!e.ok||r.error)return void eG(r.error??b("workspace.unable"));let n=r.cwd??t,a=L(n),i=eT.projects.find(e=>e.key===a);if(i?.hidden===!0)try{await tS([{key:a,path:n,hidden:!1}])}catch{}V(n),eV(!1)}catch{eG(b("workspace.unable"))}finally{eZ(!1)}}},[tS,eJ,eT.projects,b]),tZ=(0,a.useCallback)(()=>{eV(!0),eG(null)},[]),tY=(0,a.useCallback)(async()=>{let e=e8.trim();if(e&&!e3&&eY){e7(!0),e6(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eY.projectRoot,branch:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error||!r.path)return void e6(r.error??`HTTP ${t.status}`);e2(!1),e4(""),e0(!1),eX(t=>t?{...t,forCwd:r.path,worktrees:[...t.worktrees,{path:r.path,branch:e,isMain:!1}]}:t),V(r.path),tG(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e7(!1)}}},[e8,e3,eY]),tX=(0,a.useCallback)(async(e,t)=>{if(eY&&!e3){e7(!0),e6(null);try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eY.projectRoot,path:e,force:t})}),n=await r.json().catch(()=>({}));if(!r.ok){if(n.dirty&&!t)return void te(e);e6(n.error??`HTTP ${r.status}`);return}te(null),q===e&&V(eY.projectRoot),tG(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e7(!1)}}},[eY,e3,q]);(0,a.useEffect)(()=>{let e=e=>{tt.current&&!tt.current.contains(e.target)&&(eN(null),e0(!1),e2(!1),e4(""),e6(null),te(null),eB(""),eS(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tQ=(0,a.useCallback)(e=>{e.cwd&&V(e.cwd),r(e)},[r]),t0=(0,a.useCallback)((e=q)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;V(e),i?.(t,e)},[q,i]),[t1,t2]=(0,a.useState)(!1),[t8,t4]=(0,a.useState)(null),t5=(0,a.useCallback)(async()=>{t2(!0),t4(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);t0(t.cwd)}catch(e){t4(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{t2(!1)}},[t0,b]),t6=(0,a.useCallback)(e=>{ew(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]),t3=tB(q),t7=null===t3?null:L(t3),t9=(0,a.useMemo)(()=>new Map(eT.projects.map(e=>[e.key,e])),[eT.projects]),re=A(W);if(null!==t3){let e=L(t3);re.some(t=>L(t)===e)||re.unshift(t3)}let rt=P(re,eT.projects),rr=rt.filter(e=>e$||!t9.get(L(e))?.hidden),rn=rt.some(e=>t9.get(L(e))?.hidden),ra=()=>{eN(null),e0(!1),e2(!1),e4(""),e6(null),te(null),eB("")},ri=async(e,t)=>{ra();try{await tS([{key:L(e),path:e,hidden:t}]),t&&t7&&t7===L(e)&&V(null),t||rt.some(t=>L(t)!==L(e)&&t9.get(L(t))?.hidden)||eR(!1)}catch{}},rs=async e=>{if(ta.current){ta.current=!1,eF(null);return}let t=e_.trim();if(t===(t9.get(L(e))?.alias??""))return void eF(null);eH(null);try{await tS([{key:L(e),path:e,alias:t||null}]),eF(null)}catch{eH(b("sidebar.projectUpdateFailed"))}},ro=async(e,t)=>{if(X)return;let r=rr.indexOf(e),n=r+t;if(r<0||n<0||n>=rr.length)return;let a=new Set(rr),i=rt.map((e,t)=>a.has(e)?t:-1).filter(e=>e>=0),s=[...rt],o=i[r],l=i[n];[s[o],s[l]]=[s[l],s[o]],ra();try{await tS(s.map((e,t)=>({key:L(e),path:e,order:t})))}catch{}},rl=new Map;for(let e of W){let t=e.projectRoot??e.cwd;if(!t)continue;let r=L(t),n=rl.get(r);n?n.push(e):rl.set(r,[e])}let rc=(0,a.useMemo)(()=>{let e=new Map;for(let t of W){let r=t.projectRoot??t.cwd;if(!r)continue;let n=L(r),a=e.get(n);a||(a={running:0,unread:0},e.set(n,a)),tl.has(t.id)&&a.running++,tp.has(t.id)&&a.unread++}return e},[W,tl,tp]),rd=X.trim().toLowerCase(),ru=X.length>0,rp=rr.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,r=L(e),n=t9.get(r),a=n?.alias??t,i=(rl.get(r)??[]).slice().sort((e,t)=>{let r=Number(tm.has(t.id))-Number(tm.has(e.id));return 0!==r?r:t.modified.localeCompare(e.modified)});if(!rd)return[{project:e,key:r,name:a,sessions:i,hidden:n?.hidden===!0}];let s=a.toLowerCase().includes(rd)||t.toLowerCase().includes(rd),o=i.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(rd));return s||0!==o.length?[{project:e,key:r,name:a,sessions:s?i:o,hidden:n?.hidden===!0}]:[]}),rh=[],rm=[];for(let e of rp){let t=e.key===t7||(rc.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?rm.push(e):rh.push(e)}let rf={running:0,unread:0};for(let e of rm){let t=rc.get(e.key);t&&(rf.running+=t.running,rf.unread+=t.unread)}let rg=ru||eL,rx=[...rh.map(e=>({kind:"project",group:e})),...rm.length>0?[{kind:"temporary"}]:[],...rg?rm.map(e=>({kind:"project",group:e})):[]],rv=function(e){let t=new Map;for(let r of e){let e=r.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(rx.flatMap(e=>"project"===e.kind?[e.group.name]:[])),rb=(0,a.useMemo)(()=>tg?W.filter(e=>(function(e,t,r,n=$){if(e.transient||e.trial)return!1;if(n.has(e.id))return!0;if(t.has(e.id))return!1;let a=M(e);return null!==a&&a>(r.opened[e.id]??r.since)})(e,tl,tg,td)):[],[tg,tl,W,td]),ry=tv&&null!==tg,[rw,rk]=(0,a.useState)(null),rj=(0,a.useMemo)(()=>(function(e,t,r,n,a="Priority",i=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let r=Date.parse(e.modified),n=Date.parse(t.modified);return(Number.isFinite(n)?n:0)-(Number.isFinite(r)?r:0)}),c=l.filter(e=>i.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(i.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let r=new Date(e.modified);if(p>=o)continue;p+=1;let n=[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"),a=u.get(n);a?a.push(e):u.set(n,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:a,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,r){let[n,a,i]=e.split("-").map(Number),s=new Date(n,a-1,i),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(r,{weekday:"long"}).format(s):new Intl.DateTimeFormat(r,{month:"short",day:"numeric"}).format(s)}(e,r,n),running:!1,sessions:u.get(e)??[]});return h})(ry?W.filter(e=>e.id===rw&&!tl.has(e.id)||rb.includes(e)):W,tl,new Date,y,b("navigator.priority"),tm,b("sidebar.pinned"),ry?1/0:void 0),[rw,y,tm,rb,ry,tl,W,b]),rS=(0,a.useCallback)(e=>{rk(e.id),tQ(e)},[tQ]),rC=!!(eY?.isGit&&eY.isTopLevel&&q&&t3===eY.projectRoot),rN=eY?.worktrees.find(e=>e.path===q)??eY?.worktrees.find(e=>e.isMain),rT=(eY?.worktrees.length??0)>=8,rI=rT&&eU.trim()?(eY?.worktrees??[]).filter(e=>(e.branch??el(e.path,K)).toLowerCase().includes(eU.trim().toLowerCase())):eY?.worktrees??[],rM=(()=>{if(!tT)return[];let e="project"===tT.kind?rl.get(L(tT.project))??[]:rj.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),rE=rM.filter(e=>!tl.has(e.id)),r$=e=>{let t=new Set;for(let r of e)r.transient||tl.has(r.id)||t.has(r.id)||t.add(r.id);return t.size},rR=void 0!==m&&f;return(0,n.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eq&&(0,n.jsx)(Z?Q:J,{busy:eJ,error:eK,onCancel:()=>{eV(!1),eG(null)},onSelect:e=>void tJ(e)}),tT&&(0,n.jsx)(ef,{scope:tT,eligible:rE.length,runningExcluded:rM.length-rE.length,busy:tM,error:t$,onCancel:tL,onConfirm:()=>void tA(rE)}),(0,n.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,n.jsx)(ep,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,n.jsx)("button",{className:"navigator-icon-action",onClick:()=>t0(),disabled:!q,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:q?"var(--text-muted)":"var(--text-dim)",cursor:q?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:"var(--radius-control)",fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:q?b("sidebar.newSessionTitle",{path:q}):b("sidebar.selectProject"),"aria-label":q?b("sidebar.newSessionTitle",{path:q}):b("sidebar.selectProject"),onMouseEnter:e=>{q&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=q?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,n.jsx)("button",{className:`navigator-icon-action${ts?" is-success":""}`,onClick:()=>tC(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ts?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ts?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ts?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:"var(--radius-control)",padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{ts||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{ts||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:ts?(0,n.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),Z&&!rR&&(0,n.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tZ,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,n.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,n.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),r=!rR&&et===e;return(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":r,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tW(e),rR&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"transparent",color:r?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:r?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":rR,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!rR),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:rR?"var(--bg-selected)":"transparent",color:rR?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:rR?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!rR&&"projects"===et&&(0,n.jsx)("button",{type:"button",onClick:()=>eR(e=>!e),disabled:!rn,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":e$,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:e$?"var(--bg-selected)":"transparent",color:e$?"var(--accent)":"var(--text-dim)",cursor:rn?"pointer":"default",opacity:rn?1:.45,flexShrink:0},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!e$&&(0,n.jsx)("path",{d:"m4 4 16 16"})]})}),!rR&&"projects"===et&&(0,n.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tZ,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,n.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),rR&&m,!rR&&"projects"===et&&(0,n.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,n.jsx)("input",{className:"navigator-search-input",type:"search",value:X,onChange:e=>ee(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),ee(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!rR&&"projects"===et&&(0,n.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(O||!eM)&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),eD&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!O&&eM&&!H&&0===rp.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:rd?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!O&&eM&&!H&&rx.map(t=>{let r,a,i;if("temporary"===t.kind)return(0,n.jsx)("div",{className:"navigator-project-group",children:(0,n.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":rg,title:b("sidebar.temporaryProjects"),onClick:()=>eA(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,n.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:rg?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:rm.length}),ej(rf,b)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t7,p=rv.has(l.toLowerCase())&&el((a=Math.max((r=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),r.lastIndexOf("/")))<=0?"":r.slice(0,a),K)||null,h=!ey.has(s)&&!rd,m=eu.has(s),f=eP===s,g=rr.indexOf(s),x=eW||ru||g<=0,v=eW||ru||g>=rr.length-1,y=function(e){let t=new Map;for(let r of e)t.set(r.id,{session:r,children:[]});let r=new Map;for(let t of e)t.parentSessionId&&r.set(t.id,t.parentSessionId);let n=[];for(let e of t.values()){let a=function(e){let n=r.get(e),a=new Set;for(;n&&!a.has(n);){if(a.add(n),t.has(n))return n;n=r.get(n)}return null}(e.session.id);a?t.get(a).children.push(e):n.push(e)}let a=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>a(e.children))};return a(n),n}(m?c:c.slice(0,5)),k=c.length>5;return(0,n.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,n.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:eC===s?tt:void 0,onMouseEnter:()=>eS(s),onMouseLeave:()=>eS(e=>e===s&&eC!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:"var(--radius-control)",background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t6(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,n.jsx)("input",{ref:tn,value:e_,onChange:e=>ez(e.target.value),onBlur:()=>void rs(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),ta.current=!0,eF(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,n.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>V(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,n.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,n.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),ej(rc.get(o),b)]}),(0,n.jsx)("button",{type:"button",onClick:()=>t0(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||ek===s?1:0,pointerEvents:w||ek===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>eS(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,n.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,n.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,n.jsx)("button",{type:"button",onClick:()=>{eN(eC===s?null:s),e0(!1),e2(!1),e6(null),u||V(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":eC===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eC===s?"var(--bg-selected)":"transparent",color:u&&rN&&!rN.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ek===s||eC===s?1:0,pointerEvents:w||ek===s||eC===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>eS(s),children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,n.jsxs)(ed,{open:eC===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[rC&&eY&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",onClick:()=>e0(e=>!e),title:rN?b("sidebar.switchWorktreeTitle",{path:rN.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eQ,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eQ?"1px solid var(--border)":"none",background:eQ?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,n.jsxs)(ed,{open:eQ,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[rT&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("input",{value:eU,onChange:e=>eB(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eB(""),e0(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,n.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[rI.map(e=>{let t=e.path===q||e.isMain&&!eY.worktrees.some(e=>e.path===q);return e9===e.path?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,n.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,n.jsx)("button",{onClick:()=>void tX(e.path,!0),disabled:e3,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,n.jsx)("button",{onClick:()=>te(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:b("sidebar.cancel")})]},e.path):(0,n.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("button",{onClick:()=>{V(e.path),e0(!1),e6(null),eB("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)(ec,{text:e.branch??el(e.path,K),style:{flex:1}}),e.isMain&&(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,n.jsx)("button",{onClick:()=>void tX(e.path,!1),disabled:e3,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:"var(--radius-control)",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),rT&&0===rI.length&&eU.trim()&&(0,n.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e1?(0,n.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,n.jsx)("input",{ref:tr,value:e8,onChange:e=>{e4(e.target.value),e6(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tY()),"Escape"===e.key&&(e2(!1),e4(""),e6(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,n.jsx)("button",{onClick:()=>void tY(),disabled:e3||!e8.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e3||!e8.trim()?"not-allowed":"pointer",opacity:e3||!e8.trim()?.65:1},children:e3?b("sidebar.creating"):b("sidebar.create")}),(0,n.jsx)("button",{onClick:()=>{e2(!1),e4(""),e6(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),e2(!0),e6(null),setTimeout(()=>tr.current?.focus(),0)},title:b("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,n.jsx)("span",{children:b("sidebar.newWorktree")})]}),e5&&(0,n.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e5})]})]}),(0,n.jsxs)("button",{type:"button",disabled:eW,onClick:()=>{let e;return e=t9.get(L(s))?.alias??"",void(ta.current=!1,eH(null),ez(e),eF(s),ra())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eW?"default":"pointer",textAlign:"left",fontSize:11,opacity:eW?.55:1},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,n.jsx)("path",{d:"m13.5 8 3 3"})]}),b(t9.get(L(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,n.jsxs)("button",{type:"button",disabled:x,title:ru?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ro(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,n.jsxs)("button",{type:"button",disabled:v,title:ru?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ro(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,n.jsxs)("button",{type:"button",disabled:eW,onClick:()=>void ri(s,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eW?"default":"pointer",textAlign:"left",fontSize:11,opacity:eW?.55:1},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,n.jsx)("path",{d:"m4 4 16 16"})]}),b(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(i=0===r$(rl.get(o)??[])||tM,(0,n.jsxs)("button",{type:"button",disabled:i,onClick:()=>{ra(),tR(null),tI({kind:"project",project:s,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:i?"default":"pointer",textAlign:"left",fontSize:11,opacity:i?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,n.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,n.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,n.jsx)(eb,{node:t,selectedSessionId:e,runningSessionIds:tl,unreadSessionIds:tp,pinnedSessionIds:tm,onSelectSession:tQ,onTogglePinnedSession:tO,onRenamed:tC,onSessionDeleted:tN,onSessionArchived:t_,depth:0},t.session.id))}),!h&&k&&(0,n.jsx)("button",{type:"button",onClick:()=>{eg(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!rR&&(0,n.jsx)(ev,{refreshKey:tP,selectedSessionId:e,onSelectSession:tQ,onRestored:t_}),!rR&&"priority"===et&&(0,n.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[O&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,n.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),!O&&!H&&(x=r$(rj.flatMap(e=>e.sessions)),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,n.jsx)("button",{type:"button",disabled:t1,onClick:()=>void t5(),title:b("sidebar.newScratchSessionTitle"),style:eo(t1,w),children:b("sidebar.newScratchSession")}),rj.length>0&&!ry&&(0,n.jsx)("button",{type:"button",disabled:0===x||tM,onClick:()=>{tR(null),tI({kind:"priority"})},style:eo(0===x||tM,w),children:b("sidebar.clearPriorityList")})]})),!O&&!H&&tg&&(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,n.jsxs)("button",{type:"button","aria-pressed":ry,"aria-label":b("navigator.resultsToCheckCount",{count:rb.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{rk(null),tb(e=>!e)},style:{...eo(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ry?"var(--border-strong)":"var(--border)",background:ry?"var(--bg-selected)":"transparent",color:ry||rb.length>0?"var(--text)":"var(--text-muted)",fontWeight:ry?600:500,whiteSpace:"nowrap"},children:[b("navigator.resultsToCheck"),(0,n.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:rb.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:rb.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:rb.length})]}),rb.some(e=>!td.has(e.id))&&(0,n.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{rk(null),tx(e=>e&&function(e,t,r){let n=e;for(let e of t)n=E(n,e,r);return n}(e,rb,Date.now()))},style:eo(!1,w),children:b("navigator.acknowledgeResults")})]}),t8&&(0,n.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:t8}),!O&&!H&&0===rj.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ry?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!O&&!H&&rj.map((t,r)=>(0,n.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,n.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===r?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,n.jsx)(ex,{session:t,selected:t.id===e,running:tl.has(t.id),waiting:td.has(t.id),unread:tp.has(t.id),pinned:tm.has(t.id),onSelect:ry?rS:tQ,onTogglePin:tO},t.id))]},t.key))]})]})}function ef({scope:e,eligible:t,runningExcluded:r,busy:i,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,z.s)(),d=i||0===t,u=(0,a.useRef)(null),p=(0,a.useRef)(null),h=(0,a.useRef)(i);h.current=i;let m=(0,a.useRef)(o);return m.current=o,(0,a.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,r=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let n=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let a=r[0],i=r[r.length-1];t.shiftKey&&(n===a||!e.contains(n))?(t.preventDefault(),i.focus()):t.shiftKey||n!==i&&e.contains(n)||(t.preventDefault(),a.focus())};return e.addEventListener("keydown",n),()=>{e.removeEventListener("keydown",n);let t=r?.isConnected?r:e.closest(".session-navigator");t?.focus()}},[]),(0,n.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{i||e.target!==e.currentTarget||o()},children:(0,n.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,n.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,n.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),r>0&&(0,n.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:r})}),0===t&&(0,n.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{ref:p,type:"button",onClick:o,disabled:i,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:i?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,n.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":i,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(i?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function eg({filled:e=!1}){return(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 17v5"}),(0,n.jsx)("path",{d:"M5 17h14"}),(0,n.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ex({session:e,selected:t,running:r,waiting:a,unread:i,pinned:s,onSelect:o,onTogglePin:l}){let{t:c}=(0,z.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),u=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,n.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${r?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,n.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>o(e),title:`${d}
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2498:e=>{e.exports={view:"MemoryTraceView_view__62Ck_",body:"MemoryTraceView_body__gELit",message:"MemoryTraceView_message__pDO_k",errorText:"MemoryTraceView_errorText__GkoKJ",sectionTitle:"MemoryTraceView_sectionTitle__lmuuo",sectionCount:"MemoryTraceView_sectionCount__9yRSn",requests:"MemoryTraceView_requests__scPBk",requestScroller:"MemoryTraceView_requestScroller__4ALfU",requestList:"MemoryTraceView_requestList__rQ4G0",requestRow:"MemoryTraceView_requestRow__LZd3A",stationButton:"MemoryTraceView_stationButton__BztyW",requestIndex:"MemoryTraceView_requestIndex__TacwG",requestTime:"MemoryTraceView_requestTime__fJjQF",noticeChip:"MemoryTraceView_noticeChip__gz9AO",requestPreview:"MemoryTraceView_requestPreview__HwG7v",miniRail:"MemoryTraceView_miniRail__84C2v",flow:"MemoryTraceView_flow__UCgmI",titleText:"MemoryTraceView_titleText__38Tl7",flowPreview:"MemoryTraceView_flowPreview__HjgKe",rail:"MemoryTraceView_rail__HlWbE",station:"MemoryTraceView_station__ulNBH",stationStep:"MemoryTraceView_stationStep__CgFYZ",stationCount:"MemoryTraceView_stationCount__2_rrN",stationLabel:"MemoryTraceView_stationLabel__QGYpC",stationNote:"MemoryTraceView_stationNote__Jc30I",detail:"MemoryTraceView_detail__Rnn_d",stageEmpty:"MemoryTraceView_stageEmpty__x0H_J",group:"MemoryTraceView_group__1SCqK",bucket:"MemoryTraceView_bucket__Vmuau",groupTitle:"MemoryTraceView_groupTitle__6Q1oM",groupCode:"MemoryTraceView_groupCode__qgzOG",query:"MemoryTraceView_query__DK87N",items:"MemoryTraceView_items__D8Wz8",item:"MemoryTraceView_item__wyulb",idList:"MemoryTraceView_idList__mQArH",path:"MemoryTraceView_path__97O3u",itemHead:"MemoryTraceView_itemHead__B0bQo",memoryId:"MemoryTraceView_memoryId__5KjoX",itemMeta:"MemoryTraceView_itemMeta__wbj6K",itemText:"MemoryTraceView_itemText__O92R_",graph:"MemoryTraceView_graph__RHbn9",graphHead:"MemoryTraceView_graphHead__sEDhc",scopeSwitch:"MemoryTraceView_scopeSwitch__3HBI2",legend:"MemoryTraceView_legend__52_dq",legendMark:"MemoryTraceView_legendMark__hS7sK",legendTitle:"MemoryTraceView_legendTitle__z_lgW",legendMemory:"MemoryTraceView_legendMemory__mkYqP",graphCaption:"MemoryTraceView_graphCaption__ot7gW",captionKind:"MemoryTraceView_captionKind__e1fLD",graphFrame:"MemoryTraceView_graphFrame__SgiqG",graphSvg:"MemoryTraceView_graphSvg___JeWV",columnHeads:"MemoryTraceView_columnHeads__drsYb",edges:"MemoryTraceView_edges__4zMSL",node:"MemoryTraceView_node__ymwrL",hit:"MemoryTraceView_hit__HS6HS",mark:"MemoryTraceView_mark__WxCZl",arrow:"MemoryTraceView_arrow__oz9U4",nodeText:"MemoryTraceView_nodeText__Tp4ud",ring:"MemoryTraceView_ring___LM5n"}},2730:(e,t,r)=>{"use strict";function n(e,t,r,a={}){let i=r[e]?.[t]??r.en?.[t];return void 0===i?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,r)=>{let n=t[r];return void 0===n?e:String(n)})}(i,a)}r.d(t,{u0:()=>n})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,r)=>{"use strict";r.d(t,{C1:()=>i,IN:()=>a,getPresetFromTools:()=>o,xG:()=>l});let n=[],a=["read","bash","edit","write"],i=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(i.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let r=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return r===[...a].sort().join(",")?"default":r===[...i].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...n]:"full"===e?[...i]:[...a]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},29213:e=>{e.exports={view:"PluginLabPanel_view__Sot51",toolbar:"PluginLabPanel_toolbar__co_Uq",hint:"PluginLabPanel_hint__kb7Hq",body:"PluginLabPanel_body__T_QMu",message:"PluginLabPanel_message__QbEDh",errorText:"PluginLabPanel_errorText__EI47_",list:"PluginLabPanel_list__BnAn6",card:"PluginLabPanel_card__5479R",cardHead:"PluginLabPanel_cardHead__SCiZ3",titleBlock:"PluginLabPanel_titleBlock__zfcvo",titleLine:"PluginLabPanel_titleLine__OmG7U",name:"PluginLabPanel_name__t4Ea0",id:"PluginLabPanel_id__osclH",control:"PluginLabPanel_control___gzgN",switch:"PluginLabPanel_switch__m3agg",switchLabel:"PluginLabPanel_switchLabel__DGX6y",description:"PluginLabPanel_description__PfruO",enhancement:"PluginLabPanel_enhancement__TOHjM",enhancementHead:"PluginLabPanel_enhancementHead__sgewN",enhancementDate:"PluginLabPanel_enhancementDate__4YWB1",enhancementSummary:"PluginLabPanel_enhancementSummary__srTnj",tools:"PluginLabPanel_tools__raR8s",metaLabel:"PluginLabPanel_metaLabel__LY5ak",toolList:"PluginLabPanel_toolList___rd6_",tool:"PluginLabPanel_tool___AjRR",problem:"PluginLabPanel_problem__Sx4aQ",problemLabel:"PluginLabPanel_problemLabel__rBSUT",cardActions:"PluginLabPanel_cardActions__GI_Bb",stage:"PluginLabPanel_stage__1l0FR",frame:"PluginLabPanel_frame__sP_V0",status:"PluginLabPanel_status__BYiAs",lines:"PluginLabPanel_lines__ONctT",notice:"PluginLabPanel_notice__mn_vu"}},40960:e=>{e.exports={active:"ComputerTakeoverControl_active__7430b"}},66592:e=>{e.exports={root:"TypedInterpreter_root__q_c0E",results:"TypedInterpreter_results__6j7HQ",turn:"TypedInterpreter_turn__BELhE",label:"TypedInterpreter_label__tFGb1",original:"TypedInterpreter_original__IxOOM",translation:"TypedInterpreter_translation__bR55x",composer:"TypedInterpreter_composer__IgxpT",direction:"TypedInterpreter_direction__8Chyz",field:"TypedInterpreter_field__6QmFe",submit:"TypedInterpreter_submit__tRKd5",error:"TypedInterpreter_error__h7BTN",modes:"TypedInterpreter_modes__Krr0C",toolbar:"TypedInterpreter_toolbar__L_2u0"}},80455:(e,t,r)=>{Promise.resolve().then(r.bind(r,81353)),Promise.resolve().then(r.bind(r,84183))},81353:(e,t,r)=>{"use strict";r.d(t,{AppShell:()=>yC});var n=r(95155),a=r(12115),i=r(73321),s=r(16871),o=r(81886),l=r(68890),c=r(66919);let d=["chat","process","subagents","files","resource","sidechat","efficiency","plugins","memory"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),m=Object.fromEntries(d.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let r,n=f(t.view);return{activeView:n,transientLayer:null,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"open-layer":{let r,n=f(e.activeView);return{activeView:n,transientLayer:t.layer,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"toggle-layer":{let r,n=f(e.activeView);return{activeView:n,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(r=!0===e.deckExpanded,"chat"!==n&&r)}}case"close-layer":{let t,r=f(e.activeView);return{activeView:r,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==r&&t)}}case"set-deck-expanded":{let r,n=f(e.activeView);return{activeView:n,transientLayer:e.transientLayer,deckExpanded:(r=t.expanded,"chat"!==n&&r)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function T(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[r,n]of Object.entries(t.opened))"number"==typeof n&&Number.isFinite(n)&&(e[r]=n);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let r=null;for(let[n,a]of Object.entries(t.opened))(e.opened[n]??-1/0)>=a||((r??={...e.opened})[n]=a);return!r&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:r??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function E(e,t,r){let n=Math.max(r,M(t)??0);return(e.opened[t.id]??-1/0)>=n?e:{since:e.since,opened:{...e.opened,[t.id]:n}}}let $=new Set;function R(e,t){let r=null;for(let n of t)Object.hasOwn(e.opened,n)&&(r??={...e.opened},delete r[n]);return r?{since:e.since,opened:r}:e}function L(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function A(e){let t=new Map;for(let r of e){let e=r.projectRoot??r.cwd;if(!e)continue;let n=L(e),a=t.get(n);(!a||r.modified>a.modified)&&t.set(n,{project:e,modified:r.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function P(e,t){let r=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&r.set(L(e.key),e.order);let n=[...e],a=new Set(e.map(L));for(let e of t){let t=L(e.key);!t||a.has(t)||(n.push(e.path??e.key),a.add(t))}return n.map((e,t)=>({project:e,defaultIndex:t,order:r.get(L(e))})).sort((e,t)=>{let r=void 0!==e.order,n=void 0!==t.order;return r!==n?r?-1:1:r&&n&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let F=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function _(e){let t=e.match(F);if(!t)return null;let[,r,,,n]=t;return n?`/skill:${r} ${n}`:`/skill:${r}`}var z=r(84183);let W=`(max-width: ${p.navigator-1}px)`;function O(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let r=window.matchMedia(e);return r.addEventListener("change",t),()=>r.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=O("(max-width: 640px)"),H=O(W);function U(){return!1}function B(){return(0,a.useSyncExternalStore)(D.subscribe,D.getSnapshot,U)}var q=r(47650);async function V(e){let t=e?`?path=${encodeURIComponent(e)}`:"",r=await fetch(`/api/cwd/browse${t}`),n=await r.json();if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return n}function K(){return(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function G(){return(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,n.jsx)("path",{d:"M2 9h12"}),(0,n.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function J({onCancel:e,onSelect:t,busy:r=!1,error:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(""),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(""),[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)(null),[w,k]=(0,a.useState)(null),[j,S]=(0,a.useState)(!0),C=(0,a.useCallback)(async e=>{S(!0),k(null);try{let t=await V(e),r=t.path??e??"/";d(r),p(t.parentPath??null),m(!0===t.upToDrives),g(r),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,a.useEffect)(()=>{l(document.body),C()},[C]);let N=f.trim()!==c,T=!!c&&!N&&!r,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,q.createPortal)((0,n.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||r||e()},onKeyDown:t=>{"Escape"!==t.key||r||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,n.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1},children:(0,n.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,n.jsx)("button",{type:"button",onClick:e,disabled:r,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:r?"default":"pointer",opacity:r?.5:1},children:"\xd7"})]}),(0,n.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!I,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:I?"pointer":"default",opacity:I?1:.45},children:(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,n.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,n.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,n.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,n.jsx)(n.Fragment,{children:b.length>0?b.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(G,{}),(0,n.jsx)("span",{children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,n.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,n.jsx)(K,{}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,n.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||i)&&(0,n.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??i})]}),(0,n.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:r,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:r?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,n.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!T,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:T?1:.6,cursor:T?"pointer":"default"},children:s(r?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Z=r(21443),Y=r.n(Z);async function X(e,t){let r=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),n=await r.json();if(!r.ok)throw Error(n.error||`HTTP ${r.status}`);return n}function Q({onCancel:e,onSelect:t,busy:r=!1,error:i}){let{t:s}=(0,z.s)(),o=(0,a.useRef)(null),[l,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(!1),[p,h]=(0,a.useState)(null),[m,f]=(0,a.useState)([]),[g,x]=(0,a.useState)(""),[v,b]=(0,a.useState)(""),[y,w]=(0,a.useState)(!0),[k,j]=(0,a.useState)(!1),[S,C]=(0,a.useState)(!1),[N,T]=(0,a.useState)(null),[I,M]=(0,a.useState)(!1),[E,$]=(0,a.useState)(50),R=p?.device?.state==="pending",L=r||S,A=(0,a.useCallback)(async()=>{w(!0),T(null);try{let e=await X("/api/github/projects");h(e),e.connected&&f((await X("/api/github/projects?view=repositories")).repositories)}catch(e){T(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function P(){j(!0),T(null);try{let{device:e}=await X("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){T(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function F(e){if(e.preventDefault(),v.trim()&&!L){C(!0),T(null);try{let{cwd:e}=await X("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){T(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,a.useEffect)(()=>{c(!0),A()},[A]),(0,a.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,a.useEffect)(()=>{let e;if(!R||d)return;let t=!1,r=async()=>{try{let e=await X("/api/github/projects");if(t)return;if(h(e),e.connected)return void await A();if(e.device?.state!=="pending")return}catch(e){t||T(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(r,3e3))};return e=window.setTimeout(r,1500),()=>{t=!0,clearTimeout(e)}},[R,d,A]),!l)return null;if(d)return(0,n.jsx)(J,{onCancel:()=>u(!1),onSelect:t,busy:r,error:i});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),W=N??i??p?.device?.error;return(0,q.createPortal)((0,n.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),L||e()},children:(0,n.jsxs)("form",{onSubmit:F,className:Y().form,children:[(0,n.jsxs)("header",{className:Y().header,children:[(0,n.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,n.jsx)("p",{children:s("cloudProjects.description")})]}),(0,n.jsxs)("div",{className:Y().sources,children:[(0,n.jsx)("span",{className:Y().activeSource,children:s("cloudProjects.github")}),(0,n.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:L,children:s("cloudProjects.serverFolder")})]}),(0,n.jsxs)("div",{className:Y().body,children:[(0,n.jsxs)("section",{className:Y().account,"aria-label":s("cloudProjects.account"),children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,n.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:y||L,children:s("cloudProjects.refresh")}):(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:y||k||R||L,children:k||R?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),R&&(0,n.jsxs)("div",{className:Y().login,role:"status",children:[(0,n.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:Y().codeRow,children:[(0,n.jsx)("code",{children:p.device.code}),(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>T(s("cloudProjects.copyFailure")))},children:I?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,n.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Y().loginLink,children:s("cloudProjects.openLogin")}),(0,n.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,n.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,n.jsxs)("section",{className:Y().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,n.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,n.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),$(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:L}),y?(0,n.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:Y().list,children:_.slice(0,E).map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":v===e.fullName,disabled:L,onClick:()=>b(e.fullName),children:[(0,n.jsxs)("span",{className:Y().repoHeading,children:[(0,n.jsx)("strong",{children:e.fullName}),(0,n.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,n.jsx)("span",{className:Y().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,n.jsx)("p",{children:s("cloudProjects.empty")}),_.length>E&&(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>$(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,n.jsxs)("div",{className:Y().repositoryInput,children:[(0,n.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,n.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:L,"aria-describedby":"cloud-repo-help"}),(0,n.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),W&&(0,n.jsxs)("div",{className:Y().error,role:"alert",children:[(0,n.jsx)("strong",{children:s("cloudProjects.error")}),(0,n.jsx)("p",{children:W}),(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:L,children:s("cloudProjects.refresh")})]}),S&&(0,n.jsx)("p",{role:"status",className:Y().progress,children:s("cloudProjects.openingHelp")})]}),(0,n.jsxs)("footer",{className:Y().footer,children:[(0,n.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:L,children:s("i18n.cancel")}),(0,n.jsx)("button",{type:"submit",className:Y().primary,disabled:L||!v.trim(),children:L?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function ee({label:e="CUELO",markSize:t=22,gap:r=10,style:a,labelStyle:i}){return(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:r,minWidth:0,color:"var(--text)",...a},children:[(0,n.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,n.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...i},children:e})]})}var et=r(2730);let er={ko:{"translator.modeVoice":"대화","translator.modeType":"타자","translator.source":"입력 언어","translator.swapDirection":"방향 바꾸기","translator.typeLabel":"번역할 문장","translator.typePlaceholder":"여행 중 전할 말을 입력하세요.","translator.typeSubmit":"번역","translator.typePending":"번역 중…","translator.typeError":"번역하지 못했어요. 다시 시도해 주세요.","translator.typeAuth":"Codex 로그인 상태를 확인해 주세요.","translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브가 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록","translator.mood":"분위기","translator.mood.casual":"편하게","translator.mood.polite":"정중하게","translator.mood.formal":"격식 있게","translator.mood.haggling":"흥정","translator.mood.urgent":"긴급","translator.gender":"내 성별","translator.gender.male":"남성","translator.gender.female":"여성","translator.age":"내 나이대","translator.age.20s":"20대","translator.age.30s":"30대","translator.age.40s":"40대","translator.age.50s":"50대","translator.age.60s":"60대 이상","translator.partnerGender":"상대 성별","translator.partnerAge":"상대 나이","translator.partnerAge.child":"아이","translator.partnerAge.younger":"나보다 어리거나 비슷","translator.partnerAge.older":"나보다 위","translator.partnerAge.parent":"부모님 또래","translator.partnerAge.grandparent":"조부모님 또래","translator.notSet":"선택 안 함","translator.face":"마주보기","translator.faceHint":"상대 쪽 자막을 뒤집어 마주 앉은 사람이 읽게 합니다","translator.reconnecting":"다시 연결 중…","translator.idleStopped":"한동안 대화가 없어 통역을 멈췄습니다. 다시 시작하면 앞 대화에 이어집니다.","translator.generationSkipped":"방금 말은 통역하지 못하고 넘어갔습니다. 이어서 말씀하시면 계속 통역합니다.","translator.setup":"언어\xb7상황 설정","translator.sizeDown":"글자 작게","translator.sizeUp":"글자 크게","translator.faceExit":"마주보기 끄기","translator.translating":"옮기는 중…","translator.errorStatus":"통역이 멈췄습니다","translator.translation":"통역","translator.unknownLanguage":"언어 모름","translator.jumpLatest":"최근 말로","translator.voice":"통역 음성 듣기","translator.voiceHint":"끄면 통역을 글로만 보여 줍니다. 스피커가 조용하니 마이크를 막지 않아 통역 중에 끼어든 말도 들립니다.","translator.echoGuard":"통역 음성이 나올 때 마이크 끄기","translator.echoGuardHint":"스피커로 나온 통역이 다시 통역되지 않게 합니다. 그동안 상대가 한 말은 들리지 않으니 이어폰을 쓰면 꺼 두세요.","translator.noiseSuppression":"AI 소음 제거","translator.fastDrafts":"빠른 초안 자막","translator.fastDraftsHint":"전용 번역 모델이 초안 자막을 먼저 띄우고 Codex가 곧 바로잡습니다. 켜 둔 동안 추가 요금이 들 수 있습니다.","translator.noiseSuppressionHint":"시끄러운 곳에서 마이크 소음을 줄여 통역이 말을 더 잘 알아듣게 합니다. 목소리가 뭉개지면 꺼 두세요."},en:{"translator.modeVoice":"Voice","translator.modeType":"Type","translator.source":"Input language","translator.swapDirection":"Swap direction","translator.typeLabel":"Text to translate","translator.typePlaceholder":"Type what you want to say.","translator.typeSubmit":"Translate","translator.typePending":"Translating…","translator.typeError":"Translation failed. Try again.","translator.typeAuth":"Check your Codex sign-in.","translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and Codex Live on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log","translator.mood":"Mood","translator.mood.casual":"Casual","translator.mood.polite":"Polite","translator.mood.formal":"Formal","translator.mood.haggling":"Haggling","translator.mood.urgent":"Urgent","translator.gender":"My gender","translator.gender.male":"Male","translator.gender.female":"Female","translator.age":"My age","translator.age.20s":"20s","translator.age.30s":"30s","translator.age.40s":"40s","translator.age.50s":"50s","translator.age.60s":"60+","translator.partnerGender":"Their gender","translator.partnerAge":"Their age","translator.partnerAge.child":"Child","translator.partnerAge.younger":"Younger or same age","translator.partnerAge.older":"Older than me","translator.partnerAge.parent":"My parents' age","translator.partnerAge.grandparent":"My grandparents' age","translator.notSet":"Not set","translator.face":"Face to face","translator.faceHint":"Flip the other side's captions so the person across from you can read them","translator.reconnecting":"Reconnecting…","translator.idleStopped":"Interpreting stopped after a long silence. Start again to continue the conversation.","translator.generationSkipped":"That last line couldn't be interpreted and was skipped. Keep talking; interpreting continues.","translator.setup":"Languages and setting","translator.sizeDown":"Smaller text","translator.sizeUp":"Larger text","translator.faceExit":"Leave face to face","translator.translating":"Interpreting…","translator.errorStatus":"Interpreting stopped","translator.translation":"Interpretation","translator.unknownLanguage":"Language unknown","translator.jumpLatest":"Jump to latest","translator.voice":"Play the interpretation aloud","translator.voiceHint":"Off, the interpretation is shown as text only. With the speaker silent the mic stays open, so words spoken over an interpretation are heard too.","translator.echoGuard":"Mute the mic while the interpretation plays","translator.echoGuardHint":"Keeps the speaker's interpretation from being interpreted again. Words spoken meanwhile are not heard, so turn it off with earphones.","translator.noiseSuppression":"AI noise suppression","translator.fastDrafts":"Quick draft captions","translator.fastDraftsHint":"A dedicated translation model shows a quick draft first and Codex corrects it. Extra charges may apply while this is on.","translator.noiseSuppressionHint":"Cuts background noise from the mic in a loud place so the interpreter hears you better. Turn it off if your voice sounds muffled."}};function en(){let{locale:e}=(0,z.s)();return{tt:(0,a.useCallback)((t,r)=>(0,et.u0)(e,t,er,r),[e]),locale:e}}let ea="omp-web:unread-session-ids",ei="omp-web:pinned-session-ids",es="omp-web:removed-projects";function eo(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function el(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function ec({text:e,style:t}){return(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,n.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function ed({open:e,children:t,style:r}){let[i,s]=(0,a.useState)(e),[o,l]=(0,a.useState)(e);return((0,a.useEffect)(()=>{let t,r;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),r=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),r&&clearTimeout(r)}},[e]),i)?(0,n.jsx)("div",{style:{...r,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let eu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ep(){let[e,t]=(0,a.useState)(!1),[r,i]=(0,a.useState)(!1),s=(0,a.useRef)(null),o=function(e,t){let[r,n]=(0,a.useState)(e),i=(0,a.useRef)(null),s=(0,a.useRef)(0);return(0,a.useEffect)(()=>{if(!t)return void n(e);s.current=0;let r=4*e.length,a=()=>{s.current+=1;let t=Math.floor(s.current/r*e.length);n(e.split("").map((e,r)=>" "===e?" ":r<t?e:eu[Math.floor(Math.random()*eu.length)]).join("")),s.current<r?i.current=requestAnimationFrame(a):n(e)};return i.current=requestAnimationFrame(a),()=>{i.current&&cancelAnimationFrame(i.current)}},[e,t]),r}(e?"0.10.232/18.20.0":"CUELO",r),l=(0,a.useCallback)(e=>{t(e),i(!0),setTimeout(()=>i(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,a.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,a.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,n.jsx)("button",{className:"navigator-brand",onClick:c,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,n.jsx)(ee,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eh(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function em({selectedSessionId:e,optimisticSession:t,onSelectSession:r,onNewSession:i,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:m,translatorActive:f=!1,onTranslatorActiveChange:g}){let x,{tt:v}=en(),{t:b,locale:y}=(0,z.s)(),w=B(),[F,_]=(0,a.useState)([]),W=(0,a.useMemo)(()=>t&&!F.some(e=>e.id===t.id)?[t,...F]:F,[F,t]),[O,D]=(0,a.useState)(!0),[H,U]=(0,a.useState)(null),[q,V]=(0,a.useState)(null),[K,G]=(0,a.useState)(""),[Z,Y]=(0,a.useState)(!1),[X,ee]=(0,a.useState)(""),[et,er]=(0,a.useState)("projects"),[eu,eg]=(0,a.useState)(()=>new Set),[ey,ew]=(0,a.useState)(()=>new Set),[ek,eS]=(0,a.useState)(null),[eC,eN]=(0,a.useState)(null),[eT,eI]=(0,a.useState)({version:1,projects:[]}),[eM,eE]=(0,a.useState)(!1),[e$,eR]=(0,a.useState)(!1),[eL,eA]=(0,a.useState)(!1),[eP,eF]=(0,a.useState)(null),[e_,ez]=(0,a.useState)(""),[eW,eO]=(0,a.useState)(!1),[eD,eH]=(0,a.useState)(null),[eU,eB]=(0,a.useState)(""),[eq,eV]=(0,a.useState)(!1),[eK,eG]=(0,a.useState)(null),[eJ,eZ]=(0,a.useState)(!1),[eY,eX]=(0,a.useState)(null),[eQ,e0]=(0,a.useState)(!1),[e1,e2]=(0,a.useState)(!1),[e8,e4]=(0,a.useState)(""),[e5,e6]=(0,a.useState)(null),[e3,e7]=(0,a.useState)(!1),[e9,te]=(0,a.useState)(null),tt=(0,a.useRef)(null),tr=(0,a.useRef)(null),tn=(0,a.useRef)(null),ta=(0,a.useRef)(!1),ti=(0,a.useRef)(!1),[ts,to]=(0,a.useState)(!1),[tl,tc]=(0,a.useState)(()=>new Set),[td,tu]=(0,a.useState)(()=>new Set),[tp,th]=(0,a.useState)(()=>(function(){try{let e=window.localStorage.getItem(ea);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[tm,tf]=(0,a.useState)(()=>new Set),[tg,tx]=(0,a.useState)(null),[tv,tb]=(0,a.useState)(!1),ty=(0,a.useRef)(new Set),tw=(0,a.useRef)(!1),tk=(0,a.useRef)(null);(0,a.useEffect)(()=>{tf(function(){try{let e=window.localStorage.getItem(ei);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]),(0,a.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}tx(T(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=T(e.newValue,Date.now());tx(e=>e?I(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let tj=(0,a.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eI(await e.json())}catch{eI({version:1,projects:[]})}finally{eE(!0)}},[]);(0,a.useEffect)(()=>{tj()},[tj,c]),(0,a.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(es)}catch{return}if(!e)return;let t=[];try{let r=JSON.parse(e);Array.isArray(r)&&(t=r.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let r=t.slice(e,e+500);await eh(r.map(e=>({key:L(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(es)}catch{}await tj()})()},[tj]);let tS=(0,a.useCallback)(async e=>{if(ti.current)throw Error("Project update in progress");ti.current=!0,eO(!0);try{await eh(e),await tj()}finally{ti.current=!1,eO(!1)}},[tj]);(0,a.useEffect)(()=>{eP&&tn.current?.select()},[eP]);let tC=(0,a.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();_(n.sessions),tw.current||tc(new Set(n.runningSessionIds??[])),U(null),e||(to(!0),tk.current&&clearTimeout(tk.current),tk.current=setTimeout(()=>to(!1),2e3))}catch(e){U(String(e))}finally{e&&D(!1)}},[]),tN=(0,a.useCallback)(e=>{th(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),tf(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r}),tx(t=>t&&R(t,[e])),d?.(e),tC()},[tC,d]),[tT,tI]=(0,a.useState)(null),[tM,tE]=(0,a.useState)(!1),[t$,tR]=(0,a.useState)(null),tL=(0,a.useCallback)(()=>{tM||(tI(null),tR(null))},[tM]),tA=(0,a.useCallback)(async e=>{tE(!0),tR(null);let t=[],r=[],n=[];for(let a of e)if(!a.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(a.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){r.push(a.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(a.id)}catch{n.push(a.name?.trim()||a.id.slice(0,8))}if(r.length>0&&(tw.current=!0,tc(e=>{if(r.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of r)t.add(e);return t})),t.length>0){let e=new Set(t),r=r=>t.some(e=>r.has(e))?new Set([...r].filter(t=>!e.has(t))):r;for(let e of(th(r),tf(r),tx(e=>e&&R(e,t)),t))d?.(e)}(await tC(),tE(!1),n.length>0)?tR(b("sidebar.clearSessionsFailed",{count:n.length,names:n.join(", ")})):r.length>0||tI(null)},[tC,d,b]),[tP,tF]=(0,a.useState)(0),t_=(0,a.useCallback)(()=>{tF(e=>e+1),tC()},[tC]),tz=(0,a.useRef)(!1);(0,a.useEffect)(()=>{let e=!tz.current;tz.current=!0,tC(e,!e)},[tC,c]),(0,a.useEffect)(()=>{try{er(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tW=(0,a.useCallback)(e=>{er(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,a.useEffect)(()=>{if("priority"!==et)return;let e=()=>{"visible"===document.visibilityState&&tC(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tC,et]),(0,a.useEffect)(()=>{try{0===tp.size?window.localStorage.removeItem(ea):window.localStorage.setItem(ea,JSON.stringify([...tp]))}catch{}},[tp]),(0,a.useEffect)(()=>{try{0===tm.size?window.localStorage.removeItem(ei):window.localStorage.setItem(ei,JSON.stringify([...tm]))}catch{}},[tm]),(0,a.useEffect)(()=>{if(tg)try{var e,t,r;let n,a,i=window.localStorage;i.setItem(N,(e=i.getItem(N),t=Date.now(),a=(n=Object.entries((r=I(tg,T(e,t))).opened)).length>500?n.sort((e,t)=>t[1]-e[1]).slice(0,500):n,JSON.stringify({since:r.since,opened:Object.fromEntries(a)})))}catch{}},[tg]);let tO=(0,a.useCallback)(e=>{tf(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]);(0,a.useEffect)(()=>{let e=!1,t=null,r=null,n=()=>{t&&clearTimeout(t),t=null},a=async()=>{if(e||"visible"!==document.visibilityState)return;let i=new AbortController;r?.abort(),r=i;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:i.signal});if(!t.ok)return;let n=await t.json();if(e||r!==i)return;tw.current=!0,tc(new Set(n.runningSessionIds??[])),tu(new Set(n.waitingSessionIds??[]))}catch{}finally{r===i&&(r=null),n(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void a(),2500))}},i=()=>{"visible"===document.visibilityState?a():(n(),r?.abort(),r=null)};return a(),document.addEventListener("visibilitychange",i),()=>{e=!0,n(),r?.abort(),document.removeEventListener("visibilitychange",i)}},[]),(0,a.useEffect)(()=>{let t=ty.current,r=[...t].filter(t=>!tl.has(t)&&t!==e),n=[...tl].filter(e=>!t.has(e));(r.length>0||n.length>0)&&th(e=>{let t=new Set(e);return tl.forEach(e=>t.delete(e)),r.forEach(e=>t.add(e)),t});let a=n.some(e=>!F.some(t=>t.id===e));(r.length>0||a)&&tC(!1,!0),r.length>0&&h?.(),ty.current=tl},[tl,e,F,tC,h]),(0,a.useEffect)(()=>{e&&th(t=>{if(!t.has(e))return t;let r=new Set(t);return r.delete(e),r})},[e]);let tD=e?W.find(t=>t.id===e)?.modified:void 0,tH=null!==tg;(0,a.useEffect)(()=>{e&&void 0!==tD&&tH&&tx(t=>t&&E(t,{id:e,modified:tD},Date.now()))},[e,tD,tH]),(0,a.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&G(e.home),Y(!0===e.cloudProjects)}).catch(()=>{})},[]);let tU=(0,a.useRef)(!1),tB=(0,a.useCallback)(e=>{if(!e)return null;if(eY&&eY.forCwd===e||eY?.worktrees.some(t=>t.path===e))return eY.projectRoot;let t=W.find(t=>t.cwd===e);return t?.projectRoot??e},[eY,W]),tq=(0,a.useRef)(null);(0,a.useEffect)(()=>{tq.current!==q&&(tq.current=q,p?.(q,tB(q)))},[q,p,tB]);let tV=(0,a.useRef)(null);(0,a.useEffect)(()=>{u&&u!==tV.current&&(tV.current=u,V(u))},[u]);let[tK,tG]=(0,a.useState)(0);(0,a.useLayoutEffect)(()=>{if(!q)return void eX(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(q)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eX(null);eX({forCwd:q,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eX(null)}),()=>{e=!0}},[q,tK,c]),(0,a.useEffect)(()=>{if(0!==F.length&&!o&&null===q){if(s&&!tU.current){tU.current=!0;let e=F.find(e=>e.id===s);if(e){V(e.cwd),r(e,!0);return}l?.()}if(!eM)return;let e=new Map(eT.projects.map(e=>[e.key,e])),t=P(F.length>0?A(F):[],eT.projects).filter(t=>!e.get(L(t))?.hidden);t.length>0&&V(t[0])}},[F,q,s,o,r,l,eT,eM]);let tJ=(0,a.useCallback)(async e=>{let t=e.trim();if(t&&!eJ){eZ(!0),eG(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await e.json().catch(()=>({}));if(!e.ok||r.error)return void eG(r.error??b("workspace.unable"));let n=r.cwd??t,a=L(n),i=eT.projects.find(e=>e.key===a);if(i?.hidden===!0)try{await tS([{key:a,path:n,hidden:!1}])}catch{}V(n),eV(!1)}catch{eG(b("workspace.unable"))}finally{eZ(!1)}}},[tS,eJ,eT.projects,b]),tZ=(0,a.useCallback)(()=>{eV(!0),eG(null)},[]),tY=(0,a.useCallback)(async()=>{let e=e8.trim();if(e&&!e3&&eY){e7(!0),e6(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eY.projectRoot,branch:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error||!r.path)return void e6(r.error??`HTTP ${t.status}`);e2(!1),e4(""),e0(!1),eX(t=>t?{...t,forCwd:r.path,worktrees:[...t.worktrees,{path:r.path,branch:e,isMain:!1}]}:t),V(r.path),tG(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e7(!1)}}},[e8,e3,eY]),tX=(0,a.useCallback)(async(e,t)=>{if(eY&&!e3){e7(!0),e6(null);try{let r=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eY.projectRoot,path:e,force:t})}),n=await r.json().catch(()=>({}));if(!r.ok){if(n.dirty&&!t)return void te(e);e6(n.error??`HTTP ${r.status}`);return}te(null),q===e&&V(eY.projectRoot),tG(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e7(!1)}}},[eY,e3,q]);(0,a.useEffect)(()=>{let e=e=>{tt.current&&!tt.current.contains(e.target)&&(eN(null),e0(!1),e2(!1),e4(""),e6(null),te(null),eB(""),eS(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tQ=(0,a.useCallback)(e=>{e.cwd&&V(e.cwd),r(e)},[r]),t0=(0,a.useCallback)((e=q)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;V(e),i?.(t,e)},[q,i]),[t1,t2]=(0,a.useState)(!1),[t8,t4]=(0,a.useState)(null),t5=(0,a.useCallback)(async()=>{t2(!0),t4(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);t0(t.cwd)}catch(e){t4(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{t2(!1)}},[t0,b]),t6=(0,a.useCallback)(e=>{ew(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})},[]),t3=tB(q),t7=null===t3?null:L(t3),t9=(0,a.useMemo)(()=>new Map(eT.projects.map(e=>[e.key,e])),[eT.projects]),re=A(W);if(null!==t3){let e=L(t3);re.some(t=>L(t)===e)||re.unshift(t3)}let rt=P(re,eT.projects),rr=rt.filter(e=>e$||!t9.get(L(e))?.hidden),rn=rt.some(e=>t9.get(L(e))?.hidden),ra=()=>{eN(null),e0(!1),e2(!1),e4(""),e6(null),te(null),eB("")},ri=async(e,t)=>{ra();try{await tS([{key:L(e),path:e,hidden:t}]),t&&t7&&t7===L(e)&&V(null),t||rt.some(t=>L(t)!==L(e)&&t9.get(L(t))?.hidden)||eR(!1)}catch{}},rs=async e=>{if(ta.current){ta.current=!1,eF(null);return}let t=e_.trim();if(t===(t9.get(L(e))?.alias??""))return void eF(null);eH(null);try{await tS([{key:L(e),path:e,alias:t||null}]),eF(null)}catch{eH(b("sidebar.projectUpdateFailed"))}},ro=async(e,t)=>{if(X)return;let r=rr.indexOf(e),n=r+t;if(r<0||n<0||n>=rr.length)return;let a=new Set(rr),i=rt.map((e,t)=>a.has(e)?t:-1).filter(e=>e>=0),s=[...rt],o=i[r],l=i[n];[s[o],s[l]]=[s[l],s[o]],ra();try{await tS(s.map((e,t)=>({key:L(e),path:e,order:t})))}catch{}},rl=new Map;for(let e of W){let t=e.projectRoot??e.cwd;if(!t)continue;let r=L(t),n=rl.get(r);n?n.push(e):rl.set(r,[e])}let rc=(0,a.useMemo)(()=>{let e=new Map;for(let t of W){let r=t.projectRoot??t.cwd;if(!r)continue;let n=L(r),a=e.get(n);a||(a={running:0,unread:0},e.set(n,a)),tl.has(t.id)&&a.running++,tp.has(t.id)&&a.unread++}return e},[W,tl,tp]),rd=X.trim().toLowerCase(),ru=X.length>0,rp=rr.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,r=L(e),n=t9.get(r),a=n?.alias??t,i=(rl.get(r)??[]).slice().sort((e,t)=>{let r=Number(tm.has(t.id))-Number(tm.has(e.id));return 0!==r?r:t.modified.localeCompare(e.modified)});if(!rd)return[{project:e,key:r,name:a,sessions:i,hidden:n?.hidden===!0}];let s=a.toLowerCase().includes(rd)||t.toLowerCase().includes(rd),o=i.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(rd));return s||0!==o.length?[{project:e,key:r,name:a,sessions:s?i:o,hidden:n?.hidden===!0}]:[]}),rh=[],rm=[];for(let e of rp){let t=e.key===t7||(rc.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?rm.push(e):rh.push(e)}let rf={running:0,unread:0};for(let e of rm){let t=rc.get(e.key);t&&(rf.running+=t.running,rf.unread+=t.unread)}let rg=ru||eL,rx=[...rh.map(e=>({kind:"project",group:e})),...rm.length>0?[{kind:"temporary"}]:[],...rg?rm.map(e=>({kind:"project",group:e})):[]],rv=function(e){let t=new Map;for(let r of e){let e=r.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(rx.flatMap(e=>"project"===e.kind?[e.group.name]:[])),rb=(0,a.useMemo)(()=>tg?W.filter(e=>(function(e,t,r,n=$){if(e.transient||e.trial)return!1;if(n.has(e.id))return!0;if(t.has(e.id))return!1;let a=M(e);return null!==a&&a>(r.opened[e.id]??r.since)})(e,tl,tg,td)):[],[tg,tl,W,td]),ry=tv&&null!==tg,[rw,rk]=(0,a.useState)(null),rj=(0,a.useMemo)(()=>(function(e,t,r,n,a="Priority",i=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let r=Date.parse(e.modified),n=Date.parse(t.modified);return(Number.isFinite(n)?n:0)-(Number.isFinite(r)?r:0)}),c=l.filter(e=>i.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(i.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let r=new Date(e.modified);if(p>=o)continue;p+=1;let n=[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-"),a=u.get(n);a?a.push(e):u.set(n,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:a,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,r){let[n,a,i]=e.split("-").map(Number),s=new Date(n,a-1,i),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(r,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(r,{weekday:"long"}).format(s):new Intl.DateTimeFormat(r,{month:"short",day:"numeric"}).format(s)}(e,r,n),running:!1,sessions:u.get(e)??[]});return h})(ry?W.filter(e=>e.id===rw&&!tl.has(e.id)||rb.includes(e)):W,tl,new Date,y,b("navigator.priority"),tm,b("sidebar.pinned"),ry?1/0:void 0),[rw,y,tm,rb,ry,tl,W,b]),rS=(0,a.useCallback)(e=>{rk(e.id),tQ(e)},[tQ]),rC=!!(eY?.isGit&&eY.isTopLevel&&q&&t3===eY.projectRoot),rN=eY?.worktrees.find(e=>e.path===q)??eY?.worktrees.find(e=>e.isMain),rT=(eY?.worktrees.length??0)>=8,rI=rT&&eU.trim()?(eY?.worktrees??[]).filter(e=>(e.branch??el(e.path,K)).toLowerCase().includes(eU.trim().toLowerCase())):eY?.worktrees??[],rM=(()=>{if(!tT)return[];let e="project"===tT.kind?rl.get(L(tT.project))??[]:rj.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),rE=rM.filter(e=>!tl.has(e.id)),r$=e=>{let t=new Set;for(let r of e)r.transient||tl.has(r.id)||t.has(r.id)||t.add(r.id);return t.size},rR=void 0!==m&&f;return(0,n.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eq&&(0,n.jsx)(Z?Q:J,{busy:eJ,error:eK,onCancel:()=>{eV(!1),eG(null)},onSelect:e=>void tJ(e)}),tT&&(0,n.jsx)(ef,{scope:tT,eligible:rE.length,runningExcluded:rM.length-rE.length,busy:tM,error:t$,onCancel:tL,onConfirm:()=>void tA(rE)}),(0,n.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,n.jsx)(ep,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,n.jsx)("button",{className:"navigator-icon-action",onClick:()=>t0(),disabled:!q,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:q?"var(--text-muted)":"var(--text-dim)",cursor:q?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:"var(--radius-control)",fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:q?b("sidebar.newSessionTitle",{path:q}):b("sidebar.selectProject"),"aria-label":q?b("sidebar.newSessionTitle",{path:q}):b("sidebar.selectProject"),onMouseEnter:e=>{q&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=q?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,n.jsx)("button",{className:`navigator-icon-action${ts?" is-success":""}`,onClick:()=>tC(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ts?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ts?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ts?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:"var(--radius-control)",padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{ts||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{ts||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:ts?(0,n.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),Z&&!rR&&(0,n.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tZ,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,n.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,n.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),r=!rR&&et===e;return(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":r,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tW(e),rR&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"transparent",color:r?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:r?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,n.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":rR,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!rR),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:rR?"var(--bg-selected)":"transparent",color:rR?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:rR?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!rR&&"projects"===et&&(0,n.jsx)("button",{type:"button",onClick:()=>eR(e=>!e),disabled:!rn,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":e$,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:e$?"var(--bg-selected)":"transparent",color:e$?"var(--accent)":"var(--text-dim)",cursor:rn?"pointer":"default",opacity:rn?1:.45,flexShrink:0},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!e$&&(0,n.jsx)("path",{d:"m4 4 16 16"})]})}),!rR&&"projects"===et&&(0,n.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tZ,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,n.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),rR&&m,!rR&&"projects"===et&&(0,n.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,n.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,n.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,n.jsx)("input",{className:"navigator-search-input",type:"search",value:X,onChange:e=>ee(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),ee(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!rR&&"projects"===et&&(0,n.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(O||!eM)&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),eD&&(0,n.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!O&&eM&&!H&&0===rp.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:rd?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!O&&eM&&!H&&rx.map(t=>{let r,a,i;if("temporary"===t.kind)return(0,n.jsx)("div",{className:"navigator-project-group",children:(0,n.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":rg,title:b("sidebar.temporaryProjects"),onClick:()=>eA(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,n.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:rg?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:rm.length}),ej(rf,b)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t7,p=rv.has(l.toLowerCase())&&el((a=Math.max((r=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),r.lastIndexOf("/")))<=0?"":r.slice(0,a),K)||null,h=!ey.has(s)&&!rd,m=eu.has(s),f=eP===s,g=rr.indexOf(s),x=eW||ru||g<=0,v=eW||ru||g>=rr.length-1,y=function(e){let t=new Map;for(let r of e)t.set(r.id,{session:r,children:[]});let r=new Map;for(let t of e)t.parentSessionId&&r.set(t.id,t.parentSessionId);let n=[];for(let e of t.values()){let a=function(e){let n=r.get(e),a=new Set;for(;n&&!a.has(n);){if(a.add(n),t.has(n))return n;n=r.get(n)}return null}(e.session.id);a?t.get(a).children.push(e):n.push(e)}let a=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>a(e.children))};return a(n),n}(m?c:c.slice(0,5)),k=c.length>5;return(0,n.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,n.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:eC===s?tt:void 0,onMouseEnter:()=>eS(s),onMouseLeave:()=>eS(e=>e===s&&eC!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:"var(--radius-control)",background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t6(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,n.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,n.jsx)("input",{ref:tn,value:e_,onChange:e=>ez(e.target.value),onBlur:()=>void rs(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),ta.current=!0,eF(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,n.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>V(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,n.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,n.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,n.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),ej(rc.get(o),b)]}),(0,n.jsx)("button",{type:"button",onClick:()=>t0(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||ek===s?1:0,pointerEvents:w||ek===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>eS(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,n.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,n.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,n.jsx)("button",{type:"button",onClick:()=>{eN(eC===s?null:s),e0(!1),e2(!1),e6(null),u||V(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":eC===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eC===s?"var(--bg-selected)":"transparent",color:u&&rN&&!rN.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ek===s||eC===s?1:0,pointerEvents:w||ek===s||eC===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>eS(s),children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,n.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,n.jsxs)(ed,{open:eC===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[rC&&eY&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",onClick:()=>e0(e=>!e),title:rN?b("sidebar.switchWorktreeTitle",{path:rN.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eQ,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eQ?"1px solid var(--border)":"none",background:eQ?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,n.jsxs)(ed,{open:eQ,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[rT&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,n.jsx)("input",{value:eU,onChange:e=>eB(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eB(""),e0(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,n.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[rI.map(e=>{let t=e.path===q||e.isMain&&!eY.worktrees.some(e=>e.path===q);return e9===e.path?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,n.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,n.jsx)("button",{onClick:()=>void tX(e.path,!0),disabled:e3,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,n.jsx)("button",{onClick:()=>te(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:b("sidebar.cancel")})]},e.path):(0,n.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("button",{onClick:()=>{V(e.path),e0(!1),e6(null),eB("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)(ec,{text:e.branch??el(e.path,K),style:{flex:1}}),e.isMain&&(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,n.jsx)("button",{onClick:()=>void tX(e.path,!1),disabled:e3,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:"var(--radius-control)",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),rT&&0===rI.length&&eU.trim()&&(0,n.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e1?(0,n.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,n.jsx)("input",{ref:tr,value:e8,onChange:e=>{e4(e.target.value),e6(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tY()),"Escape"===e.key&&(e2(!1),e4(""),e6(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,n.jsx)("button",{onClick:()=>void tY(),disabled:e3||!e8.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e3||!e8.trim()?"not-allowed":"pointer",opacity:e3||!e8.trim()?.65:1},children:e3?b("sidebar.creating"):b("sidebar.create")}),(0,n.jsx)("button",{onClick:()=>{e2(!1),e4(""),e6(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),e2(!0),e6(null),setTimeout(()=>tr.current?.focus(),0)},title:b("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,n.jsx)("span",{children:b("sidebar.newWorktree")})]}),e5&&(0,n.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e5})]})]}),(0,n.jsxs)("button",{type:"button",disabled:eW,onClick:()=>{let e;return e=t9.get(L(s))?.alias??"",void(ta.current=!1,eH(null),ez(e),eF(s),ra())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eW?"default":"pointer",textAlign:"left",fontSize:11,opacity:eW?.55:1},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,n.jsx)("path",{d:"m13.5 8 3 3"})]}),b(t9.get(L(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,n.jsxs)("button",{type:"button",disabled:x,title:ru?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ro(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,n.jsxs)("button",{type:"button",disabled:v,title:ru?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ro(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,n.jsxs)("button",{type:"button",disabled:eW,onClick:()=>void ri(s,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eW?"default":"pointer",textAlign:"left",fontSize:11,opacity:eW?.55:1},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,n.jsx)("path",{d:"m4 4 16 16"})]}),b(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(i=0===r$(rl.get(o)??[])||tM,(0,n.jsxs)("button",{type:"button",disabled:i,onClick:()=>{ra(),tR(null),tI({kind:"project",project:s,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:i?"default":"pointer",textAlign:"left",fontSize:11,opacity:i?.55:1},children:[(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,n.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,n.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,n.jsx)(eb,{node:t,selectedSessionId:e,runningSessionIds:tl,unreadSessionIds:tp,pinnedSessionIds:tm,onSelectSession:tQ,onTogglePinnedSession:tO,onRenamed:tC,onSessionDeleted:tN,onSessionArchived:t_,depth:0},t.session.id))}),!h&&k&&(0,n.jsx)("button",{type:"button",onClick:()=>{eg(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!rR&&(0,n.jsx)(ev,{refreshKey:tP,selectedSessionId:e,onSelectSession:tQ,onRestored:t_}),!rR&&"priority"===et&&(0,n.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[O&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,n.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),!O&&!H&&(x=r$(rj.flatMap(e=>e.sessions)),(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,n.jsx)("button",{type:"button",disabled:t1,onClick:()=>void t5(),title:b("sidebar.newScratchSessionTitle"),style:eo(t1,w),children:b("sidebar.newScratchSession")}),rj.length>0&&!ry&&(0,n.jsx)("button",{type:"button",disabled:0===x||tM,onClick:()=>{tR(null),tI({kind:"priority"})},style:eo(0===x||tM,w),children:b("sidebar.clearPriorityList")})]})),!O&&!H&&tg&&(0,n.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,n.jsxs)("button",{type:"button","aria-pressed":ry,"aria-label":b("navigator.resultsToCheckCount",{count:rb.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{rk(null),tb(e=>!e)},style:{...eo(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ry?"var(--border-strong)":"var(--border)",background:ry?"var(--bg-selected)":"transparent",color:ry||rb.length>0?"var(--text)":"var(--text-muted)",fontWeight:ry?600:500,whiteSpace:"nowrap"},children:[b("navigator.resultsToCheck"),(0,n.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:rb.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:rb.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:rb.length})]}),rb.some(e=>!td.has(e.id))&&(0,n.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{rk(null),tx(e=>e&&function(e,t,r){let n=e;for(let e of t)n=E(n,e,r);return n}(e,rb,Date.now()))},style:eo(!1,w),children:b("navigator.acknowledgeResults")})]}),t8&&(0,n.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:t8}),!O&&!H&&0===rj.length&&(0,n.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ry?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!O&&!H&&rj.map((t,r)=>(0,n.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,n.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===r?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,n.jsx)(ex,{session:t,selected:t.id===e,running:tl.has(t.id),waiting:td.has(t.id),unread:tp.has(t.id),pinned:tm.has(t.id),onSelect:ry?rS:tQ,onTogglePin:tO},t.id))]},t.key))]})]})}function ef({scope:e,eligible:t,runningExcluded:r,busy:i,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,z.s)(),d=i||0===t,u=(0,a.useRef)(null),p=(0,a.useRef)(null),h=(0,a.useRef)(i);h.current=i;let m=(0,a.useRef)(o);return m.current=o,(0,a.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,r=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let n=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let r=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),n=document.activeElement;if(0===r.length){t.preventDefault(),e.focus();return}let a=r[0],i=r[r.length-1];t.shiftKey&&(n===a||!e.contains(n))?(t.preventDefault(),i.focus()):t.shiftKey||n!==i&&e.contains(n)||(t.preventDefault(),a.focus())};return e.addEventListener("keydown",n),()=>{e.removeEventListener("keydown",n);let t=r?.isConnected?r:e.closest(".session-navigator");t?.focus()}},[]),(0,n.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{i||e.target!==e.currentTarget||o()},children:(0,n.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,n.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,n.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),r>0&&(0,n.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:r})}),0===t&&(0,n.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,n.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{ref:p,type:"button",onClick:o,disabled:i,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:i?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,n.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":i,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(i?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function eg({filled:e=!1}){return(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 17v5"}),(0,n.jsx)("path",{d:"M5 17h14"}),(0,n.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ex({session:e,selected:t,running:r,waiting:a,unread:i,pinned:s,onSelect:o,onTogglePin:l}){let{t:c}=(0,z.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),u=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,n.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${r?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,n.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>o(e),title:`${d}
|
|
2
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,n.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:d}),a&&(0,n.jsx)(ey,{}),r&&!a&&(0,n.jsx)(ew,{}),!r&&i&&(0,n.jsx)(ek,{})]}),(0,n.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:u})]}),(0,n.jsx)("button",{type:"button","aria-pressed":s,"aria-label":c(s?"sidebar.unpin":"sidebar.pin"),title:c(s?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:s?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,n.jsx)(eg,{filled:s})})]})}function ev({refreshKey:e,selectedSessionId:t,onSelectSession:r,onRestored:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)([]);(0,a.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();e||d(r.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,a.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),i(t)}catch{}},[i]);return 0!==c.length||o?(0,n.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,n.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:o?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),s("sidebar.archived")," (",c.length,")"]}),o&&(0,n.jsxs)("div",{style:{paddingLeft:12},children:[0===c.length&&(0,n.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:s("sidebar.noArchivedSessions")}),c.map(e=>{let a=_(e.firstMessage)??e.firstMessage,i=e.name||a.slice(0,50)||e.id.slice(0,12);return(0,n.jsxs)("div",{onClick:()=>r(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,n.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),(0,n.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function eb({node:e,selectedSessionId:t,runningSessionIds:r,unreadSessionIds:i,pinnedSessionIds:s,onSelectSession:o,onRenamed:l,onSessionDeleted:c,onTogglePinnedSession:d,onSessionArchived:u,depth:p}){let[h,m]=(0,a.useState)(!1),f=e.children.length>0;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,n.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,n.jsx)(eS,{session:e.session,isSelected:e.session.id===t,isRunning:r.has(e.session.id),isUnread:i.has(e.session.id),isPinned:s.has(e.session.id),onClick:()=>o(e.session),onTogglePin:()=>d(e.session.id),onRenamed:l,onDeleted:e=>c?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:f,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),f&&!h&&(0,n.jsx)("div",{children:e.children.map(e=>(0,n.jsx)(eb,{node:e,selectedSessionId:t,runningSessionIds:r,unreadSessionIds:i,pinnedSessionIds:s,onSelectSession:o,onTogglePinnedSession:d,onRenamed:l,onSessionDeleted:c,onSessionArchived:u,depth:p+1},e.session.id))})]})}function ey(){let{t:e}=(0,z.s)();return(0,n.jsx)("span",{title:e("sidebar.waitingForAnswerHint"),style:{flexShrink:0,padding:"0 6px",borderRadius:"var(--radius-surface)",border:"1px solid var(--warning-line)",background:"var(--warning-soft)",color:"var(--warning)",fontSize:10.5,fontWeight:600,lineHeight:"16px",whiteSpace:"nowrap"},children:e("sidebar.waitingForAnswer")})}function ew(){let{t:e}=(0,z.s)();return(0,n.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,n.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,n.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function ek(){let{t:e}=(0,z.s)();return(0,n.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,n.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function ej(e,t){return e&&(0!==e.running||0!==e.unread)?(0,n.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,n.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,n.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,n.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function eS({session:e,isSelected:t,isRunning:r,isUnread:i,isPinned:s,onClick:o,onTogglePin:l,onRenamed:c,onDeleted:d,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:f}){let{t:g}=(0,z.s)(),[x,v]=(0,a.useState)(!1),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)(""),[j,S]=(0,a.useState)(!1),[C,N]=(0,a.useState)(!1),T=(0,a.useRef)(null);(0,a.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>T.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let I=_(e.firstMessage)??e.firstMessage,M=e.name||I.slice(0,50)||e.id.slice(0,12),E=(0,a.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||I.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,I,e.id]),$=(0,a.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[w,e.id,e.name,c,M]),R=(0,a.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),d?.(e.id)}catch{N(!1)}}},[e.id,e.transient,d]),L=(0,a.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),A=(0,a.useCallback)(e=>{e.stopPropagation(),e.shiftKey?R():S(!0)},[R]),P=(0,a.useCallback)(e=>{e.stopPropagation(),R()},[R]),F=(0,a.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),W=(0,a.useCallback)(t=>{(function(e,t=window){let r=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(r)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[c,e.cwd,e.id,e.name,e.path]);return(0,n.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${r?" is-running":""}${i?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:o,onContextMenu:j||b?void 0:W,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||b?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,n.jsxs)("button",{onClick:P,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,n.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,n.jsx)("input",{ref:T,value:w,onChange:e=>k(e.target.value),onBlur:$,onKeyDown:e=>{"Enter"===e.key&&$(),"Escape"===e.key&&y(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,n.jsxs)(n.Fragment,{children:[p>0&&(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),o()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),r&&(0,n.jsx)(ew,{}),!r&&i&&(0,n.jsx)(ek,{}),e.worktreeBranch&&(0,n.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,n.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,n.jsx)("button",{className:"navigator-session-action",onClick:e=>{e.stopPropagation(),l?.()},title:g(s?"sidebar.unpin":"sidebar.pin"),"aria-label":g(s?"sidebar.unpin":"sidebar.pin"),"aria-pressed":s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:s?"var(--bg-selected)":"transparent",border:"none",borderRadius:"var(--radius-control)",color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,n.jsx)(eg,{filled:s})}),(0,n.jsx)("button",{className:"navigator-session-action",onClick:E,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,n.jsx)("button",{className:"navigator-session-action",onClick:L,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,n.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,n.jsx)("path",{d:"M10 12h4"})]})}),(0,n.jsx)("button",{className:"navigator-session-action",onClick:A,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let eC=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eN=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eT=/\x1B\[([0-9;]*)m/g,eI=/\x1B_pi:c\x07/g,eM=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eE=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function e$(e){return e.replace(eI,"").replace(eC,"")}function eR(e){let t=[],r=0;for(;r<e.length;){if(27===e.charCodeAt(r)){let t=e.slice(r).match(eN);if(t){r+=t[0].length;continue}}let n=e.codePointAt(r);if(void 0===n)break;let a=String.fromCodePoint(n);t.push({start:r,end:r+a.length,char:a}),r+=a.length}return t}function eL(e,t){let r=eR(e)[t];return r?e.slice(0,r.start)+e.slice(r.end):e}function eA(e){return eR(e)[0]?.char}function eP(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,r=[];for(let n of e){let e=n.replace(eI,""),a=e$(e).trimEnd();if(t.test(a))continue;let i=e,s=eA(i);("│"===s||"┃"===s)&&" "===eA(i=eL(i,0))&&(i=eL(i,0));let o=function(e){let t=eR(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(i),l=o>=0?eR(i)[o]?.char:void 0;("│"===l||"┃"===l)&&(i=eL(i,o)),r.push(function(e){let t=e;for(;;){let e=eR(t),r=e[e.length-1];if(!r||""!==r.char.trim())return t;t=t.slice(0,r.start)+t.slice(r.end)}}(i))}for(;r.length>0&&""===e$(r[0]).trim();)r.shift();for(;r.length>0&&""===e$(r[r.length-1]).trim();)r.pop();return r.length?r:e}function eF(e){let t,r=[],n={},a=0;for(eT.lastIndex=0;null!==(t=eT.exec(e));)t.index>a&&r.push({text:e.slice(a,t.index),style:n}),n=function(e,t){let r={...e};for(let e=0;e<t.length;e++){let n=t[e];if(0===n)for(let e of Object.keys(r))delete r[e];else if(1===n)r.fontWeight=700;else if(2===n)r.opacity=.65;else if(3===n)r.fontStyle="italic";else if(4===n)r.textDecoration="underline";else if(22===n)delete r.fontWeight,delete r.opacity;else if(23===n)delete r.fontStyle;else if(24===n)delete r.textDecoration;else if(39===n)delete r.color;else if(49===n)delete r.backgroundColor;else if(n>=30&&n<=37)r.color=eM[n-30];else if(n>=90&&n<=97)r.color=eE[n-90];else if(n>=40&&n<=47)r.backgroundColor=eM[n-40];else if(n>=100&&n<=107)r.backgroundColor=eE[n-100];else if((38===n||48===n)&&2===t[e+1]){let[a,i,s]=[t[e+2],t[e+3],t[e+4]];[a,i,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===n?r.color=`rgb(${a}, ${i}, ${s})`:r.backgroundColor=`rgb(${a}, ${i}, ${s})`),e+=4}else if((38===n||48===n)&&5===t[e+1]){let a=function(e){if(e>=0&&e<8)return eM[e];if(e>=8&&e<16)return eE[e-8];if(e>=16&&e<=231){let t=e-16,r=Math.floor(t/36),n=Math.floor(t%36/6),a=e=>0===e?0:55+40*e;return`rgb(${a(r)}, ${a(n)}, ${a(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);a&&(38===n?r.color=a:r.backgroundColor=a),e+=2}}return r}(n,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),a=t.index+t[0].length;return a<e.length&&r.push({text:e.slice(a),style:n}),r}let e_={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},ez={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eW={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},eO={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm",webm:"audio/webm"};function eD(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eH(e){return null!==(eW[eD(e)]??null)}function eU(e){let t;return null!==("pdf"===(t=eD(e))||"docx"===t?t:null)}function eB(e,t,r={}){let n={...e,content:t};return r.omitUsage&&(n.usage=void 0),n}function eq(e,t={}){return!!t.hideThinking&&"thinking"===e.type||function(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}(e,t)}function eV(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eK(e,t){let r=e[t];if(r?.role!=="assistant"||"error"!==r.stopReason)return!1;for(let r=t+1;r<e.length;r++){let t=e[r].role;if("user"===t)break;if("assistant"===t)return!0}return!1}function eG(e,t={}){let r=[];for(let n of function(e,t={}){return(e.content??[]).filter(e=>!eq(e,t))}(e,t)){let e="image"===n.type||"text"===n.type&&n.text.trim().length>0?"answer":"process",t=r[r.length-1];t?.kind===e?t.blocks.push(n):r.push({kind:e,blocks:[n]})}return r}function eJ(e){return e.filter(e=>"toolCall"===e.type).length}let eZ=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function eY(e){let t=0,r=0;for(let n of e)eZ.test(n)?t++:r++;return t+r/4}function eX(e){return"text"===e.type?e.text:"thinking"===e.type?e.thinking:"toolCall"===e.type?JSON.stringify(e.input??{})??"":null}function eQ(e,t){if(!e)return eY(t);let r=Math.min(e.text.length,t.length),n=0;for(;n<r&&e.text.charCodeAt(n)===t.charCodeAt(n);)n++;let a=n>0?t.charCodeAt(n-1):0;return a>=55296&&a<=56319&&n--,e.tokens-eY(e.text.slice(n))+eY(t.slice(n))}function e0(e,t,r){let n=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==r&&n.set("index",String(r)),`/api/tool-image?${n}`}let e1=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function e2(e){let t=new Map;for(let r of e)"toolResult"===r.role&&t.set(r.toolCallId,r);let r=[],n=-1;return{collect(e,a){for(let i of a)"toolCall"===i.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let r=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===r.path;if("eval"===e.toolName){let e;return e=t.content?.at(-1),e?.type==="text"&&e1.test(e.text)}return"read"===e.toolName&&"string"==typeof r.path&&eH(r.path)}(i,t.get(i.toolCallId))&&(r.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:i.toolCallId}}),n=e)},attach(e){if(0===r.length)return e;let t=[...r,...e];return r=[],t},takeRemaining(){if(0===r.length)return null;let e={idx:n,blocks:r};return r=[],e}}}let e8=new Map,e4=new Map,e5="[한국어 번역]\n";function e6(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function e3(e){if("custom"!==e.role||"korean-reply-translation"!==e.customType)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let r="sourceTimestamp"in t&&"number"==typeof t.sourceTimestamp?t.sourceTimestamp:void 0,n="sourceHash"in t&&"string"==typeof t.sourceHash?t.sourceHash:void 0;return void 0===r&&void 0===n?null:{sourceTimestamp:r,sourceHash:n}}let e7="command",e9="autolearn-saved";function te(e){return"custom"===e.role&&(e.customType===e7||e.customType===e9&&!1!==e.display)}function tt(e,t){let r=e[t];if(r?.role!=="custom"||"user-input-translation"!==r.customType)return -1;for(let r=t-1;r>=0;r--)if("user"===e[r].role)return r;return -1}let tr="local-command:";function tn(e){return e?.startsWith(tr)===!0}function ta(e,t,r){let n=new Set(r.map(e=>e.message)),a=[],i=[];for(let r=0;r<e.length;r++){let s=r<t.length;!(n.has(e[r])||s&&tn(t[r]))&&(a.push(e[r]),s&&i.push(t[r]))}for(let e of r){let t=0;if(null!==e.baseEntryId){let r=i.indexOf(e.baseEntryId);if(-1===r)continue;t=r+1}let r=e.message.timestamp??0;for(;t<a.length;){let e=a[t];if(!n.has(e)&&"number"==typeof e.timestamp&&e.timestamp>r)break;t+=1}a.splice(t,0,e.message),t<=i.length&&i.splice(t,0,e.entryId)}return{messages:a,entryIds:i}}function ti(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let ts={create:!0,update:!0};function to(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function tl(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let r of e)r&&"object"==typeof r&&"type"in r&&"text"===r.type&&"text"in r&&"string"==typeof r.text&&t.push(r.text);return t.join("\n")}function tc(e,t){if(0===e.length)return -1;if(!t)return 0;let r=-1;for(let n=0;n<e.length;n++){let a=e[n];if(a.item===t.item){if(a.k===t.k)return n;r=n}}return -1===r?0:r}function td(e){try{return decodeURIComponent(e)}catch{return e}}function tu(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tp(e){let t=tu(e),r=/^[a-zA-Z]:\//.test(t),n=t.startsWith("//"),a=t.startsWith("/")&&!r&&!n,i=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){i.length>0&&".."!==i[i.length-1]?i.pop():a||r||n||i.push(e);continue}i.push(e)}let s=i.join("/");return r?s:n?`//${s}`:a?`/${s}`:s}function th(e,t,r=t){let n,a,i,s,o;if(!e)return null;let l=e.split("#",1)[0].split("?",1)[0].trim();if(!l)return null;let c=null,d=null,u=td(l),p=u.startsWith("\\\\"),h=tu(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let r=td(t.pathname);if(t.hostname)return`//${t.hostname}${r.startsWith("/")?r:`/${r}`}`;if(/^\/[a-zA-Z]:\//.test(r))return r.slice(1);return r}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(c=h,d="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(c=`${tu(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let f=tp(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&r&&(n=tp(f).replace(/\/+$/,""),a=tp(r).replace(/\/+$/,""),s=(i=/^[a-zA-Z]:\//.test(n)||/^[a-zA-Z]:\//.test(a))?n.toLowerCase():n,!(s===(o=i?a.toLowerCase():a)||s.startsWith(`${o}/`)))?null:f}function tm(e,t){let r;if(!e)return null;let n=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),a=e=>n?e.replace(/\\/g,"/"):e,i=a(e),s=t?a(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(i),l=i.startsWith("//");if(o||l)r=i;else if(i.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];r=e?`${e}${i}`:i}else{if(!s)return null;r=`${s}/${i}`}return tp(r)}function tf(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function tg(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function tx(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tv(e,t){if(!e||"object"!=typeof e||"delete"===e.op&&!t)return null;let r=e.path??e.resolvedPath;return"string"==typeof r&&r.length>0?r:null}function tb(e,t,r=!1){let n=t.details,a=tx(e);if(a)return!r&&n&&"object"==typeof n&&"delete"===n.op?[]:[a];if(!n||"object"!=typeof n)return[];if(Array.isArray(n.perFileResults))return n.perFileResults.map(e=>tv(e,r)).filter(e=>null!==e);let i=tv(n,r);return i?[i]:[]}function ty(e,t){let r=tx(e);return(t?tb(e,t,!0):r?[r]:[]).filter(tC)}function tw(e,t,r){let n=ty(e,t);return n.length>0&&n.every(e=>tS(e,r))}let tk=new Map(["skills","commands","rules","prompts","extensions","instructions","hooks","tools","agents","plugins","mcp.json",".mcp.json","SYSTEM.md","SYSTEM_TEMPLATE.md","APPEND_SYSTEM.md","AGENTS.md","settings.json","config.yml","secrets.yml"].map(e=>[e.toLowerCase(),e])),tj=[/^\/(?:private\/)?(?:var\/)?tmp(?:\/|$)/,/^\/(?:private\/)?var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/,/^(?:[a-z]:|\/mnt\/[a-z])\/(?:windows\/)?temp(?:\/|$)/i,/^(?:[a-z]:|\/mnt\/[a-z])\/users\/[^/]+\/appdata\/local\/temp(?:\/|$)/i];function tS(e,t){let r=tm(e,t),n=t?tm(t)?.replace(/\/+$/,""):void 0,a=r??e.replace(/\\/g,"/"),i=/^(?:[a-zA-Z]:\/|\/\/|\/mnt\/[a-zA-Z](?:\/|$))/.test(a)||void 0!==n&&/^(?:[a-zA-Z]:\/|\/\/)/.test(n),s=e=>i?e.toLowerCase():e,o=null===r||void 0!==n&&(s(r)===s(n)||s(r).startsWith(`${s(n)}/`));return!!function(e,t){let r=(e,r)=>void 0!==e&&(t?e.toLowerCase()===r:e===r),n=e.findIndex(e=>r(e,".omp"));if(n<0||n===e.length-1)return!1;let a=e[n+1];if(r(a,"agent")||r(a,"wt")||r(a,"profiles")&&r(e[n+3],"agent"))return!1;let i=tk.get(a.toLowerCase());return!(void 0!==i&&(t||i===a))}((null!==r&&o&&void 0!==n?r.slice(n.length):a).split("/").filter(e=>""!==e&&"."!==e),i)||!o&&tj.some(e=>e.test(a))}function tC(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tN(e,t,r){let n=new Set,a=[];for(let s of e){var i;if("toolCall"!==s.type||!(tf(i=s.toolName)||tg(i)))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of tb(s.input,e)){if(!tC(t))continue;let e=tm(t,r);!(!e||tS(t,r))&&(n.has(e)||(n.add(e),a.push({filePath:e})))}}return a}function tT(e){let t=[];for(let r of e){if(!r||"object"!=typeof r||!("name"in r)||!("tasks"in r))return{phases:t,malformed:!0};let{name:e,tasks:n}=r;if("string"!=typeof e||!Array.isArray(n))return{phases:t,malformed:!0};let a=Array.isArray(n)?n.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:r}=e;if("string"!=typeof t||"pending"!==r&&"in_progress"!==r&&"completed"!==r&&"abandoned"!==r&&"blocked"!==r)return[];let n="blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0,a="dependsOn"in e&&Array.isArray(e.dependsOn)?e.dependsOn.filter(e=>"string"==typeof e):[];return[{content:t,status:r,blocker:n,...a.length>0?{dependsOn:a}:{}}]}):[];if(a.length!==n.length)return{phases:t,malformed:!0};a.length>0&&t.push({name:e,tasks:a})}return{phases:t,malformed:!1}}function tI(e){if(!Array.isArray(e))return null;let{phases:t,malformed:r}=tT(e);return r?null:t}function tM(e,t){var r;let n;if(t){let e=t.details,r=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(r))return{kind:"unknown"};let{phases:n,malformed:a}=tT(r);return a?{kind:"unknown"}:{kind:"authoritative",phases:n}}let a=Array.isArray(n=(r=e.input)&&"object"==typeof r&&"list"in r?r.list:void 0)?n.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:r}=e;if("string"!=typeof t||!Array.isArray(r))return[];let n=r.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return n.length>0?[{name:t,tasks:n}]:[]}):[];return a.length>0?{kind:"preview",phases:a}:{kind:"unknown"}}function tE(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}function t$(e,t,r=null,n=null){return r||(function(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r],a=n.trackerTodos??[];for(let e=a.length-1;e>=0;e-=1){let t=tI(a[e]);if(t)return t}if("assistant"!==n.role)continue;let i=n.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let r=i[e];if("toolCall"!==r.type||!tE(r.toolName))continue;let n=tM(r,t.get(r.toolCallId));if("unknown"!==n.kind)return n.phases}}return null}(e,t)??n)}function tR(e,t){if(!e.dependsOn?.length)return[];let r=new Set(t.flatMap(e=>e.tasks.filter(e=>"completed"===e.status).map(e=>e.content)));return e.dependsOn.filter(e=>!r.has(e))}function tL(e){let t=0,r=0,n=null,a=null,i=null;for(let s of e)for(let o of s.tasks){if("completed"===o.status){t+=1;continue}"abandoned"!==o.status&&(r+=1,tR(o,e).length>0?i||(i={phase:s,task:o}):"in_progress"===o.status?n||(n={phase:s,task:o}):"blocked"===o.status?i||(i={phase:s,task:o}):a||(a={phase:s,task:o}))}let s=n??a??i,o=t+r;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:r,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}function tA(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tP(e){return tA(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tF(e){let t=tA(e).replace(/\/+$/,"");return t.split("/").pop()??t}function t_(e,t){if(!t)return e;let r=tA(e),n=tA(t).replace(/\/$/,"");return r.startsWith(n+"/")?r.slice(n.length+1):e}var tz=r(65063),tW=r(7644),tO=r(32316),tD=r(88374),tH=r(63280),tU=r(94764),tB=r(63835),tq=r(54152),tV=r(84678),tK=r(98164);let tG={...tU.j,attributes:{...tU.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...tU.j.strip||[],"iframe","object","style","form"]};function tJ(e){let t=e.includes("\r\n")?"\r\n":"\n",r=e.split(/\r?\n/),n=[],a=null,i=0,s=null,o=new Map;for(let e=0;e<r.length;e++){var l;let t=r[e];if(s){n.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],r=c[1].length;a?e===a.marker&&r>=a.size&&(a=null):a={marker:e,size:r},i=0,n.push(t);continue}if(a){n.push(t);continue}let d=t.match(/<(code|pre|script|style)\b/i);if(d){let e=d[1].toLowerCase(),r=t.slice((d.index??0)+d[0].length);RegExp(`</${e}\\s*>`,"i").test(r)||(s=e),i=0,n.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){i=0,n.push(t);continue}if(i||t.includes("`")){i=function(e,t){let r=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let n=t+1;for(;"`"===e[n];)n++;let a=n-t;0===r?r=a:a===r&&(r=0),t=n}return r}(t,i),n.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){n.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let r=t;r<e.length;r++){let t=e[r];if(/^ {0,3}\\\][ \t]*$/.test(t))return r;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(r,e+1);if(-1!==t){n.push(`${p[1]}$$`,...r.slice(e+1,t).map(e=>tY(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){n.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],a=m[2].trimEnd();if(a&&!a.includes("$$")){let i=tZ(r,e+1,t,o);if(i){n.push(`${t}$$`,`${t}${a}`);for(let a=e+1;a<i.index;a++)n.push(tY(r[a],t));i.content&&n.push(`${t}${i.content}`),n.push(`${t}$$`),e=i.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],a=tZ(r,e+1,t,o);if(a&&(a.glued||""!==t)){n.push(`${t}$$`);for(let i=e+1;i<a.index;i++)n.push(tY(r[i],t));a.content&&n.push(`${t}${a.content}`),n.push(`${t}$$`),e=a.index;continue}}n.push((l=t,/^\s{0,3}\[[^\]]+\]:/.test(l)||/]\s*\(/.test(l)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(l)||/\b(?:https?|file|mailto):/i.test(l)||/\b[A-Za-z]:\\/.test(l)?l:l.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return n.join(t)}function tZ(e,t,r,n){let a=n.get(r);if(void 0!==a&&t<a)return null;for(let a=t;a<e.length;a++){var i,s,o,l;let t=e[a];if(i=t,""===(s=r)?/^ {0,3}\$\$\s*$/.test(i):i.startsWith(s)&&/^\$\$\s*$/.test(i.slice(s.length)))return{index:a,content:"",glued:!1};if(o=t,/^ {0,3}(`{3,}|~{3,})/.test(o)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(o)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(o)||/^ {0,3}>/.test(o)||/<(code|pre|script|style)\b/i.test(o)||(l=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(l)))return n.set(r,a),null;let c=function(e,t){if(!e.startsWith(t))return null;let r=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!r)return null;let n=r[1].trimEnd();return n&&!n.includes("$$")?n:null}(t,r);if(null!==c)return{index:a,content:c,glued:!0}}return n.set(r,e.length),null}function tY(e,t){if(!t||!e||e.startsWith(" "))return e;let r=e.match(/^ */)?.[0].length??0;return r>=t.length?e:`${t.slice(r)}${e}`}let tX={singleTilde:!1},tQ=[[tq.A,["yaml"]],[tV.A,tX],tK.A],t0=[[tq.A,["yaml"]],[tV.A,tX],tK.A],t1=[tH.A,[tB.A,tG],[tD.A,{throwOnError:!1,strict:!1}]],t2=[tH.A,[tB.A,tG],[tD.A,{throwOnError:!1,strict:!1}]],t8="pi-theme",t4=["light","dark","auto"],t5={preference:"auto",theme:"light"},t6="omp-theme",t3=null,t7=0,t9=new Set,re=null,rt=!1;function rr(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function rn(e){return"auto"===e?rr():e}let ra="--omp-md-";function ri(e){let t=document.documentElement,r=t3?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let r=t.style.item(e);r.startsWith("--")&&!r.startsWith(ra)&&t.style.removeProperty(r)}if(r){for(let[e,n]of Object.entries(r.variables))e.startsWith(ra)&&t.style.setProperty(e,n);t.dataset.ompThemeName=r.name}try{localStorage.setItem(t6,e)}catch{}}function rs(){if(re)return re;let e=function(){try{let e=localStorage.getItem(t8);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(t6);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=rn(e);return ri(t),re={preference:e,theme:t}}function ro(e,t,r){if(ri(t),r)try{localStorage.setItem(t8,e)}catch{}re={preference:e,theme:t},t9.forEach(e=>e())}function rl(){let e=rs();if("auto"!==e.preference)return;let t=rr();t!==e.theme&&ro("auto",t,!1)}function rc(e){return t9.add(e),rs(),rt||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",rl),window.addEventListener("focus",rl),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&rl()}),rt=!0),rl(),()=>{t9.delete(e)}}function rd(){return rs()}function ru(){return t5}async function rp(e){let t=++t7,r=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/theme${r}`,{cache:"no-store"});if(!n.ok)throw Error(`Theme request failed (${n.status})`);let a=await n.json();if(t===t7){t3=a;try{localStorage.setItem("omp-theme-config",JSON.stringify(t3))}catch{}ri(rs().theme)}}function rh(e){let t=(0,a.useSyncExternalStore)(rc,rd,ru);(0,a.useEffect)(()=>{e?.syncWithOmp&&rp(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let r=(0,a.useCallback)((e,t)=>{let r=rn(e),n=()=>{ro(e,r,!0)},a=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||a)return void n();let i=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(i,window.innerWidth-i),Math.max(s,window.innerHeight-s));document.startViewTransition(n).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${i}px ${s}px)`,`circle(${o}px at ${i}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),n=(0,a.useCallback)(e=>{var t;let n;r((t=rs().preference,n=t4.indexOf(t),t4[(n+1)%t4.length]),e)},[r]),i=(0,a.useCallback)((e,t)=>{r(e,t)},[r]);return{theme:t.theme,preference:t.preference,toggleTheme:n,setPreference:i,isDark:"dark"===t.theme}}function rm(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}let rf={...tW.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tW.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function rg({code:e,isStreaming:t}){let{isDark:i}=rh(),{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1),h=`${i?"dark":"light"}
|
|
4
4
|
${e}`,m=o&&!t;(0,a.useEffect)(()=>{if(!m)return;let t=!1;return d({key:h,status:"loading"}),(async()=>{let{default:n}=await Promise.all([r.e(866),r.e(8367),r.e(3308)]).then(r.bind(r,43328)),a=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${a}`,e),await document.fonts.ready,t)return;if(n.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:i?"dark":"default",fontFamily:a}),!await n.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let s="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await n.render(s,e);t||d({key:h,status:"ready",svg:o.svg})})().catch(()=>{t||d({key:h,status:"error"})}),()=>{t=!0}},[e,h,i,m]);let f=(0,a.useMemo)(()=>(0,n.jsx)("button",{type:"button",onClick:()=>l(e=>!e),disabled:t,title:t?s("i18n.previewAfterStreaming"):m?s("i18n.showMermaidSource"):s("i18n.previewMermaid"),className:["markdown-code-action",m?"is-active":""].filter(Boolean).join(" "),children:m?s("i18n.source"):s("i18n.preview")}),[t,m,s]);if(!m)return(0,n.jsx)(rv,{code:e,lang:"mermaid",headerAction:f,isStreaming:t});let g=c?.key===h&&"error"===c.status?(0,n.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==h||"ready"!==c.status?(0,n.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,n.jsxs)(n.Fragment,{children:[!u&&(0,n.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openMermaidViewer"),"aria-label":s("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),u&&(0,n.jsx)(rx,{svg:c.svg,onClose:()=>p(!1)})]});return(0,n.jsxs)("div",{className:"markdown-code-block",children:[(0,n.jsxs)("div",{className:"markdown-code-header",children:[(0,n.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),f]}),g]})}function rx({svg:e,onClose:t}){let{t:r}=(0,z.s)(),i=(0,a.useRef)(null),[s,o]=(0,a.useState)(1);return(0,a.useEffect)(()=>{let e=i.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,n.jsx)("dialog",{ref:i,className:"mermaid-zoom-dialog","aria-label":r("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,n.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,n.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,n.jsx)("span",{className:"mermaid-zoom-title",children:r("i18n.mermaidDiagram")}),(0,n.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,n.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,n.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:r("i18n.zoomOut"),"aria-label":r("i18n.zoomOut"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M5 12h14"})})}),(0,n.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,n.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:s>=3,title:r("i18n.zoomIn"),"aria-label":r("i18n.zoomIn"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,n.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>o(1),title:r("i18n.fitToWidth"),"aria-label":r("i18n.fitToWidth"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,n.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:r("i18n.close"),"aria-label":r("i18n.close"),children:(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,n.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,n.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let rv=(0,a.memo)(function({code:e,lang:t,headerAction:r,isStreaming:i}){let{isDark:s}=rh(),{t:o}=(0,z.s)(),[l,c]=(0,a.useState)(!1);return(0,n.jsxs)("div",{className:"markdown-code-block",children:[(0,n.jsxs)("div",{className:"markdown-code-header",children:[(0,n.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,n.jsxs)("div",{className:"markdown-code-actions",children:[r,(0,n.jsx)("button",{onClick:()=>{rm(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),i?(0,n.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,n.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,n.jsx)(tz.A,{language:t||"text",style:s?tW.xJ:rf,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-muted)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function rb({children:e,className:t,isStreaming:r,cwd:i,onOpenFile:s}){let o=(0,a.useMemo)(()=>tJ(e),[e]),l=(0,a.useMemo)(()=>({code({className:e,children:t,...a}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,n.jsx)(rg,{code:s.replace(/\n$/,""),isStreaming:r}):(0,n.jsx)(rv,{code:s.replace(/\n$/,""),lang:i,isStreaming:r}):(0,n.jsx)("code",{className:"markdown-inline-code",...a,children:t})},pre:({children:e})=>(0,n.jsx)(n.Fragment,{children:e}),a({href:e,children:t,...r}){delete r.node;let a=s?th(e,i):null;return a&&s?(0,n.jsx)("a",{href:e,...r,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(a))},children:t}):(0,n.jsx)("a",{href:e,...r,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...r}){delete r.node;let a="string"==typeof e?th(e,i):null,s=a?`/api/files/${tP(a)}?type=read`:e;return(0,n.jsx)("img",{src:s,alt:t??"",loading:"lazy",...r})},table:({children:e})=>(0,n.jsx)("div",{className:"markdown-table-wrap",children:(0,n.jsx)("table",{children:e})})}),[i,r,s]);return(0,n.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,n.jsx)(tO.oz,{remarkPlugins:tQ,rehypePlugins:t1,components:l,children:o})})}function ry(e){let[t,r]=(0,a.useState)(()=>Date.now());return(0,a.useEffect)(()=>{let t=setInterval(()=>r(Date.now()),e);return()=>clearInterval(t)},[e]),t}let rw=new Map,rk=new Set;function rj(){rk.forEach(e=>e())}function rS(e){return rk.add(e),()=>{rk.delete(e)}}function rC(e,t){return e&&t?`${e}\u0000${t}`:null}function rN(e){let t=!1;for(let r of e)t=rw.delete(r)||t;t&&rj()}var rT=r(54265);let rI=(0,a.createContext)(null);function rM(e,t,r){return Math.min(r,Math.max(t,e))}function rE(e,t,r){let n=t.width>0?r.width/t.width:0,a=t.height>0?r.height/t.height:0;return{x:rM((e.x-t.left)*n,0,r.width),y:rM((e.y-t.top)*a,0,r.height)}}function r$(e){let t=rM(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let rR="#e5191f",rL="#ffffff";function rA(e){let{promise:t,resolve:r,reject:n}=Promise.withResolvers();return e.toBlob(e=>e?r(e):n(Error("canvas encode failed")),"image/png"),t}function rP(e,t){let r=document.createElement("canvas");r.width=e,r.height=t;let n=r.getContext("2d");if(!n)throw Error("canvas 2d unavailable");return[r,n]}async function rF(e,t){let r=await createImageBitmap(e);try{let e={width:r.width,height:r.height},{inner:n,outer:a}=r$(e),i=Math.max(14,7*r$(e).inner),[s,o]=rP(e.width,e.height);o.drawImage(r,0,0),t.forEach((t,r)=>{let s=function(e,t){let{inner:r,outer:n}=r$(t),a=(r,n)=>{let a=rM(e.x-r,n,t.width-n),i=rM(e.y-r,n,t.height-n),s=rM(e.x+e.w+r,n,t.width-n);return{x:a,y:i,w:Math.max(0,s-a),h:Math.max(0,rM(e.y+e.h+r,n,t.height-n)-i)}};return{inner:a(r/2,r/2),outer:a(r+n/2,n/2)}}(t,e);o.lineJoin="miter",o.strokeStyle=rL,o.lineWidth=a,o.strokeRect(s.outer.x,s.outer.y,s.outer.w,s.outer.h),o.strokeStyle=rR,o.lineWidth=n,o.strokeRect(s.inner.x,s.inner.y,s.inner.w,s.inner.h);let l=String(r+1);o.font=`700 ${i}px sans-serif`;let c=Math.round(.35*i),d=Math.ceil(o.measureText(l).width)+2*c,u=Math.round(1.3*i),p=Math.min(Math.max(0,t.x-n),e.width-d),h=t.y-n-u,m=h>=0?h:Math.min(t.y,e.height-u);o.fillStyle=rL,o.fillRect(p-1,m-1,d+2,u+2),o.fillStyle=rR,o.fillRect(p,m,d,u),o.fillStyle=rL,o.textBaseline="middle",o.textAlign="center",o.fillText(l,p+d/2,m+u/2)});let l=await Promise.all(t.map(t=>{let n=function(e,t,r=.12){let n=Math.round(e.w*r),a=Math.round(e.h*r),i=rM(e.x-n,0,t.width),s=rM(e.y-a,0,t.height),o=rM(e.x+e.w+n,0,t.width);return{x:i,y:s,w:o-i,h:rM(e.y+e.h+a,0,t.height)-s}}(t,e),[a,i]=rP(n.w,n.h);return i.drawImage(r,n.x,n.y,n.w,n.h,0,0,n.w,n.h),rA(a)}));return{marked:await rA(s),crops:l}}finally{r.close()}}function r_({src:e,regions:t,max:r,onAdd:i,onNaturalSize:s,regionLabel:o}){let l=(0,a.useRef)(null),[c,d]=(0,a.useState)(null),u=(0,a.useRef)(null),[p,h]=(0,a.useState)(null),m=e=>{let t=l.current,r=u.current;return t&&r&&c?function(e,t,r,n){let a=rM(Math.min(e.x,t.x),r.left,r.left+r.width),i=rM(Math.max(e.x,t.x),r.left,r.left+r.width),s=rM(Math.min(e.y,t.y),r.top,r.top+r.height),o=rM(Math.max(e.y,t.y),r.top,r.top+r.height);if(i-a<6||o-s<6)return null;let l=rE({x:a,y:s},r,n),c=rE({x:i,y:o},r,n),d=Math.floor(l.x),u=Math.floor(l.y),p=Math.min(n.width,Math.ceil(c.x))-d,h=Math.min(n.height,Math.ceil(c.y))-u;return p>0&&h>0?{x:d,y:u,w:p,h}:null}(r.start,e,t.getBoundingClientRect(),c):null},f=(e,t)=>{if(u.current?.pointerId!==e.pointerId)return;let r=t?m({x:e.clientX,y:e.clientY}):null;u.current=null,h(null),r&&i(r)};return(0,n.jsxs)("div",{className:"tool-image-marker","data-drawing":c&&t.length<r?"true":void 0,onPointerDown:e=>{c&&!(t.length>=r)&&("mouse"!==e.pointerType||0===e.button)&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),u.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY}})},onPointerMove:e=>{u.current?.pointerId===e.pointerId&&h(m({x:e.clientX,y:e.clientY}))},onPointerUp:e=>f(e,!0),onPointerCancel:e=>f(e,!1),children:[(0,n.jsx)("img",{ref:l,className:"tool-image-full",src:e,alt:"",draggable:!1,onLoad:e=>{let t={width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight};d(t),s(t)}}),c&&t.map((e,t)=>(0,n.jsx)(rz,{region:e,natural:c,label:String(t+1),title:o(t+1)},`${t}-${e.x}-${e.y}`)),c&&p&&(0,n.jsx)(rz,{region:p,natural:c})]})}function rz({region:e,natural:t,label:r,title:a}){let i={left:e.x/t.width*100,top:e.y/t.height*100,width:e.w/t.width*100,height:e.h/t.height*100};return(0,n.jsx)("span",{className:"tool-image-region","data-draft":r?void 0:"true",role:r?"img":void 0,"aria-label":a,style:{left:`${i.left}%`,top:`${i.top}%`,width:`${i.width}%`,height:`${i.height}%`},children:r&&(0,n.jsx)("span",{className:"tool-image-region-number","aria-hidden":"true",children:r})})}function rW(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),r=e.length-t;for(let t=0;t<r;t+=1){var n;if(!((n=e.charCodeAt(t))>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||43===n||47===n))return null}for(let t=r;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}function rO(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let r=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),n=/Command exited with code (-?\d+)\s*$/.exec(r.trimEnd());return n?Number(n[1]):null}let rD=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,rH=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function rU(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let rB={hideThinkingBlock:!1},rq=new Set,rV=rB,rK=0;function rG(e){return rq.add(e),()=>{rq.delete(e)}}function rJ(){return rV}function rZ(){return rB}async function rY(e){let t=++rK,r=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/display-settings${r}`,{cache:"no-store"});if(!n.ok)throw Error(`Display settings request failed (${n.status})`);let a=await n.json();t!==rK||a.hideThinkingBlock!==rV.hideThinkingBlock&&(rV={hideThinkingBlock:!0===a.hideThinkingBlock},rq.forEach(e=>e()))}function rX(){return(0,a.useSyncExternalStore)(rG,rJ,rZ)}function rQ(e){let t=new Date(e),r=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}:${r(t.getMinutes())}`}let r0=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","MITSU(미츠)","SHION(시온)","HIKARI(히카리)"],r1={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","MITSU(미츠)":"mitsu","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},r2=["approval","choice","done","failed","blocked","working"],r8={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},r4={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0},r5="/api/office-characters/",r6={voice:"/audio/completion/",sticker:"/stickers/"};function r3(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function r7(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(r8,e)?e:null}function r9(e,t){let r=new Map,n=new Map;if(!Array.isArray(e))return{files:r,lines:n};for(let a of e){if("object"!=typeof a||null===a)continue;let{file:e,tag:i,ko:s}=a;if("string"!=typeof e||""===e)continue;let o=r7(i);if(null===o)continue;let l=t+e.replace(/^\/+/,""),c=r.get(o);c?c.push(l):r.set(o,[l]),"string"==typeof s&&""!==s.trim()&&n.set(l,s.trim())}return{files:r,lines:n}}function ne(e,t=r6){let r=new Map;if("object"!=typeof e||null===e)return r;let{characters:n}=e;if(!Array.isArray(n))return r;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:a,stickers:i,captions:s}=e;if("string"!=typeof n||""===n)continue;let o=r9(a,t.voice),l=r9(i,t.sticker),c=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if("object"!=typeof r||null===r)continue;let{tag:e,ko:n}=r;if("string"!=typeof n||""===n.trim())continue;let a=r7(e);if(null===a)continue;let i=t.get(a);i?i.push(n.trim()):t.set(a,[n.trim()])}return t}(s),d=new Map;for(let e of r2){let t=o.files.get(e)??[],r=new Map;for(let e of t){let t=o.lines.get(e);void 0!==t&&r.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:r,captions:c.get(e)??[]})}r.set(n,d)}return r}function nt(e,t,r){let n=t&&Object.hasOwn(r1,t)?r1[t]:null;return n?e.get(n)?.get(r)??null:null}function nr(e,t,r){return e.get(t)?.get(r)??null}async function nn(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return ne(await t.json())}catch{return new Map}}function na(e,t,r=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let n=null===t?-1:e.indexOf(t),a=-1===n?e.length:e.length-1,i=Math.min(a-1,Math.max(0,Math.floor(r()*a)));return e[-1!==n&&i>=n?i+1:i]}function ni(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let r of e.content)if("text"===r.type)t.push(r.text.trim());else if("toolCall"===r.type){let e="id"in r&&"string"==typeof r.id?r.id:"";t.push(`toolCall:${r.toolCallId||e}`)}}let r="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,r,t.filter(Boolean)])}function ns(e,t,r,n){if(t&&("web6"!==t.provider||t.model!==no))return{provider:t.provider,model:t.model,credentialId:t.credentialId};for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role)break;if("assistant"===r.role&&("web6"!==r.provider||r.model!==no))return{provider:r.provider,model:r.model,credentialId:r.credentialId}}return{provider:r,model:n,credentialId:void 0}}let no="ChatGPT 6PRO",nl="/api/sidecars/resource";function nc(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},r=e=>{let r=t[e];return"number"==typeof r&&Number.isFinite(r)?r:null},n=r("usedFraction");if(null!==n&&n>=1)return!0;let a=r("remainingFraction");if(null!==a&&a<=0)return!0;let i=r("used"),s=r("limit");if(null!==i&&null!==s&&i>=s)return!0;let o=r("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==i&&i>=100}let nd=[{alias:"RIN(린)",file:"rin.webp"},{alias:"MIO(미오)",file:"mio.webp"},{alias:"MITSU(미츠)",file:"mitsu.webp",provider:"hive",model:"zai-org/glm-5.3-flash"},{alias:"YUKI(유키)",file:"yuki.webp",provider:"openai-codex"},{alias:"ISANA(이사나)",file:"isana.webp",provider:"hive"},{alias:"SHION(시온)",file:"shion.webp",provider:"web6"},{alias:"HIKARI(히카리)",file:"hikari.webp",provider:"google-vertex",model:"gemini-4-argon"}],nu={"gemini-4-argon":"HIKARI(히카리)"},np=[{seed:3,alias:nd[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:nd[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:nd[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:nd[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:nd[2].alias,provider:"hive",model:"zai-org/glm-5.3-flash",voice:"부지런한 배달\xb7통통 튀는 보고\xb7끈질긴 재도전",summonExample:"미츠 불러와",switchExample:"미츠로 교체해"},{seed:6,alias:nd[6].alias,provider:"google-vertex",model:"gemini-4-argon",voice:"빠른 관찰\xb7톡 쏘는 한마디\xb7장난스러운 여유",summonExample:"히카리 불러와",switchExample:"히카리로 교체해"},{seed:5,alias:nd[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],nh=np.filter(e=>null!==e.switchExample),nm={mode:"default",rosterAvailable:!1,seats:[]},nf=nm,ng=new Map,nx=new Map,nv=np,nb=new Set,ny=null,nw=0,nk=new Map,nj=new Map,nS=null,nC=!1;function nN(e){let t="office"===e.mode?e.seats.filter(e=>!nd.some(t=>t.alias===e.alias)&&"MITSU(미츠)"!==e.seat):[];nw+=1;let r=JSON.stringify([e.mode,e.rosterAvailable,t]);if(r!==nS)for(let n of(nS=r,nf={...e,seats:t},nx=new Map([...ng=new Map(t.flatMap(e=>{let t=nd.findIndex(t=>t.alias===e.seat);return t>=0?[[t,e]]:[]}))].flatMap(([e,t])=>{let r=nd[e];return"provider"in r&&!("model"in r)?[[r.provider,{seed:e,alias:t.alias}]]:[]})),nk=new Map([...ng].flatMap(([e,t])=>{let r=nd[e];return"model"in r?[[`${r.provider}/${r.model}`,{seed:e,alias:t.alias}]]:[]})),nj=new Map(Object.entries(nu).flatMap(([e,t])=>{let r=nd.findIndex(e=>e.alias===t),n=ng.get(r);return n?[[e,{seed:r,alias:n.alias}]]:[]})),nv=0===ng.size?np:np.map(e=>{let t,r,n,a=ng.get(nd.findIndex(t=>t.alias===e.alias));return a?(t=a.names.findLast(e=>/[가-힣]/.test(e))??a.names[0]??a.alias.split("(",1)[0],{...e,alias:a.alias,voice:a.voice.temperament.split(/(?<=[.。])\s/,1)[0].replace(/[.。]$/,""),summonExample:`${t} 불러와`,switchExample:`${n=(r=t.charCodeAt(t.length-1)-44032)>=0&&r<=11171?r%28:0,`${t}${0===n||8===n?"로":"으로"}`} 교체해`}):e}),nb))n()}function nT(){return nf}function nI(e){return nb.add(e),()=>{nb.delete(e)}}async function nM(e=fetch){let t=nw;try{let r=await e("/api/character-mode",{cache:"no-store"});if(!r.ok)return!1;let n=await r.json();if("object"!=typeof n||null===n)return!1;if(t!==nw)return!0;let{mode:a,rosterAvailable:i,seats:s}=n;return nN({mode:"office"===a?"office":"default",rosterAvailable:!0===i,seats:Array.isArray(s)?s:[]}),!0}catch{return!1}}let nE=new WeakMap;function n$(e){let t=nE.get(e);return t||(t=ne(e.manifest,{voice:r5,sticker:r5}),nE.set(e,t)),t}function nR(e){return e?nf.seats.find(t=>t.seat===e||t.alias===e)??null:null}function nL(e){return nf.seats.find(t=>t.seat===e)?.alias??e}let nA=nd.filter(e=>!("provider"in e)).length,nP=new Map(nd.flatMap((e,t)=>"provider"in e&&!("model"in e)?[[e.provider,t]]:[])),nF=new Map(nd.flatMap((e,t)=>"model"in e?[[`${e.provider}/${e.model}`,{seed:t,alias:e.alias}]]:[])),n_=new Map(Object.entries(nu).map(([e,t])=>[e,{seed:nd.findIndex(e=>e.alias===t),alias:t}])),nz=new Map([...nP].map(([e,t])=>[e,{seed:t,alias:nd[t].alias}])),nW=new Map(Object.entries({"google-antigravity":"HIKARI(히카리)"}).map(([e,t])=>[e,nd.findIndex(e=>e.alias===t)]));function nO(e,t){if(void 0===t)return null;let r=`${e}/${t}`;return nk.get(r)??nj.get(t)??nF.get(r)??n_.get(t)??null}function nD(e){return nx.get(e)??nz.get(e)??null}function nH(e){let t=e%nd.length;return ng.get(t)?.alias??nd[t].alias}function nU(e){let t=e%nd.length;return ng.get(t)?.faceUrl??`/avatars/${nd[t].file}`}function nB(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function nq(e){return({"openai-codex":"OpenAI Codex",anthropic:"Anthropic","google-gemini":"Google Gemini","github-copilot":"GitHub Copilot","opencode-go":"OpenCode Go",devin:"Devin","b-ai":"B.AI",web6:"WEB6"})[e]??e.replace(/(^|-)(\w)/g,(e,t,r)=>`${t?" ":""}${r.toUpperCase()}`)}function nV(e){let t=new Map;for(let r of e){if(!Number.isSafeInteger(r.oauthPosition)||r.oauthPosition<0)continue;let e=t.get(r.provider)??new Set;e.add(r.oauthPosition),t.set(r.provider,e)}return e.map(e=>{var r;let n=e.metadata?.email,a=e.metadata?.accountId,i="string"==typeof n&&n.length>0?n:"string"==typeof a?a:"",s=i.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return nB(e);let r=e.slice(t+1),n=r.lastIndexOf("."),a=n<0?r:r.slice(0,n),i=n<0?"":r.slice(n);return`${nB(e.slice(0,t))}@${0===a.length?"":`${a[0]}•••`}${i}`}(i):"",o=(r=e.provider,nP.get(r)??-1);if(o>=0)return{seed:o,alias:nH(o),masked:s,raw:i};let l=e.oauthPosition;if(!Number.isSafeInteger(l)||l<0){let r=t.get(e.provider)??new Set;for(l=0;r.has(l);)l++;r.add(l),t.set(e.provider,r)}let c=nW.get(e.provider)??-1;if(c>=0)return{seed:c,alias:`${nH(c)}${l+1}`,masked:s,raw:i};let d=l%nA,u=l<nA?nH(d):`${nH(d)}${l+1}`;return{seed:d,alias:u,masked:s,raw:i}})}class nK extends Error{constructor(e,t,r,n){super(e,n),this.kind=t,this.status=r,this.name="ResourceClientError",this.code=n?.code,this.outcomeUnknown=n?.outcomeUnknown}}function nG(e,t){return`${nl}${e}${t?"?refresh=1":""}`}function nJ(e,t,r=!1){return e instanceof nK?e:t?new nK("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):r||e instanceof DOMException&&"AbortError"===e.name?new nK("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new nK(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function nZ(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function nY(e,t){let r,n=t.fetchImpl??fetch,a=new AbortController,i=!1,s=()=>a.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0}),null!=t.timeoutMs&&(r=setTimeout(()=>{i=!0,a.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,r=await n(e,{signal:a.signal});try{t=await r.json()}catch(e){throw new nK("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",r.status,{cause:e})}let i=t&&"object"==typeof t?t:null,s="string"==typeof i?.error?i.error:null;if(!r.ok||s)throw new nK(s??`HTTP ${r.status}`,"http",r.status,{code:"string"==typeof i?.code?i.code:void 0,outcomeUnknown:i?.outcomeUnknown===!0});return t}catch(e){throw nJ(e,i,a.signal.aborted)}finally{clearTimeout(r),t.signal?.removeEventListener("abort",s)}}function nX(e){return"google-antigravity"===e.provider&&Array.isArray(e.limits)?{...e,limits:e.limits.filter(e=>"google"===e.id.split(":")[1]||/gemini/i.test(e.label??""))}:e}async function nQ(e={}){try{let t=await nY(nG("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new nK("사용량 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:{...t,reports:t.reports.map(nX)},error:null}}catch(t){return nZ(e.previous,nJ(t,!1))}}async function n0(e,t={}){if(!e)return nZ(void 0,new nK("세션 id가 올바르지 않습니다.","invalid-response"));try{let r=await nY(`/api/agent/${encodeURIComponent(e)}/account`,t),n=r?.state==="resolved"||r?.state==="unresolved"||r?.state==="not-running"||r?.state==="unsupported";if(!r||r.sessionId!==e||"number"!=typeof r.observedAt||!n||!Array.isArray(r.resetRecommendations))throw new nK("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:r,error:null}}catch(e){return nZ(void 0,nJ(e,!1))}}async function n1(e={}){try{let t=await nY(nG("/models",!0===e.refresh),{...e,timeoutMs:e.timeoutMs??12e4});if(!t||!Array.isArray(t.models)||!Array.isArray(t.agents)||!Array.isArray(t.daily))throw new nK("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return nZ(e.previous,nJ(t,!1))}}async function n2(e={}){try{let t=await nY(`${nl}/credits${!0===e.refresh?"?refresh=1":""}`,{...e,timeoutMs:e.timeoutMs??6e4});if(!(t&&"object"==typeof t&&t.settings&&"object"==typeof t.settings&&t.hive&&Array.isArray(t.hive.rows)&&(void 0===t.anthropic||Array.isArray(t.anthropic?.rows))&&(void 0===t.balances||Array.isArray(t.balances)&&t.balances.every(e=>!!e&&"string"==typeof e.wallet&&(null===e.recorded||"object"==typeof e.recorded&&Number.isFinite(e.recorded?.amountUsd)&&Number.isFinite(e.recorded?.observedAt))))))throw new nK("API 크레딧 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return nZ(e.previous,nJ(t,!1))}}async function n8(e,t={}){await n5({wallet:"hive",value:e},t)}async function n4(e,t,r={}){await n5({kind:"balance",wallet:e,value:t},r)}async function n5(e,t){await nY(`${nl}/credits/settings`,{...t,timeoutMs:t.timeoutMs??2e4,fetchImpl:async(r,n)=>{let a=new Headers(n?.headers);return a.set("Content-Type","application/json"),(t.fetchImpl??fetch)(r,{...n,method:"POST",headers:a,body:JSON.stringify(e)})}})}async function n6(e,t,r={}){if(!Number.isSafeInteger(e)||e<=0)throw new nK("credential id가 올바르지 않습니다.","invalid-response");let n=await nY(`${nl}/credential/${e}/${t?"enable":"disable"}`,{...r,timeoutMs:r.timeoutMs??2e4,fetchImpl:async(e,t)=>(r.fetchImpl??fetch)(e,{...t,method:"POST"})});if(!n||!0!==n.ok||n.credentialId!==e||!t!==n.disabled)throw new nK("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return n}async function n3(e,t,r={}){if(!Number.isSafeInteger(e)||e<=0)throw new nK("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new nK("credit id가 올바르지 않습니다.","invalid-response");let n=await nY(`${nl}/credential/${e}/reset`,{...r,timeoutMs:r.timeoutMs??2e4,fetchImpl:async(e,n)=>{let a=new Headers(n?.headers);return a.set("Content-Type","application/json"),(r.fetchImpl??fetch)(e,{...n,method:"POST",headers:a,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!n||"boolean"!=typeof n.ok||n.credentialId!==e||n.creditId!==t||"string"!=typeof n.code||n.ok!==("reset"===n.code))throw new nK("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return n}function n7(e,t){if(e.has(t))return null;e.add(t);let r=!1;return()=>{r||(r=!0,e.delete(t))}}let n9={faces:new Map,pins:new Map},ae=[],at=n9,ar=null,an=ae,aa=new Map,ai=new Set;function as(e){let t=(ai.add(e),()=>{ai.delete(e)}),r=nI(e);return()=>{t(),r()}}function ao(e){at=e,ai.forEach(e=>e())}function al(e){return Number.isSafeInteger(e)&&e>0}function ac(e,t){return`${e}:${t}`}function ad(e){let t=e??ae;an=t;let r=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(r===ar)return;ar=r;let n=nV(t),a=new Map;t.forEach((e,t)=>{let r=e.credentialId;if(!al(r))return;let i=ac(e.provider,r);a.has(i)||a.set(i,{seed:n[t].seed,alias:n[t].alias})}),ao({faces:a,pins:at.pins})}function au(e,t,r,n){if(!t)return null;let a=nO(t,n);if(a)return a;if(al(r)){let e=at.faces.get(ac(t,r));if(e)return e}let i=e?at.pins.get(e):void 0;if(i&&i.provider===t){let e=at.faces.get(ac(t,i.credentialId));if(e)return e}return nD(t)??("anthropic"!==t||al(r)||i?.provider===t?null:nv.find(e=>e.provider===t&&0===e.oauthPosition)??null)}async function ap(e,t,r,n){if(!t||al(r)||nD(t))return au(e,t,r,n);try{let{data:r}=await n0(e);if(r?.state==="resolved"&&r.provider===t&&al(r.credentialId)){let n=new Map(at.pins);n.set(e,{provider:t,credentialId:r.credentialId,observedAt:Date.now()}),ao({faces:at.faces,pins:n})}}catch{}return au(e,t,void 0,n)}function ah(e,t,r,n){let i=!!t&&!al(r)&&!!e;return(0,a.useEffect)(()=>{i&&e&&t&&function(e,t){let r=Date.now(),n=at.pins.get(e);if(n&&n.provider===t&&r-n.observedAt<3e4)return;let a=`${e}\u0000${t}`,i=aa.get(a);void 0!==i&&r-i<3e4||(aa.set(a,r),n0(e).then(t=>{let r=t.data;if(!r||"resolved"!==r.state)return;let{provider:n,credentialId:a}=r;if("string"!=typeof n||""===n||!al(a))return;let i=new Map(at.pins);i.set(e,{provider:n,credentialId:a,observedAt:Date.now()}),ao({faces:at.faces,pins:i})}).catch(()=>{}))}(e,t)},[i,e,t]),(0,a.useSyncExternalStore)(as,()=>au(e,t,r,n),()=>null)}function am(){return(0,a.useEffect)(()=>{if(!nC){nC=!0;let e=()=>{"visible"===document.visibilityState&&nM()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e)}null===ny&&(ny=nM().then(e=>{e||(ny=null)}))},[]),(0,a.useSyncExternalStore)(nI,nT,()=>nm)}nI(()=>{ar=null,ad(an)});let af={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","run.dispatching":"발주 중","run.pending":"대기","run.running":"실행 중","run.completed":"실행 완료","run.failed":"실행 실패","run.aborted":"중단됨","run.unobserved":"실행 상태 미관측","verdict.accepted":"Main 수용","verdict.rework":"Main 재작업 요청","verdict.held":"Main 보류","verdict.none":"검수 미기록","verdict.attempt":"{attempt}차","detail.stage":"현재 단계","detail.stageNone":"기록 없음","detail.model":"모델","detail.modelNone":"미관측","detail.fallback":"대체 모델","detail.agentId":"담당 ID","detail.reason":"판정 사유","detail.source.live":"실시간 관측","detail.source.record":"세션 기록","detail.openSubagents":"서브에이전트 상세 열기","detail.openProcess":"작업 기록 열기","summary.live":"진행 중","summary.files":"변경 파일 {count}","summary.files.one":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checks.one":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.verdictUnverified":"판정 미확인 {count}","summary.verdictUnverified.one":"판정 미확인 {count}","summary.expand":"턴 요약 펼치기","summary.collapse":"턴 요약 접기","result.label":"이번 결과","result.open":"결과 보기","result.openNamed":"{name} 결과 보기","result.previewTitle":"{name} 미리보기","result.previewFailed":"미리보기를 불러오지 못했습니다. 결과 보기를 누르세요.","result.more":"다른 결과 {count}","result.previewLoading":"미리보기를 불러오는 중","result.kind.html":"화면","result.kind.pdf":"PDF","result.kind.document":"문서","result.kind.image":"이미지","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.check.exit":"exit {code}","summary.makers":"Maker {count}","summary.makers.one":"Maker {count}","summary.remaining":"남은 일 {count}","summary.heading.remaining":"남은 일","summary.time.unobserved":"시간 기록 없음","summary.time.running":"아직 실행 중","summary.todo.pending":"대기","summary.todo.in_progress":"진행 중","summary.todo.blocked":"막힘","summary.todo.blocker":"막힌 이유: {blocker}","summary.todo.none":"남은 일 없음","flow.heading":"작업 흐름","flow.aria":"이번 턴의 작업 단계","flow.toggle":"작업 흐름","flow.stage.investigate":"조사","flow.stage.edit":"수정","flow.stage.check":"검사","flow.stage.review":"교차리뷰","flow.stage.commit":"커밋\xb7푸시","flow.stage.ci":"CI","flow.stage.deploy":"배포","flow.state.waiting":"대기","flow.state.running":"진행 중","flow.state.done":"완료","flow.state.redone":"다시 고침","flow.state.passed":"통과","flow.state.unverified":"판정 미확인","flow.state.failed":"실패","flow.state.unobserved":"결과 미관측","flow.state.findings":"지적 {count}건","flow.state.findings.one":"지적 {count}건","flow.state.noFindings":"지적 없음","flow.state.open":"미해결 {count}건","flow.state.reviewUnusable":"리뷰 불가","flow.state.skipped":"건너뜀","flow.state.notNeeded":"필요 없음","flow.count.passed":"통과 {count}","flow.count.unverified":"판정 미확인 {count}","flow.count.failed":"실패 {count}","flow.count.unobserved":"결과 미관측 {count}","flow.count.running":"진행 중 {count}","flow.earlier":"이전 회차 {count}건","flow.attempt":"{attempt}회차","flow.label.typecheck":"타입 검사","flow.label.lint":"린트","flow.label.test":"테스트","flow.label.build":"빌드","flow.label.verify":"검증","flow.label.smoke":"스모크 확인","flow.label.check":"검사","flow.label.ci":"CI 확인","flow.label.deploy":"배포 실행","flow.label.review":"리뷰","flow.label.resolve":"지적 처리","flow.label.commit":"커밋\xb7푸시","flow.details":"자세히","flow.commandOmitted":"명령 본문은 압축된 요청의 요약에서 생략했어요.","flow.exit":"셸 종료 코드 {code}","flow.exit.none":"종료 코드 기록 없음","flow.exit.error":"오류로 끝남","flow.evidence":"판정에 쓴 기록","flow.why.confirmed":"확인된 것","flow.why.missing":"없는 것","flow.why.exitZero":"셸 종료 코드 0","flow.why.check":"{label} 명령의 종료 코드. 뒤에 이어 붙인 명령(파이프, ;, || 등)이 결과를 가릴 수 있어서 통과로 세지 않았어요.","flow.why.ci":"CI 결과를 종료 코드로 돌려준 기록. gh run watch --exit-status처럼 결과를 돌려주는 명령이 아니라서 통과로 세지 않았어요.","flow.why.ciOtherRun":"이 커밋의 CI 실행이라는 기록. 기다린 실행은 기록상 다른 커밋 {sha}의 실행이에요.","flow.why.ciPublishRun":"이 커밋의 CI 실행 결과. 이 명령이 기다린 실행은 게시 실행이라 CI 판정으로 세지 않았어요.","flow.why.watched.passed":"기다린 실행이 통과로 끝남","flow.why.watched.failed":"기다린 실행이 실패로 끝남","flow.why.watched.unjudged":"기다린 실행이 판정 없이 끝남({conclusion})","flow.why.ciUnjudged":"이 커밋의 CI 판정. 기다린 실행이 통과도 실패도 아닌 {conclusion} 상태로 끝나서, 명령의 실패를 CI 실패로 세지 않았어요.","flow.why.deploy":"배포가 끝났다는 기록. 배포를 띄우고 바로 돌아오는 명령이라 셸 종료 코드만으로는 끝났는지 알 수 없어요.","flow.strip.running":"{stage} 진행 중","flow.loop.badge":"↻ {attempt}회차","flow.loop.failed":"{stage} {attempt}회차 실패로 수정에 되돌아옴","flow.loop.findings":"{stage} {attempt}회차 지적으로 수정에 되돌아옴","flow.state.stale":"수정 전 통과","flow.state.staleDone":"수정 전 완료","flow.count.stale":"수정 전 통과 {count}","flow.why.stale":"이 결과 뒤에 파일을 다시 고쳐서, 마지막 수정본은 아직 확인하지 않았어요.","flow.compound.failed":"묶은 명령 실패","flow.why.compoundConfirmed":"{stages}를 한 명령으로 돌렸고, 명령 전체가 실패로 끝남","flow.why.compoundMissing":"어느 단계에서 실패했는지","flow.why.next":"다음에 할 일","flow.why.check.syntax":"{label} 명령의 종료 코드. 명령에 $(…)\xb7백틱\xb7( ) 묶음\xb7{ } 같은 셸 구문이 있어서, 그 종료 코드가 셸 종료 코드까지 그대로 왔는지 이 화면은 따지지 않아요. 그래서 통과로 세지 않았어요.","flow.why.check.optional":"{label} 스크립트가 실제로 실행된 기록. --if-present를 쓰면 스크립트가 없을 때 실행기가 아무것도 실행하지 않고 종료 코드 0으로 끝나요.","flow.why.noExit":"이 호출의 종료 코드. 결과 기록에 종료 코드가 없어요.","flow.why.noResult":"이 호출의 결과. 결과 기록이 없어요.","flow.why.interrupted":"이 호출의 결과. 호출이 끝나기 전에 끊겼어요.","flow.why.noCompletion":"이 호출의 종료 코드. 호출이 백그라운드 job으로 넘어갔고, 그 job의 완료 기록이 없어요.","flow.next.rerun":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 검사 명령 자체의 종료 코드를 찾을 수 없을 때만 파이프, ;, ||, 감싸는 구문 없이 검사 명령을 단독으로 다시 실행하세요. 긴 출력은 tail이나 grep으로 자르지 말고 결과 artifact에서 확인하세요.","flow.next.optional":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 스크립트 실행 기록을 찾을 수 없을 때만 --if-present 없이 스크립트 이름으로 다시 실행하세요.","flow.next.compound":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 어느 단계가 실패했는지 찾을 수 없을 때만 단계마다 명령을 나눠 다시 실행하세요.","flow.next.again":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 종료 코드를 찾을 수 없을 때만 같은 검사를 다시 실행하세요.","flow.repeats":"반복 실행 {count}건","flow.ci.notNeeded":"비공개 저장소에만 반영됐어요. 게시 실행 {run} 뒤에도 공개 {repo}의 {ref}는 CI를 통과한 {sha} 그대로예요.","flow.ci.nothingToPublish":"커밋 {sha}의 게시 실행 로그에 「Public tree already matches; nothing to publish」가 남았어요. 공개 저장소가 그대로라 새로 돌 CI가 없어요.","summary.stale":"수정 전 통과 {count}","summary.compoundFailed":"묶은 명령 실패 {count}","graph.branch":"수정 중 맡긴 Maker {count}","graph.branch.one":"수정 중 맡긴 Maker {count}","graph.parallel.observed":"동시 실행 관측","graph.join":"Main 판정","graph.parallel.batch":"같은 발주 묶음","graph.concurrency.overlapped":"겹쳐 실행","graph.concurrency.unknown":"겹침 여부 모름","graph.kind.feature":"기능","graph.kind.maintenance":"유지보수","graph.kind.diagnostic":"진단","graph.kind.unknown":"종류 미기록","graph.outputs":"변경 결과","graph.files":"파일 {count}","graph.docs":"문서 {count}","graph.files.one":"파일 {count}","graph.docs.one":"문서 {count}","graph.detail.aria":"선택한 노드 자세히","graph.maker.open":"Maker 기록 열기","graph.maker.unavailable":"실시간 기록이 없어 여기서 열 수 없어요.","graph.motion.pause":"움직임 멈춤","graph.replay":"재생","graph.replay.stop":"재생 멈춤","subflow.aria":"이 서브에이전트 실행의 단계","subflow.calls":"도구 {count}회","subflow.reedits":"다시 수정 {count}회","subflow.checks":"검사 {passed}/{total} 통과","subflow.reported":"보고함","subflow.unobserved":"기록 미관측","subflow.rework":"↻ Main 재작업 요청 {count}회로 구현에 되돌아옴","subflow.prior":"이전 판정","subflow.firstTitle":"첫 발주 제목","subflow.runTitle":"이번 실행 제목","delivery.title":"보낸 입력 {count}","delivery.kind.steer":"지금 지시","delivery.kind.followUp":"완료 후 요청","delivery.stage.sending":"보내는 중","delivery.stage.accepted":"접수됨 \xb7 전달 대기","delivery.stage.delivered":"전달됨 \xb7 대화에 들어감","delivery.stage.failed":"보내지 못함 \xb7 입력창에 되돌림","delivery.stage.unconfirmed":"전달 확인 못 함 \xb7 큐에서 빠짐","delivery.images":"이미지 {count}개","delivery.images.one":"이미지 {count}개","delivery.showOlder":"이전 {count}개 더 보기","delivery.showRecent":"최근 {count}개만 보기","live.nativeVoice":"기본 음성","progress.label":"진행","phase.investigate":"조사","phase.implement":"구현","phase.verify":"검증","phase.report":"보고","phase.current":"지금 단계 {phase}","phase.hint":"도구 호출로 읽은 지금 단계입니다. 고친 뒤 다시 고치면 앞 단계로 돌아갑니다.","progress.todo":"할 일 {completed}/{total} ({percent}%)","eta.label":"예상 시간","eta.elapsed":"경과 {duration}","eta.remaining":"남은 시간 보통 {range} (과거 {samples}건)","eta.percent":"약 {percent}% 추정","eta.overrun":"과거 최장 기록({longest}) 이상 경과","eta.sparseTail":"과거 {samples}건 중 {longerRuns}건만 이보다 오래 걸림","eta.hint":"같은 모델\xb7작업 등급의 과거 첫 시도 가운데 지금 경과보다 오래 걸린 실행들의 남은 시간 분포(가운데 절반)입니다.","eta.byTodo":"할 일 기준 약 {duration} 남음 ({completed}/{total} 단계)","eta.byTodoSoon":"할 일 기준 1분 이내 ({completed}/{total} 단계)","eta.byTodoHint":"todo 완료 비율로만 잰 값입니다. 단계마다 걸리는 시간이 달라 오차가 큽니다.","eta.rework":"재작업 {attempt}차 \xb7 첫 발주부터 {duration}","eta.reworkAttempt":"재작업 {attempt}차","eta.reworkHint":"재작업 시도는 과거 소요 기록이 거의 없어 남은 시간\xb7%를 추정하지 않습니다. 첫 발주부터의 시간에는 시도 사이 Main 검수\xb7대기 시간이 들어 있습니다.","eta.rangeMinutes":"{low}~{high}분","eta.range":"{low}~{high}","duration.seconds":"{seconds}초","duration.minutesSeconds":"{minutes}분 {seconds}초","duration.minutes":"{minutes}분","duration.hours":"{hours}시간","duration.hoursMinutes":"{hours}시간 {minutes}분","duration.underMinute":"1분 미만"},en:{"dispatch.title":"Subagents: {count}","dispatch.tally":"{running} running \xb7 {done} finished \xb7 {accepted} accepted by Main","dispatch.expand":"Show dispatch details","dispatch.collapse":"Hide dispatch details","run.dispatching":"Dispatching","run.pending":"Queued","run.running":"Running","run.completed":"Run finished","run.failed":"Run failed","run.aborted":"Stopped","run.unobserved":"Run state not observed","verdict.accepted":"Accepted by Main","verdict.rework":"Main asked for rework","verdict.held":"Held by Main","verdict.none":"No review recorded","verdict.attempt":"attempt {attempt}","detail.stage":"Current step","detail.stageNone":"Not recorded","detail.model":"Model","detail.modelNone":"Not observed","detail.fallback":"fallback","detail.agentId":"Agent ID","detail.reason":"Review note","detail.source.live":"live","detail.source.record":"session record","detail.openSubagents":"Open subagent details","detail.openProcess":"Open work log","summary.live":"In progress","summary.files":"{count} files changed","summary.files.one":"{count} file changed","summary.checks":"{count} checks","summary.checks.one":"{count} check","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.verdictUnverified":"{count} verdicts not confirmed","summary.verdictUnverified.one":"{count} verdict not confirmed","summary.expand":"Show turn summary","summary.collapse":"Hide turn summary","result.label":"Result","result.open":"View result","result.openNamed":"View result: {name}","result.previewTitle":"Preview of {name}","result.previewFailed":"Couldn't load the preview. Use View result to open it.","result.more":"{count} more","result.previewLoading":"Loading preview","result.kind.html":"Page","result.kind.pdf":"PDF","result.kind.document":"Document","result.kind.image":"Image","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.check.exit":"exit {code}","summary.makers":"{count} Makers","summary.makers.one":"{count} Maker","summary.remaining":"{count} left","summary.heading.remaining":"Still to do","summary.time.unobserved":"time not recorded","summary.time.running":"still running","summary.todo.pending":"pending","summary.todo.in_progress":"in progress","summary.todo.blocked":"blocked","summary.todo.blocker":"blocked by: {blocker}","summary.todo.none":"nothing left","flow.heading":"Work flow","flow.aria":"Work stages of this turn","flow.toggle":"Work flow","flow.stage.investigate":"Investigate","flow.stage.edit":"Edit","flow.stage.check":"Check","flow.stage.review":"Cross review","flow.stage.commit":"Commit & push","flow.stage.ci":"CI","flow.stage.deploy":"Deploy","flow.state.waiting":"waiting","flow.state.running":"in progress","flow.state.done":"done","flow.state.redone":"fixed again","flow.state.passed":"passed","flow.state.unverified":"verdict not confirmed","flow.state.failed":"failed","flow.state.unobserved":"result not observed","flow.state.findings":"{count} findings","flow.state.findings.one":"{count} finding","flow.state.noFindings":"no findings","flow.state.open":"{count} open","flow.state.reviewUnusable":"review unusable","flow.state.skipped":"skipped","flow.state.notNeeded":"not needed","flow.count.passed":"{count} passed","flow.count.unverified":"{count} not confirmed","flow.count.failed":"{count} failed","flow.count.unobserved":"{count} not observed","flow.count.running":"{count} running","flow.earlier":"{count} from earlier attempts","flow.attempt":"Attempt {attempt}","flow.label.typecheck":"Type check","flow.label.lint":"Lint","flow.label.test":"Tests","flow.label.build":"Build","flow.label.verify":"Verification","flow.label.smoke":"Smoke check","flow.label.check":"Check","flow.label.ci":"CI check","flow.label.deploy":"Deploy run","flow.label.review":"Review","flow.label.resolve":"Resolve","flow.label.commit":"Commit & push","flow.details":"Details","flow.commandOmitted":"The command body is omitted from this compacted request summary.","flow.exit":"shell exit code {code}","flow.exit.none":"no exit code recorded","flow.exit.error":"ended with an error","flow.evidence":"Judged from","flow.why.confirmed":"Confirmed","flow.why.missing":"Missing","flow.why.exitZero":"shell exit code 0","flow.why.check":"The exit code of the {label} command itself. Commands chained after it (a pipe, ;, || and so on) can hide its result, so it was not counted as passed.","flow.why.ci":"A CI result returned as an exit code. The command does not return one the way gh run watch --exit-status does, so it was not counted as passed.","flow.why.ciOtherRun":"A record that the run belongs to this commit. The watched run is recorded for another commit, {sha}.","flow.why.ciPublishRun":"The result of this commit's CI run. The run this command waited on is the publish run, so its result was not counted as CI.","flow.why.watched.passed":"The watched run ended as passed","flow.why.watched.failed":"The watched run ended as failed","flow.why.watched.unjudged":"The watched run ended without a verdict ({conclusion})","flow.why.ciUnjudged":"This commit's CI verdict. The watched run ended as {conclusion}, neither passed nor failed, so the command's failure was not counted as a CI failure.","flow.why.deploy":"A record that the deploy finished. The command starts the deploy and returns at once, so its exit code cannot tell whether the deploy finished.","flow.strip.running":"{stage} in progress","flow.loop.badge":"↻ attempt {attempt}","flow.loop.failed":"{stage} failed in attempt {attempt}, so the flow went back to edit","flow.loop.findings":"{stage} raised findings in attempt {attempt}, so the flow went back to edit","flow.state.stale":"Passed before edit","flow.state.staleDone":"Done before edit","flow.count.stale":"{count} passed before edit","flow.why.stale":"Files were edited after this result, so the latest revision has not been checked.","flow.compound.failed":"Combined command failed","flow.why.compoundConfirmed":"{stages} ran as one command, and the whole command failed","flow.why.compoundMissing":"Which stage failed","flow.why.next":"Next","flow.why.check.syntax":"The exit code of the {label} command itself. The command contains shell syntax such as $(…), backticks, ( ) grouping or { } braces, and this panel does not trace whether that exit code reaches the shell exit code, so it was not counted as passed.","flow.why.check.optional":"A record that the {label} script actually ran. With --if-present, the runner exits 0 without running anything when the script does not exist.","flow.why.noExit":"The exit code of this call. The result record has no exit code.","flow.why.noResult":"The result of this call. There is no result record for it.","flow.why.interrupted":"The result of this call. The call was interrupted before it finished.","flow.why.noCompletion":"The exit code of this call. The call moved to a background job and has no completion record for that job.","flow.next.rerun":"First check this call's completion record and output. Rerun the check command on its own without a pipe, ;, || or wrapping syntax only if the run has ended and the check's own exit code cannot be recovered. Read long output from the result artifact instead of cutting it with tail or grep.","flow.next.optional":"First check this call's completion record and output. Rerun the script by name without --if-present only if the run has ended and proof that the script ran cannot be recovered.","flow.next.compound":"First check this call's completion record and output. Rerun each stage as a separate command only if the run has ended and the failing stage cannot be recovered.","flow.next.again":"First check this call's completion record and output. Rerun the same check only if the run has ended and no exit code can be recovered.","flow.repeats":"{count} repeated runs","flow.ci.notNeeded":"Only the private repository changed. After publish run {run}, public {repo} {ref} still points at {sha}, which already passed CI.","flow.ci.nothingToPublish":"The publish run log for commit {sha} says “Public tree already matches; nothing to publish”. The public repository did not change, so there is no new CI run.","summary.stale":"{count} passed before edit","summary.compoundFailed":"{count} combined failed","graph.branch":"{count} Makers dispatched during edit","graph.branch.one":"{count} Maker dispatched during edit","graph.parallel.observed":"Seen running together","graph.join":"Main verdict","graph.parallel.batch":"Same dispatch batch","graph.concurrency.overlapped":"Overlapped","graph.concurrency.unknown":"Overlap unknown","graph.kind.feature":"Feature","graph.kind.maintenance":"Maintenance","graph.kind.diagnostic":"Diagnostic","graph.kind.unknown":"Kind not recorded","graph.outputs":"Changed","graph.files":"{count} files","graph.docs":"{count} docs","graph.files.one":"{count} file","graph.docs.one":"{count} doc","graph.detail.aria":"Selected node details","graph.maker.open":"Open Maker record","graph.maker.unavailable":"No live record, so it can't be opened here.","graph.motion.pause":"Pause motion","graph.replay":"Replay","graph.replay.stop":"Stop replay","subflow.aria":"Stages of this subagent run","subflow.calls":"tool calls: {count}","subflow.reedits":"re-edited {count}\xd7","subflow.checks":"{passed}/{total} checks passed","subflow.reported":"Reported","subflow.unobserved":"Not observed","subflow.rework":"↻ Back to implement \xb7 Main rework requests: {count}","subflow.prior":"Previous verdict","subflow.firstTitle":"First dispatch title","subflow.runTitle":"Current run title","delivery.title":"{count} sent","delivery.kind.steer":"Now","delivery.kind.followUp":"After this run","delivery.stage.sending":"Sending","delivery.stage.accepted":"Received \xb7 waiting to deliver","delivery.stage.delivered":"Delivered \xb7 in the conversation","delivery.stage.failed":"Not sent \xb7 back in the composer","delivery.stage.unconfirmed":"Delivery not confirmed \xb7 left the queue","delivery.images":"{count} images","delivery.images.one":"{count} image","delivery.showOlder":"Show {count} earlier","delivery.showRecent":"Show only the latest {count}","live.nativeVoice":"default voice","progress.label":"Progress","phase.investigate":"Investigate","phase.implement":"Implement","phase.verify":"Verify","phase.report":"Report","phase.current":"current phase {phase}","phase.hint":"Current phase read from tool calls. It goes back when the child edits again after checking.","progress.todo":"todo {completed}/{total} ({percent}%)","eta.label":"Estimate","eta.elapsed":"{duration} elapsed","eta.remaining":"usually {range} left ({samples} past runs)","eta.percent":"about {percent}% (estimate)","eta.overrun":"At or beyond the longest past run ({longest})","eta.sparseTail":"Only {longerRuns} of {samples} past runs took longer","eta.hint":"Middle half of the remaining time among past first attempts of the same model and class that ran longer than this one has so far.","eta.byTodo":"about {duration} left by todo ({completed}/{total} steps)","eta.byTodoSoon":"under a minute left by todo ({completed}/{total} steps)","eta.byTodoHint":"Measured from the todo completion ratio only. Steps take different amounts of time, so this can be far off.","eta.rework":"rework attempt {attempt} \xb7 {duration} since first dispatch","eta.reworkAttempt":"rework attempt {attempt}","eta.reworkHint":"Rework attempts have almost no recorded durations, so no remaining time or % is estimated. Time since the first dispatch includes Main review and waiting between attempts.","eta.rangeMinutes":"{low}–{high} min","eta.range":"{low}–{high}","duration.seconds":"{seconds} s","duration.minutesSeconds":"{minutes} min {seconds} s","duration.minutes":"{minutes} min","duration.hours":"{hours} h","duration.hoursMinutes":"{hours} h {minutes} min","duration.underMinute":"under 1 min"}};function ag(){let{locale:e}=(0,z.s)();return{st:(0,a.useCallback)((t,r)=>(0,et.u0)(e,t,af,r),[e]),locale:e}}function ax({seed:e,size:t,provider:r}){am();let i=nU(e),[s,o]=(0,a.useState)(null),l=s===i,[c,d]=(0,a.useState)(!1);return l?(0,n.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:nH(e).slice(0,1)}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),d(!0)},"aria-label":nH(e),children:(0,n.jsx)("img",{className:"account-avatar",src:i,width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>o(i)})}),c&&(0,n.jsx)(av,{seed:e,provider:r,onClose:()=>d(!1)})]})}function av({seed:e,provider:t,onClose:r}){let{t:i}=(0,z.s)(),s=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let o=nH(e);return(0,q.createPortal)((0,n.jsxs)("dialog",{ref:s,className:"account-avatar-dialog","aria-label":o,onCancel:e=>{e.preventDefault(),r()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),r())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&r()},children:[(0,n.jsx)("img",{className:"account-avatar-full",src:nU(e),width:256,height:256,alt:o,draggable:!1}),(0,n.jsxs)("p",{className:"account-avatar-caption",children:[(0,n.jsx)("span",{className:"account-avatar-caption-alias",children:o}),t?(0,n.jsx)("span",{className:"account-avatar-caption-provider",children:nq(t)}):null]}),(0,n.jsx)("button",{type:"button",className:"account-avatar-close",onClick:r,children:i("i18n.close")})]}),document.body)}function ab(e){let t,r=[],n=null,a=0,i=0,s=0,o=0,l=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!n){l=[],c=[];return}let e=Math.max(l.length,c.length);for(let t=0;t<e;t++){let e=l[t]?{lineNo:l[t].lineNo,text:l[t].text,type:"removed"}:d(),r=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();n.rows.push({type:"line",left:e,right:r})}l=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(s>0||o>0)){if(d.startsWith("--- ")){u(),t=ay(d.slice(4));continue}if(d.startsWith("+++ ")){u(),n={oldPath:t,newPath:ay(d.slice(4)),rows:[]},r.push(n);continue}}let e=d.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){n||(n={rows:[]},r.push(n)),u(),a=Number(e[1]),i=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]),n.rows.push({type:"hunk",text:d});continue}if(!n)continue;if(d.startsWith("\\ ")){u(),n.rows.push({type:"hunk",text:d});continue}let p=d[0],h=d.slice(1);" "===p?(u(),n.rows.push({type:"line",left:{lineNo:a++,text:h,type:"context"},right:{lineNo:i++,text:h,type:"context"}}),s>0&&s--,o>0&&o--):"-"===p?(l.push({lineNo:a++,text:h}),s>0&&s--):"+"===p?(c.push({lineNo:i++,text:h}),o>0&&o--):""!==d&&(u(),n.rows.push({type:"hunk",text:d}))}u();let p=r.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function ay(e){return e.split(" ")[0].trim()}function aw({task:e,phases:t}){let{t:r}=(0,z.s)(),a="completed"===e.status,i="abandoned"===e.status,s="in_progress"===e.status,o="blocked"===e.status,l=!t||a||i?[]:tR(e,t),c=l.length>0?r("todo.waiting",{tasks:l.join(", ")}):!t||a||i||o?null:r("todo.ready"),d=a?"✓":i?"\xd7":o?"!":s?"›":"",u=a?"is-completed":i?"is-abandoned":o?"is-blocked":s?"is-active":"is-pending";return(0,n.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}${c?`; ${c}`:""}`,className:`todo-checklist-row ${u}`,children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:d}),(0,n.jsxs)("span",{className:"todo-checklist-content",children:[e.content,o&&e.blocker?(0,n.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null,c&&(0,n.jsxs)("span",{className:`todo-checklist-readiness${l.length>0?" is-waiting":""}`,children:[" \xb7 ",c]})]})]})}let ak="/icons/catppuccin";function aj({name:e,size:t=14}){let r={width:t,height:t,"--catppuccin-icon-light":`url(${ak}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${ak}/mocha/${e}.svg)`};return(0,n.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:r})}function aS({size:e=14,open:t=!1}){return(0,n.jsx)(aj,{name:t?"_folder_open":"_folder",size:e})}function aC({size:e=14}){return(0,n.jsx)(aj,{name:"_file",size:e})}let aN={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",markdown:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function aT(e,t=14){let r=e.toLowerCase(),a="dockerfile"===r||r.startsWith("dockerfile.")?"docker":".env"===r||r.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(r)?"git":"package-lock.json"===r?"npm-lock":"bun.lock"===r?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(r)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(r)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(r)?"lock":r.endsWith(".config.ts")||r.endsWith(".config.js")||r.endsWith(".config.mjs")||r.endsWith(".config.cjs")?"config":void 0;if(a)return(0,n.jsx)(aj,{name:a,size:t});let i=aN[r.split(".").pop()??""];return i?(0,n.jsx)(aj,{name:i,size:t}):(0,n.jsx)(aC,{size:t})}function aI({files:e,onOpenFile:t}){let{t:r}=(0,z.s)();return 0===e.length?null:(0,n.jsx)("div",{"aria-label":r("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let a=tF(e);return(0,n.jsxs)("button",{type:"button",title:e,"aria-label":r("chat.openWrittenFile",{name:a}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer"},children:[aT(a,12),(0,n.jsx)("span",{children:a})]},e)})})}let aM=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function aE(e){if(!e)return null;let t=/^\s*TASK_GUARD\s*:\s*$/im.exec(e),r=e;if(t){let n=t.index+t[0].length;"\r"===e[n]&&(n+=1),"\n"===e[n]&&(n+=1);let a=n;for(;n<e.length;){let t=e.indexOf("\n",n),r=-1===t?e.length:t,i=r>n&&"\r"===e[r-1]?r-1:r;if(!aM.test(e.slice(n,i)))break;a=i,n=-1===t?e.length:t+1}let i=t[0].length-t[0].trimStart().length;r=`${e.slice(0,t.index+i)}${e.slice(a)}`}let n=[...r.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===n.length&&n[0]&&n[0]===n[0].trim()&&/[가-힣]/u.test(n[0])?n[0]:null}function a$(e){let t=e.live,r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,n=[t?.assignment,t?.progress?.assignment,t?.task].map(aE).find(e=>null!==e)??(r?.taskTitle?.trim()||null),a=t?.progress?.lastIntent?.trim()||"",i=t?.progress?.currentTool?.trim()||"";return{title:n??"담당 업무 미확인",stage:a&&i?`${a} \xb7 ${i}`:a||(i?`${i} 실행 중`:null),explicitTitle:null!==n}}function aR(e){let t=e.live?.progress,r="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",n=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,a="string"==typeof t?.resolvedThinkingLevel?t.resolvedThinkingLevel.trim():"",i="string"==typeof n?.thinkingLevel?n.thinkingLevel.trim():"";if(r){let e=r.split("/").pop()||r;return{model:r,modelShort:a&&e.endsWith(`:${a}`)?e.slice(0,-(a.length+1)):e,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:a||i||null}}let s="string"==typeof n?.model?n.model.trim():"";return{model:s||null,modelShort:s?s.split("/").pop()||s:null,modelIsFallback:!!s&&n?.modelIsFallback===!0,effort:i||null}}class aL extends Error{constructor(e,t,r){super(t),this.kind=e,this.status=r,this.name="SubagentClientError"}}async function aA(e){try{return await e.json()}catch{throw new aL("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function aP(e){return!!e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.bytes&&"number"==typeof e.modified&&(null===e.messages||"number"==typeof e.messages)&&(void 0===e.taskTitle||"string"==typeof e.taskTitle)&&"string"==typeof e.firstTask}function aF(e){return!!e&&"object"==typeof e&&"string"==typeof e.role&&("message"===e.kind||"custom"===e.kind)&&"string"==typeof e.text&&(null===e.at||"number"==typeof e.at)}function a_(e){return!!e&&"object"==typeof e&&!!("id"in e&&"string"==typeof e.id)&&!!("index"in e&&"number"==typeof e.index)&&!!("agent"in e&&"string"==typeof e.agent)&&!!("agentSource"in e&&("bundled"===e.agentSource||"user"===e.agentSource||"project"===e.agentSource))&&!!("status"in e&&("pending"===e.status||"running"===e.status||"completed"===e.status||"failed"===e.status||"aborted"===e.status||"unknown"===e.status))&&!!("lastUpdate"in e&&"number"==typeof e.lastUpdate)&&!0}function az(e){return!!e&&"object"==typeof e&&(!("id"in e)||void 0===e.id||"string"==typeof e.id)&&(!("type"in e)||void 0===e.type||"string"==typeof e.type)&&(!("message"in e)||void 0===e.message||null!==e.message&&"object"==typeof e.message)}function aW(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let r=async(t,r,n)=>{let a;try{a=await e(t,r)}catch(e){if(r.signal?.aborted)throw e;throw new aL(n,"sidecar-unreachable"===n?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let i=await aA(a);if(!a.ok)throw new aL("http",function(e,t){if(e&&"object"==typeof e&&"error"in e){let t=e.error;if("string"==typeof t&&t)return t}return t}(i,`HTTP ${a.status}`),a.status);return{response:a,body:i}};return{async getLiveSnapshots(e,t){let{body:n}=await r(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!n||"object"!=typeof n)throw new aL("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof n.error&&n.error)throw new aL("http",n.error);if(!0!==n.running)return{runtime:"detached",subagents:[]};let a=n.state?.subagents;if(void 0!==a&&(!Array.isArray(a)||!a.every(a_)))throw new aL("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:a??[]}},async getLiveTranscript(e,t,n,a){let{body:i}=await r(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:n}),signal:a},"live-unreachable");if(!i||"object"!=typeof i)throw new aL("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof i.error&&i.error)throw new aL("http",i.error);if(!0!==i.success||!i.data||"object"!=typeof i.data)throw new aL("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let s=i.data;if(!Array.isArray(s.entries)||!s.entries.every(az)||"number"!=typeof s.fromByte||"number"!=typeof s.nextByte||"boolean"!=typeof s.reset)throw new aL("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:s.fromByte,nextByte:s.nextByte,reset:s.reset,entries:s.entries}},async getArchive(e,n){let a=`${t}/archive?session=${encodeURIComponent(e)}`,{body:i}=await r(a,{method:"GET",signal:n},"sidecar-unreachable");if(!i||"object"!=typeof i||"string"!=typeof i.sessionId||"string"!=typeof i.dir||"boolean"!=typeof i.found||!Array.isArray(i.subagents)||!i.subagents.every(aP))throw new aL("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:i.sessionId,dir:i.dir,found:i.found,subagents:i.subagents,...!0===i.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,n,a=400,i){let s=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(n)}&limit=${encodeURIComponent(String(a))}`,{body:o}=await r(s,{method:"GET",signal:i},"sidecar-unreachable");if(!o||"object"!=typeof o||"string"!=typeof o.sessionId||"string"!=typeof o.name||"number"!=typeof o.bytes||"boolean"!=typeof o.truncated||!Array.isArray(o.entries)||!o.entries.every(aF))throw new aL("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}let aO=["feature","maintenance","diagnostic"],aD=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function aH(e){if("string"!=typeof e)return null;let t=e.split(/\r?\n/),r=t.findIndex(e=>/^\s*TASK_GUARD\s*:\s*$/.test(e));if(r<0)return null;for(let e=r+1;e<t.length;e+=1){let r=aD.exec(t[e]);if(!r)break;if("WORK_CLASS"!==r[1])continue;let n=r[2].toLowerCase();return aO.includes(n)?n:null}return null}let aU={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function aB(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function aq(e){return"string"==typeof e&&e.trim()?e:null}function aV(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function aK(e){switch(e){case"pending":case"queued":return"pending";case"running":return"running";case"completed":case"success":return"completed";case"failed":case"error":return"failed";case"aborted":case"cancelled":case"canceled":return"aborted";default:return null}}function aG(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function aJ(e,t){if(t?.isError)return null;let r=aB(e.input.tasks),n=aB(t?.details?.progress),a=Math.max(r.length,n.length),i=[];for(let s=0;s<a;s++){let a=n.find(e=>e.index===s)??n[s],o=r[s],l=aq(a?.id)??aq(o?.name);l&&i.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:l,agent:aq(a?.agent)??aq(o?.agent),task:aq(a?.task)??aq(o?.task)??"",workClass:aH(o?.task)??aH(a?.task),spawned:!!t})}return i}let aZ=/<task-result\b([^>]*)>/g,aY=/(\w+)="([^"]*)"/g;function aX(e,t,r){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&r.latestByAgent.get(e.agentId)===e.key)}function aQ(e,t,r){var n;let a,i,s,o,l=aX(e,t,r),c=l?{key:e.key,identity:"live",live:l.assignment?l:{...l,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},d=a$(c),u=r.runs.get(e.key),p=null;l&&"unknown"!==l.status?(a=l.status,p="live"):u&&"unknown"!==u.status?(a=u.status,p="record"):a=e.spawned?"unobserved":"dispatching";let h=r.verdicts.get(e.key),m=h&&h.length>0?h[h.length-1]:null,f=m?.at??null,g=null===f?null:(n=e.key,i=r.runStartedAt.get(n)??null,s=l?.progress?.durationMs,o=l&&("pending"===l.status||"running"===l.status)&&"number"==typeof s&&l.lastUpdate>0?l.lastUpdate-s:null,null===i?o:null===o?i:Math.max(i,o)),x=null!==f&&null!==g&&g>f;return{member:e,title:d.title,explicitTitle:d.explicitTitle,stage:l?d.stage:null,model:l?aR(c):null,run:a,runSource:p,verdict:x?null:m,priorVerdict:x?m:null,runTitle:x?aE(l?.progress?.task):null,observedParallelWith:r.parallelWith.get(e.key)}}function a0(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function a1(e,t){let r=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),n=new Map,a=[];for(let e of r){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?a.push(t):n.set(e.attempt,t)}return[...a,...[...n.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}function a2(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function a8(e,t,r){let n=-1;r.forEach((e,t)=>{"user"===e.role&&(n=t)});let a=r.slice(0,n+1).flatMap(a2),i=r.slice(n+1).flatMap(a2),s=t.findIndex(e=>"user"===e.role),o=0===i.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===o?{continuing:null,atCompaction:[...a,...i]}:{continuing:{position:o,calls:i},atCompaction:a}}let a4="끊기기 전에 바깥에 영향을 주는 행동(커밋\xb7push, `git_finalize`\xb7`git_integrate`, 배포\xb7`update.sh`, CI 재실행, 이슈\xb7PR 댓글, 메시지 전송)을 하던 중이었다면 다시 하기 전에 그 결과가 이미 반영됐는지 `git log`\xb7`git status`\xb7원격 브랜치, `gh run list`, 배포 로그, 해당 페이지로 먼저 확인하고, 반영됐으면 되풀이하지 않는다. ",a5="[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+a4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a6="[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. "+a4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a3="[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+a4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a7=new Set(["[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.","[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.","[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."]),a9={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function ie(e){return e.trim()}function it(e){return ie(e.text)||(e.images>0?"[Image]":"")}function ir(e){let t=e.filter(e=>!a9[e.stage]);if(t.length<=4)return e;let r=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!r.has(e.id))}function ia(e,t){switch(t.type){case"submit":return ir([...e,{id:t.id,kind:t.kind,text:t.text,images:t.images??0,stage:"sending",inQueue:!1}]);case"ack":return e.map(e=>e.id===t.id&&"sending"===e.stage?{...e,stage:"accepted"}:e);case"fail":return ir(e.map(e=>e.id===t.id&&a9[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,r){let n=new Map,a=(e,t)=>{let r=`${e}\u0000${ie(t)}`;n.set(r,(n.get(r)??0)+1)};for(let e of t)a("steer",e);for(let e of r)a("followUp",e);let i=!1,s=e.map(e=>{if(!a9[e.stage])return e;let t=`${e.kind}\u0000${it(e)}`,r=n.get(t)??0;return r>0?(n.set(t,r-1),e.inQueue&&"accepted"===e.stage)?e:(i=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(i=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return i?s:e}(e,t.steering,t.followUp);case"user-message":{let r=ie(t.text);if(!r&&0===t.images)return e;let n=e.find(e=>(a9[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&ie(e.text)===r&&e.images===t.images);if(!n)return e;return ir(e.map(e=>e===n?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let r=e=>a9[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!r(e));let n=ie(t.text),a=e.find(e=>r(e)&&e.kind===t.kind&&(ie(e.text)===n||it(e)===n));return a?e.filter(e=>e!==a):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}function ii(e){return"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function is(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}let io=["investigate","edit","check","review","commit","ci","deploy"];function il(e,t){let r="",n=t;for(;n<e.length&&'"'!==e[n];){let t=e[n];if("\\"===t&&n+1<e.length){let a=e[n+1];"\n"!==a&&(r+='$`"\\'.includes(a)?a:t+a),n+=2}else if("$"===t&&"("===e[n+1]){let t=ic(e,n+1);r+=e.slice(n,t),n=t}else if("`"===t){let t=id(e,n+1);r+=e.slice(n,t),n=t}else r+=t,n+=1}return{text:r,end:Math.min(n+1,e.length)}}function ic(e,t){let r=e[t],n="{"===r?"}":")",a=0,i=t;for(;i<e.length;){let t=e[i];if("\\"===t)i+=2;else if("'"===t){let t=e.indexOf("'",i+1);i=t<0?e.length:t+1}else if('"'===t)i=il(e,i+1).end;else if("`"===t)i=id(e,i+1);else{if(t===r)a+=1;else if(t===n&&0==--a)return i+1;i+=1}}return e.length}function id(e,t){let r=t;for(;r<e.length&&"`"!==e[r];)r+="\\"===e[r]?2:1;return Math.min(r+1,e.length)}function iu(e){let{tokens:t,groups:r,expandingHeredoc:n}=function(e){let t=[],r=[],n=!1,a=[],i=[],s="",o=-1,l=!1,c=e=>{if(o<0)return;let r={value:s,start:o,end:e,risky:l};for(let e of(t.push(r),i.splice(0)))e.at===t.length-1&&(e.owner=r);s="",o=-1,l=!1},d=0;for(;d<e.length;){let u=e[d];if("\\"===u)"\n"!==e[d+1]&&(o<0&&(o=d),s+=e[d+1]??""),d+=2;else if("'"===u){o<0&&(o=d);let t=e.indexOf("'",d+1),r=t<0?e.length:t;s+=e.slice(d+1,r),d=r+1}else if('"'===u){o<0&&(o=d);let t=il(e,d+1);/\$[({]|`/.test(e.slice(d,t.end))&&(l=!0),s+=t.text,d=t.end}else if("$"===u&&("("===e[d+1]||"{"===e[d+1])){o<0&&(o=d);let t=ic(e,d+1);s+=e.slice(d,t),l=!0,d=t}else if("`"===u){o<0&&(o=d);let t=id(e,d+1);s+=e.slice(d,t),l=!0,d=t}else if("#"===u&&o<0){let t=e.indexOf("\n",d);d=t<0?e.length:t}else if(" "===u||" "===u||"\r"===u)c(d),d+=1;else if("\n"===u){c(d);let r=t[t.length-1];for(let s of("&&"!==r&&"||"!==r&&"|"!==r&&t.push(";"),d+=1,i.length=0,a.splice(0)))for(;d<e.length;){let t=e.indexOf("\n",d),r=t<0?e.length:t,a=e.slice(d,r);if(d=r+1,(s.stripTabs?a.replace(/^\t+/,""):a)===s.delimiter)break;!s.quoted&&/\$[({]|`/.test(a)&&(s.owner?s.owner.risky=!0:n=!0)}}else if("<"===u&&"<"===e[d+1]&&"<"!==e[d+2]){c(d);let r=d+2,n="-"===e[r];for(n&&(r+=1);" "===e[r]||" "===e[r];)r+=1;let s="",o=!1;for(;r<e.length&&!/[\s;&|<>()]/.test(e[r]);){let t=e[r];if("'"===t||'"'===t){o=!0;let n=e.indexOf(t,r+1),a=n<0?e.length:n;s+=e.slice(r+1,a),r=a+1}else"\\"===t&&(o=!0),s+="\\"===t?e[r+1]??"":t,r+="\\"===t?2:1}if(s){let e=t[t.length-1],r={delimiter:s,stripTabs:n,quoted:o,owner:void 0!==e&&"string"!=typeof e?e:null,at:t.length};a.push(r),r.owner||i.push(r)}d=r}else";"===u?(c(d),t.push(";"),d+=";"===e[d+1]?2:1):"&"===u?"&"===e[d+1]?(c(d),t.push("&&"),d+=2):(">"===e[d+1]||/[<>]$/.test(s)?(o<0&&(o=d),s+=u):(c(d),t.push("&")),d+=1):"|"===u?"|"===e[d+1]?(c(d),t.push("||"),d+=2):s.endsWith(">")?(s+=u,d+=1):(c(d),t.push("|"),d+="&"===e[d+1]?2:1):("("===u||")"===u?(c(d),r.push(d)):(o<0&&(o=d),("{"===u||"}"===u||"!"===u)&&(l=!0),s+=u),d+=1)}return c(e.length),{tokens:t,groups:r,expandingHeredoc:n}}(e),a=[],i=[],s={pipelines:[],operators:[],background:!1},o={commands:[],negated:!1},l=[],c=()=>{let t=l.map(e=>e.value).filter(e=>"{"!==e&&"}"!==e);if(0===o.commands.length&&"!"===t[0]&&(o.negated=!0,t.shift()),t.length>0){let n=l[0].start,a=l[l.length-1].end,s=l.some(e=>e.risky)||r.some(e=>e>=n&&e<=a),c={words:t,text:e.slice(n,a),uncertain:s};o.commands.push(c),i.push(c)}l=[]},d=()=>{c(),o.commands.length>0&&s.pipelines.push(o),o={commands:[],negated:!1}},u=e=>{d(),s.pipelines.length>0&&a.push({...s,background:e}),s={pipelines:[],operators:[],background:!1}};for(let e of t)"string"!=typeof e?l.push(e):"|"===e?c():"&&"===e||"||"===e?(d(),s.operators.push(e)):u("&"===e);return u(!1),{lists:a,commands:i,uncertain:r.length>0||n||t.some(e=>"string"!=typeof e&&e.risky)}}function ip(e){return e.slice(e.lastIndexOf("/")+1)}let ih={bash:!0,sh:!0,zsh:!0,dash:!0},im={sudo:!0,env:!0,command:!0,exec:!0,nice:!0,nohup:!0,time:!0,timeout:!0,setsid:!0,"systemd-run":!0},ig={"-u":!0,"--unit":!0,"-p":!0,"--property":!0,"-E":!0,"--setenv":!0,"--description":!0,"--slice":!0,"-M":!0,"--machine":!0,"-H":!0,"--host":!0,"--uid":!0,"--gid":!0,"--working-directory":!0,"-s":!0,"--signal":!0,"-k":!0,"--kill-after":!0},ix={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},iv={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function ib(e){let t=ik(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(ih,ip(e[t]))||iy(e,t))return null;for(let r=t+1;r<e.length&&/^[-+]/.test(e[r]);r+=1){if(/^-[a-zA-Z]*c[a-zA-Z]*$/.test(e[r]))return e[r+1]??null;(/^[-+][a-zA-Z]*[oO]$/.test(e[r])||"--rcfile"===e[r]||"--init-file"===e[r])&&(r+=1)}return null}function iy(e,t){for(let r=t+1;r<e.length&&/^[-+]/.test(e[r]);r+=1){if(/^-[a-zA-Z]*n[a-zA-Z]*$/.test(e[r])||/^-[a-zA-Z]*o$/.test(e[r])&&"noexec"===e[r+1])return!0;(/^[-+][a-zA-Z]*[oO]$/.test(e[r])||"--rcfile"===e[r]||"--init-file"===e[r])&&(r+=1)}return!1}let iw={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function ik(e){let t=!1,r="";for(let n=0;n<e.length;n+=1){let a=e[n];if(!(/^[A-Za-z_]\w*=/.test(a)||!t&&Object.hasOwn(iv,a))){if(t&&(a.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(a))){if(Object.hasOwn(iw,r)&&iw[r].test(a))return -1;"command"!==r&&Object.hasOwn(ig,a)&&(n+=1);continue}if(!Object.hasOwn(im,ip(a)))return n;t=!0,r=ip(a)}}return -1}let ij=/(?:^|\/)wsl\/update\.sh$/;function iS(e,t=0){let r=ib(e);if(null!==r)return t<3&&iu(r).commands.some(e=>iS(e.words,t+1));let n=ik(e);if(n<0)return!1;if(ij.test(e[n]))return!0;if(!Object.hasOwn(ih,ip(e[n]))||iy(e,n))return!1;let a=e.slice(n+1).find(e=>!e.startsWith("-"));return void 0!==a&&ij.test(a)}function iC(e){let t=ik(e),r=t<0?e:e.slice(0,t),n=r.map(ip);return n.includes("systemd-run")?!r.some(e=>Object.hasOwn(ix,e)):!!(n.includes("sudo")&&r.some(e=>"--background"===e||/^-[a-zA-Z]*b[a-zA-Z]*$/.test(e)))||n.includes("setsid")&&!r.includes("-w")&&!r.includes("--wait")}function iN(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function iT(e){if(e.every(e=>/^[A-Za-z_]\w*=/.test(e)))return!0;let[t,...r]=e;return"cd"===t?r.length<=1:"export"===t?r.every(e=>/^[A-Za-z_]\w*=/.test(e)):"set"===t&&r.every(e=>/^[-+][a-zA-Z]+$/.test(e)&&!/^-[a-zA-Z]*n/.test(e)||"pipefail"===e)}let iI={tail:!0,head:!0,cat:!0,tee:!0},iM=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,iE={bun:!0,bunx:!0,npm:!0,npx:!0,pnpm:!0,yarn:!0,node:!0,python:!0,python3:!0,deno:!0},i$={"--help":!0,"-h":!0,"--version":!0},iR=Object.fromEntries(["-C","-r","--allow-fs-read","--allow-fs-write","--build-snapshot-config","--conditions","--cpu-prof-dir","--debug-port","--inspect-port","--experimental-config-file","--experimental-default-config-file","--experimental-test-isolation","--test-isolation","--report-dir","--report-directory","--cpu-prof-interval","--cpu-prof-name","--diagnostic-dir","--disable-proto","--disable-warning","--dns-result-order","--env-file","--env-file-if-exists","--experimental-loader","--experimental-package-map","--experimental-sea-config","--experimental-test-tag-filter","--heap-prof-dir","--heap-prof-interval","--heap-prof-name","--heapsnapshot-near-heap-limit","--heapsnapshot-signal","--icu-data-dir","--import","--input-type","--inspect-publish-uid","--loader","--localstorage-file","--max-http-header-size","--max-old-space-size-percentage","--network-family-autoselection-attempt-timeout","--openssl-config","--redirect-warnings","--report-filename","--report-signal","--require","--run","--secure-heap","--secure-heap-min","--snapshot-blob","--test-concurrency","--test-coverage-branches","--test-coverage-exclude","--test-coverage-functions","--test-coverage-include","--test-coverage-lines","--test-global-setup","--test-name-pattern","--test-random-seed","--test-reporter","--test-reporter-destination","--test-rerun-failures","--test-shard","--test-skip-pattern","--test-timeout","--title","--tls-cipher-list","--tls-keylog","--trace-event-categories","--trace-event-file-pattern","--trace-require-module","--unhandled-rejections","--use-largepages","--v8-pool-size","--watch-kill-signal","--watch-path"].map(e=>[e,!0]));function iL(e){let t=ik(e);if(t<0)return!1;let r=ip(e[t]);if("test"===r||"["===r||e.slice(t+1).some(e=>Object.hasOwn(i$,e)))return!1;if(iM.test(r))return!0;if(!Object.hasOwn(iE,r))return!1;if("node"===r&&function(e,t){for(let r=t;r<e.length;r+=1){let t=e[r];if("--test"===t)return!0;if("--"===t||!t.startsWith("-"))break;Object.hasOwn(iR,t)&&(r+=1)}return!1}(e,t+1))return!0;let n=function(e,t){for(let r=t;r<e.length;r+=1){let t=e[r];if("-m"===t)return e[r+1];if(/^-[a-zA-Z]*[cep]/.test(t)||/^--(?:eval|print)(?:=|$)/.test(t))break;if(!t.startsWith("-")){if("run"===t||"exec"===t||"x"===t||"dlx"===t)return e.slice(r+1).find(e=>!e.startsWith("-"));return t}}}(e,t+1);return void 0!==n&&iM.test(n)}let iA={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},iP={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function iF(e){let t=ik(e);if(t<0||"git"!==ip(e[t]))return null;for(let r=t+1;r<e.length;r+=1)if(Object.hasOwn(iA,e[r]))r+=1;else if(!e[r].startsWith("-"))return{name:e[r],at:r};return null}function i_(e,t=0,r){let n=ib(e);if(null!==n)return t<3&&iu(n).commands.some(e=>i_(e.words,t+1,r));let a=iF(e);if(!a||"commit"!==a.name&&"push"!==a.name||void 0!==r&&a.name!==r)return!1;let i=iP[a.name];return!e.slice(a.at+1).some(e=>Object.hasOwn(i,e)||"push"===a.name&&/[nd]/.test(function(e){if(!/^-[a-zA-Z0-9]/.test(e))return"";let t="";for(let r of e.slice(1)){if("o".includes(r)||!/[a-zA-Z0-9]/.test(r))break;t+=r}return t}(e)))}function iz(e){return iT(e)||null!==iF(e)}let iW={check:({words:e})=>iL(e),commit:({words:e})=>i_(e),ci:({words:e})=>{let t=ik(e);return t>=0&&"gh"===ip(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>iS(e.words)},iO={test:"test",tests:"test",vitest:"test",jest:"test",pytest:"test",typecheck:"typecheck",tsc:"typecheck",lint:"lint",eslint:"lint",build:"build",check:"verify",verify:"verify",smoke:"smoke"};function iD(e){return!e||"object"!=typeof e||"bash"!==e.toolName||!e.input||"object"!=typeof e.input||Array.isArray(e.input)?null:("string"==typeof e.input.command?e.input.command.trim():"")||null}let iH={"$?":!1,"${PIPESTATUS[0]}":!0};function iU(e,t){let r=i1(t);if("notRun"===r)return[];let n=r?void 0:t,a=iu(e),i=[];if(a.commands.some(({words:e})=>(function e(t,r=0){let n=ib(t);return null!==n?r<3&&iu(n).commands.some(t=>e(t.words,r+1)):iL(t)})(e))&&i.push("check"),a.commands.some(({words:e})=>i_(e))&&i.push("commit"),a.commands.some(({words:e})=>(function e(t,r=0){let n=ib(t);if(null!==n)return r<3&&iu(n).commands.some(t=>e(t.words,r+1));let a=ik(t);return a>=0&&"gh"===ip(t[a])&&"run"===t[a+1]&&["watch","view","list"].includes(t[a+2])})(e))&&i.push("ci"),a.commands.some(iW.deploy)&&i.push("deploy"),0===i.length)return[];let s=n?rO(n):null,o=null===s?!!n?.isError:0!==s,l=i.length>1?{stages:i,failed:o}:void 0,c=n?sp(n):"";return i.map(e=>{var t;let i,d,u,p="commit"===e?iz:iT,h=function e(t,r,n=iT,a=0){let{lists:i}=t,s=[],o=t.uncertain,l=!1;return i.forEach((t,c)=>{for(let d of(t.pipelines.some(e=>e.commands.some(({words:e})=>e.some(e=>e.includes("pipefail"))))&&(l=!1),t.pipelines)){let u=!1;for(let p of d.commands){let h=a<3?ib(p.words):null,m=null===h?null:e(iu(h),r,n,a+1);if(m&&m.decisive.length>0)s.push(...m.decisive);else if(r(p))s.push(p);else{let e=ik(p.words);u&&l&&e>=0&&Object.hasOwn(iI,ip(p.words[e]))||n(p.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let r=iN(e[t])?.words;return r?.[0]==="exit"&&(1===r.length||2===r.length&&"$?"===r[1])}(i,c)||(o=!0);continue}u=!0,(m?.reach==="masked"||d.negated||d.commands.length>1&&!l||t.operators.includes("||")||t.background||iC(p.words)||!function(e,t){if(t===e.length-1)return!0;let r=e[e.length-1],n=iN(r)?.words;return!!n&&"exit"===n[0]&&!r.background&&t===e.length-2&&(1===n.length||2===n.length&&"$?"===n[1])}(i,c))&&(o=!0)}}let d=iN(t)?.words;!t.background&&d?.[0]==="set"&&3===d.length&&"pipefail"===d[2]&&(/^-[a-zA-Z]*o$/.test(d[1])?l=!0:/^\+[a-zA-Z]*o$/.test(d[1])&&(l=!1))}),{reach:0===s.length?"absent":o?"masked":"carried",decisive:s}}(a,iW[e],p),m="check"===e&&h.decisive.some(({words:e})=>e.includes("--if-present")),f=n?(t=iW[e],i=new Map,d=a.lists.map(e=>(function(e){let t=e&&!e.background?iN(e)?.words:void 0;if(!t||"echo"!==t[0]||t.length<2)return null;let r=t.slice(1);if(r.some(e=>e.startsWith("-")||/^(?:\d*[<>]|&>)/.test(e)))return null;let n=r.join(" ");for(let[e,t]of Object.entries(iH)){let r=n.indexOf(e);if(r<0||n.indexOf(e,r+1)>=0)continue;let a=n.slice(0,r),i=n.slice(r+e.length);if(/[$`\\]/.test(a+i)||!/[^\s\d]/.test(a))break;return{prefix:a,suffix:i,first:t}}return null})(e)),u=c.split("\n").map(e=>e.trimEnd()),a.lists.forEach((e,r)=>{let n=d[r+1];if(!n||e.background||e.operators.includes("||"))return;let a=e.pipelines[e.pipelines.length-1],s=e.pipelines.slice(0,-1);if(a.negated||s.some(e=>e.negated||1!==e.commands.length||!p(e.commands[0].words)))return;let o=n.first||1===a.commands.length?a.commands[0]:void 0;if(!o||!t(o)||iC(o.words)||o.uncertain)return;let l=d.filter(e=>e?.prefix===n.prefix&&e.suffix===n.suffix),c=RegExp(`^${n.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(-?\\d+)${n.suffix.trimEnd().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`),h=u.flatMap(e=>{let t=c.exec(e);return t?[{code:Number(t[1]),line:e}]:[]});if(h.length!==l.length)return;let m=d.slice(0,r+2).filter(e=>l.includes(e)).length-1;i.set(o,h[m])}),i):new Map,g=h.decisive.flatMap(e=>f.get(e)??[]),x=g.length>0&&g.length===h.decisive.length?g.find(({code:e})=>0!==e)??g[0]:null,v=x?0!==x.code?"failed":m?"unverified":"passed":o?l?"unverified":"failed":null===s?"unobserved":"carried"!==h.reach||m?"unverified":"passed",b="unobserved"===v?"interrupted"===r?"interrupted":n?"noExit":"noResult":"unverified"!==v?null:m?"optional":o&&l?"compound":a.uncertain?"syntax":"masked";return{stage:e,state:v,exitCode:s,labels:"check"===e?function(e){let t=[];for(let{words:r}of e){let e=ik(r);r.forEach((r,n)=>{if(n!==e||"test"!==r)for(let e of r.replace(/^-+/,"").toLowerCase().split(":")){let r=Object.hasOwn(iO,e)?iO[e]:void 0;r&&!t.includes(r)&&t.push(r)}})}return t}(h.decisive):[],...l?{compound:l}:{},...x?{evidence:x.line}:{},...b?{reason:b}:{}}})}function iB(e,t){let r=iD(e),n=null===r?void 0:iU(r,t).find(e=>"check"===e.stage);return null!==r&&n?{toolCallId:e.toolCallId,command:r,state:n.state,exitCode:n.exitCode,labels:n.labels,...n.compound?{compound:n.compound}:{},...n.reason?{reason:n.reason}:{}}:null}let iq=/\.(?:md|mdx|markdown|txt)$/i,iV=/^docs?$/i;function iK(e){return iq.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>iV.test(e))}let iG={read:!0,grep:!0,glob:!0,find:!0,ls:!0,skim:!0,web_search:!0,fetch:!0,ast_grep:!0,lsp:!0,recall:!0,reflect:!0},iJ={multiedit:!0,notebookedit:!0,draft:!0},iZ={rename:!0,rename_file:!0},iY={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function iX(e){return e.split("\n")[0].trim()||void 0}let iQ=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,i0=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function i1(e){let t=e?.details;return t&&"object"==typeof t?"__synthetic"in t&&!0===t.__synthetic&&"executed"in t&&!1===t.executed?"notRun":"__interrupted"in t&&!0===t.__interrupted?"interrupted":null:null}let i2=/\btool\.git_(?:finalize|integrate)\s*\(/,i8=/\b(?:Committed|Integrated \S+) and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,i4=/\bgit_(?:finalize|integrate) failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,i5=/\bstage["']?\s*:\s*["'](?:up-to-date|aborted)["']/,i6=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/;function i3(e,t){if("string"==typeof t.commitSha&&""!==t.commitSha.trim())return t.commitSha.trim();let r=i8.exec(sp(e));return r?.[1]??r?.[2]??null}let i7=/^bg_\d+$/;function i9(e){let t=e.details,r=t&&"object"==typeof t&&"async"in t?t.async:null;if(r&&"object"==typeof r&&"jobId"in r&&"string"==typeof r.jobId&&i7.test(r.jobId))return r.jobId;let n=sp(e).trimStart();return n.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(n)?.[1]??null:null}function se(e,t){let r=/Command exited with code (-?\d+)\s*$/.exec(t.trimEnd());return{jobId:e,text:t,exitCode:r?Number(r[1]):null}}function st(e){return"passed"===e||"failed"===e||"done"===e}function sr(e){let t=null;for(let r of e.values())"failed"===r.outcome&&(!t||r.order>t.order)&&(t=r);return t?.stage??null}function sn(e){return e.commandKey??JSON.stringify([e.cwd??"",e.command])}function sa(e){let t=new Map;for(let r of e){if("check"!==r.stage)continue;let e=sn(r),n=t.get(e);(n?.outcome!=="failed"||st(r.outcome))&&t.set(e,r)}return[...t.values()]}function si(e){return"compound"in e&&e.compound?.failed===!0}let ss={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function so(e){return"stale"!==e&&(st(e)||"running"===e)}function sl(e){if("ci"!==e.stage)return null;let t=iu(e.command).commands.flatMap(({words:e})=>sm(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?sv(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let sc={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},sd={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},su=/^[0-9a-f]{40}$/i;function sp(e){let t=e.content;return"string"==typeof t?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:"").join("\n"):""}function sh(e){let t=[];for(let r of e.split("\n")){let e,n=r.trim();if(n.startsWith("{")||n.startsWith("[")){try{e=JSON.parse(n)}catch{continue}for(let r of Array.isArray(e)?e:[e])r&&"object"==typeof r&&!Array.isArray(r)&&t.push(r)}}return t}function sm(e,t=0){let r=ib(e);if(null!==r)return t<3?iu(r).commands.flatMap(e=>sm(e.words,t+1)):[];let n=ik(e);return n>=0&&"gh"===ip(e[n])?[e.slice(n+1)]:[]}function sf(e,t){for(let r=0;r<e.length;r+=1)for(let n of t){if(e[r]===n)return e[r+1]??null;if(n.startsWith("--")&&e[r].startsWith(`${n}=`))return e[r].slice(n.length+1)}return null}let sg={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function sx(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(sg,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function sv(e){let t=sx(e);return null!==t&&/^\d+$/.test(t)?t:null}let sb=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function sy(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==rO(t))return[];let r=iu(e).commands.flatMap(({words:e})=>sm(e)).filter(e=>"run"===e[0]&&("list"===e[1]||"view"===e[1]));if(0===r.length)return[];let n=1===r.length?r[0]:null,a=n?.[1]==="list"?sf(n,["-c","--commit"])?.toLowerCase():void 0,i=a&&/^[0-9a-f]{7,40}$/.test(a)?a:null,s=sp(t);return i||s.includes("headSha")?sh(s).flatMap(e=>{let t="string"==typeof e.headSha?e.headSha.toLowerCase():i;if(null===t)return[];let r="string"==typeof e.url?sb.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):n?.[1]==="view"?sv(n):null,repo:(r??(n?sf(n,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:n?sf(n,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:n?sf(n,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let sw=/\b\d{9,12}\b/g,sk=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function sj(e,t){if(e?.type!=="toolCall")return[];let r=iD(e);return null===r?[]:sy(r,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(sd,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let sS="Public tree already matches; nothing to publish";function sC(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function sN(e){let t="run"===e[0]&&"list"===e[1]?sf(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(sc,t)}function sT(e,t){let r=new Map,n=[];for(let{words:a}of iu(e).commands){let e=a.map(e=>/^([A-Za-z_]\w*)=([\s\S]*)$/.exec(e));if(a.length>0&&e.every(e=>null!==e)){for(let t of e){if(!t)continue;let e=/^\$\(([\s\S]*)\)$/.exec(t[2])?.[1],n=void 0===e?[]:iu(e).commands.flatMap(e=>sm(e.words));r.set(t[1],1===n.length&&sN(n[0]))}continue}for(let e of sm(a)){if(sN(e)){n.push({args:e,publish:!0});continue}let a="run"===e[0]&&("watch"===e[1]||"view"===e[1])?sx(e):null,i=sC(a),s=null!==i?!0===r.get(i):null!==a&&/^\d+$/.test(a)&&t(a);n.push({args:e,publish:s})}}return n}function sI(e,t){let r=sT(e,t);return r.length>0&&r.every(({publish:e})=>e)}function sM(e,t){if(!e||!t)return!1;let[r,n]=e.length<=t.length?[e.toLowerCase(),t.toLowerCase()]:[t.toLowerCase(),e.toLowerCase()];return r.length>=7&&/^[0-9a-f]+$/.test(n)&&n.startsWith(r)}function sE(e,t,r){if(sM(e.sha,t.step.commit))return!0;let{title:n}=t.step;return!!n&&!!e.title&&!!e.repo&&!(e.order<=t.order)&&!!e.workflow&&!!Object.hasOwn(sd,e.workflow)&&[...r.publishRuns.values()].some(r=>r.order>t.order&&null!==r.sha&&sM(r.sha,t.step.commit)&&null!==r.repo&&r.repo!==e.repo)&&function(e,t){if(e===t)return!0;let r=e.endsWith("…")?e.slice(0,-1):null;return null!==r&&r.length>=20&&t.startsWith(r)}(e.title,n)}let s$={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},sR=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,sL=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) (ROLLED_BACK|ROLLBACK_FAILED|FAIL)\b/,sA=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) START old=\S* target=([0-9a-f]{7,40})\b/;function sP(e,t,r=!1,n=[],a,i=[]){let s,o,l=[],c=[],d=1,u=new Map,p=-1,h=-1,m=new Map,f={publishRuns:new Map,watched:[],heads:[],ciHeads:[],nothingToPublish:[],runs:[]},g=Array.isArray(e)?e:[],x=t instanceof Map?t:new Map,v=function(e,t,r=[]){let n=new Map,a=new Map,i=new Map;for(let e of r)null!==e.after&&i.set(e.after,[...i.get(e.after)??[],e]);let s=(e,t)=>{for(let r of e){let e=a.get(r.jobId);e&&(a.delete(r.jobId),n.set(e.toolCallId,{...e.result,isError:!1,content:[{type:"text",text:r.text}],details:{...null===r.exitCode?{}:{exitCode:r.exitCode},backgroundJob:{jobId:r.jobId,after:t}}}))}};for(let r of Array.isArray(e)?e:[]){if(!r||"toolCall"!==r.type)continue;let e=t.get(r.toolCallId);if(e){let t="bash"===r.toolName||"eval"===r.toolName?i9(e):null;t?a.set(t,{toolCallId:r.toolCallId,result:e}):n.set(r.toolCallId,e),"wait"===r.toolName&&s(function(e){let t=e.details,r=t&&"object"==typeof t&&"jobs"in t?t.jobs:null,n=(Array.isArray(r)?r:[]).flatMap(e=>{if(!e||"object"!=typeof e||!("id"in e)||!("status"in e)||!("resultText"in e)||"string"!=typeof e.id||!i7.test(e.id)||"completed"!==e.status&&"failed"!==e.status||"string"!=typeof e.resultText)return[];let t="exitCode"in e&&"number"==typeof e.exitCode?e.exitCode:null;return[{...se(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(n.length>0)return n;let a=sp(e),i=[...a.matchAll(/^### (bg_\d+) \[\w+\] — (?:completed|failed)$/gm)];return i.map((e,t)=>{let r=(e.index??0)+e[0].length,n=a.slice(r,t+1<i.length?i[t+1].index:a.length),s=n.indexOf("\n```\n"),o=n.lastIndexOf("\n```");return se(e[1],s>=0&&o>s?n.slice(s+5,o):"")})}(e),r.toolCallId);let i="read"===r.toolName?function(e,t){let r=e.input.path,n="string"==typeof r?/^proc:\/\/(bg_\d+)$/.exec(r)?.[1]:void 0;if(!n)return null;let[a,...i]=sp(t).split("\n");return RegExp(`^1\\|${n} \\[\\w+\\] — (?:completed|failed)\\b`).test(a)?se(n,i.map(e=>e.replace(/^\d+\|/,"")).join("\n")):null}(r,e):null;i&&s([i],r.toolCallId)}for(let e of i.get(r.toolCallId)??[])s(function(e){let t=e.replace(/^\s*<system-notice>\s*\n?/,"").replace(/\s*<\/system-notice>\s*$/,""),r=/^Background job (bg_\d+) has (?:completed|failed)\b[^\n]*(?:\n|$)/.exec(t);if(r)return[se(r[1],t.slice(r[0].length))];let n=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return n.flatMap((e,r)=>{if(!i7.test(e[1]))return[];let a=(e.index??0)+e[0].length;return[se(e[1],t.slice(a,r+1<n.length?n[r+1].index:t.length).replace(/^\n/,""))]})}(e.text),r.toolCallId)}return n}(g,x,Array.isArray(i)?i:[]),b=[];g.forEach((e,t)=>{let n;if(!e||"toolCall"!==e.type)return;let i=v.get(e.toolCallId);for(let s of(!function(e,t,r,n){let a=iD(t);if(null===a||!a.includes("gh"))return;let i=(t,r)=>{let a=e.publishRuns.get(t);a&&(null===r.sha||null!==a.sha)||e.publishRuns.set(t,{...r,order:a?.order??n})};for(let t of sy(a,r))e.runs.push({...t,order:n}),t.id&&t.sha&&t.workflow&&Object.hasOwn(sc,t.workflow)&&i(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==rO(t))return[];let r=iu(e).commands.flatMap(({words:e})=>sm(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==r.length)return[];let n=sf(r[0],["-w","--workflow"])?.toLowerCase(),a=void 0!==n&&Object.hasOwn(sc,n),i=sf(r[0],["-R","--repo"])?.toLowerCase()??null;return sp(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let r=t.toLowerCase();if(!a&&!Object.keys(sc).some(e=>r.includes(e)))return[];let n=t.match(sw)??[];return 1===n.length?[{id:n[0],sha:sk.exec(r)?.[0]??null,repo:i}]:[]})}(a,r))i(e.id,e);for(let a of sj(t,r))e.ciHeads.push({...a,order:n});for(let t of function(e,t){let r=iu(e),n=r.commands.flatMap(({words:e})=>sm(e)).filter(e=>"api"===e[0]),a=!r.uncertain&&1===r.commands.length&&1===n.length,i=t&&!t.isError&&0===rO(t)?sp(t).trim():"",s=[];for(let e of n){let t=e.slice(1).find(e=>/^\/?repos\//.test(e)),r=t?/^\/?repos\/([^/]+\/[^/]+)\/commits\/([^/?\s]+)$/.exec(t):null;if(!r)continue;let n=sf(e,["-q","--jq"]),o=null;if(a&&".sha"===n)o=i.split("\n")[0]?.trim();else if(a&&null===n&&i.startsWith("{"))try{o=JSON.parse(i.slice(0,i.lastIndexOf("}")+1)).sha}catch{}let l="string"==typeof o&&su.test(o)?o.toLowerCase():null;s.push({repo:r[1].toLowerCase(),ref:r[2],sha:l})}return s}(a,r))e.heads.push({...t,order:n});let s=function(e,t){if(!t||t.isError||0!==rO(t)||2!==e.split(sS).length)return null;let{lists:r}=iu(e),n=0;for(;n<r.length&&["set","cd"].includes(iN(r[n])?.words[0]??"");)n+=1;let a=n<r.length-1?function(e){let t=iN(e)?.words,r=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!r)return null;let n=iu(r[2]),a=1===n.lists.length?iN(n.lists[0]):null,i=a?.words[0]==="gh"?sm(a.words):[];if(1!==i.length||"run"!==i[0][0]||"list"!==i[0][1])return null;let s=sf(i[0],["-c","--commit"]),o=sf(i[0],["-w","--workflow"])?.toLowerCase();return s&&su.test(s)&&o&&Object.hasOwn(sc,o)?{name:r[1],sha:s.toLowerCase()}:null}(r[n]):null;return a&&function(e,t){if(e.background||1!==e.pipelines.length)return!1;let[r]=e.pipelines,[n,a,...i]=r.commands;if(r.negated||!a||i.length>1||"gh"!==n.words[0])return!1;let s=sm(n.words);if(1!==s.length||"run"!==s[0][0]||"view"!==s[0][1]||!s[0].includes("--log"))return!1;let o=sx(s[0]);if(sC(o)!==t)return!1;for(let e=2;e<s[0].length;e+=1){let t=s[0][e];if("-R"===t||"--repo"===t)e+=1;else if(t!==o&&"--log"!==t&&!t.startsWith("--repo=")&&!/^2>/.test(t))return!1}let[l,...c]=a.words,d=c.filter(e=>e.startsWith("-")),u=c.filter(e=>!e.startsWith("-"));if("grep"!==l||!d.every(e=>/^-[oFas]+$/.test(e))||!d.some(e=>e.includes("o"))||1!==u.length||u[0]!==sS)return!1;let[p]=i;return!p||("head"===p.words[0]||"tail"===p.words[0])&&p.words.slice(1).every(e=>/^(?:-n?\d*|\d+)$/.test(e))}(r[r.length-1],a.name)&&r.slice(n+1,-1).flatMap(e=>e.pipelines.flatMap(({commands:e})=>e)).every(({words:e})=>(function(e,t){let[r,...n]=e;if("["===r||"[["===r||"test"===r||"exit"===r||"true"===r||":"===r||"sleep"===r)return!0;if("echo"===r||"printf"===r)return n.every(e=>!/`|\$\(/.test(e)&&!/public|tree|already|matches|nothing|publish/i.test(e)&&[...e.matchAll(/\$\{?([A-Za-z_]\w*|[?])/g)].every(e=>e[1]===t||"?"===e[1]));if("gh"!==r)return!1;let a=sm(e);return 1===a.length&&"run"===a[0][0]&&"watch"===a[0][1]&&sC(sx(a[0]))===t})(e,a.name))&&sp(t).split("\n").some(e=>e.trim()===sS)?a.sha:null}(a,r);s&&e.nothingToPublish.push({sha:s,order:n})}(f,e,i,t),Array.isArray(n=function(e,t,r,n){if(!e.input||"object"!=typeof e.input||Array.isArray(e.input)||"string"!=typeof e.toolName)return null;let a=i1(t);if("notRun"===a)return null;let i={toolCallId:e.toolCallId,attempt:0},s=r&&!a?"running":"unobserved",o=iD(e);if(null!==o){var l;let r,a,c=(l=t,(a=(r=l?.details)&&"object"==typeof r&&"backgroundJob"in r?r.backgroundJob:null)&&"object"==typeof a&&"jobId"in a&&"after"in a&&"string"==typeof a.jobId&&"string"==typeof a.after?{jobId:a.jobId,after:a.after}:null);return iU(o,t).map(r=>{var a,l,d,u;let p,h;if("commit"===r.stage){let e,n,l=t?"unobserved"===r.state&&function(e,t){if(t.isError)return!1;let{commands:r}=iu(e),n=sp(t),a=e=>r.some(({words:t})=>i_(t,0,e));return(!a("commit")||iQ.test(n))&&(!a("push")||i0.test(n))}(o,t)?"done":iY[r.state]:s;return{...i,stage:"commit",..."done"===l?(e=(a=t)?sp(a):"",(n=iQ.exec(e))?{commit:n[1],title:n[2].trim()}:{commit:i0.exec(e)?.[1]??null}):{commit:null},docsOnly:!1,outcome:l}}let m=r.evidence??(c&&null!==r.exitCode?`Command exited with code ${r.exitCode}`:void 0),f=m&&c?`${c.jobId} \xb7 ${m}`:m,g="ci"===r.stage&&"failed"===r.state&&t?function(e,t){let r=iu(e).commands.flatMap(({words:e})=>sm(e)),n=r.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),a=n?sx(n):null;if(null===a||!r.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&sx(e)===a))return null;let i=sh(sp(t)).filter(e=>"completed"===e.status&&"string"==typeof e.conclusion),s=1===i.length?i[0].conclusion:null;return"string"!=typeof s||""===s||"success"===s||Object.hasOwn(s$,s)?null:s}(o,t):null,x=g?"unverified":t?r.state:s,v="check"===r.stage&&x===r.state?r.reason:void 0;return{...i,stage:r.stage,command:o,..."check"===r.stage?{cwd:(l=e.input,d=n,u=e.toolCallId,p=d?tm(d)??d:void 0,(h="string"==typeof l.cwd?l.cwd:"")?tm(h,p)??(p?tm(`${p.replace(/\/+$/,"")}/${h}`):null)??`?${u}`:p??"")}:{},exitCode:r.exitCode,labels:r.labels,outcome:x,...r.compound?{compound:r.compound}:{},...f?{evidence:g?`${f} \xb7 ${g}`:f}:{},...g?{otherRun:{kind:"unjudged",conclusion:g}}:{},...v?{reason:v}:{}}})}let c=e.toolName.toLowerCase().split(/[.:/]/).pop()??"",d=a?void 0:t,u=d?.details&&"object"==typeof d.details?d.details:{};if("cross_review"===c){let t="resolve"===e.input.action?"resolve":"review";if(!d||d.isError)return{...i,stage:"review",action:t,findings:null,outcome:d?"failed":s};if("resolve"===t){if(!0===u.pass)return{...i,stage:"review",action:t,findings:0,outcome:"passed"};let e=Array.isArray(u.open)?u.open.length:null;return{...i,stage:"review",action:t,findings:e,outcome:!1===u.pass?"failed":"unobserved"}}let r=Array.isArray(u.findings)?u.findings.length:null;if(null!==r&&r>0)return{...i,stage:"review",action:t,findings:r,outcome:"failed"};let n=Array.isArray(u.reviewers)?u.reviewers:[];return!1===u.passable||n.some(e=>!e||"object"!=typeof e||!("status"in e)||"ok"!==e.status)?{...i,stage:"review",action:t,findings:r,outcome:"unverified",unusable:!0}:{...i,stage:"review",action:t,findings:r,outcome:null===r?"unobserved":"done"}}if("git_finalize"===c){let t="string"==typeof e.input.message?iX(e.input.message):void 0,r=t?{title:t}:{};if(!d)return{...i,stage:"commit",commit:null,docsOnly:!1,...r,outcome:s};let n=i3(d,u),a=d.isError||!1===u.ok,o=!a&&(!0===u.ok||null!==n),l=e.input.files,c=o&&Array.isArray(l)&&l.length>0&&l.every(e=>"string"==typeof e&&iK(e));return{...i,stage:"commit",commit:o?n:null,docsOnly:c,...r,outcome:o?"done":a?"failed":"unobserved"}}if("git_integrate"===c){if("abort"===e.input.action||"up-to-date"===u.stage)return null;if(!d)return{...i,stage:"commit",commit:null,docsOnly:!1,outcome:s};let t=i3(d,u),r=d.isError||!1===u.ok,n=!r&&null!==t,a=u.files,o=n&&Array.isArray(a)&&a.length>0&&a.every(e=>"string"==typeof e&&iK(e));return{...i,stage:"commit",commit:n?t:null,docsOnly:o,outcome:n?"done":r?"failed":"unobserved"}}if("eval"===c)return function(e,t,r){let n=function(e){if("string"==typeof e.code)return e.code;let t=e.cells;return Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"").join("\n"):""}(e.input);if(!i2.test(n))return null;let a=i6.exec(n)?.[2],i=void 0===a?void 0:iX(a.replace(/\\n/g,"\n").replace(/\\(["'`\\])/g,"$1")),s={toolCallId:e.toolCallId,attempt:0,stage:"commit",docsOnly:!1,...i?{title:i}:{}};if(!t)return{...s,commit:null,outcome:r};let o=sp(t),l=i8.exec(o),c=l?(l[1]??l[2]).toLowerCase():null;if(!c&&i5.test(o))return null;let d=i4.test(o);return c&&!d?{...s,commit:c,outcome:"done"}:{...s,commit:null,outcome:!c&&(d||t.isError)?"failed":"unobserved"}}(e,d,s);if(function(e,t){if("task"===t||Object.hasOwn(iJ,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(iZ,e.input.action);if(!tf(e.toolName)&&!tg(e.toolName))return!1;let r=e.input.file_path??e.input.path;return"string"!=typeof r||/^[a-zA-Z]:[\\/]/.test(r)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(r)}(e,c))return!a&&t?.isError?null:(tf(e.toolName)||tg(e.toolName))&&tw(e.input,d,n)?{...i,stage:"investigate",outcome:a?"unobserved":t||!r?"done":"running"}:{...i,stage:"edit",outcome:d?"done":s,..."task"===c?{dispatch:!0}:{},...!function(e,t,r){if(!t||!(tf(e.toolName)||tg(e.toolName)))return!1;let n=ty(e.input,t);return n.length>0&&n.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let r=t?tm(t)??t:void 0,n=t_(tm(e,t)??e,r);if(/^[\\/]/.test(n)||/^[a-zA-Z]:[\\/]/.test(n))return!1;let a=n.split(/[\\/]/).filter(e=>""!==e&&"."!==e);return"HANDOFF.md"===a.at(-1)||"doc"===a[0]&&"history"===a[1]&&a.length>2})(e,r))}(e,d,n)?{}:{recordOnly:!0}};return Object.hasOwn(iG,c)?{...i,stage:"investigate",outcome:a?"unobserved":t||!r?"done":"running"}:null}(e,i,r,a))?n:n?[n]:[])){let r=i?void 0:x.get(e.toolCallId);"check"===s.stage&&"noResult"===s.reason&&r&&i9(r)&&(s.reason="noCompletion"),b.push({step:s,order:t})}}),s=null,o=!1,b.forEach((e,t)=>{let{step:r,order:n}=e;if("commit"===r.stage&&"done"===r.outcome&&r.commit&&(s={step:{...r,commit:r.commit},order:n},o=!1),"edit"!==r.stage||"done"!==r.outcome||r.dispatch||r.recordOnly||(o=!0),"ci"!==r.stage||!s)return;let a=s,i=iu(r.command).commands.flatMap(({words:e})=>sm(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(i){let e,s=sv(i),l=e=>(f.publishRuns.get(e)?.order??1/0)<=n;if((e=sT(r.command,l).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){sI(r.command,l)||"passed"!==r.outcome&&"failed"!==r.outcome||(s&&"passed"===r.outcome&&f.watched.push({id:s,order:n}),b[t]={order:n,step:{...r,outcome:"unverified",evidence:void 0,otherRun:{kind:"publish",outcome:r.outcome}}});return}let c=s?f.runs.filter(e=>e.id===s):[],d=c.find(e=>null!==e.sha)?.sha;if(!d||c.some(e=>sE(e,a,f))){d&&o&&"passed"===r.outcome&&(b[t]={order:n,step:{...r,stale:!0}});return}if("passed"===r.outcome||"failed"===r.outcome){let e=d.slice(0,7);b[t]={order:n,step:{...r,outcome:"unverified",evidence:`run ${s} \xb7 ${e}`,otherRun:{kind:"commit",sha:e,outcome:r.outcome}}}}return}if("unverified"!==r.outcome)return;let l=f.runs.find(e=>e.order===n&&null!==e.workflow&&Object.hasOwn(sd,e.workflow)&&sE(e,a,f));if(!l||"completed"!==l.status||"string"!=typeof l.conclusion)return;let c="success"===l.conclusion?"passed":Object.hasOwn(s$,l.conclusion)?"failed":null;c&&(b[t]={order:n,step:{...r,outcome:c,evidence:`run ${l.id??"?"} \xb7 ${l.status} ${l.conclusion}`,..."passed"===c&&o?{stale:!0}:{}}})}),b.forEach((e,t)=>{let{step:r,order:n}=e;if("deploy"!==r.stage||"unverified"!==r.outcome&&"unobserved"!==r.outcome)return;let a=function(e){let t=[],r=(e,n)=>{let a=ib(e);if(null!==a){if(n<3)for(let e of iu(a).commands)r(e.words,n+1);return}if(!iS(e))return;let i=ik(e),s=ij.test(e[i])?i:e.findIndex((e,t)=>t>i&&!e.startsWith("-")),o=e[s+1];t.push(void 0!==o&&/^[0-9a-f]{7,40}$/i.test(o)?o.toLowerCase():null)};for(let{words:t}of iu(e).commands)r(t,0);return 1===t.length?t[0]:null}(r.command),i=x.get(r.toolCallId);if("number"!=typeof i?.timestamp)return;let s=i.details,o=s&&"object"==typeof s&&"wallTimeMs"in s&&"number"==typeof s.wallTimeMs?s.wallTimeMs:0,l=1e3*Math.floor((i.timestamp-o)/1e3);for(let e=n;e<g.length;e+=1){let i=g[e],s=i?.type==="toolCall"?v.get(i.toolCallId):void 0;if(s)for(let e of sp(s).split("\n")){let i=e.trim().replace(/^\d+[:-](?=\d{4}-\d\d-\d\dT)/,"");if(null===a){let e=sA.exec(i);e&&Date.parse(e[1])>=l&&(a=e[2]);continue}let s=sR.exec(i);if(s&&Date.parse(s[1])>=l&&sM(s[2],a)){b[t]={order:n,step:{...r,outcome:"passed",evidence:`${s[1]} READY ${s[2].slice(0,12)}`}};return}let o=sL.exec(i);if(o&&Date.parse(o[1])>=l){b[t]={order:n,step:{...r,outcome:"failed",evidence:i.length>120?`${i.slice(0,119)}…`:i}};return}}}});let y=(e,t)=>null!==e&&(f.publishRuns.get(e)?.order??1/0)<=t;for(let{step:e,order:t}of b){let r=e;if("ci"===r.stage){let e=iu(r.command).commands.flatMap(({words:e})=>sm(e)).find(e=>"run"===e[0]&&"watch"===e[1]),n=e?sv(e):null;n&&"passed"===r.outcome&&f.watched.push({id:n,order:t}),!r.compound&&sI(r.command,e=>y(e,t))&&(r={toolCallId:r.toolCallId,attempt:r.attempt,stage:"investigate",outcome:"passed"===r.outcome||"unverified"===r.outcome?"done":r.outcome})}if("edit"!==r.stage||"done"!==r.outcome||r.dispatch){if("check"===r.stage||"review"===r.stage||"ci"===r.stage){let e="check"===r.stage?`check:${sn(r)}`:r.stage,t=u.get(e);(t?.outcome!=="failed"||st(r.outcome))&&u.set(e,{stage:r.stage,outcome:r.outcome,order:l.length})}}else{let e=sr(u);e&&(c.push({from:e,attempt:d}),d+=1),u=new Map,p=l.length,r.recordOnly||(h=l.length)}r.attempt=d,m.set(r,t),l.push(r)}let w=!1;l.forEach((e,t)=>{t<("commit"===e.stage||w&&("ci"===e.stage||"deploy"===e.stage)?h:p)&&"investigate"!==e.stage&&"edit"!==e.stage&&("passed"===e.outcome||"done"===e.outcome)&&(e.stale=!0),"commit"===e.stage&&"done"===e.outcome&&(w=!0)});let k=l.filter(e=>"commit"===e.stage&&"done"===e.outcome&&e.attempt===d).at(-1),j=k?m.get(k)??-1:-1,S=k&&!k.stale&&k.commit&&su.test(k.commit)?{sha:k.commit.toLowerCase(),order:j}:null,C=S?function(e,t,r){let n=e.watched.find(({id:r,order:n})=>{let a=e.publishRuns.get(r);return n>t.order&&a?.sha===t.sha&&a.order>t.order&&a.order<=n});if(!n)return null;let a=new Map;for(let t of e.heads)t.order>n.order&&a.set(`${t.repo}#${t.ref}`,t);let i=[...r,...e.ciHeads.filter(e=>e.order<t.order)];for(let e of a.values())if(null!==e.sha&&e.sha!==t.sha&&i.some(t=>t.repo===e.repo&&t.sha===e.sha&&t.branch===e.ref))return{kind:"publicHeadUnchanged",repo:e.repo,ref:e.ref,sha:e.sha,runId:n.id};return null}(f,S,n)??(f.nothingToPublish.some(({sha:e,order:t})=>e===S.sha&&t>S.order)?{kind:"nothingToPublish",commit:S.sha}:null):null;if(C?.kind==="nothingToPublish"){let e=C.commit;l.forEach((t,r)=>{var n;let a,i=m.get(t)??-1;if("ci"!==t.stage||"unverified"!==t.outcome||i<=j||!f.nothingToPublish.some(t=>t.order===i&&t.sha===e)&&(n=t.command,!((a=iu(n).commands.flatMap(({words:e})=>sm(e))).length>0&&a.every(t=>"run"===t[0]&&"list"===t[1]&&sf(t,["-c","--commit"])?.toLowerCase()===e))))return;let s={toolCallId:t.toolCallId,attempt:t.attempt,stage:"investigate",outcome:"done"};l[r]=s,m.set(s,i)})}let N=io.map(e=>{let t=l.filter(t=>t.stage===e),r="investigate"===e?t:t.filter(e=>e.attempt===d);return{stage:e,status:function(e,t){if(0===t.length)return"waiting";if("check"!==e){let e=new Set,r=null;for(let n of t){let t=n.stale?"stale":n.outcome;if("failed"!==r||st(n.outcome)){if(null!==r&&!("ci"!==n.stage||so(t))&&!iu(n.command).commands.some(({words:e})=>sm(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===r&&(sl(n)?.every(t=>e.has(t))??!1);if(so(r)||t)continue}if(r=t,"stale"===t||"passed"===n.outcome||"failed"===n.outcome)for(let t of sl(n)??[])e.add(t)}}return r??"waiting"}let r="done";for(let e of sa(t)){let t=e.stale?"stale":e.outcome;ss[t]>ss[r]&&(r=t)}return r}(e,r),steps:r,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),T=N[io.indexOf("deploy")],I=l.some(e=>"commit"===e.stage&&"done"===e.outcome&&!e.docsOnly);!k?.docsOnly||k.stale||I||"waiting"!==T.status||(T.status="notNeeded");let M=N[io.indexOf("ci")],E=M.steps.some(e=>(m.get(e)??1/0)>j);C&&("waiting"===M.status||("unverified"===M.status||"stale"===M.status)&&!E)?M.status="notNeeded":C=null;let $=-1;N.forEach((e,t)=>{"waiting"!==e.status&&"failed"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status&&"stale"!==e.status&&e.steps.some(e=>!e.stale&&"failed"!==e.outcome&&!si(e))&&($=t)});let R=null;if(r&&l.length>0)if(sr(u))R={stage:"edit",returning:!0};else if($<0)R={stage:N.find(e=>"waiting"!==e.status)?.stage??io[0],returning:!1};else{let e=N[$].steps.at(-1);if(e?.stage==="review"&&e.unusable)R={stage:"review",returning:!1};else{let e=N.slice($+1).find(e=>"skipped"!==e.status&&"notNeeded"!==e.status);R=e?{stage:e.stage,returning:!1}:null}}if(N.forEach((e,t)=>{t<$&&"waiting"===e.status&&(e.status="skipped")}),!r&&l.length>0){let e=!I;for(let t of N)"waiting"===t.status&&(t.status=e&&("ci"===t.stage||"deploy"===t.stage)?"notNeeded":"skipped")}return{steps:l,attempt:d,loops:c,stages:N,current:function(e,t,r){let n=e.at(-1);if(!n)return null;if(!r||r.stale)return n.stage;let a=t.filter(e=>("commit"===e.stage||"ci"===e.stage||"deploy"===e.stage)&&e.steps.length>0&&"notNeeded"!==e.status&&"skipped"!==e.status),i=a.find(e=>"commit"!==e.stage&&Object.hasOwn(sF,e.status));return i?.stage??a.at(-1)?.stage??n.stage}(l,N,k),reached:$<0?null:io[$],next:R,publication:C}}let sF={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0};function s_(e){return e.flatMap(e=>e.tasks.flatMap(t=>"completed"===t.status||"abandoned"===t.status?[]:[{phase:e.name,content:t.content,status:t.status,blocker:t.blocker??null}]))}function sz(e,t,r){let n=[],a=[],i=null;for(let r of e){if("toolCall"!==r.type)continue;if("task"===r.toolName){a.push(r);continue}if(tE(r.toolName)){let e=tM(r,t.get(r.toolCallId));"authoritative"===e.kind&&(i=e.phases);continue}let e=iB(r,t.get(r.toolCallId));e&&n.push(e)}return{checks:n,dispatchCalls:a,files:tN(e,t,r),remaining:i?s_(i):null}}function sW(e,t,r){let n=[];for(let a=Math.max(0,t);a<Math.min(e.length,r);a++){let t=e[a];"assistant"===t.role&&n.push(...t.content??[])}return n}function sO(e,t,r){let n=[],a=null;for(let i=Math.max(0,t);i<Math.min(e.length,r);i++){let t=e[i];if("assistant"===t.role)for(let e of t.content??[])"toolCall"===e.type&&(a=e.toolCallId);else if("custom"===t.role&&"async-result"===t.customType){let e="string"==typeof t.content?t.content:t.content.map(e=>"text"===e.type?e.text:"").join("\n");n.push({text:e,after:a})}}return n}function sD(e,t){var r;let n=t;for(;n>=0&&(r=e[n],r?.role==="custom"?"compaction"===r.customType:r?.role==="user"&&("steer"===is(r)||function(e){if(e===a5||e===a6||e===a3||a7.has(e))return!0;let[t,r]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==r&&r.startsWith("requestId=")}(ii(r))));){let t=n-1;for(;t>=0&&"user"!==e[t].role;)t-=1;n=t}return n}function sH(e,t,r,n){let a=Math.min(e.length,n),i=new Map;for(let t=Math.max(0,r);t<a;t++){let r=e[t];"toolResult"===r.role&&i.set(r.toolCallId,t)}let s=[];for(let n=Math.max(0,r-1);n<a;n++){let a=e[n];if(n>=r&&"assistant"===a.role)for(let e of a.content??[]){if("toolCall"!==e.type||!tE(e.toolName))continue;let r=tM(e,t.get(e.toolCallId));"authoritative"===r.kind&&s.push({at:i.get(e.toolCallId)??n,phases:r.phases})}for(let e of a.trackerTodos??[]){let t=tI(e);t&&s.push({at:n+.5,phases:t})}}let o=null;for(let e of s)(!o||e.at>=o.at)&&(o=e);return o?o.phases:null}function sU(e,t,r,n=0,a=[]){for(let i=Math.max(0,n);i<Math.min(e.length,r);i++){let r=e[i];if("assistant"===r.role)for(let e of r.content??[])"toolCall"===e.type&&a.push(...sj(e,t.get(e.toolCallId)))}return a}function sB(e,t,r){let n=null,a=null;for(let i=Math.max(0,t-1);i<Math.min(e.length,r);i++){let t=e[i];for(let e of[t.timestamp,"assistant"===t.role?t.completedAt:void 0])"number"==typeof e&&Number.isFinite(e)&&((null===n||e<n)&&(n=e),(null===a||e>a)&&(a=e))}return{startedAt:n,endedAt:a}}function sq(e,t){if(0===e.length)return null;let r=[...e].sort((e,t)=>e-t),n=(r.length-1)*t,a=Math.floor(n),i=Math.ceil(n);return r[a]+(r[i]-r[a])*(n-a)}let sV=["investigate","implement","verify","report"],sK={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},sG={bash:!0,eval:!0};function sJ(e){let t=[],r=new Map;for(let n of e)if("toolResult"===n.role&&r.set(n.toolCallId,n),"assistant"===n.role&&Array.isArray(n.content))for(let e of n.content)"toolCall"===e.type&&t.push(e);return{blocks:t,results:r}}function sZ(e,t,r,n){return!0===sK[t]&&!tw(e.input,r.get(e.toolCallId),n)}function sY(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function sX(e){return"yield"===sY(e)&&!Array.isArray(e.input?.type)}function sQ(e,t){if(0===e.length)return null;let{blocks:r,results:n}=sJ(e),a=-1;r.forEach((e,t)=>{sX(e)&&(a=t)});let i=a>=0&&a===r.length-1,s=i?r.findLastIndex((e,t)=>t<a&&sX(e))+1:a+1,o={calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:i,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1},l=!1;for(let e of r.slice(s)){let r=sY(e);if(sZ(e,r,n,t))"verify"===o.phase&&(o.reedits+=1),l=!0,o.phase="implement",o.verifiedAfterEdit=!1;else if(sG[r]){if(o.phase=l?"verify":"investigate",l){o.verifiedAfterEdit=!0;let t=iB(e,n.get(e.toolCallId));t?.state==="passed"?o.checks.passed+=1:t?.state==="failed"?o.checks.failed+=1:t&&(o.checks.unknown+=1)}}else"yield"===r&&(o.phase="report",l=!1);o.calls[o.phase]+=1}return o}function s0(e,t){if(!e)return{run:null,stations:sV.map(e=>({phase:e,state:"unobserved",calls:0}))};let r=t&&e.ended?{calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:!1,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1}:e,n=t?sV.indexOf(r.phase):sV.findLastIndex(e=>r.calls[e]>0),a=sV.map((e,a)=>{let i,s=r.calls[e];return i=t&&e===r.phase?"active":s>0?"verify"!==e||r.verifiedAfterEdit?"done":"stale":a<n?"skipped":t?"waiting":"none",{phase:e,state:i,calls:s}});return{run:r,stations:a}}function s1(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function s2(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let r=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:r}}function s8(e){return"pending"===e||"running"===e}let s4=new Map;function s5(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function s6(e){return e instanceof aL&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function s3(e,{sessionId:t,client:r,enabled:n}){let[i,s]=(0,a.useState)(s4),o=(0,a.useRef)(new Map),l=(0,a.useRef)(e);l.current=e;let c=(0,a.useCallback)(()=>{let e=o.current;s(t=>{let r=!1,n=new Map;for(let[a,i]of e){let e=t.get(a),s=e&&e.entries===i.collected&&e.state===i.state?e:{state:i.state,entries:i.collected};s!==e&&(r=!0),n.set(a,s)}return n.size!==t.size&&(r=!0),r?n:t})},[]),d=e.map(e=>`${e.key}|${s5(e)}`).join("\n");return(0,a.useEffect)(()=>{if(!n)return;let e=!1,a=!1,i=null,s=o.current,d=new Set(l.current.map(e=>e.key));for(let e of[...s.keys()])d.has(e)||s.delete(e);for(let e of l.current){let t=s5(e);s.get(e.key)?.signature!==t&&s.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(n,a,i,s)=>{if(!n.archiveName){a.state={kind:"empty",source:"live",note:s};return}try{let o=await r.getArchiveTranscript(t,n.archiveName,400,i);if(e)return;0===a.collected.length&&(a.collected=o.entries.flatMap((e,t)=>{let r=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:r,message:e.message}]:e.irc?[{id:r,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),a.state=0===o.entries.length?{kind:"empty",source:"archive",note:s}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:s}}catch(r){if(e||i.aborted)return;let t=s6(r);a.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(n,a)=>{let i=s.get(n.key);if(i){if(!n.liveId)return void await u(n,i,a);try{var o,l;let s=await r.getLiveTranscript(t,n.liveId,i.nextByte,a);if(e)return;let c=(o=s.entries,l=s.fromByte,o.flatMap((e,t)=>{let r=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:r,message:s2(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:r,irc:{from:"string"==typeof t.from?t.from:void 0,message:"string"==typeof t.message?t.message:void 0}}]}return[]}));s.reset||0===s.fromByte?i.collected=c:c.length>0&&(i.collected=[...i.collected,...c]),i.nextByte=s.nextByte,i.collected.length>0?("ready-live"!==i.state.kind||i.state.entries!==i.collected)&&(i.state={kind:"ready-live",entries:i.collected}):await u(n,i,a)}catch(t){if(e||a.aborted)return;if(n.archiveName){let e=s6(t);await u(n,i,a,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=s6(t);i.state="unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message}}}}},h=async()=>{if(e||a||"u">typeof document&&"visible"!==document.visibilityState)return;a=!0;let t=new AbortController;i=t;try{for(let e of l.current)await p(e,t.signal)}finally{a=!1}e||c()};h();let m=l.current.some(e=>s8(e.status))?setInterval(()=>void h(),3e3):void 0,f=()=>{"visible"===document.visibilityState&&h()};return document.addEventListener("visibilitychange",f),()=>{e=!0,i?.abort(),clearInterval(m),document.removeEventListener("visibilitychange",f)}},[r,n,c,t,d]),i}let s7=(0,a.createContext)({ledger:aU,subagents:[],toolResults:new Map}),s9="omp-web:flow-motion",oe=new Set,ot=null;function or(){if(null===ot)try{ot="paused"===window.localStorage.getItem(s9)}catch{ot=!1}return ot}function on(e){return oe.add(e),()=>{oe.delete(e)}}function oa(){return(0,a.useSyncExternalStore)(on,or,()=>!1)}function oi({paused:e}){let{st:t}=ag();return(0,n.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){ot=e;try{e?window.localStorage.setItem(s9,"paused"):window.localStorage.removeItem(s9)}catch{}for(let e of oe)e()})(!e),children:t("graph.motion.pause")})}function os(e,t,r){return r&&t.current===e.stage?"active":"waiting"===e.status?"deploy"===e.stage?"approval":"waiting":"skipped"===e.status||"notNeeded"===e.status?"skipped":"stale"===e.status?"stale":"done"===e.status||"passed"===e.status?"done":"failed"===e.status||"running"===e.status?e.status:"unverified"}function oo(e){return e.stale?"stale":e.outcome}let ol=(0,n.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"6 9 12 15 18 9"})});function oc({look:e}){return(0,n.jsxs)("span",{className:"flow-node","aria-hidden":"true",children:[("done"===e||"stale"===e)&&(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:"stale"===e?"3 4":void 0,children:(0,n.jsx)("polyline",{points:"5 12 10 17 19 7"})}),"unverified"===e&&(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"6",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"18",x2:"12",y2:"18.5"})]}),"failed"===e&&(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"7",y1:"7",x2:"17",y2:"17"}),(0,n.jsx)("line",{x1:"17",y1:"7",x2:"7",y2:"17"})]}),"skipped"===e&&(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:(0,n.jsx)("line",{x1:"6",y1:"12",x2:"18",y2:"12"})})]})}function od({outcome:e}){let t={className:"flow-check-icon",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"stale"===e?(0,n.jsxs)("svg",{...t,strokeWidth:2,children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"}),(0,n.jsx)("path",{d:"M12 7v5l4 2"})]}):"passed"===e||"done"===e?(0,n.jsx)("svg",{...t,strokeWidth:2.5,children:(0,n.jsx)("polyline",{points:"5 12 10 17 19 7"})}):"failed"===e?(0,n.jsxs)("svg",{...t,strokeWidth:2.5,children:[(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"}),(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"})]}):"running"===e?(0,n.jsxs)("svg",{...t,strokeWidth:2,children:[(0,n.jsx)("path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0"}),(0,n.jsx)("path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0"}),(0,n.jsx)("path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7"}),(0,n.jsx)("path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8"}),(0,n.jsx)("path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69"}),(0,n.jsx)("path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8"}),(0,n.jsx)("path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69"}),(0,n.jsx)("path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7"})]}):(0,n.jsxs)("svg",{...t,strokeWidth:2,children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,n.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,n.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}function ou({step:e,st:t}){let r=t(`flow.state.${e.outcome}`);if(e.stale)r=t("passed"===e.outcome?"flow.state.stale":"flow.state.staleDone");else if("review"===e.stage&&"failed"===e.outcome&&null!==e.findings){let n=1===e.findings?"flow.state.findings.one":"flow.state.findings";r=t("resolve"===e.action?"flow.state.open":n,{count:e.findings})}else"review"===e.stage&&e.unusable?r=t("flow.state.reviewUnusable"):"review"===e.stage&&"done"===e.outcome&&(r=t("flow.state.noFindings"));return(0,n.jsxs)("span",{className:"flow-tone","data-tone":oo(e),children:[r,"commit"===e.stage&&e.commit&&(0,n.jsxs)(n.Fragment,{children:[" ",(0,n.jsxs)("span",{className:"flow-sha-tail",children:["\xb7\xa0",(0,n.jsx)("code",{className:"flow-sha",children:e.commit.slice(0,7)})]})]})]})}let op={syntax:"flow.why.check.syntax",optional:"flow.why.check.optional",noExit:"flow.why.noExit",noResult:"flow.why.noResult",noCompletion:"flow.why.noCompletion",interrupted:"flow.why.interrupted"},oh={masked:"flow.next.rerun",syntax:"flow.next.rerun",optional:"flow.next.optional",compound:"flow.next.compound",noExit:"flow.next.again",noResult:"flow.next.again",noCompletion:"flow.next.again",interrupted:"flow.next.again"};function om({step:e,label:t,st:r}){let a=si(e),i=e.compound?.stages.map(e=>r(`flow.stage.${e}`)).join("\xb7")??"",s=e.otherRun,o=e.reason?op[e.reason]:void 0,l=a?r("flow.why.compoundConfirmed",{stages:i}):s?.kind==="unjudged"?r("flow.why.watched.unjudged",{conclusion:s.conclusion}):s?r(`flow.why.watched.${s.outcome}`):r("flow.why.exitZero"),c=a?r("flow.why.compoundMissing"):o?r(o,{label:t}):"check"===e.stage?r("flow.why.check",{label:t}):s?.kind==="commit"?r("flow.why.ciOtherRun",{sha:s.sha}):s?.kind==="publish"?r("flow.why.ciPublishRun"):s?.kind==="unjudged"?r("flow.why.ciUnjudged",{conclusion:s.conclusion}):r(`flow.why.${e.stage}`),d=e.reason?r(oh[e.reason]):a?r("flow.next.compound"):null,u="unverified"===e.outcome||"unobserved"===e.outcome&&void 0!==e.reason,p=null!==e.exitCode?r("flow.exit",{code:e.exitCode}):r("failed"===e.outcome?"flow.exit.error":"running"===e.outcome?"flow.state.running":"flow.exit.none");return(0,n.jsxs)("div",{className:"flow-raw",children:[u&&(0,n.jsxs)("p",{className:"flow-why",children:["unverified"===e.outcome&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("b",{children:r("flow.why.confirmed")})," ",l,(0,n.jsx)("br",{})]}),(0,n.jsx)("b",{children:r("flow.why.missing")})," ",c,d&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("br",{}),(0,n.jsx)("b",{children:r("flow.why.next")})," ",d]})]}),e.stale&&(0,n.jsx)("p",{className:"flow-why",children:r("flow.why.stale")}),void 0===e.commandKey?(0,n.jsx)("code",{className:"flow-raw-command",children:e.command}):(0,n.jsx)("p",{className:"flow-why",children:r("flow.commandOmitted")}),(0,n.jsx)("div",{className:"flow-exit",children:p}),e.evidence&&(0,n.jsxs)("div",{className:"flow-exit",children:[r("flow.evidence")," ",(0,n.jsx)("code",{className:"flow-evidence",children:e.evidence})]})]})}function of({steps:e,st:t,attempts:r=!1}){return(0,n.jsx)("ul",{className:"flow-checks",children:e.map(e=>{let a="check"===e.stage?e.labels.map(e=>t(`flow.label.${e}`)).join("\xb7")||t("flow.label.check"):"review"===e.stage?t("resolve"===e.action?"flow.label.resolve":"flow.label.review"):"ci"===e.stage||"deploy"===e.stage||"commit"===e.stage?t(`flow.label.${e.stage}`):t(`flow.stage.${e.stage}`),i=oo(e),s=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(od,{outcome:i}),(0,n.jsx)(ou,{step:e,st:t}),(0,n.jsxs)("span",{className:"flow-check-label",children:[r?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${a}`:a,si(e)&&(0,n.jsx)("span",{className:"flow-compound",children:t("flow.compound.failed")})]})]});return"check"!==e.stage&&"ci"!==e.stage&&"deploy"!==e.stage?(0,n.jsx)("li",{className:"flow-check","data-result":i,children:(0,n.jsx)("div",{className:"flow-check-head",children:s})},e.toolCallId):(0,n.jsx)("li",{className:"flow-check","data-result":i,children:(0,n.jsxs)("details",{children:[(0,n.jsxs)("summary",{className:"flow-check-head",children:[s,(0,n.jsxs)("span",{className:"flow-disclose",children:[t("flow.details"),ol]})]}),(0,n.jsx)(om,{step:e,label:a,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function og({steps:e,st:t}){return 0===e.length?null:(0,n.jsxs)("details",{className:"flow-earlier",children:[(0,n.jsxs)("summary",{className:"flow-earlier-toggle",children:[t("flow.earlier",{count:e.length}),ol]}),(0,n.jsx)(of,{steps:e,st:t,attempts:!0})]})}function ox({view:e,steps:t,st:r}){if(0===t.length)return null;if("check"!==e.stage)return(0,n.jsx)(of,{steps:t,st:r});let a=sa(t),i=e=>{let t=ov.indexOf(oo(e));return t<0?ov.length:t},s=[...a].sort((e,t)=>i(e)-i(t)),o=t.filter(e=>!a.includes(e));return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(of,{steps:s,st:r}),o.length>0&&(0,n.jsxs)("details",{className:"flow-earlier",children:[(0,n.jsxs)("summary",{className:"flow-earlier-toggle",children:[r("flow.repeats",{count:o.length}),ol]}),(0,n.jsx)(of,{steps:o,st:r})]})]})}let ov=["failed","unverified","unobserved","stale","running","passed"];function ob({view:e,flow:t,live:r,st:a,compact:i=!1}){if(r&&t.current===e.stage)return a("flow.state.running");if("waiting"===e.status)return a("flow.state.waiting");if("skipped"===e.status||"notNeeded"===e.status)return a(`flow.state.${e.status}`);let s=e.steps[e.steps.length-1];if("investigate"===e.stage)return a("running"===e.status?"flow.state.running":"flow.state.done");if("edit"===e.stage&&"done"===e.status)return a(t.attempt>1?"flow.state.redone":"flow.state.done");if("check"===e.stage&&!i){let t=new Map;for(let r of sa(e.steps))t.set(oo(r),(t.get(oo(r))??0)+1);return ov.filter(e=>t.has(e)).map((e,r)=>(0,n.jsxs)("span",{children:[r>0&&" \xb7 ",(0,n.jsx)("span",{className:"flow-tone","data-tone":e,children:a(`flow.count.${e}`,{count:t.get(e)??0})})]},e))}return"check"===e.stage||"edit"===e.stage?(0,n.jsx)("span",{className:"flow-tone","data-tone":e.status,children:a(`flow.state.${e.status}`)}):(0,n.jsx)(ou,{step:s,st:a})}function oy({flow:e,live:t,st:r,id:a}){let i=e.loops[e.loops.length-1],s=i?e.steps.filter(e=>e.stage===i.from):[],o=r("flow.loop.badge",{attempt:e.attempt});return(0,n.jsxs)("div",{className:"flow-chain-panel",id:a,children:[(0,n.jsxs)("div",{className:"flow-chain-wrap","data-loop":i?"":void 0,style:i?{"--loop-from":io.indexOf(i.from)}:void 0,children:[(0,n.jsx)("ol",{className:"flow-chain","aria-label":r("flow.aria"),children:e.stages.map(a=>{let i=os(a,e,t);return(0,n.jsxs)("li",{className:"flow-link","data-state":i,"aria-current":"active"===i?"step":void 0,children:[(0,n.jsx)(oc,{look:i}),(0,n.jsx)("span",{className:"flow-link-name",children:r(`flow.stage.${a.stage}`)}),(0,n.jsx)("span",{className:"flow-link-state",children:(0,n.jsx)(ob,{view:a,flow:e,live:t,st:r,compact:!0})})]},a.stage)})}),i&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flow-loop","aria-hidden":"true",children:[(0,n.jsx)("svg",{width:"22",height:"15",viewBox:"0 0 22 15",children:(0,n.jsx)("polyline",{points:"3 12 11 3 19 12",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,n.jsx)("span",{className:"flow-loop-count",children:o})]}),(0,n.jsxs)("p",{className:"flow-loop-caption",children:[(0,n.jsx)("span",{className:"flow-loop-caption-count",children:o}),r("review"===i.from?"flow.loop.findings":"flow.loop.failed",{stage:r(`flow.stage.${i.from}`),attempt:i.attempt})]})]})]}),s.length>0&&(0,n.jsx)("div",{className:"flow-chain-attempts",children:(0,n.jsx)(of,{steps:s,st:r,attempts:!0})})]})}function ow({sessionId:e,snapshots:t,client:r,enabled:n,transcripts:i=!0,cwd:s}){let o=(0,a.useMemo)(()=>t.filter(e=>s8(e.status)),[t]),l=n&&!!e&&o.length>0,c=s3((0,a.useMemo)(()=>o.map(e=>({key:e.id,liveId:e.id,status:e.status})),[o]),{sessionId:e??"",client:r,enabled:l&&i}),[d,u]=(0,a.useState)(null),p=o.map(e=>e.id).sort().join("\n");return(0,a.useEffect)(()=>{let t;if(!l||!e)return;let r=new AbortController,n=p.split("\n"),a=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,i=!0,s=0;async function o(){try{let t=await fetch(a,{signal:AbortSignal.any([r.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!r.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),i=n.some(e=>!s.histories[e]))}catch{}finally{if(!r.signal.aborted){let e=i&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{r.abort(),window.clearTimeout(t)}},[p,l,e]),(0,a.useMemo)(()=>{let t=new Map;if(!l)return t;let r=d&&d.sessionId===e?d.histories:void 0;for(let e of o){let n=(i?c.get(e.id)?.entries??[]:[]).flatMap(e=>"message"in e?[e.message]:[]);t.set(e.id,{phase:function(e,t){if(0===e.length)return null;let{blocks:r,results:n}=sJ(e),a="investigate",i=!1;for(let e of r){let r=sY(e);sZ(e,r,n,t)?(i=!0,a="implement"):sG[r]?a=i?"verify":"investigate":"yield"===r&&(a="report",i=!1)}return a}(n,s),trace:sQ(n,s),todo:function(e){let t=new Map;for(let r of e)"toolResult"===r.role&&t.set(r.toolCallId,r);let r=t$([...e],t);if(!r)return null;let n=tL(r);return 0===n.total||null===n.percent?null:{completed:n.completed,total:n.total,percent:n.percent,activeTask:n.activeTask?.content??null}}(n),history:r?.[e.id]??null})}return t},[o,s,d,l,c,e,i])}function ok(e,t){let r=s1(t);return r?0===r.hours?e("duration.minutes",{minutes:r.minutes}):0===r.minutes?e("duration.hours",{hours:r.hours}):e("duration.hoursMinutes",{hours:r.hours,minutes:r.minutes}):e("duration.underMinute")}function oj(e,t){let r=Math.floor(t/1e3);return r<60?e("duration.seconds",{seconds:r}):r<3600?e("duration.minutesSeconds",{minutes:Math.floor(r/60),seconds:r%60}):ok(e,t)}function oS({phase:e}){let{st:t}=ag();return(0,n.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,n.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,n.jsx)("span",{"aria-hidden":"true",children:sV.map((r,a)=>(0,n.jsxs)("span",{children:[a>0&&(0,n.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,n.jsx)("span",{"data-current":r===e?"":void 0,style:r===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${r}`)})]},r))})]})}let oC={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function oN(e,t){let r=t.passed+t.failed+t.unknown,a=t.failed>0?"failed":t.unknown>0?"unverified":"passed";return(0,n.jsx)("span",{className:"flow-tone","data-tone":a,children:e("subflow.checks",{passed:t.passed,total:r})})}function oT({flow:e,live:t,verdict:r,attempts:a}){let{st:i}=ag(),s=oa(),o=e.stations.findIndex(e=>"active"===e.state),l=sV.indexOf("implement"),c=a.filter(e=>"rework"===e.verdict).length,d=r?"accepted"===r.verdict?"done":"unverified":"waiting",u=r?`${i(`verdict.${r.verdict}`)}${null!==r.attempt&&r.attempt>1?` \xb7 ${i("verdict.attempt",{attempt:r.attempt})}`:""}`:i(t?"flow.state.waiting":"verdict.none");return(0,n.jsxs)("div",{className:"subagent-flow",children:[t&&o>=0&&(0,n.jsx)(oi,{paused:s}),(0,n.jsxs)("ol",{className:"flow-graph","aria-label":i("subflow.aria"),"data-live":t?"":void 0,"data-motion":s?"paused":void 0,children:[e.stations.map((t,r)=>{let a=oC[t.state];return(0,n.jsx)("li",{className:"flow-graph-station","data-stage":t.phase,"data-state":a,"data-loop":c>0&&r>=l?"":void 0,"aria-current":"active"===t.state?"step":void 0,style:{"--col":r+1},children:(0,n.jsxs)("div",{className:"flow-graph-stop",children:[(0,n.jsx)("span",{className:"flow-graph-stop-name",children:i(`phase.${t.phase}`)}),(0,n.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,n.jsx)(oc,{look:a}),(0,n.jsx)("span",{className:"flow-graph-stop-word",children:function(e,t,r){let a="verify"===t.phase&&null!==r&&r.checks.passed+r.checks.failed+r.checks.unknown>0;switch(t.state){case"active":return a&&r?(0,n.jsxs)(n.Fragment,{children:[e("flow.state.running")," \xb7 ",oN(e,r.checks)]}):e("flow.state.running");case"waiting":return e("flow.state.waiting");case"skipped":return e("flow.state.skipped");case"none":return e("detail.stageNone");case"unobserved":return e("subflow.unobserved");case"stale":return e(r&&r.checks.passed>0?"flow.state.stale":"flow.state.staleDone");case"done":if("report"===t.phase)return e("subflow.reported");if(a&&r)return oN(e,r.checks);if("implement"===t.phase&&r&&r.reedits>0)return`${e("subflow.calls",{count:t.calls})} \xb7 ${e("subflow.reedits",{count:r.reedits})}`;return e("subflow.calls",{count:t.calls})}}(i,t,e.run)})]})]})},t.phase)}),(0,n.jsx)("li",{className:"flow-graph-station","data-stage":"verdict","data-state":d,style:{"--col":sV.length+1},children:(0,n.jsxs)("div",{className:"flow-graph-stop",children:[(0,n.jsx)("span",{className:"flow-graph-stop-name",children:i("graph.join")}),(0,n.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,n.jsx)(oc,{look:d}),(0,n.jsx)("span",{className:"flow-graph-stop-word",children:u})]})]})}),c>0&&(0,n.jsxs)("li",{className:"flow-graph-return",style:{"--from":l+1,"--to":sV.length+1},children:[(0,n.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,n.jsx)("span",{className:"flow-graph-return-text",children:i("subflow.rework",{count:c})})]})]})]})}function oI(e,t){let r=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${r} \xb7 ${t.activeTask}`:r}function oM({snapshot:e,view:t,id:r}){var a,i,s;let o,l,c,{st:d}=ag(),u=ry(5e3),p="number"!=typeof(o=e.progress?.durationMs)?null:o+(("pending"===e.status||"running"===e.status)&&e.lastUpdate>0?Math.max(0,u-e.lastUpdate):0);if(null===p)return null;let h=function(e,t){if(!e||e.rework||null===t||e.durationsSec.length<3)return null;let r=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(r.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:r.length};let n=sq(r,.5)??0;return{kind:"remaining",p25Ms:sq(r,.25)??0,medianMs:n,p75Ms:sq(r,.75)??0,samples:r.length,percent:Math.round(t/(t+n)*100)}}(t.history,p),m=(a=t.todo,!a||null===p||0===a.completed||a.completed>=a.total?null:p*(a.total-a.completed)/a.completed),f={color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},g=t.history,x=g?.rework&&null!==g.firstDispatchedAtMs?u-g.firstDispatchedAtMs:null;return(0,n.jsxs)("span",{id:r,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,n.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:d("eta.elapsed",{duration:oj(d,p)})}),g?.rework&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:f,title:d("eta.reworkHint"),children:null!==x&&x>=0?d("eta.rework",{attempt:g.attempt,duration:oj(d,x)}):d("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{title:d("eta.hint"),children:d("eta.remaining",{range:(i=h.p25Ms,s=h.p75Ms,l=s1(i),c=s1(s),l&&c&&0===l.hours&&0===c.hours?l.minutes===c.minutes?d("duration.minutes",{minutes:l.minutes}):d("eta.rangeMinutes",{low:l.minutes,high:c.minutes}):d("eta.range",{low:ok(d,i),high:ok(d,s)})),samples:h.samples})})," \xb7 ",(0,n.jsx)("span",{style:f,children:d("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:{color:"var(--warning)"},title:d("eta.hint"),children:0===h.longerRuns?d("eta.overrun",{longest:ok(d,h.longestMs)}):d("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==m&&t.todo&&(0,n.jsxs)(n.Fragment,{children:[" \xb7 ",(0,n.jsx)("span",{style:f,title:d("eta.byTodoHint"),children:m<6e4?d("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):d("eta.byTodo",{duration:ok(d,m),completed:t.todo.completed,total:t.todo.total})})]})]})}let oE={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},o$={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function oR({maker:e,st:t}){let r=e.verdict?.verdict??"none",a=e.verdict?.attempt;return(0,n.jsxs)("span",{className:"answer-status-pair",children:[(0,n.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(oE[e.run])}),(0,n.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,n.jsxs)("span",{className:"answer-status-verdict","data-verdict":r,children:[t(o$[r]),null!=a&&a>1?` \xb7 ${t("verdict.attempt",{attempt:a})}`:null]})]})}function oL(e,t){let r=[],n=new Map;for(let t of e)"message"in t&&("assistant"===t.message.role?r.push(...t.message.content??[]):"toolResult"===t.message.role&&n.set(t.message.toolCallId,t.message));return sz(r,n,t)}function oA(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function oP(e,t){let r=e?.state;return r?.kind!=="ready-live"?null:sQ(r.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function oF({maker:e,st:t}){let r=e.runTitle??e.title;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"answer-dispatch-name",title:r,children:r}),e.priorVerdict&&!e.runTitle&&(0,n.jsx)("span",{className:"answer-dispatch-title-note",children:t("subflow.firstTitle")})]})}function o_({calls:e}){let{ledger:t,subagents:r,toolResults:i,onOpenPanel:s,sessionId:o,cwd:l,onOpenMaker:c,selectedMaker:d}=(0,a.useContext)(s7),{st:u}=ag(),{t:p}=(0,z.s)(),[h,m]=(0,a.useState)(!1),f=(0,a.useId)(),g=(0,a.useMemo)(()=>aW(),[]),x=(0,a.useMemo)(()=>e.flatMap(e=>aJ(e,i.get(e.toolCallId))??[]).map(e=>aQ(e,r,t)),[e,i,r,t]),v=(0,a.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let n=aX(e.member,r,t);return n?[n]:[]}),[x,r,t]),b=ow({sessionId:o,snapshots:v,client:g,enabled:!0,transcripts:h,cwd:l}),y=(0,a.useMemo)(()=>new Map(x.flatMap(e=>{let t=a0(e.member,r);return t?[[e.member.key,t]]:[]})),[x,r]),w=(0,a.useMemo)(()=>h?[...y].filter(([,e])=>!s8(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:oA(t)})):[],[y,h]),k=s3(w,{sessionId:o??"",client:g,enabled:h&&!!o&&w.length>0}),j=d?.origin?x.find(e=>e.member.key===d.origin):void 0,S=j?.run,C=j?.verdict??null;if((0,a.useEffect)(()=>{if(!d||!c||!S)return;let e=d.status;e&&e.run===S&&e.verdict?.order===C?.order||c({...d,status:{run:S,verdict:C}},!1)},[c,d,S,C]),0===x.length)return null;let N=0,T=0,I=0;for(let e of x)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(N+=1),"completed"===e.run&&(T+=1),e.verdict?.verdict==="accepted"&&(I+=1);return(0,n.jsxs)("section",{className:"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,n.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":h,"aria-controls":f,title:u(h?"dispatch.collapse":"dispatch.expand"),onClick:()=>m(e=>!e),children:[(0,n.jsx)("span",{className:"answer-dispatch-heading",children:u("dispatch.title",{count:x.length})}),(0,n.jsx)("span",{className:"answer-dispatch-tally",children:u("dispatch.tally",{running:N,done:T,accepted:I})}),(0,n.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,n.jsx)("ul",{className:"answer-dispatch-list",id:f,"aria-label":h?p("dispatchLane.label"):void 0,children:x.map(e=>{var r;let a,i="pending"===e.run||"running"===e.run,s=i?v.find(t=>t.id===e.member.agentId):void 0,o=s?b.get(s.id):void 0,p=y.get(e.member.key),m=e.member.key===d?.origin,f=i&&"live"===e.runSource,g=h?s0(f?o?.trace??null:oP(k.get(e.member.key),l),f):null,x=h?a1(e.member,t):[];return(0,n.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":m?"":void 0,children:[h?(0,n.jsx)(oz,{maker:e,phase:f&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,r){if(!t)return{kind:"unobserved"};if(s8(t.status))return{kind:"running"};let n=e?.state;if(!n||"loading"===n.kind)return{kind:"loading"};if("ready-live"===n.kind){let{checks:e}=oL(n.entries,r);return{kind:"counted",passed:e.filter(e=>"passed"===e.state).length,total:e.length}}return"empty"===n.kind&&"live"===n.source?{kind:"counted",passed:0,total:0}:{kind:"unobserved"}}(k.get(e.member.key),p,l),onOpen:p&&c?()=>c({key:`live:${p.id}`,toolCallId:e.member.toolCallId,origin:e.member.key,status:{run:e.run,verdict:e.verdict}}):null}):(0,n.jsxs)("div",{className:"answer-dispatch-line",children:[(0,n.jsx)(oF,{maker:e,st:u}),(0,n.jsx)(oR,{maker:e,st:u})]}),g&&(0,n.jsx)(oT,{flow:g,live:f,verdict:e.verdict,attempts:x}),h&&(0,n.jsx)(oO,{attempts:x}),s&&o&&(0,n.jsxs)("div",{className:"answer-dispatch-progress",children:[o.todo?`${oI(u,o.todo)} \xb7 `:null,(0,n.jsx)(oM,{snapshot:s,view:o})]}),h&&(0,n.jsxs)("dl",{className:"answer-dispatch-detail",children:[i&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.stage")}),(0,n.jsx)("dd",{children:e.stage??u("detail.stageNone")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.model")}),(0,n.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${u("detail.fallback")}`:""}`:u("detail.modelNone")})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.agentId")}),(0,n.jsxs)("dd",{children:[(0,n.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${u("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.priorVerdict&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("subflow.prior")}),(0,n.jsx)("dd",{children:(a=null!==(r=e.priorVerdict).attempt&&r.attempt>1?` \xb7 ${u("verdict.attempt",{attempt:r.attempt})}`:"",`${u(o$[r.verdict])}${a}${r.reason?` \xb7 ${r.reason}`:""}`)})]}),e.priorVerdict&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u(e.runTitle?"subflow.firstTitle":"subflow.runTitle")}),(0,n.jsx)("dd",{children:e.runTitle?e.title:u("detail.stageNone")})]}),e.verdict?.reason&&(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:u("detail.reason")}),(0,n.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),h&&s&&(0,n.jsxs)("div",{className:"answer-dispatch-links",children:[(0,n.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:u("detail.openSubagents")}),(0,n.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:u("detail.openProcess")})]})]})}function oz({maker:e,phase:t,checks:r,onOpen:a}){let{st:i}=ag(),{t:s}=(0,z.s)(),o=e.verdict?.verdict??"none",l=i(oE[e.run]),c="running"===r.kind?null:"counted"===r.kind?s("dispatchLane.checks",{passed:r.passed,total:r.total}):s("loading"===r.kind?"dispatchLane.checksLoading":"dispatchLane.checksUnobserved");return(0,n.jsxs)("div",{className:"answer-dispatch-line is-lane",children:[(0,n.jsx)(oF,{maker:e,st:i}),(0,n.jsxs)("span",{className:"answer-status-pair",children:[(0,n.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?s("dispatchLane.runPhase",{run:l,phase:t}):l}),c&&(0,n.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===r.kind&&r.passed<r.total?"failed":r.kind,children:c}),(0,n.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,n.jsx)("span",{className:"answer-status-verdict","data-verdict":o,children:i(o$[o])})]}),a?(0,n.jsx)("button",{type:"button",className:"answer-link answer-dispatch-open","aria-label":s("dispatchLane.openLabel",{title:e.title}),onClick:a,children:s("dispatchLane.open")}):(0,n.jsx)("span",{className:"answer-dispatch-unavailable",title:s("makerDetail.unavailable"),children:s("dispatchLane.unavailable")})]})}function oW({maker:e}){let{ledger:t,subagents:r,sessionId:i,cwd:s}=(0,a.useContext)(s7),o=(0,a.useMemo)(()=>aW(),[]),l="pending"===e.run||"running"===e.run,c=l&&"live"===e.runSource,d=l?aX(e.member,r,t):void 0,u=ow({sessionId:i,snapshots:(0,a.useMemo)(()=>d?[d]:[],[d]),client:o,enabled:!0,transcripts:!0,cwd:s}),p=a0(e.member,r),h=(0,a.useMemo)(()=>p&&!s8(p.status)?[{key:e.member.key,liveId:p.id,status:p.status,archiveName:oA(p)}]:[],[p,e.member.key]),m=s3(h,{sessionId:i??"",client:o,enabled:!!i&&h.length>0}),f=d?u.get(d.id):void 0,g=s0(c?f?.trace??null:oP(m.get(e.member.key),s),c),x=a1(e.member,t);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(oT,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,n.jsx)(oO,{attempts:x})]})}function oO({attempts:e}){let{t}=(0,z.s)();return e.length<2?null:(0,n.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":t("dispatchLane.label"),children:e.map((e,r)=>(0,n.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[r>0&&(0,n.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→ "}),null===e.attempt?t("dispatchLane.attemptUnknown"):t("dispatchLane.attempt",{attempt:e.attempt})," ",t(`dispatchLane.verdict.${e.verdict}`)]},`${e.attempt??"n"}-${r}`))})}let oD={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},oH={html:0,document:1,image:2},oU=/\.(?:md|mdx|markdown|txt)$/i;function oB(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function oq(e,t,r){return"investigate"!==e.stage&&("edit"===e.stage?r>0||e.earlier.length>0:e.steps.length>0||e.earlier.length>0||"ci"===e.stage&&null!==t.publication)}function oV({entry:e,st:t}){let r="running"===e.maker.run||"pending"===e.maker.run||"dispatching"===e.maker.run;return e.bar&&null!==e.durationMs?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"flow-graph-track","aria-hidden":"true",children:(0,n.jsx)("span",{className:"flow-graph-bar",style:{left:oB(e.bar.offset),width:oB(e.bar.width)}})}),(0,n.jsx)("span",{className:"flow-graph-time",children:oj(t,e.durationMs)})]}):(0,n.jsx)("span",{className:"flow-graph-time-missing",children:t(r?"summary.time.running":"summary.time.unobserved")})}function oK({entry:e,together:t,batch:r=!1,st:a}){let i=e.maker.member.workClass;return(0,n.jsxs)("span",{className:"flow-graph-maker-tags",children:[(0,n.jsx)("span",{className:"flow-graph-chip","data-unknown":i?void 0:"",children:a(`graph.kind.${i??"unknown"}`)}),r&&e.batchSize>1&&(0,n.jsx)("span",{className:"flow-graph-chip",children:a("graph.parallel.batch")}),t&&(0,n.jsx)("span",{className:"flow-graph-chip","data-unknown":"unknown"===e.concurrency?"":void 0,"data-concurrency":e.concurrency,children:a(`graph.concurrency.${e.concurrency}`)})]})}function oG({selectable:e,selected:t,detailId:r,onSelect:a,className:i,children:s,style:o}){return e?(0,n.jsx)("button",{type:"button",className:i,style:o,"aria-pressed":t,"aria-controls":r,onClick:a,children:s}):(0,n.jsx)("div",{className:i,style:o,children:s})}function oJ({summary:e,makers:t,timings:r,live:i=!1,onOpenFile:s}){let o,l,c,{subagents:d,onOpenMaker:u}=(0,a.useContext)(s7),{st:p}=ag(),h=(0,a.useId)(),{flow:m}=e,f=(0,a.useMemo)(()=>(function(e,t,r,n){let a=function(e,t){let r=t.map(e=>null!==e.startedAt&&null!==e.durationMs?{start:e.startedAt,end:e.startedAt+e.durationMs}:null),n=e.startedAt,a=e.endedAt;for(let e of r)e&&((null===n||e.start<n)&&(n=e.start),(null===a||e.end>a)&&(a=e.end));let i=null!==n&&null!==a?a-n:0;return r.map(e=>e?i<=0||null===n?{offset:0,width:1}:{offset:(e.start-n)/i,width:(e.end-e.start)/i}:null)}(r,t),i=e.map(e=>"live"===e.runSource&&"running"===e.run),s=new Map;for(let t of e)s.set(t.member.toolCallId,(s.get(t.member.toolCallId)??0)+1);let o=e.map((r,n)=>{let o="unknown";for(let t=0;t<e.length;t+=1)if(t!==n&&(i[n]&&i[t]||r.observedParallelWith?.has(e[t].member.key))){o="overlapped";break}return{maker:r,bar:a[n],durationMs:t[n]?.durationMs??null,concurrency:o,batchSize:s.get(r.member.toolCallId)??1,liveRunning:i[n]}});return{makers:o,parallel:o.some(e=>"overlapped"===e.concurrency)?"observed":o.some(e=>e.batchSize>1)?"batch":"none",files:n.filter(e=>!oU.test(e.filePath)),docs:n.filter(e=>oU.test(e.filePath))}})(t,r,e.span,e.files),[t,r,e.span,e.files]),[g,x]=(0,a.useState)(void 0),v=oa(),b=e.files.length,y=i&&m.current?m.stages.find(e=>e.stage===m.current):void 0,w=void 0===g?y&&oq(y,m,b)?`stage:${y.stage}`:(o=m.stages.filter(e=>oq(e,m,b)),l=m.loops[m.loops.length-1],(c=(m.next?.returning&&l?o.find(e=>e.stage===l.from):void 0)??o.find(e=>"failed"===e.status)??o.find(e=>"unverified"===e.status||"stale"===e.status)??o.findLast(e=>"notNeeded"!==e.status&&"skipped"!==e.status)??o[o.length-1])?`stage:${c.stage}`:b>0?"files":null):g,k=m.loops[m.loops.length-1],j=k?io.indexOf(k.from):-1,S=io.indexOf("edit"),C=y?io.indexOf(y.stage):-1,N=f.makers.some(e=>e.liveRunning),T=f.files.length>0||f.docs.length>0,I=(0,a.useMemo)(()=>i?[]:function(e,t,r,n){let a=io.indexOf("edit"),i=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,s=[],o=r,l=e=>{let t=io.indexOf(e.stage);o&&t>a&&(s.push("branch"),o=!1),s.push(e.stage),o&&t===a&&(s.push("branch"),o=!1)},c=t[t.length-1];if(c){let t=io.indexOf(c.from);for(let r of e)io.indexOf(r.stage)<=t&&(i(r)||r.earlier.length>0||r.stage===c.from)&&l(r);for(let t of(o&&(s.push("branch"),o=!1),s.push("return"),e))io.indexOf(t.stage)>=a&&i(t)&&l(t)}else for(let t of e)i(t)&&l(t);return o&&s.push("branch"),n&&s.push("outputs"),s}(m.stages,m.loops,f.makers.length>0,T),[i,m.stages,m.loops,f.makers.length,T]),[M,E]=(0,a.useState)(null),$=null!==M&&M<I.length?M:null;(0,a.useEffect)(()=>{if(null===$)return;let e=window.setTimeout(()=>E($+1<I.length?$+1:null),800);return()=>window.clearTimeout(e)},[$,I.length]);let R=e=>{if(null!==$&&I.includes(e))return I[$]===e?"now":I.slice(0,$).includes(e)?"past":"ahead"},L=new Map;for(let e of f.makers){let t=e.maker.verdict?.verdict??"none";L.set(t,(L.get(t)??0)+1)}let A=1===L.size&&L.has("accepted"),P=m.stages[S+1],F=P?os(P,m,i):"skipped",_=f.makers.length>0&&(0,n.jsxs)("li",{className:"flow-graph-branch","data-loop":k&&j>S?"":void 0,"data-merge":"skipped"===F||"waiting"===F||"approval"===F?"quiet":void 0,"data-beat":R("branch"),children:[(0,n.jsxs)("p",{className:"flow-graph-branch-head",children:[(0,n.jsx)("span",{children:p(1===f.makers.length?"graph.branch.one":"graph.branch",{count:f.makers.length})}),"none"!==f.parallel&&(0,n.jsx)("span",{className:"flow-graph-chip","data-parallel":f.parallel,children:p(`graph.parallel.${f.parallel}`)})]}),(0,n.jsx)("ul",{className:"flow-graph-lanes",children:f.makers.map(e=>{let t=`maker:${e.maker.member.key}`;return(0,n.jsx)("li",{className:"flow-graph-lane","data-run":e.maker.run,"data-live":e.liveRunning?"":void 0,children:(0,n.jsxs)(oG,{selectable:!0,selected:w===t,detailId:h,onSelect:()=>x(w===t?null:t),className:"flow-graph-maker",children:[(0,n.jsx)("span",{className:"flow-graph-maker-name",title:e.maker.title,children:e.maker.title}),(0,n.jsx)(oK,{entry:e,together:f.makers.length>1,st:p}),(0,n.jsx)("span",{className:"flow-graph-maker-time",children:(0,n.jsx)(oV,{entry:e,st:p})}),(0,n.jsx)(oR,{maker:e.maker,st:p})]})},e.maker.member.key)})}),(0,n.jsxs)("p",{className:"flow-graph-join","data-state":A?"done":"unverified",children:[(0,n.jsx)(oc,{look:A?"done":"unverified"}),(0,n.jsx)("span",{className:"flow-graph-join-label",children:p("graph.join")}),(0,n.jsx)("span",{className:"flow-graph-join-counts",children:["accepted","rework","held","none"].filter(e=>L.has(e)).map(e=>(0,n.jsxs)("span",{className:"answer-status-verdict","data-verdict":e,children:[p(o$[e])," ",L.get(e)]},e))})]})]},"branch"),z=k&&(0,n.jsxs)("li",{className:"flow-graph-return","data-beat":R("return"),style:{"--from":S+1,"--to":j+1},children:[(0,n.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,n.jsxs)("span",{className:"flow-graph-return-text",children:[(0,n.jsx)("b",{children:p("flow.loop.badge",{attempt:m.attempt})})," ",p("review"===k.from?"flow.loop.findings":"flow.loop.failed",{stage:p(`flow.stage.${k.from}`),attempt:k.attempt})]})]},"return"),W=m.stages.map((e,t)=>{let r=os(e,m,i),a=`stage:${e.stage}`,s=e.steps.some(si);return(0,n.jsx)("li",{className:"flow-graph-station","data-stage":e.stage,"data-state":r,"data-again":e.earlier.length>0?"":void 0,"data-loop":k&&t>=S&&t<j?"":void 0,"data-beat":R(e.stage),"aria-current":"active"===r?"step":void 0,style:{"--col":t+1},children:(0,n.jsxs)(oG,{selectable:oq(e,m,b),selected:w===a,detailId:h,onSelect:()=>x(a),className:"flow-graph-stop",children:[(0,n.jsx)("span",{className:"flow-graph-stop-name",children:p(`flow.stage.${e.stage}`)}),(0,n.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,n.jsx)(oc,{look:r}),(0,n.jsx)("span",{className:"flow-graph-stop-word",children:(0,n.jsx)(ob,{view:e,flow:m,live:i,st:p})})]}),s&&(0,n.jsx)("span",{className:"flow-compound",children:p("flow.compound.failed")})]})},e.stage)}),O=[];W.forEach((e,t)=>{O.push(e),t===S&&_&&O.push(_),t===j&&z&&O.push(z)});let D=null;if(w?.startsWith("stage:")){let t=m.stages.find(e=>`stage:${e.stage}`===w);if(t){let r="ci"===t.stage&&null!==m.publication&&"notNeeded"===t.status,a="edit"===t.stage||r?[]:t.steps;D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"flow-graph-detail-title",children:p(`flow.stage.${t.stage}`)}),"ci"===t.stage&&m.publication&&(0,n.jsx)("p",{className:"flow-graph-note",children:"nothingToPublish"===m.publication.kind?p("flow.ci.nothingToPublish",{sha:m.publication.commit.slice(0,7)}):p("flow.ci.notNeeded",{run:m.publication.runId,repo:m.publication.repo,ref:m.publication.ref,sha:m.publication.sha.slice(0,7)})}),"edit"===t.stage&&(0,n.jsx)(aI,{files:e.files,onOpenFile:s}),(0,n.jsx)(ox,{view:t,steps:a,st:p}),(0,n.jsx)(og,{steps:t.earlier,st:p})]})}}else if(w?.startsWith("maker:")){let e=f.makers.find(e=>`maker:${e.maker.member.key}`===w);if(e){let t=a0(e.maker.member,d);D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,n.jsx)(oK,{entry:e,together:f.makers.length>1,batch:!0,st:p}),(0,n.jsx)("p",{className:"flow-graph-detail-line",children:(0,n.jsx)(oR,{maker:e.maker,st:p})}),(0,n.jsx)("div",{className:"flow-graph-maker-time",children:(0,n.jsx)(oV,{entry:e,st:p})}),(0,n.jsx)(oW,{maker:e.maker}),t&&u?(0,n.jsx)("button",{type:"button",className:"flow-graph-open",onClick:()=>u({key:`live:${t.id}`,toolCallId:e.maker.member.toolCallId,origin:e.maker.member.key,status:{run:e.maker.run,verdict:e.maker.verdict}}),children:p("graph.maker.open")}):(0,n.jsx)("p",{className:"flow-graph-note",children:p("graph.maker.unavailable")})]})}}else("files"===w||"docs"===w)&&(D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"flow-graph-detail-title",children:"files"===w?p(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length}):p(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})}),(0,n.jsx)(aI,{files:"files"===w?f.files:f.docs,onOpenFile:s})]}));return(0,n.jsxs)("section",{className:"flow-section",children:[(0,n.jsxs)("div",{className:"flow-graph-head",children:[(0,n.jsx)("h4",{className:"flow-heading",children:p("flow.heading")}),(C>=0||N)&&(0,n.jsx)(oi,{paused:v}),I.length>1&&(0,n.jsx)("button",{type:"button",className:"flow-graph-replay",onClick:()=>E(null===$?0:null),children:p(null===$?"graph.replay":"graph.replay.stop")})]}),(0,n.jsx)("div",{className:"flow-graph-frame",children:(0,n.jsxs)("ol",{className:"flow-graph","aria-label":p("flow.aria"),"data-live":i?"":void 0,"data-motion":v?"paused":void 0,"data-replay":null===$?void 0:"",children:[O,T&&(0,n.jsxs)("li",{className:"flow-graph-outputs","data-beat":R("outputs"),children:[(0,n.jsx)("span",{className:"flow-graph-outputs-label",children:p("graph.outputs")}),f.files.length>0&&(0,n.jsx)(oG,{selectable:!0,selected:"files"===w,detailId:h,onSelect:()=>x("files"),className:"flow-graph-output",children:p(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length})}),f.docs.length>0&&(0,n.jsx)(oG,{selectable:!0,selected:"docs"===w,detailId:h,onSelect:()=>x("docs"),className:"flow-graph-output",children:p(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})})]})]})}),D&&(0,n.jsx)("div",{className:"flow-graph-detail",id:h,role:"region","aria-label":p("graph.detail.aria"),children:D})]})}function oZ(e,t,r){let n=new URLSearchParams({type:t});return r&&n.set("sessionId",r),`/api/files/${tP(e)}?${n}`}function oY(e,t){let[r,n]=(0,a.useState)({kind:"loading"});return(0,a.useEffect)(()=>{let r=new AbortController;return n({kind:"loading"}),fetch(e,{method:"head"===t?"HEAD":"GET",cache:"no-store",signal:r.signal}).then(async e=>{if(!e.ok)return null;if("head"===t)return"";if("text"===t)return e.text();let r=await e.json();return"string"==typeof r.content?r.content:null}).then(e=>{r.signal.aborted||n(null===e?{kind:"failed"}:{kind:"ready",content:e})}).catch(()=>{r.signal.aborted||n({kind:"failed"})}),()=>r.abort()},[e,t]),r}function oX({messageKey:e}){let{st:t}=ag();return(0,n.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function oQ({deliverable:e,sessionId:t,title:r}){let{filePath:a,kind:i}=e;if("image"===i){let e=oZ(a,"read",t);return(0,n.jsx)(o8,{src:e,title:r},e)}if("html"===i){let e=oZ(a,"read",t);return(0,n.jsx)(o0,{url:e,title:r},e)}if(a.toLowerCase().endsWith(".pdf")){let e=oZ(a,"read",t);return(0,n.jsx)(o1,{url:e,title:r},e)}let s=oZ(a,"preview",t);return(0,n.jsx)(o2,{url:s,title:r},s)}function o0({url:e,title:t}){let r=oY(e,"json");return"ready"!==r.kind?(0,n.jsx)(oX,{messageKey:"failed"===r.kind?"result.previewFailed":"result.previewLoading"}):(0,n.jsx)("iframe",{className:"answer-result-media",srcDoc:r.content,sandbox:"allow-scripts",title:t,scrolling:"no",inert:!0})}function o1({url:e,title:t}){let r=oY(e,"head");return"ready"!==r.kind?(0,n.jsx)(oX,{messageKey:"failed"===r.kind?"result.previewFailed":"result.previewLoading"}):(0,n.jsx)("iframe",{className:"answer-result-media",src:`${e}#toolbar=0&view=FitH`,title:t,inert:!0})}function o2({url:e,title:t}){let r=oY(e,"text");return"ready"!==r.kind?(0,n.jsx)(oX,{messageKey:"failed"===r.kind?"result.previewFailed":"result.previewLoading"}):(0,n.jsx)("iframe",{className:"answer-result-media",srcDoc:r.content,sandbox:"allow-same-origin",title:t,inert:!0})}function o8({src:e,title:t}){let[r,i]=(0,a.useState)("loading");return"failed"===r?(0,n.jsx)(oX,{messageKey:"result.previewFailed"}):(0,n.jsxs)(n.Fragment,{children:["loading"===r?(0,n.jsx)(oX,{messageKey:"result.previewLoading"}):null,(0,n.jsx)("img",{className:"answer-result-media","data-fit":"contain",src:e,alt:t,draggable:!1,hidden:"loading"===r,onLoad:()=>i("ready"),onError:()=>i("failed")})]})}function o4({deliverables:e,onOpenFile:t}){let{sessionId:r}=(0,a.useContext)(s7),{st:i}=ag(),[o,l]=function(){let e=(0,a.useRef)(null),[t,r]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{let n=e.current;if(!n||t)return;if("u"<typeof IntersectionObserver)return void r(!0);let a=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&r(!0)},{rootMargin:"200px 0px"});return a.observe(n),()=>a.disconnect()},[t]),[e,t]}(),[c,...d]=e;if(!c)return null;let u=tF(c.filePath),p=i("result.previewTitle",{name:u}),h=t?()=>t(c.filePath):void 0;return(0,n.jsxs)("section",{className:"answer-result","aria-label":i("result.label"),children:[(0,n.jsxs)("div",{ref:o,className:"answer-result-frame","data-kind":c.kind,children:[l&&(0,n.jsx)(oQ,{deliverable:c,sessionId:r,title:p}),h&&(0,n.jsx)("button",{type:"button",className:"answer-result-cover",tabIndex:-1,"aria-hidden":"true",onClick:h})]}),(0,n.jsxs)("div",{className:"answer-result-bar",children:[(0,n.jsxs)("span",{className:"answer-result-title",children:[(0,n.jsx)("span",{className:"answer-result-kind",children:i("html"===c.kind?"result.kind.html":"image"===c.kind?"result.kind.image":c.filePath.toLowerCase().endsWith(".pdf")?"result.kind.pdf":"result.kind.document")}),(0,n.jsx)("span",{className:"answer-result-name",title:c.filePath,children:u})]}),h&&(0,n.jsx)(s.r,{className:"answer-result-open",variant:"neutralSolid",size:"medium",onClick:h,"aria-label":i("result.openNamed",{name:u}),children:i("result.open")})]}),d.length>0&&(0,n.jsxs)("div",{className:"answer-result-more",children:[(0,n.jsx)("span",{className:"answer-result-more-label",children:i("result.more",{count:d.length})}),(0,n.jsx)(aI,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}function o5({summary:e,live:t=!1,onOpenFile:r}){let{ledger:i,subagents:s,toolResults:o}=(0,a.useContext)(s7),{st:l}=ag(),c=(0,a.useMemo)(()=>t?[]:function(e){let t=[];for(let r of e){if(function(e){let t=e.toLowerCase().replace(/\\/g,"/").split("/");for(let e=0;e<t.length;e+=1){let r=t[e];if(Object.hasOwn(oD,r)||r.startsWith(".next")||"doc"===r&&"history"===t[e+1])return!0}return!1}(r.filePath))continue;let e=function(e){let t=eD(e);return"html"===t||"htm"===t?"html":eU(e)?"document":eH(e)?"image":null}(r.filePath);e&&t.push({filePath:r.filePath,kind:e})}return t.map((e,t)=>({deliverable:e,index:t})).sort((e,t)=>oH[e.deliverable.kind]-oH[t.deliverable.kind]||e.index-t.index).map(({deliverable:e})=>e)}(e.files),[t,e.files]),[d,u]=(0,a.useState)(null),p=d??(e.latest&&0===c.length),h=(0,a.useId)(),m=(0,a.useMemo)(()=>e.dispatchCalls.flatMap(e=>aJ(e,o.get(e.toolCallId))??[]).map(e=>aQ(e,s,i)),[e.dispatchCalls,o,s,i]),f=(0,a.useMemo)(()=>m.map(e=>({startedAt:i.spawnedAt.get(e.member.key)??null,durationMs:i.durations.get(e.member.key)??null})),[m,i]),{flow:g,remaining:x}=e,v=sa(g.steps),b=v.filter(e=>"failed"===e.outcome).length,y=v.filter(e=>"failed"===e.outcome||"unobserved"===e.outcome).length,w=v.filter(e=>e.compound?.failed).length,k=v.filter(e=>"unverified"===e.outcome&&!e.compound?.failed).length,j=v.filter(e=>e.stale).length,S=y+m.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted").length;if(0===g.steps.length&&(t||0===e.files.length&&0===e.checks.length&&0===m.length&&!x?.length))return null;let C=[l(1===e.files.length?"summary.files.one":"summary.files",{count:e.files.length}),l(1===v.length?"summary.checks.one":"summary.checks",{count:v.length})];t&&C.unshift(l("summary.live")),b>0&&C.push(l("summary.checksFailed",{count:b})),w>0&&C.push(l("summary.compoundFailed",{count:w})),m.length>0&&C.push(l(1===m.length?"summary.makers.one":"summary.makers",{count:m.length})),x&&C.push(l("summary.remaining",{count:x.length})),!t&&S>0&&C.push(l("summary.unverified",{count:S})),k>0&&C.push(l(1===k?"summary.verdictUnverified.one":"summary.verdictUnverified",{count:k})),j>0&&C.push(l("summary.stale",{count:j}));let N=!t&&S>0||b>0||k>0||w>0||j>0;return(0,n.jsxs)("div",{className:"answer-summary","data-open":p?"":void 0,"data-live":t?"":void 0,"data-result":c.length>0?"":void 0,children:[c.length>0&&(0,n.jsx)(o4,{deliverables:c,onOpenFile:r}),(0,n.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":p,"aria-controls":h,title:l(p?"summary.collapse":"summary.expand"),onClick:()=>u(!p),children:[(0,n.jsx)("span",{className:"answer-summary-text","data-unverified":N?"":void 0,children:C.join(" \xb7 ")}),(0,n.jsx)("svg",{className:"answer-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),p&&(0,n.jsxs)("div",{className:"answer-summary-body",id:h,children:[g.steps.length>0&&(0,n.jsx)(oJ,{summary:e,makers:m,timings:f,live:t,onOpenFile:r}),x&&(0,n.jsxs)("section",{className:"flow-remaining",children:[(0,n.jsx)("h4",{className:"flow-heading",children:l("summary.heading.remaining")}),0===x.length?(0,n.jsx)("p",{className:"answer-summary-empty",children:l("summary.todo.none")}):(0,n.jsx)("ul",{className:"flow-remaining-list",children:x.map((e,t)=>(0,n.jsxs)("li",{className:"answer-remaining","data-status":e.status,title:e.phase||void 0,children:[(0,n.jsx)("span",{className:"answer-remaining-status",children:l(`summary.todo.${e.status}`)}),(0,n.jsx)("span",{className:"answer-remaining-text",children:e.content}),e.blocker&&(0,n.jsx)("span",{className:"answer-remaining-blocker",children:l("summary.todo.blocker",{blocker:e.blocker})})]},`${e.phase}#${t}`))})]})]})]})}let o6=/^att_[0-9a-f]{32}$/,o3=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function o7(e){return"string"==typeof e&&o6.test(e)}function o9(e){return"string"==typeof e&&o3.test(e)}class le extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let lt={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},lr={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},ln={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function la(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let r=t.lastIndexOf(".");if(r>0&&lr[t.slice(r)])return"text";let n=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===n?"markdown":"application/pdf"===n?"pdf":n&&ln[n]?"text":null}let li={".mp3":"audio/mpeg",".wav":"audio/wav",".wave":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".oga":"audio/ogg",".opus":"audio/ogg",".flac":"audio/flac",".webm":"audio/webm",".aac":"audio/aac",".aif":"audio/aiff",".aiff":"audio/aiff"};function ls(e){let t=e.name.toLocaleLowerCase(),r=t.lastIndexOf("."),n=r>0?li[t.slice(r)]:void 0;if(n)return n;let a=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return a?.startsWith("audio/")?a:null}function lo(e,t){try{let r=new TextDecoder(e,{fatal:!0}).decode(t);return r.includes("\0")?null:r}catch{return null}}function ll(e){if(!Array.isArray(e))return[];let t=[],r=0,n=0;for(let a of e){if(a&&"object"==typeof a&&"string"==typeof a.name&&a.name.length>0&&("text/markdown"===a.mimeType||"text/plain"===a.mimeType||"application/pdf"===a.mimeType)&&"number"==typeof a.size&&Number.isSafeInteger(a.size)&&a.size>=0&&a.size<=8388608&&"string"==typeof a.text&&a.text.length<=12e4){if(t.length>=3)break;!(r+a.size>0x1000000)&&(n+a.text.length>24e4||(t.push({name:a.name,mimeType:a.mimeType,size:a.size,text:a.text,...o7(a.attachmentId)?{attachmentId:a.attachmentId}:{}}),r+=a.size,n+=a.text.length))}}return t}async function lc(e){let t,r=la(e);if(!r)throw new le("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new le("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===r)t=await lb(e);else{try{t=await e.text()}catch(e){throw new le("read_failed",e instanceof Error?e.message:String(e))}ly(t)}return{name:e.name,mimeType:lt[r],size:e.size,text:t}}function ld(e,t){let r=ll(t);if(0===r.length)return e;let n={userMessageLength:e.length,documents:r.map(({name:e,mimeType:t,size:r,text:n})=>({name:e,mimeType:t,size:r,textLength:n.length}))},a=`${lw}${JSON.stringify(n)}${lk}
|
|
@@ -17,7 +17,7 @@ ${t}`)),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(()=>new Set);if((0,a.use
|
|
|
17
17
|
${t}`,n=e8.get(r);if(void 0!==n)return Promise.resolve(n);let a=e4.get(r);if(a)return a;let i=fetch(e0(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),n=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return e8.set(r,n),n}).catch(()=>0).finally(()=>e4.delete(r));return e4.set(r,i),i})(e,t).then(e=>{r&&s(e)}),()=>{r=!1}},[i,e,t]),!i)return null;let u=Array.from({length:i},(e,t)=>t).filter(e=>!c.has(e));return 0===u.length?null:(0,n.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(a=>(0,n.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":r("i18n.zoomIn"),onClick:()=>l(a),children:(0,n.jsx)("img",{src:e0(e,t,a),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(a))})},a)),null!==o&&(0,n.jsx)(lH,{src:e0(e,t,o),fileName:`screen-${t.slice(-8)}-${o+1}`,onClose:()=>l(null)})]})}let lD={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function lH({src:e,fileName:t,onClose:r}){let{t:i}=(0,z.s)(),o=(0,a.useContext)(rI),l=(0,a.useRef)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)([]),[f,g]=(0,a.useState)(null),x=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=l.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{x.current?.abort(),document.body.style.overflow=t,e.open&&e.close()}},[]);let v=()=>{x.current?.abort(),r()},b=async()=>{let n,a;if(!o)return void p(i("toolImage.noComposer"));x.current?.abort();let s=new AbortController;x.current=s,d(!0),p(null);try{let r=await fetch(e,{signal:s.signal});if(!r.ok)throw Error(`HTTP ${r.status}`);let o=await r.blob(),l=lD[o.type];if(!l)throw Error(`unsupported ${o.type}`);if(0!==h.length&&f){let e=await rF(o,h);n=[new File([e.marked],`${t}-marked.png`,{type:"image/png"}),...e.crops.map((e,r)=>new File([e],`${t}-region-${r+1}.png`,{type:"image/png"}))];let r=1===h.length?"1":`1~${h.length}`;a=[i("toolImage.locatorIntro",{range:r}),...h.map((e,t)=>i("toolImage.locatorRegion",{n:t+1,x:e.x,y:e.y,w:e.w,h:e.h,width:f.width,height:f.height}))].join("\n")+"\n"}else n=[new File([o],`${t}.${l}`,{type:o.type})]}catch{if(s.signal.aborted)return;d(!1),p(i("toolImage.loadFailed"));return}if(!s.signal.aborted&&l.current?.open){if(!o(n,a)){d(!1),p(i("toolImage.noComposer"));return}r()}};return(0,q.createPortal)((0,n.jsxs)("dialog",{ref:l,className:"tool-image-dialog","aria-label":i("toolImage.dialogLabel"),onCancel:e=>{e.preventDefault(),v()},onClick:e=>{e.target===e.currentTarget&&v()},children:[(0,n.jsx)(r_,{src:e,regions:h,max:9,onAdd:e=>m(t=>t.length<9?[...t,e]:t),onNaturalSize:g,regionLabel:e=>i("toolImage.regionLabel",{n:e})}),u?(0,n.jsx)("p",{role:"alert",className:"tool-image-error",children:u}):(0,n.jsx)("p",{className:"tool-image-hint","data-hidden":h.length>0&&h.length<9?"true":void 0,children:h.length>=9?i("toolImage.markLimit",{count:9}):i("toolImage.markHint")}),(0,n.jsxs)("div",{className:"tool-image-actions",children:[(0,n.jsx)(s.r,{variant:"neutralSolid",size:"medium",loading:c,onClick:()=>void b(),title:i("toolImage.requestEditHint"),children:i("toolImage.requestEdit")}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"medium",disabled:0===h.length,onClick:()=>m([]),children:i("toolImage.clearMarks")}),(0,n.jsx)(s.r,{variant:"neutralWeak",size:"medium",onClick:v,children:i("i18n.close")})]})]}),document.body)}function lU({block:e,isStreaming:t,cwd:r,onOpenFile:a}){return(0,n.jsx)(lI,{isStreaming:t,cwd:r,onOpenFile:a,children:e.text})}function lB({block:e,duration:t,sessionId:r,entryId:i,blockIndex:s}){let{t:o}=(0,z.s)(),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!0===e.deferred),[p,h]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(!e.deferred){c(null),u(!1),h(null);return}let t=!1;return r&&i?(u(!0),h(null),(function(e,t,r){let n=`${e}:${t}:${r}`,a=lT.get(n);if(a)return lT.delete(n),lT.set(n,a),a;let i=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${r}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw lT.delete(n),e});if(lT.set(n,i),lT.size>100){let e=lT.keys().next().value;e&&lT.delete(e)}return i})(r,i,s).then(e=>{t||c(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(o("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,s,i,r,o]);let m=e.deferred?l:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,n.jsxs)("div",{className:"markdown-thinking","aria-label":o("i18n.thinking"),children:[(0,n.jsx)("div",{className:"markdown-thinking-content",children:d?(0,n.jsx)("span",{className:"markdown-thinking-status",children:o("i18n.loadingThinking")}):p?(0,n.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,n.jsx)(rb,{className:"markdown-thinking-body",children:m}):(0,n.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&f&&(0,n.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function lq({block:e,result:t,duration:r,runStartedAt:i,sessionId:s}){var o;let l,{t:c}=(0,z.s)(),d=(0,a.useId)(),[u]=(0,a.useState)(()=>Date.now()),[p,h]=(0,a.useState)(null),m=(o=t?null:rC(s,e.toolCallId),(0,a.useSyncExternalStore)(rS,()=>o?rw.get(o)??null:null,()=>null)),f=e.toolName.toLowerCase(),g=JSON.stringify(e.input,null,2),x="todo"===f||f.endsWith(".todo")||f.endsWith("_todo"),v="bash"===f||f.startsWith("bash ")||f.endsWith(".bash")||f.endsWith("_bash"),b=t&&!t.isError?function(e){var t;let r=e.details;if(!("object"==typeof(t=r)&&null!==t&&!Array.isArray(t)))return null;let n="string"==typeof r.patch?r.patch:null;if(n)return{text:n};let a="string"==typeof r.diff?r.diff:null;return a?{text:a}:null}(t):null,y=x?"unknown"===(l=tM(e,t)).kind||0===l.phases.length?null:l.phases:null,w=b?b.text.split(/\r?\n/).reduce((e,t)=>(t.startsWith("+")&&!t.startsWith("+++")&&(e.added+=1),t.startsWith("-")&&!t.startsWith("---")&&(e.removed+=1),e),{added:0,removed:0}):null,k=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,j=null!==k&&("(no output)"===k.trim()||""===k.trim()),S=t?rO(t):null,C=t?t.isError||null!==S&&0!==S?"failed":"done":"running",N="failed"===C,T=p??N;if(x&&y)return(0,n.jsx)(lX,{phases:y});let I=v&&"string"==typeof e.input.command?e.input.command:"",M=function(e,t,r){let n,a=t.html;if(!("ask"===(n=e.trim().toLowerCase())||n.endsWith(".ask")||n.endsWith("_ask"))||"string"!=typeof a)return null;let i="object"==typeof r&&null!==r?r:{},s=[];if(Array.isArray(i.answers))for(let e of i.answers)"string"==typeof e?.question&&"string"==typeof e.answer&&s.push({question:e.question,answer:e.answer});let o=!0===i.timedOut,l=s[0]?.question||a.replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi," ").replace(/<[^>]*>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s+/g," ").trim(),c=s.length>1?` (+${s.length-1})`:"",d=Math.max(0,120-c.length),u=l.length>d?`${l.slice(0,Math.max(0,d-1))}…`:l;return{target:`${u}${c}`,rows:s,timedOut:o}}(e.toolName,e.input,t?.details),E=null!==M&&M.rows.length>0?M:null,$=!!(y||b||E),R=v?I.split(/\r?\n/,1)[0]??"":M?.target??function(e,t){if(t){let e=t.flatMap(e=>e.tasks),r=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${r}/${e.length} tasks`}return function(e){var t;let r=e.input;if(!r||"object"!=typeof r)return"";let n=Object.keys(r);if(0===n.length)return"";let a=e.toolName.toLowerCase();if(t=a,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof r.i){let e=r.i.trim();if(e)return e.slice(0,120)}if(("eval"===a||a.endsWith(".eval")||a.endsWith("_eval"))&&"string"==typeof r.title){let e=r.title.trim();if(e)return e.slice(0,120)}if("command"in r)return String(r.command).slice(0,120);if("path"in r)return String(r.path).slice(-120);if("file_path"in r)return String(r.file_path).slice(-120);if("pattern"in r)return String(r.pattern).slice(0,120);if("query"in r)return String(r.query).slice(0,120);let i=n.map(e=>r[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==i)return String(i).slice(0,120);try{return JSON.stringify(r).slice(0,120)}catch{return n.join(", ").slice(0,120)}}(e)}(e,y),L=!v&&/^\S+$/.test(R)&&/[\\/]/.test(R),A=w?c("toolRun.diffStats",{added:w.added,removed:w.removed}):"";return(0,n.jsxs)("div",{className:`tool-call-card ${N?"is-error":"running"===C?"is-running":"is-done"}${v?" is-shell":""}`,"aria-busy":"running"===C||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,n.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>h(!T),"aria-expanded":T,"aria-controls":T?d:void 0,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,n.jsx)(lZ,{toolName:e.toolName}),(0,n.jsx)("span",{className:"tool-call-name",children:v?"bash":e.toolName}),v&&f.includes("(local)")&&(0,n.jsx)("span",{className:"shell-local-label",children:"local"}),(0,n.jsx)("span",{className:`tool-call-target${L?" is-path":""}`,title:v?I:R,children:L?(0,n.jsx)("bdi",{dir:"ltr",children:R}):R}),w&&(0,n.jsxs)("span",{className:"tool-call-diffstats",title:A,"aria-label":A,children:[(0,n.jsxs)("span",{style:{color:"var(--success)"},children:["+",w.added]}),(0,n.jsxs)("span",{style:{color:"var(--danger)"},children:["−",w.removed]})]}),(0,n.jsx)(lK,{state:C,duration:r,exitCode:S,startedAt:i??u}),(0,n.jsx)("svg",{className:"tool-call-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:T?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),"running"===C&&m&&(0,n.jsx)("div",{className:"tool-call-progress",title:m,style:{padding:"0 10px 6px 29px",color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:m}),T&&(0,n.jsx)("div",{id:d,className:"tool-call-body",children:v?(0,n.jsx)(lQ,{command:I,output:k??"",pending:!t,isError:N}):(0,n.jsxs)(n.Fragment,{children:[b&&(0,n.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,n.jsx)(l0,{diff:b})}),t&&N&&(0,n.jsx)(l5,{text:k??"",isEmpty:j,isError:!0}),E&&!N&&(0,n.jsx)(lV,{summary:E}),!$&&(0,n.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:g}),t&&!$&&!N&&(0,n.jsx)(l5,{text:k??"",isEmpty:j,isError:!1})]})})]})}function lV({summary:e}){let{t}=(0,z.s)();return(0,n.jsxs)("div",{className:"tool-call-ask",style:{padding:"8px 10px"},children:[(0,n.jsx)("dl",{style:{margin:0,display:"grid",gap:8},children:e.rows.map((e,t)=>(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("dt",{style:{color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflowWrap:"anywhere"},children:e.question}),(0,n.jsx)("dd",{style:{margin:"2px 0 0",color:"var(--text)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:""===e.answer?"—":e.answer})]},t))}),e.timedOut&&(0,n.jsx)("p",{style:{margin:"8px 0 0",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:t("toolRun.askTimedOut")})]})}function lK({state:e,duration:t,exitCode:r,startedAt:a}){let{t:i}=(0,z.s)();return"running"===e?(0,n.jsx)(lG,{startedAt:a}):(0,n.jsxs)(n.Fragment,{children:[void 0!==t&&(0,n.jsxs)("span",{className:"tool-run-duration",children:[t,"s"]}),"failed"===e&&(0,n.jsxs)("span",{className:"tool-run-failed",children:[(0,n.jsx)(rT.E,{tone:"critical",variant:"weak",size:"medium",children:i("toolRun.failed")}),null!==r&&(0,n.jsx)("span",{className:"tool-run-exit",children:i("toolRun.exitCode",{code:r})})]})]})}function lG({startedAt:e}){let{t}=(0,z.s)(),r=ry(500)-e;return r<400?null:(0,n.jsxs)("span",{className:"tool-run-running",children:[t("toolRun.running"),(0,n.jsxs)("span",{className:"tool-run-duration",children:[Math.floor(r/1e3),"s"]})]})}function lJ(e,t){let r=e.trim().toLowerCase();return r===t||r.endsWith(`.${t}`)||r.endsWith(`_${t}`)||r.split(/[.\s:_-]+/).includes(t)}function lZ({toolName:e}){let t,r=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||lJ(t,"edit")?"edit":lJ(t,"read")||lJ(t,"cat")?"read":lJ(t,"write")||lJ(t,"save")?"write":lJ(t,"glob")||lJ(t,"find")?"glob":lJ(t,"grep")||lJ(t,"search")?"grep":lJ(t,"bash")||lJ(t,"shell")||lJ(t,"exec")?"bash":lJ(t,"todo")?"todo":lJ(t,"eval")?"eval":lJ(t,"task")||lJ(t,"agent")?"task":lJ(t,"browser")||lJ(t,"web_search")||lJ(t,"fetch")?"browser":lJ(t,"image")||lJ(t,"inspect_image")?"image":"generic";return(0,n.jsx)("span",{"aria-hidden":"true","data-tool-icon":r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:"var(--text-muted)"},children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)(lY,{kind:r})})})}function lY({kind:e}){switch(e){case"read":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,n.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,n.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,n.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,n.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,n.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,n.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,n.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,n.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,n.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,n.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,n.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,n.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,n.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,n.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,n.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,n.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,n.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function lX({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),r=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,n.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,n.jsxs)("div",{className:"todo-checklist-header",children:[(0,n.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,n.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,n.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,n.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),r>0&&r<t&&(0,n.jsxs)("span",{className:"todo-checklist-progress",children:[r,"/",t]})]}),(0,n.jsx)("div",{className:"todo-checklist-body",children:e.map((t,r)=>(0,n.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,n.jsx)(aw,{task:e},`${e.content}-${t}`))]},`${t.name}-${r}`))})]})}function lQ({command:e,output:t,pending:r,isError:a}){let{isDark:i}=rh(),{t:s}=(0,z.s)(),o=eP(t.split(/\r?\n/)),l=1===o.length&&""===o[0]?[]:o;return(0,n.jsxs)("div",{className:`shell-output-preview${a?" is-error":""}`,children:[(0,n.jsxs)("div",{className:"shell-command-line",children:[(0,n.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,n.jsx)(tz.A,{className:"shell-command-code",language:"bash",style:i?tW.xJ:tW.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "})]}),(0,n.jsxs)("div",{className:"shell-output-panel",children:[(0,n.jsx)("div",{className:"shell-output-divider",children:(0,n.jsx)("span",{className:"shell-output-label",children:"Output"})}),(0,n.jsxs)("div",{className:"shell-output-body",children:[0===l.length&&!r&&(0,n.jsx)("span",{className:"shell-output-empty",children:s("i18n.noOutput")}),l.map((e,t)=>{let r=e$(e).trimStart(),i=a||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(r)?"is-error":/^(?:warning|warn|!)/i.test(r)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(r)?"is-success":"";return(0,n.jsxs)("div",{className:`shell-output-line ${i}`.trim(),children:[eF(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},t):(0,n.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)})]})]})]})}function l0({diff:e}){return(0,n.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,n.jsx)(l1,{text:e.text})})}function l1({text:e}){let{t}=(0,z.s)(),r=(0,a.useMemo)(()=>ab(e),[e]);if(!r)return(0,n.jsx)(l4,{text:e});let i=r.length>1;return(0,n.jsx)("div",{style:{background:"var(--bg)"},children:r.map((e,r)=>(0,n.jsxs)("div",{style:{minWidth:0,borderTop:0===r?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[i&&(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)(l2,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,n.jsx)(l2,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,n.jsxs)("div",{style:{display:"contents"},children:[(0,n.jsx)(l8,{cell:e.left,side:"left"}),(0,n.jsx)(l8,{cell:e.right,side:"right"})]},t))})]},r))})}function l2({title:e,side:t}){return(0,n.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function l8({cell:e,side:t}){let r="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",a="added"===e.type?"+":"removed"===e.type?"-":" ",i="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",minWidth:0,background:r,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,n.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,n.jsx)("span",{style:{width:18,padding:"0 5px",color:i,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:a}),(0,n.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function l4({text:e}){let t=e.split(/\r?\n/);return(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let r=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,n.jsxs)("div",{style:{display:"flex",background:"added"===r?"var(--success-soft)":"removed"===r?"var(--danger-soft)":"hunk"===r?"var(--accent-soft)":"transparent",borderLeft:"added"===r?"3px solid var(--success)":"removed"===r?"3px solid var(--danger)":"hunk"===r?"3px solid var(--accent)":"3px solid transparent"},children:[(0,n.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,n.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===r?"var(--success)":"removed"===r?"var(--danger)":"hunk"===r?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function l5({text:e,isEmpty:t,isError:r}){let{t:a}=(0,z.s)();return(0,n.jsx)("div",{style:{borderTop:`1px solid ${r?"var(--danger-line)":"var(--success-line)"}`,background:r?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,n.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:r?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?a("i18n.noOutput"):e})})}function l6({message:e}){let{t}=(0,z.s)(),r=ce(e.content),i=(0,a.useMemo)(()=>{let e,t,n,a,i;return e=[],t=[],n=r.match(rH),a=n?.[1]??"",i=n?.index===void 0?r:r.slice(0,n.index),a.replace(rD,(r,n,a)=>{let i=a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===n?e.push(...i):t.push(...i),""}),{body:i.trim(),readFiles:e,modifiedFiles:t}},[r]),s=lR(e.timestamp),o=e.details&&"object"==typeof e.details&&"tokensBefore"in e.details&&"number"==typeof e.details.tokensBefore&&e.details.tokensBefore>0?e.details.tokensBefore:null;return(0,n.jsx)("div",{style:{marginBottom:16},children:(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",overflow:"hidden",background:"var(--bg)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==o&&(0,n.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:rU(o)})}),s&&(0,n.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,n.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,n.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),i.body?(0,n.jsx)(rb,{className:"markdown-compaction-message",children:i.body}):(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,n.jsx)(l3,{readFiles:i.readFiles,modifiedFiles:i.modifiedFiles})]})]})})}function l3({readFiles:e,modifiedFiles:t}){let{t:r}=(0,z.s)();if(0===e.length+t.length)return null;let a=[];return e.length>0&&a.push(`${e.length} read`),t.length>0&&a.push(`${t.length} modified`),(0,n.jsxs)("details",{className:"compaction-file-details",children:[(0,n.jsx)("summary",{children:r("i18n.fileContext",{details:a.join(", ")})}),t.length>0&&(0,n.jsx)(l7,{title:r("i18n.modifiedFiles"),files:t}),e.length>0&&(0,n.jsx)(l7,{title:r("i18n.readFiles"),files:e})]})}function l7({title:e,files:t}){return(0,n.jsxs)("div",{className:"compaction-file-section",children:[(0,n.jsx)("div",{className:"compaction-file-title",children:e}),(0,n.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,n.jsx)("li",{children:e},e))})]})}function l9({message:e,cwd:t,onOpenFile:r}){var i;let s,{t:o}=(0,z.s)(),l=!1===e.display,[c,d]=(0,a.useState)(!l),[u,p]=(0,a.useState)(!1),[h,m]=(0,a.useState)(!1),f=ce(e.content),g="string"==typeof(i=e.content)?[]:i.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=lR(e.timestamp);return(0,n.jsx)("div",{style:{marginBottom:16},children:(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",overflow:"hidden",background:l?"var(--bg-subtle)":"var(--bg)",opacity:l&&!c?.82:1},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),l&&(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),y&&(0,n.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),c?(0,n.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,n.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let r=ct(e);return r?(0,n.jsx)("img",{src:r,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,n.jsx)(rb,{className:"markdown-custom-message",cwd:t,onOpenFile:r,children:f}):(0,n.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}):(0,n.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(s=f.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":o("i18n.showExtensionMessage")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,n.jsx)("button",{className:"message-meta-action",onClick:()=>{rm(f||v).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(h?"i18n.copied":"i18n.copy")}):null,(x||l)&&(0,n.jsx)("button",{onClick:()=>{l?d(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(l?c?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(l&&c||!l&&u)&&(0,n.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function ce(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function ct(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}function cr({message:e,sessionId:t}){let[r,i]=(0,a.useState)(null),[s,o]=(0,a.useState)(!1),[l,c]=(0,a.useState)(null),d=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===r,m=r??e.output;async function f(){if(p){o(!0),c(null);try{let e=await fetch(p),t=await e.json();t.success?i(t.data?.output??""):c(t.error??"failed")}catch(e){c(String(e))}finally{o(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=d?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:m?[{type:"text",text:m}]:[],isError:u,details:void 0!==e.exitCode?{exitCode:e.exitCode}:void 0,timestamp:e.timestamp};return(0,n.jsxs)("div",{style:{margin:"6px 0"},children:[(0,n.jsx)(lq,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&p&&(0,n.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,n.jsx)("button",{onClick:f,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,n.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),l&&(0,n.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",l,")"]})]})]})}r(21340);let cn="cuelo-chat-search",ca="cuelo-chat-search-active";function ci(e,t){if("u">typeof CSS&&"highlights"in CSS){if(0===t.length||"u"<typeof Highlight)return void CSS.highlights.delete(e);CSS.highlights.set(e,new Highlight(...t))}}function cs({open:e,onClose:t,containerRef:r,index:i,renderedStart:s,renderedEnd:o,contentKey:l,onReveal:c,onProgrammaticScroll:d,focusRequest:u,t:p}){let h=(0,a.useRef)(null),[m,f]=(0,a.useState)(""),[g,x]=(0,a.useState)(null),[v,b]=(0,a.useState)({index:-1,total:0}),y=(0,a.useDeferredValue)(m),w=e?y.trim().toLowerCase():"",k=(0,a.useRef)(g);k.current=g;let j=(0,a.useRef)([]),S=(0,a.useRef)({key:null,needle:"",rendered:!1});(0,a.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,a.useEffect)(()=>()=>{ci(cn,[]),ci(ca,[])},[]),(0,a.useLayoutEffect)(()=>{let t=r.current;if(!e||!w||!t){ci(cn,[]),ci(ca,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let n=requestAnimationFrame(()=>{let e=function(e,t){let r=new Map,n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=n.nextNode();e;e=n.nextNode()){let n=e.parentElement?.closest("[data-chat-item]"),a=n?Number(n.dataset.chatItem):NaN;if(!Number.isInteger(a))continue;let i=(e.textContent??"").toLowerCase(),s=r.get(a);s||(s=[],r.set(a,s));for(let r=i.indexOf(t);-1!==r;r=i.indexOf(t,r+t.length)){let n=document.createRange();n.setStart(e,r),n.setEnd(e,r+t.length),s.push(n)}}return r}(t,w),r=new Map;for(let[t,n]of e)r.set(t,n.length);let n=function(e,t,r,n,a){let i=[];if(!t)return i;for(let s=0;s<e.length;s++){let o=s>=n&&s<a?r.get(s)??0:function(e,t){if(!t)return 0;let r=0;for(let n=e.indexOf(t);-1!==n;n=e.indexOf(t,n+t.length))r+=1;return r}(e[s],t);for(let e=0;e<o;e++)i.push({item:s,k:e})}return i}(i,w,r,s,o);j.current=n;let a=tc(n,k.current);b(e=>e.index===a&&e.total===n.length?e:{index:a,total:n.length});let l=[];for(let t of e.values())for(let e of t)l.push(e);if(ci(cn,l),a<0){ci(ca,[]),S.current={key:null,needle:w,rendered:!1};return}let u=n[a],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=s&&u.item<o,m=S.current,f=m.needle!==w||m.key?.item!==u.item||m.key?.k!==u.k||!m.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){ci(ca,[]),f&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(ci(ca,g?[g]:[]),f)if(d(),g){let e,r;e=g.getBoundingClientRect(),r=t.getBoundingClientRect(),e.height<=0||e.top>=r.top+48&&e.bottom<=r.bottom-48||(t.scrollTop+=e.top-r.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(n)},[e,w,i,s,o,l,g,r,c,d]);let C=(0,a.useCallback)(e=>{let t=j.current;if(0===t.length)return;let r=tc(t,k.current);x(t[(r+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,n.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,n.jsx)("input",{ref:h,type:"search",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,n.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,n.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,n.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M18 6 6 18"}),(0,n.jsx)("path",{d:"m6 6 12 12"})]})})]})}function co({questions:e,containerRef:t,layoutKey:r,onJump:i,label:s}){let o=(0,a.useRef)(null),[l,c]=(0,a.useState)(-1),[d,u]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=d&&e.length>=2;(0,a.useEffect)(()=>{let r=t.current;if(!r||!p)return;let n=0,a=null,i=()=>{n=0,a?.[0]?.isConnected||(a=r.querySelectorAll("[data-chat-item]"));let t=r.getBoundingClientRect().top+8,i=0,s=a.length-1,o=a.length-1;for(;i<=s;){let e=i+s>>1,r=a[e].firstElementChild?.getBoundingClientRect();r&&r.bottom>t?(o=e,s=e-1):i=e+1}let l=o>=0?Number(a[o].dataset.chatItem):-1,d=-1;for(let t of e){if(t.item>l)break;d=t.item}c(d)},s=()=>{n||(n=requestAnimationFrame(i))};return n=requestAnimationFrame(i),r.addEventListener("scroll",s,{passive:!0}),()=>{r.removeEventListener("scroll",s),n&&cancelAnimationFrame(n)}},[e,p,r,t]),(0,a.useEffect)(()=>{let e=o.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let r=t.offsetTop-e.scrollTop;(r<0||r+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[l]);let h=e.length,m=(0,a.useCallback)((e,t)=>{let r="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===r)return;e.preventDefault();let n=Math.max(0,Math.min(h-1,r));o.current?.querySelectorAll("button")[n]?.focus()},[h]);if(!p)return null;let f=e.some(e=>e.item===l)?l:e[0].item;return(0,n.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,n.jsx)("div",{ref:o,className:"question-rail-list",children:e.map((e,t)=>(0,n.jsx)(cl,{question:e,position:t,count:h,active:e.item===l,focusable:e.item===f,onJump:i,onMoveFocus:m},e.item))})})}let cl=(0,a.memo)(function({question:e,position:t,count:r,active:a,focusable:i,onJump:s,onMoveFocus:o}){let l=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,n.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:i?0:-1,"aria-current":a?"true":void 0,"aria-label":`${t+1}/${r} ${l}`,title:l,onClick:()=>s(e.item),onKeyDown:e=>o(e,t),children:(0,n.jsx)("span",{"aria-hidden":"true"})})});function cc({label:e,tone:t,children:r}){return(0,n.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"run-status-label",children:e}),(0,n.jsx)("span",{className:"run-status-text",children:r})]})}let cd={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function cu({compaction:e,t}){let[r,i]=(0,a.useState)(()=>Date.now());if((0,a.useEffect)(()=>{if(!e)return;i(Date.now());let t=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((r-e.startedAt)/1e3)),o=e.reason&&!0===cd[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,n.jsxs)(cc,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),o?` \xb7 ${o}`:""]})}function cp({onDismiss:e,t}){return(0,n.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,n.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,n.jsxs)("span",{className:"interrupted-run-text",children:[(0,n.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,n.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,n.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M18 6 6 18"}),(0,n.jsx)("path",{d:"m6 6 12 12"})]})})]})}var ch=r(39092),cm=r.n(ch);let cf=["01","02","03"];function cg(e){let t=0x811c9dc5;for(let r=0;r<e.length;r+=1)t=Math.imul(t^e.charCodeAt(r),0x1000193);return(t>>>0)/0x100000000}function cx(e,t,r){if(e&&"streaming"!==t){let n=nR(e);if(n){let e="failed"===t?"failed":"done",a=na(nr(n$(n),n.id,e)?.stickers??[],null,()=>cg(r));return a?{src:a,alt:r8[e]}:null}}if(!e||"streaming"===t||!r0.includes(e))return null;let n="failed"===t?"failed":"done",a=e.slice(0,e.indexOf("(")).toLowerCase(),i=na(cf.map(e=>`/stickers/${a}/${n}/${e}.webp`),null,()=>cg(r));return i?{src:i,alt:r8[n]}:null}let cv=new Map,cb=(0,a.createContext)(cv);function cy({utterances:e,children:t}){return(0,n.jsx)(cb.Provider,{value:e,children:t})}function cw({turnIndex:e,turnEntryId:t,sessionId:r,cwd:i,onOpenFile:s}){let o=(0,a.useContext)(cb).get(e);return o&&0!==o.length?(0,n.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:o.map(e=>(0,n.jsx)(ck,{utterance:e,sessionId:r,cwd:i,onOpenFile:s},e.key))}):null}function ck({utterance:e,sessionId:t,cwd:r,onOpenFile:i}){let s=ah(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId,e.model),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(!1),u=(0,a.useRef)(null);(0,a.useLayoutEffect)(()=>{let e=u.current;e&&!o&&d(e.scrollHeight>e.clientHeight+1)},[e.text,o]);let p=e.text.trim().length>0,h=e.label?.trim(),m=s?.alias??h??nq(e.provider),f=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==f?`작업 \xb7 ${h}`:null,x=cx(s?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,n.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,n.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...s?{minHeight:40}:null},children:[s&&(0,n.jsx)(ax,{seed:s.seed,size:40,provider:e.provider}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,n.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,n.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,n.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,n.jsx)(rb,{isStreaming:"streaming"===e.status,cwd:r,onOpenFile:i,children:e.text})}):(0,n.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(c||o)&&(0,n.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:o?"접기":"더보기"}),x&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-e0a9ca790f024efb inline-utterance-sticker"}),(0,n.jsx)(cm(),{id:"e0a9ca790f024efb",children:".inline-utterance-sticker{transform-origin:center 75%;animation:inline-utterance-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes inline-utterance-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.inline-utterance-sticker{animation:none}}"})]})]})}let cj=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function cS(e,t,r,n){if("string"!=typeof r)return[];let a=cj.exec(r),i=a?.[1],s=a?.[2];return i&&s?[{toolCallId:e,...t?{name:t}:{},alias:i,model:s,batchSize:n}]:[]}function cC(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let r of e.content??[]){if("toolCall"!==r.type||"task"!==r.toolName)continue;let e=r.input,n=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...cS(r.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,n)),Array.isArray(e.tasks))for(let a of e.tasks)!a||"object"!=typeof a||Array.isArray(a)||t.push(...cS(r.toolCallId,"name"in a&&"string"==typeof a.name?a.name:void 0,"task"in a?a.task:void 0,n))}return t}function cN(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let r of e.content??[])"toolCall"===r.type&&"task"===r.toolName&&t.push(r.toolCallId);return t}let cT=/^agent:\/\/([^/?#]+)\/?$/i;function cI(e,t){if(!e||"assistant"!==e.role)return[];let r=[];for(let n of e.content??[]){if("toolCall"!==n.type||"write"!==n.toolName)continue;let e=n.input,a="string"==typeof e.path?cT.exec(e.path):null,i=a?.[1],s=e.content;if(!i||"string"!=typeof s)continue;let o=t?.get(n.toolCallId);r.push({toolCallId:n.toolCallId,to:i,message:s,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return r}function cM(e,t,r){for(let n of["string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",t?.model.trim()??""]){let e=n.indexOf("/");if(e>0&&n.slice(0,e)===r)return n.slice(e+1).trim()||void 0}}let cE=["greeting","utterance","message","text"],c$=function(e){let t=(0,a.useMemo)(()=>aW(),[]),r=function(e,t){let[r,n]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(!t)return void n(null);let r=!1,a=new AbortController;return n(null),e.getArchive(t,a.signal).then(e=>{r||n(e)}).catch(()=>{}),()=>{r=!0,a.abort()}},[e,t]),r}(t,e.sessionId),n=(0,a.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),n=[];if(r&&r.sessionId===e.sessionId){let a=e.turns.flatMap(e=>e.characterSummons);for(let i of r.subagents){if(t.has(i.name))continue;let r=[...a].reverse().find(e=>e.name===i.name);r&&n.push(function(e,t,r){let n=e.status??"unknown",a={id:e.name,index:r,agent:"",agentSource:"bundled",status:n,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},i="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,s="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==i||void 0!==s)&&(a.progress={index:r,id:e.name,agent:"",status:n,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==i?{resolvedModel:i,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),a}(i,r,e.subagents.length+n.length))}}return function(e,t){let r=new Map;for(let t of e)for(let e of t.characterSummons){let n=r.get(e.toolCallId)??{turnIndex:t.index,requests:[]};n.requests.push(e),r.set(e.toolCallId,n)}return t.flatMap(t=>{let n=t.parentToolCallId?r.get(t.parentToolCallId):void 0;if(!n)return[];let a=n.requests.filter(e=>e.name),i="string"==typeof t.task?cj.exec(t.task):null,s=i?.[1],o=i?.[2],l=a.find(e=>e.name===t.id)??(s&&o?n.requests.find(e=>e.alias===s&&e.model===o):void 0)??(1===n.requests.length&&1===n.requests[0].batchSize?n.requests[0]:void 0);if(!l)return[];let c=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:n.turnIndex,summon:l,sends:c}]})}(e.turns,[...e.subagents,...n])},[e.subagents,e.turns,e.sessionId,r]),i=(0,a.useMemo)(()=>n.map(({snapshot:t})=>{let r=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:r}:{key:t.id,status:t.status,archiveName:r}}),[n,e.subagents]),s=s3(i,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&i.length>0});return(0,a.useMemo)(()=>n.flatMap(t=>(function(e,t,r){var n;let{snapshot:a,summon:i}=e,s="completed"===(n=a.status)||"unknown"===n?"settled":"failed"===n||"aborted"===n?"failed":"streaming",o="failed"===s,l=i?.model.split("/",1)[0]?.trim()||void 0,c=o&&l?l:function(e,t,r){let n="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",a=n.indexOf("/");if(a>0)return n.slice(0,a);let i=t?.model.trim()??"",s=i.indexOf("/");return s>0?i.slice(0,s):r?.trim()||void 0}(a,i,r),d=a.id.trim()||void 0,u=`subagent:${a.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,r)=>{var n;let f;if("irc"in t){let{from:r,message:n,truncated:i}=t.irc;if(i||"string"!=typeof r||"string"!=typeof n)return;for(let t=m;t<e.sends.length;t+=1){let i=e.sends[t];if(i.send.message===n&&function(e,t){if(!e.from)return!1;let r=e.receipts;return!!r&&r.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(i.send,a.id)&&i.send.from===r){h=i.turnIndex,m=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||c;if(!g||o&&l&&g!==l)return;let x=((f=((n=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let r of e.content??[]){if("toolCall"!==r.type||"yield"!==r.toolName)continue;let e=r.input.data,n="";if("string"==typeof e)n=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...cE]){let r=e[t];if("string"==typeof r&&r.trim().length>0){n=r;break}}let a=n.trim();a.length>0&&(t=a)}return t}(n))||(o?t.message.errorMessage?.trim()??"":"");if(0===x.length)return;let v=t.message.model||cM(a,i,g);p.push({key:`${a.id}:${r}`,turnIndex:h,speakerId:u,provider:g,...v?{model:v}:{},credentialId:t.message.credentialId,accountSessionId:null,label:o&&i?i.alias:d,text:x,status:s})}),0===p.length&&"settled"!==s&&c){let e=o?a.progress?.retryFailure?.errorMessage?.trim():void 0,t=cM(a,i,c);p.push({key:`${a.id}:pending`,turnIndex:h,speakerId:u,provider:c,...t?{model:t}:{},accountSessionId:null,label:o&&i?i.alias:d,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[n,s,e.sessionProvider])},cR="web6",cL=[],cA=[],cP=function(e){let t=(0,a.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(r,n){let a=r.trim();if(!a)throw Error("sessionId가 필요하다");let i=`${t}?sessionId=${encodeURIComponent(a)}`,s=await e(i,{signal:n});if(!s.ok)throw Error(`HTTP ${s.status}`);let o=await s.json(),l=o&&"object"==typeof o&&"consults"in o?o.consults:null;if(!Array.isArray(l))throw Error("consults 배열이 아니다");return l.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let r=e.startedAt;if("number"!=typeof r||!Number.isFinite(r))return null;let n=e.status;if("ok"!==n&&"failed"!==n)return null;let a="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:r,{conversationId:i,text:s,error:o}=e;return{sessionId:t,startedAt:r,finishedAt:a,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:a-r,model:"string"==typeof e.model?e.model:"",status:n,conversationId:"string"==typeof i&&""!==i?i:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof o&&""!==o?o:void 0}}(e);return t?.sessionId===a?[t]:[]})}}})(),[]),[r,n]=(0,a.useState)(cA),i=(0,a.useRef)(""),s=e.sessionId??"",o=s.length>0;return(0,a.useEffect)(()=>{if(!o){i.current="",n(cA);return}let e=new AbortController,r=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let r=await t.listConsults(s,e.signal),a=r.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(a===i.current)return;i.current=a,n(r)}catch{}};r();let a=setInterval(()=>void r(),5e3);return()=>{e.abort(),clearInterval(a)}},[t,o,s]),(0,a.useMemo)(()=>(function(e,t,r){if(0===e.length)return cL;let n=function(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e[r];if("user"!==n.role)continue;let a=n.timestamp;"number"==typeof a&&Number.isFinite(a)&&t.push({index:r,openedAt:a})}return t}(t);if(0===n.length)return cL;let a=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==r||"failed"!==t.status)continue;let e=function(e,t){let r;for(let n of e)n.openedAt>t||(!r||n.openedAt>=r.openedAt)&&(r=n);return r?.index}(n,t.startedAt);if(void 0===e)continue;let i=t.error??"";0!==i.trim().length&&a.push({key:`${cR}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${cR}:${t.conversationId??"unknown"}`,text:i,status:"failed"})}return a.length>0?a:cL})(r,e.messages,s),[r,e.messages,s])},cF="lab:";function c_(e){return e.startsWith(cF)?e.slice(cF.length).split(":",1)[0]||null:null}let cz={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function cW(e){return e.multi&&e.options.length>1}function cO(e){return"text"===e.kind?{kind:"text",text:e.value}:{kind:"choice",checked:e.options.flatMap((e,t)=>e.checked?[t]:[]),otherOn:!1,other:""}}function cD(e,t){let r={};for(let[t,n]of e.hidden)cq(r,t,n);return e.fields.forEach((e,n)=>{let a=t[n];if(!e.name||!a)return;let i=function(e,t){if("text"===e.kind){var r,n,a="text"===t.kind?t.text:"";if(("number"===e.type||"range"===e.type)&&""!==a.trim()){let e=Number(a);if(Number.isFinite(e))return e}return a}if("choice"===t.kind){let a,i;return r=new Set(t.checked),n=t.otherOn?t.other:void 0,a=e.other?n?.trim():void 0,i=e.options.flatMap((e,t)=>r.has(t)&&!e.disabled?[e.value]:[]),cW(e)?a?[...i,a]:i:a||i[0]}}(e,a);void 0!==i&&cq(r,e.name,i)}),r}function cH(e,t){let r={};for(let n of e.fields){if(!n.name||cV(r,n.name))continue;let e=function(e,t){if("choice"===e.kind){let r=void 0===t||Array.isArray(t)&&0===t.length;if(!e.required||!r)return;return cW(e)?{code:"selectAtLeastOne"}:{code:"required"}}let r=void 0===t?"":String(t);if(""===r.trim())return e.required?{code:"required"}:void 0;if("number"===e.type||"range"===e.type){let t=Number(r);if(!Number.isFinite(t))return{code:"enterNumber"};if(void 0!==e.min&&t<e.min)return{code:"min",value:e.min};if(void 0!==e.max&&t>e.max)return{code:"max",value:e.max}}return void 0!==e.minLength&&r.length<e.minLength?{code:"minLength",value:e.minLength}:void 0!==e.maxLength&&r.length>e.maxLength?{code:"maxLength",value:e.maxLength}:"email"!==e.type||/^[^\s@]+@[^\s@]+$/.test(r)?"url"!==e.type||URL.canParse(r)?e.pattern&&(function(e){try{return RegExp(`^(?:${e})$`,"v")}catch{return}})(e.pattern)?.test(r)===!1?{code:"pattern",pattern:e.pattern.length>40?`${e.pattern.slice(0,39)}…`:e.pattern}:void 0:{code:"url"}:{code:"email"}}(n,cV(t,n.name));e&&cq(r,n.name,e)}return r}function cU(e){return e.map(e=>e.text).join("")}function cB(e,t,r){if(!e.multi)return{...t,checked:[r],otherOn:!1};let n=t.checked.includes(r)?t.checked.filter(e=>e!==r):[...t.checked,r].sort((e,t)=>e-t);return{...t,checked:n}}function cq(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:!0,writable:!0,configurable:!0})}function cV(e,t){return Object.hasOwn(e,t)?e[t]:void 0}let cK={text:!0,search:!0,tel:!0,url:!0,email:!0,number:!0,password:!0,date:!0,time:!0,"datetime-local":!0,month:!0,week:!0,color:!0,range:!0},cG={width:"100%",minWidth:0,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"},cJ={minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"};function cZ({spans:e}){return(0,n.jsx)(n.Fragment,{children:e.map((e,t)=>{let r=[];return(e.text.split("\n").forEach((e,t)=>{t>0&&r.push((0,n.jsx)("br",{},`br-${t}`)),r.push(e)}),"code"===e.style)?(0,n.jsx)("code",{style:{padding:"0 4px",borderRadius:4,background:"var(--bg-subtle)",fontFamily:"var(--font-mono)",fontSize:"0.92em"},children:r},t):"strong"===e.style?(0,n.jsx)("strong",{style:{fontWeight:600},children:r},t):"em"===e.style?(0,n.jsx)("em",{children:r},t):(0,n.jsx)("span",{children:r},t)})})}function cY({src:e,alt:t}){let{t:r}=(0,z.s)(),[i,s]=(0,a.useState)(!1);return!e||i?(0,n.jsx)("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",overflowWrap:"anywhere"},children:t||r("chat.formImageUnavailable")}):(0,n.jsx)("img",{src:e,alt:t,onError:()=>s(!0),style:{display:"block",maxWidth:"100%",maxHeight:320,height:"auto",objectFit:"contain",borderRadius:"var(--radius-control)"}})}function cX({block:e,id:t}){let r={margin:0,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.55,overflowWrap:"anywhere"};switch(e.kind){case"text":return(0,n.jsx)("p",{id:t,style:{...r,fontWeight:e.heading?600:400},children:(0,n.jsx)(cZ,{spans:e.spans})});case"list":{let t=e.ordered?"ol":"ul";return(0,n.jsx)(t,{style:{...r,paddingInlineStart:22},children:e.items.map((e,t)=>(0,n.jsx)("li",{children:(0,n.jsx)(cZ,{spans:e})},t))})}case"pre":return(0,n.jsx)("pre",{tabIndex:0,style:{margin:0,padding:"8px 10px",overflowX:"auto",maxWidth:"100%",border:"1px solid var(--hairline)",borderRadius:"var(--radius-control)",background:"var(--bg-subtle)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5},children:e.text});case"table":return(0,n.jsx)("div",{tabIndex:0,style:{maxWidth:"100%",overflowX:"auto",border:"1px solid var(--hairline)",borderRadius:"var(--radius-control)"},children:(0,n.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:(0,n.jsx)("tbody",{children:e.rows.map((t,r)=>(0,n.jsx)("tr",{children:t.map((t,a)=>{let i=r<e.headerRows?"th":"td";return(0,n.jsx)(i,{scope:r<e.headerRows?"col":void 0,style:{padding:"6px 10px",borderBottom:"1px solid var(--hairline)",color:r<e.headerRows?"var(--text-muted)":"var(--text)",fontWeight:r<e.headerRows?600:400,textAlign:"left",verticalAlign:"top",minWidth:72},children:(0,n.jsx)(cZ,{spans:t})},a)})},r))})})});case"image":return(0,n.jsx)(cY,{src:e.src,alt:e.alt})}}function cQ({field:e,id:t,index:r,error:a,children:i,hasLabel:s}){let{t:o}=(0,z.s)();return(0,n.jsxs)("div",{"data-field":r,style:{display:"grid",gap:6,minWidth:0},children:[(s||e.required)&&(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[s&&(0,n.jsx)("label",{id:`${t}-label`,htmlFor:"text"===e.kind||e.select?t:void 0,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:(0,n.jsx)(cZ,{spans:e.label})}),e.required&&(0,n.jsx)("span",{style:{marginLeft:s?0:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:o("chat.formRequired")})]}),i,a&&(0,n.jsxs)("p",{id:`${t}-error`,style:{margin:0,display:"flex",alignItems:"flex-start",gap:6,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:500,lineHeight:1.45},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",style:{flex:"none",marginTop:2},children:[(0,n.jsx)("circle",{cx:"7",cy:"7",r:"5.5"}),(0,n.jsx)("path",{d:"M7 4v3.4M7 9.6v.1"})]}),(0,n.jsx)("span",{children:function(e,t){switch(e.code){case"min":case"max":case"minLength":case"maxLength":return t(`chat.formError.${e.code}`,{value:e.value});case"pattern":return t("chat.formError.pattern",{pattern:e.pattern});default:return t(`chat.formError.${e.code}`)}}(a,o)})]})]})}function c0({field:e,id:t,index:r,state:i,error:s,captionId:o,fallbackName:l,onChange:c}){let{t:d}=(0,z.s)(),u=(0,a.useRef)(null);if("choice"!==i.kind)return null;let p=e.label.length>0,h={"aria-labelledby":p?`${t}-label`:o,"aria-label":p||o?void 0:l,"aria-required":e.required||void 0,"aria-invalid":!!s||void 0,"aria-describedby":s?`${t}-error`:void 0};if(e.select&&!e.multi)return(0,n.jsx)(cQ,{field:e,id:t,index:r,error:s,hasLabel:p,children:(0,n.jsx)("select",{id:t,...h,value:String(i.checked[0]??""),onChange:t=>c(r,cB(e,i,Number(t.target.value))),style:{...cG,height:36},children:e.options.map((e,t)=>(0,n.jsx)("option",{value:t,disabled:e.disabled,children:cU(e.label)},t))})});let m=e.multi?"checkbox":"radio",f=(e,t)=>({display:"grid",gridTemplateColumns:"16px minmax(0, 1fr)",alignItems:"start",gap:9,minHeight:40,padding:"9px 10px",border:`1px solid ${e?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:e?"var(--bg-selected)":"transparent",color:t?"var(--text-dim)":"var(--text)",cursor:t?"not-allowed":"pointer",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5,overflowWrap:"anywhere"}),g={width:16,height:16,margin:"3px 0 0",accentColor:"var(--seed-color-fg-neutral)"},x=`${t}-choice`;return(0,n.jsx)(cQ,{field:e,id:t,index:r,error:s,hasLabel:p,children:(0,n.jsxs)("div",{role:e.multi?"group":"radiogroup",...h,style:{display:"grid",gap:4},children:[e.options.map((t,a)=>{let s=i.checked.includes(a);return(0,n.jsxs)("label",{style:f(s,t.disabled),children:[(0,n.jsx)("input",{type:m,name:x,checked:s,disabled:t.disabled,"aria-required":!!e.required&&!e.multi||void 0,onChange:()=>c(r,cB(e,i,a)),style:g}),(0,n.jsx)("span",{children:(0,n.jsx)(cZ,{spans:t.label})})]},a)}),e.other&&(0,n.jsxs)("div",{style:{display:"grid",gap:6},children:[(0,n.jsxs)("label",{style:f(i.otherOn,!1),children:[(0,n.jsx)("input",{type:m,name:x,checked:i.otherOn,onChange:()=>{c(r,e.multi?{...i,otherOn:!i.otherOn}:{...i,checked:[],otherOn:!0}),i.otherOn&&e.multi||u.current?.focus()},style:g}),(0,n.jsx)("span",{children:d("chat.formOther")})]}),(0,n.jsx)("input",{ref:u,type:"text",value:i.other,"aria-label":d("chat.formOther"),placeholder:d("chat.formOtherPlaceholder"),onChange:t=>{var n;let a;return c(r,(a=""!==(n=t.target.value).trim(),{...i,other:n,otherOn:!!a||i.otherOn,checked:a&&!e.multi?[]:i.checked}))},style:{...cG,height:36,width:"calc(100% - 35px)",marginInlineStart:35}})]})]})})}function c1({field:e,id:t,index:r,state:a,error:i,captionId:s,fallbackName:o,onChange:l}){if("text"!==a.kind)return null;let c=e.label.length>0,d=Object.hasOwn(cK,e.type)?e.type:"text",u={id:t,value:a.text,placeholder:e.placeholder||void 0,"aria-labelledby":c?void 0:s,"aria-label":c||s?void 0:o,"aria-required":e.required||void 0,"aria-invalid":!!i||void 0,"aria-describedby":i?`${t}-error`:void 0},p=i?"1px solid var(--danger)":cG.border;return(0,n.jsx)(cQ,{field:e,id:t,index:r,error:i,hasLabel:c,children:e.multiline?(0,n.jsx)("textarea",{...u,rows:Math.max(2,e.rows),onChange:e=>l(r,{kind:"text",text:e.target.value}),style:{...cG,padding:"8px 10px",border:p,lineHeight:1.5,resize:"vertical"}}):(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("input",{...u,type:d,min:"number"===d||"range"===d?e.min:void 0,max:"number"===d||"range"===d?e.max:void 0,step:"number"===d?"any":void 0,onChange:e=>l(r,{kind:"text",text:e.target.value}),style:{...cG,height:"color"===d?40:36,border:p,..."range"===d?{padding:0}:{},fontVariantNumeric:"tabular-nums"}}),"range"===d&&(0,n.jsx)("output",{htmlFor:t,style:{minWidth:32,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:a.text})]})})}function c2({request:e,onRespond:t,onActivity:r,delivery:i}){let{t:s}=(0,z.s)(),o=(0,a.useId)(),l=e.form,[c,d]=(0,a.useState)(()=>l.fields.map(cO)),u=(0,a.useRef)(c),[p,h]=(0,a.useState)(!1),m=(0,a.useRef)(null),f=(0,a.useRef)(r);f.current=r;let g=(0,a.useRef)(e);g.current=e;let x=i?.status==="sending",v=(0,a.useRef)(null);if(null===v.current){let e=Array.from(crypto.getRandomValues(new Uint8Array(12)),e=>e.toString(16).padStart(2,"0")).join(""),t=0;v.current=function(e,t=cz){let r,n=-1/0,a=!1,i=()=>{a&&t.clearTimeout(r),a=!1,n=t.now(),e()};return{notify(){let e=1e3-(t.now()-n);e<=0?i():a||(a=!0,r=t.setTimeout(i,e))},cancel(){a&&t.clearTimeout(r),a=!1}}}(()=>{var r,n;let a=g.current;t+=1,f.current?.(a,(r=t,n=cD(a.form,u.current),`activity:form:v2:${e}:${r}:${JSON.stringify(n)}`))})}(0,a.useEffect)(()=>()=>v.current?.cancel(),[]);let b=(0,a.useCallback)((e,t)=>{let r=u.current.slice();r[e]=t,u.current=r,d(r),g.current.timeout&&f.current&&v.current?.notify()},[]),y=cD(l,c),w=p?cH(l,y):{},k=Object.keys(w).length>0,j=()=>{if(x)return;let r=cD(l,u.current),n=cH(l,r);if(Object.keys(n).length>0){h(!0);let e=l.fields.findIndex(e=>""!==e.name&&void 0!==cV(n,e.name));m.current?.querySelector(`[data-field="${e}"] input, [data-field="${e}"] select, [data-field="${e}"] textarea`)?.focus();return}t(e,{value:JSON.stringify(r)})};return(0,n.jsxs)("div",{"data-ask-form":"",style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentFormHint")}),e.timeout?(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askFormAutoSubmitHint",{seconds:Math.round(e.timeout/1e3)})}):null]}),(0,n.jsx)("div",{ref:m,onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&j()},style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:16},children:(0,n.jsx)("div",{style:{display:"grid",gap:20,minWidth:0},children:l.sections.map((e,t)=>{let r,a=cU(e.title);return(0,n.jsxs)("section",{"aria-labelledby":a?`${o}-s${t}`:void 0,style:{display:"grid",gap:12,minWidth:0,paddingTop:20*(0!==t),borderTop:0===t?"none":"1px solid var(--hairline)"},children:[a&&(0,n.jsx)("h3",{id:`${o}-s${t}`,style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600,lineHeight:1.4},children:(0,n.jsx)(cZ,{spans:e.title})}),e.blocks.map((e,i)=>{var s;let d;if("field"!==e.kind){let a=`${o}-s${t}b${i}`;return r="text"===e.kind?a:void 0,(0,n.jsx)(cX,{block:e,id:a},i)}let u=l.fields[e.index],h=r;r=void 0;let m=(s=e.index,d=l.fields[s],{id:`${o}-f${s}`,index:s,state:c[s],error:p&&d.name?cV(w,d.name):void 0,captionId:h,fallbackName:a||d.name,onChange:b});return"choice"===u.kind?(0,n.jsx)(c0,{...m,field:u},i):(0,n.jsx)(c1,{...m,field:u},i)})]},t)})})}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[k&&(0,n.jsx)("p",{role:"alert",style:{margin:0,marginRight:"auto",color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.formInvalid")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:cJ,children:s("chat.cancel")}),(0,n.jsx)("button",{type:"button","aria-disabled":x||void 0,onClick:j,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:x?"var(--seed-color-bg-disabled)":"var(--seed-color-bg-neutral-inverted)",color:x?"var(--seed-color-fg-disabled)":"var(--seed-color-fg-neutral-inverted)",cursor:x?"not-allowed":"pointer",fontWeight:600},children:s(x?"chat.responseSending":"chat.submitAnswer")})]})]})}let c8={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},c4={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function c5({rows:e,removeLabel:t,onRemove:r}){let i,{st:s}=ag(),[o,l]=(0,a.useState)(!1),{rows:c,hidden:d}=(i=Math.max(0,e.length-4),o||0===i?{rows:e,hidden:i}:{rows:e.slice(i),hidden:i}),u=e.length>4;return(0,a.useEffect)(()=>{u||l(!1)},[u]),(0,n.jsxs)(n.Fragment,{children:[u&&(0,n.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":o,onClick:()=>l(e=>!e),children:o?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:d})}),(0,n.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:c.map(e=>{let a=lu(e.text),i=[a?[a.message,a.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?s(1===e.images?"delivery.images.one":"delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,n.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,n.jsx)("span",{className:"answer-delivery-kind",children:s(c8[e.kind])}),(0,n.jsx)("span",{className:"answer-delivery-text",title:i,children:i}),(0,n.jsx)("span",{className:"answer-delivery-stage",children:s(c4[e.stage])}),e.removable&&r&&(0,n.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${i}`,onClick:()=>r(e.kind,e.text),children:(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}async function c6(e,t){let r=await fetch(e,{cache:"no-store",...t}),n=await r.json();if(!r.ok)throw Error(n.error||`HTTP ${r.status}`);return n}let c3=(0,a.forwardRef)(function({value:e,token:t,cwd:r,sessionTitle:i,style:s,maxHeight:o,onReplace:l,onClose:c},d){let{t:u}=(0,z.s)(),[p,h]=(0,a.useState)([]),[m,f]=(0,a.useState)(!0),[g,x]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null),[y,w]=(0,a.useState)(null),[k,j]=(0,a.useState)(-1),S=(0,a.useRef)([]),C=t.query.toLowerCase(),N=p.filter(e=>`${e.title}
|
|
18
18
|
${e.body}`.toLowerCase().includes(C)),T=e.slice(0,t.start)+e.slice(t.end),I=!!T.trim(),M=N.length+ +!!I,E=(0,a.useCallback)(async()=>{h((await c6("/api/saved-prompts")).prompts)},[]);(0,a.useEffect)(()=>{let e=!1;return c6("/api/saved-prompts").then(t=>{e||h(t.prompts)}).catch(t=>{e||b(String(t.message??t))}).finally(()=>{e||f(!1)}),()=>{e=!0}},[]),(0,a.useEffect)(()=>{j(N.length>0?0:-1),w(null)},[C,p,N.length,I]),(0,a.useEffect)(()=>{S.current[k]?.scrollIntoView({block:"nearest"})},[k]);let $=n=>{var a,s;let o=new Date,c=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`,d=(a=n.body,s={project_name:r?.replace(/[\\/]+$/,"").split(/[\\/]/).pop(),cwd:r,session_name:i,date:c},a.replace(/\{\{\s*([a-zA-Z_][\w]*)\s*\}\}/g,(e,t)=>(Object.hasOwn(s,t)?s[t]:void 0)||e));l(e,e.slice(0,t.start)+d+e.slice(t.end),t.start+d.length)},R=async()=>{if(!g&&I){x(!0),b(null);try{await c6("/api/saved-prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:T})}),l(e,T,t.start,!0),await E()}catch(e){b(e instanceof Error?e.message:String(e))}finally{x(!1)}}},L=async e=>{if(!g){if(y!==e)return void w(e);x(!0),b(null);try{await c6(`/api/saved-prompts/${encodeURIComponent(e)}`,{method:"DELETE"}),h(t=>t.filter(t=>t.id!==e)),w(null),await E()}catch(e){b(e instanceof Error?e.message:String(e))}finally{x(!1)}}};(0,a.useImperativeHandle)(d,()=>({handleKeyDown(e){if("Escape"===e.key)return c(),e.preventDefault(),!0;if(("ArrowDown"===e.key||"ArrowUp"===e.key)&&M>0)return e.preventDefault(),j(t=>"ArrowDown"===e.key?Math.min(M-1,t+1):t<0?M-1:Math.max(0,t-1)),!0;if("Tab"===e.key||"Enter"===e.key&&!e.shiftKey){if(k>=0&&k<M)return e.preventDefault(),g||(N[k]?$(N[k]):R()),!0;"Enter"===e.key&&c()}return!1}}));let A=e=>({width:"100%",minWidth:0,minHeight:44,border:"none",borderRadius:"var(--radius-control)",padding:"8px",background:e?"var(--bg-selected)":"none",color:"var(--text)",textAlign:"left",cursor:"pointer",fontSize:12});return(0,n.jsxs)("div",{id:"saved-prompt-menu",role:"region","aria-label":u("savedPrompts.title"),"data-saved-prompt-menu":"",onMouseDown:e=>e.preventDefault(),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),c())},style:{position:"absolute",left:0,right:0,zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",display:"flex",flexDirection:"column",overflow:"hidden",maxHeight:o,...s},children:[(0,n.jsx)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",flexShrink:0},children:m?u("savedPrompts.loading"):u("savedPrompts.title")}),(0,n.jsxs)("div",{style:{overflowY:"auto",minHeight:0,padding:4},children:[!m&&0===N.length&&(0,n.jsx)("div",{style:{padding:8,fontSize:12,color:"var(--text-dim)"},children:u("savedPrompts.empty")}),N.map((e,t)=>(0,n.jsxs)("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[(0,n.jsxs)("button",{type:"button",ref:e=>{S.current[t]=e},disabled:g,"data-saved-prompt-id":e.id,onClick:()=>$(e),onMouseEnter:()=>j(t),style:A(t===k),children:[(0,n.jsx)("span",{style:{display:"block",overflowWrap:"anywhere"},children:e.title}),(0,n.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:e.body.replace(/\s+/g," ")})]}),(0,n.jsx)("button",{type:"button",disabled:g,"data-delete-prompt":e.id,"aria-label":`${u("savedPrompts.delete")}: ${e.title}`,onClick:()=>void L(e.id),style:{...A(!1),width:"auto",flexShrink:0,color:"var(--danger, var(--text))"},children:u(y===e.id?"savedPrompts.confirmDelete":"savedPrompts.delete")}),y===e.id&&(0,n.jsx)("button",{type:"button",onClick:()=>w(null),style:{...A(!1),width:"auto",flexShrink:0},children:u("savedPrompts.cancel")})]},e.id)),I&&(0,n.jsx)("button",{type:"button","data-save-current-prompt":"",disabled:g||m,ref:e=>{S.current[N.length]=e},onClick:()=>void R(),onMouseEnter:()=>j(N.length),style:A(k===N.length),children:u("savedPrompts.save")})]}),v&&(0,n.jsx)("div",{role:"alert",style:{padding:"6px 10px",fontSize:12,color:"var(--danger, var(--text))",overflowWrap:"anywhere"},children:u("savedPrompts.error",{error:v})}),(0,n.jsx)("div",{style:{padding:"6px 10px",fontSize:10,color:"var(--text-dim)",borderTop:"1px solid var(--border)",overflowWrap:"anywhere",overflowY:"auto",flexShrink:0,maxHeight:"40%"},children:u("savedPrompts.hint")})]})}),c7=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),c9=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function de({soundEnabled:e,onToggle:t}){let r=e?"완료음 끄기":"완료음 켜기";return(0,n.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,n.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:r,"aria-label":r,children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?c7:c9})})})}let dt=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),dr=["normal","slow"],dn={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function da(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:r}=Promise.withResolvers(),n=()=>{clearTimeout(i),e.removeEventListener("icegatheringstatechange",a),r()},a=()=>{"complete"===e.iceGatheringState&&n()},i=setTimeout(n,3e3);return e.addEventListener("icegatheringstatechange",a),t}function di(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let ds={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},dl=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,n.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,n.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),dc=(0,n.jsx)(n.Fragment,{children:(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function dd({sessionId:e,onEnsureSession:t,onTranscriptPersisted:r}){let{t:i}=(0,z.s)(),s=function(e,t,r){let{locale:n}=(0,z.s)(),[i,s]=(0,a.useState)("idle"),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),x=(0,a.useRef)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null),y=(0,a.useRef)(null),w=(0,a.useRef)(null),k=(0,a.useRef)(0);(0,a.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,a.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,y.current?.close(),y.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let r=b.current;b.current=null,r&&(r.srcObject=null,r.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,a.useCallback)((e,t)=>{l(e),d(t??null),j("error")},[j]),C=(0,a.useCallback)(async()=>{let a,i=k.current+1;k.current=i,l(null),d(null),g(!0),s("connecting");let o=e;if(!o&&t){try{o=await t()}catch{o=void 0}if(k.current!==i)return}if(!o){k.current===i&&(g(!1),S("failed"));return}try{a=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===i&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==i){for(let e of a.getTracks())e.stop();return}v.current=a;try{let e,t,l=new RTCPeerConnection;for(let e of(x.current=l,a.getTracks()))l.addTrack(e,a);let c=document.createElement("audio");if(c.autoplay=!0,b.current=c,l.ontrack=e=>{let[t]=e.streams;t&&(c.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await da(l),k.current!==i)return;let d=l.localDescription?.sdp;if(!d)throw Error("The browser produced no offer SDP.");let u=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,sdp:d,locale:n})}),h=await u.json().catch(()=>({})),m="",f="";if(h&&"object"==typeof h&&("error"in h&&(e=h.error),"message"in h&&"string"==typeof h.message&&(t=h.message),"callId"in h&&"string"==typeof h.callId&&(m=h.callId),"sdp"in h&&"string"==typeof h.sdp&&(f=h.sdp)),!u.ok||!m||!f){k.current===i&&(g(!1),S(di(u.status,e),t));return}if(k.current!==i)return void fetch(`/api/live/call/${encodeURIComponent(m)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:f}),k.current!==i){l.close(),fetch(`/api/live/call/${encodeURIComponent(m)}`,{method:"DELETE"}).catch(()=>{});return}w.current=m;let v=new EventSource(`/api/live/events?callId=${encodeURIComponent(m)}`);y.current=v,v.onmessage=e=>{let t;if(k.current===i){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var n;if("string"!=typeof t.state||(n=t.state,!0!==dn[n]))return;"closed"===t.state?j("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&r&&Promise.resolve().then(()=>r(o)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&dt.test(e)&&j("idle")}return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},v.onerror=()=>{k.current===i&&w.current&&S("failed")},s("live")}catch(e){k.current===i&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===i&&g(!1)}},[e,t,r,n,S,j]),N=(0,a.useCallback)(()=>{if("idle"===i||"closed"===i||"error"===i){f||C();return}j("idle")},[f,i,C,j]);return(0,a.useEffect)(()=>()=>j("closed"),[j]),{state:i,failure:o,detail:c,transcript:u,supported:h,toggle:N}}(e,t,r),o="connecting"===s.state||"live"===s.state||"working"===s.state,l="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,c=i(o?"chat.liveStop":"chat.liveStart"),d=!1===s.supported?ds.unsupported:s.failure?ds[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,n.jsxs)("div",{role:"group","aria-label":i("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[d&&(0,n.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:i(d)}),l&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i(l)}),(0,n.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":o,title:p?i(p):c,"aria-label":p?i(p):c,children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o?dc:dl})})]})}let du={display:"inline-flex",alignItems:"center",flexShrink:0,height:32,padding:"0 10px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"var(--accent-soft)",color:"var(--accent-hover)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600,lineHeight:1.3,whiteSpace:"nowrap"};function dp({sessionId:e}){let{t}=(0,z.s)(),[r,i]=(0,a.useState)(null);return((0,a.useEffect)(()=>{if(!e)return void i(null);let t=!1,r=0,n=!1,a=async()=>{if("visible"===document.visibilityState)try{let r=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!r.ok)return;let a=await r.json();if(t)return;let s=Array.isArray(a.handles)?a.handles:[],o=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;n=null!==o,i(o)}catch{}},s=async()=>{await a(),t||(r=window.setTimeout(()=>void s(),n?5e3:3e4))};return s(),document.addEventListener("visibilitychange",a),()=>{t=!0,window.clearTimeout(r),document.removeEventListener("visibilitychange",a)}},[e]),r)?(0,n.jsx)("span",{style:du,title:t("gpt6.boundBadgeHint",{handle:r}),children:t("gpt6.boundBadge",{handle:r})}):null}let dh=new Map,dm="ompweb-drafts-for-reload-v1",df=!1,dg=new Map,dx=new Map,dv="\0stale",db=new Map,dy=0,dw=new Map,dk=new Map,dj=new Map,dS=new Map,dC=new Map,dN=(e,t,r)=>lv(e,t,r.length?{sentAttachmentIds:r}:{}),dT=null,dI=!1;function dM(){if(df||"u"<typeof sessionStorage)return;df=!0;let e=sessionStorage.getItem(dm);if(e){sessionStorage.removeItem(dm);try{let t=JSON.parse(e);if(!Array.isArray(t))return;for(let e of t){if(!Array.isArray(e)||2!==e.length||"string"!=typeof e[0])continue;let t=e[1];t&&"string"==typeof t.value&&Array.isArray(t.images)&&Array.isArray(t.documents)&&(dh.set(e[0],d$(t)),"string"==typeof t.draftId&&t.draftId&&(dg.set(e[0],t.draftId),dx.set(t.draftId,dv)),dO(e[0]))}}catch{}}}function dE(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(dm,JSON.stringify([...dh.entries()].map(([e,t])=>{let r=dg.get(e);return[e,r?{...d$(t),draftId:r}:d$(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function d$(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function dR(e){return!e.value&&0===e.images.length&&0===e.documents.length}function dL(e){dM();let t=dh.get(e);return t?d$(t):null}function dA(e,t){dM(),dR(t)?dh.delete(e):dh.set(e,d$(t)),dO(e)}function dP(e){dh.delete(e),dO(e)}function dF(e,t,r,n,a,i=[]){let s=[...t??[],...n].filter(rW).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=ll([...a??[],...i]);return{value:e.trim()?r.trim()?`${e}
|
|
19
19
|
|
|
20
|
-
${r}`:e:r,images:s,documents:o}}function d_(e,t,r){if(e===t)return r?d$(r):dL(t);let n=dL(e),a=r&&!dR(r)?d$(r):n??(r?d$(r):null),i=dL(t),s=dg.get(e);if(dg.delete(e),s&&!dg.has(t)&&dg.set(t,s),dP(e),!a)return i;let o=i?dF(i.value,i.images,a.value,a.images,i.documents,a.documents):a;return dA(t,o),d$(o)}function dz(e){let t=[];for(let r of e??[])r.attachmentId&&!t.includes(r.attachmentId)&&t.push(r.attachmentId);return t}function dW(e){dM();let t=dg.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let r=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}(),dg.set(e,t)),t}function dO(e){let t=dz(dh.get(e)?.documents),r=t.length?dW(e):dg.get(e);for(let[e,r]of dk){for(let e of t)r.delete(e);0===r.size&&dk.delete(e)}let n=`${r??""}|${t.join(",")}`;dS.get(e)!==n&&(0!==t.length||r?dS.set(e,n):dS.delete(e),dK())}async function dD(e){let t=dW(e);dw.set(t,(dw.get(t)??0)+1),await dC.get(t);let r=!1;return{draftId:t,end(e){if(r)return;r=!0;let n=(dw.get(t)??1)-1;if(n>0?dw.set(t,n):dw.delete(t),e){let r=dk.get(t)??new Set;r.add(e),dk.set(t,r)}dx.set(t,dv),dK()}}}function dH(e,t){let r=dj.get(e);if(!r)return[];for(let e of t)r.delete(e);return 0===r.size&&dj.delete(e),[...r].sort()}async function dU(){if(!dN)return;let e=[...function(){let e=new Map,t=(t,r)=>{let n=e.get(t)??new Set;for(let e of r)n.add(e);e.set(t,n)};for(let[e,r]of dg)t(r,dz(dh.get(e)?.documents));for(let{draftId:e,ids:r}of db.values())t(e,r);for(let[e,r]of dk)t(e,r);for(let e of dx.keys())t(e,[]);for(let e of dj.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dw.has(e))return!1;let r=dx.get(e);return dH(e,t).length>0||(0===t.length?void 0!==r:r!==t.join(","))}),t=dw.size>0,r=!1;for(let[n,a]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===a.length&&t)continue;let e=dH(n,a),i=dN(n,a,e).then(()=>{0===a.length?dx.delete(n):dx.set(n,a.join(","));let t=dj.get(n);if(t){for(let r of e)t.delete(r);0===t.size&&dj.delete(n)}},()=>{r=!0,a.length>0&&(t=!0)});dC.set(n,i),await i,dC.get(n)===i&&dC.delete(n)}r?function(){if(dV)return;dV=!0;let e=setTimeout(()=>{dV=!1,dK()},dq);"object"==typeof e&&"unref"in e&&e.unref(),dq=Math.min(2*dq,6e4)}():dq=dB}let dB=5e3,dq=5e3,dV=!1;function dK(){if(dN){if(dT){dI=!0;return}dT=Promise.resolve().then(dU).finally(()=>{dT=null,dI&&(dI=!1,dK())})}}let dG=Math.floor(Number.MAX_SAFE_INTEGER/1048576),dJ=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function dZ(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=dG}async function dY(e){let t,r=await e.json().catch(()=>null);if(!e.ok||!r||!dZ(r.uploadLimitMb)||"boolean"!=typeof r.autoCleanupEnabled)throw Error("string"==typeof r?.error?r.error:`HTTP ${e.status}`);return{uploadLimitMb:dZ((t=r&&"object"==typeof r?r:{}).uploadLimitMb)?t.uploadLimitMb:dJ.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:dJ.autoCleanupEnabled,orphanGraceDays:7}}async function dX(e={}){return dY(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function dQ(e){return dY(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function d0(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let r=/(?:^|\s)@([^\s"]*)$/.exec(e);return r?{start:e.length-(r[1].length+1),query:r[1],quoted:!1}:null}function d1(e){let t=0;for(let r=0;r<e.length;r++)"/"===e[r]&&t++;return t}function d2(e,t){if(!e)return!0;let r=0;for(let n=0;n<t.length&&r<e.length;n++)t[n]===e[r]&&r++;return r===e.length}function d8(e,t){let r=t?`${e}/`:e;return r.includes(" ")?`@"${r}" `:`@${r} `}function d4(e,t,r){let n=Math.max(1,Math.min(t,r)),a=Math.max(1,Math.max(t,r)),i=e.includes(" ")?`@"${e}"`:`@${e}`,s=n===a?`:${n}`:`:${n}-${a}`;return`${i}${s} `}let d5="omp-web:model-picks";function d6(){try{let e=JSON.parse(window.localStorage.getItem(d5)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[r,n]of Object.entries(e))"number"==typeof n&&Number.isFinite(n)&&n>0&&(t[r]=Math.floor(n));return t}catch{return{}}}function d3(e,t,r,n,a={}){let i=a.gap??8,s=a.margin??8,o=a.prefer??"above",l=Math.min(a.minHeight??120,Math.max(0,r-2*s)),c=Math.max(0,e-i-s),d=Math.max(0,r-t-i-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=n||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(n,h?u:p))}}function d7(e,t,r){return Math.min(e*t,r)}function d9(e,t,r){let{viewportFraction:n,cap:i,gap:s,margin:o,minHeight:l,prefer:c}=r,[d,u]=(0,a.useState)({side:c??"above",maxHeight:i}),p=(0,a.useCallback)(()=>{let t=e.current;if(!t)return;let r=window.visualViewport?.height??window.innerHeight,a=t.getBoundingClientRect(),d=d3(a.top,a.bottom,r,d7(r,n,i),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,i,s,o,l,c,n]);return(0,a.useEffect)(()=>{if(!t)return;p();let r=e.current,n=r?new ResizeObserver(p):null;return r&&n&&n.observe(r),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{n?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var ue=r(14755);let ut="omp-web:model-roles-expanded";async function ur(e,t,r,n,a,i,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...ug,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(i&&(!c||"builtin"===c.source))return a(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await r?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&n(d.prompt),!0}if(c&&"builtin"!==c.source)return n(e),!0;return a(`/${o} is not available in this web session.`),!1}catch(e){return a(e instanceof Error?e.message:String(e)),!1}}function un(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t||"fallback"===t}let ua=["off","default","full"],ui={off:"none",default:"default",full:"full"},us=ue.IN.join(" \xb7 "),uo=ue.C1.filter(e=>!ue.IN.includes(e)).join(" \xb7 ");function ul(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let uc=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),ud=0,uu={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function up(e,t){return uc.compare(e.name||e.modelId,t.name||t.modelId)||uc.compare(e.provider,t.provider)||uc.compare(e.modelId,t.modelId)}let uh=["auto","off","minimal","low","medium","high","xhigh","max"],um=["low","medium","high","xhigh"],uf={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},ug=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],ux=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uv={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},ub={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function uy(e,t,r){let n=e.name.toLowerCase(),a=uw(e,r).toLowerCase();return n===t?0:n.startsWith(t)?1:n.includes(t)?2:a.includes(t)?3:4}function uw(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uk(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uj(e){return{data:e.data,mimeType:e.mimeType}}function uS(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uC(e){return(e??[]).filter(rW).slice(0,10).map(uS)}let uN=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uT="\n\nTranscript of the audio ";function uI(e){return ll(e).map(e=>{let t=lf(e),r="audio"===t&&e.attachmentId&&!e.text.includes(uT)?uN.exec(e.text):null;return{...e,id:++ud,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...r?{storedInfo:{path:r[1],mimeType:r[2],size:Number(r[3])}}:{}}})}function uM({name:e,mimeType:t,size:r,text:n,attachmentId:a}){return a?{name:e,mimeType:t,size:r,text:n,attachmentId:a}:{name:e,mimeType:t,size:r,text:n}}function uE(e,t){let r=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?r.get(e.attachmentId):void 0;return t?(r.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class u$ extends Error{constructor(e,t,r,n,a=null){super(e),this.code=t,this.completedParts=r,this.parts=n,this.offer=a}}let uR="composer:unkeyed";async function uL(e){let t=await e.json().catch(()=>null),r=t&&"object"==typeof t?{...t}:{};if(e.ok)return r;let n="number"==typeof r.completedParts?r.completedParts:null,a="number"==typeof r.parts?r.parts:null,i="fallback_confirmation_required"===r.code&&"string"==typeof r.fallbackToken&&"string"==typeof r.notice&&null!==n&&null!==a?{token:r.fallbackToken,notice:r.notice,completedParts:n,parts:a}:null;throw new u$("string"==typeof r.error?r.error:`HTTP ${e.status}`,"string"==typeof r.code?r.code:null,n,a,i)}function uA(e,t){fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fallbackToken:t,approve:!1})}).catch(()=>void 0)}function uP(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function uF({tone:e,title:t,body:r}){let a="error"===e?"danger":"warning";return(0,n.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${a}-line)`,borderRadius:"var(--radius-control)",background:`var(--${a}-soft)`,color:`var(--${a})`,fontSize:11,lineHeight:1.45},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,n.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontWeight:600},children:t}),(0,n.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:r})]})]})}function u_({error:e}){return e?(0,n.jsx)(uF,{tone:"error",title:"Model error",body:e}):null}function uz({warnings:e}){return e&&0!==e.length?(0,n.jsx)(uF,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uW=(0,a.forwardRef)(function({onSend:e,onAbort:t,onSteer:r,onFollowUp:i,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:T,effectiveThinkingLevel:I,outputTokensPerSecond:M=null,outputSpeedLive:E=!1,thinkingCeiling:$,onThinkingLevelChange:R,availableThinkingLevels:L,thinkingLevelMap:A,fastMode:P=null,fastModeBusy:F=!1,onFastModeToggle:_,retryInfo:W,deliveryRows:O=[],inputHistory:D=[],onRecallQueue:H,onRemoveQueuedMessage:U,slashCommands:q,slashCommandsLoading:V,onLoadSlashCommands:K,onBuiltinCommand:G,soundEnabled:J,onSoundToggle:Z,onAudioUnlock:Y,onPromptWithStreamingBehavior:X,draftKey:Q,cwd:ee,sessionTitle:et,sessionId:er,onEnsureSession:en,onLiveTranscriptPersisted:ea},ei){let es,eo,el,ec,ed,eu,ep,eh,em,ef,{t:eg}=(0,z.s)();am();let{st:ex}=ag(),ev=O.some(e=>e.removable),eb=B(),[ey,ew]=(0,a.useState)(()=>Q?dL(Q)?.value??"":""),[ek,ej]=(0,a.useState)(!1),[eS,eC]=(0,a.useState)(null),[eN,eT]=(0,a.useState)(""),[eI,eM]=(0,a.useState)({});(0,a.useEffect)(()=>{ek&&eM(d6())},[ek]);let[eE,e$]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(ek)try{e$("1"===window.localStorage.getItem(ut))}catch{}},[ek]);let eR=()=>{e$(e=>{let t=!e;try{window.localStorage.setItem(ut,t?"1":"0")}catch{}return t})},[eL,eA]=(0,a.useState)(!1),[eP,eF]=(0,a.useState)(null),[e_,ez]=(0,a.useState)(!1),[eW,eO]=(0,a.useState)(!1),[eD,eH]=(0,a.useState)(null),[eU,eB]=(0,a.useState)(!1),[eq,eV]=(0,a.useState)(()=>Q?uC(dL(Q)?.images):[]),[eK,eG]=(0,a.useState)(()=>Q?uI(dL(Q)?.documents):[]),[eJ,eZ]=(0,a.useState)(null),eY=(0,a.useMemo)(()=>eK.filter(e=>"ready"===e.status),[eK]),eX=eK.some(e=>"ready"!==e.status||un(e)),eQ=eK.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uT))),e0=ey.trimStart(),e1=0===eq.length&&0===eK.length&&e0.startsWith("!"),e2=e1&&e0.startsWith("!!"),[e8,e4]=(0,a.useState)(!1),[e5,e6]=(0,a.useState)(0),[e3,e7]=(0,a.useState)(null),e9=e3?.value===ey&&e3.draftKey===Q?e3.token:null,[te,tt]=(0,a.useState)(!1),[tr,tn]=(0,a.useState)(!1),ta=(0,a.useRef)(null),[ti,ts]=(0,a.useState)(null),[to,tl]=(0,a.useState)(!1),[tc,td]=(0,a.useState)(0),[tu,tp]=(0,a.useState)(!1),[th,tm]=(0,a.useState)(0),[tf,tg]=(0,a.useState)(null),[tx,tv]=(0,a.useState)(!1),[tb,ty]=(0,a.useState)(null),[tw,tk]=(0,a.useState)(null),tj=ee&&tw?.cwd===ee?tw.values:{},tS=(0,a.useRef)(null),tC=(0,a.useRef)(null),tN=(0,a.useRef)(null),tT=(0,a.useRef)(null),tI=(0,a.useRef)(null),tM=(0,a.useRef)(null),tE=(0,a.useRef)(null),t$=(0,a.useRef)(null),tR=(0,a.useRef)(null),tL=(0,a.useRef)(null),tA=(0,a.useRef)(null),tP=(0,a.useRef)(!1),tF=(0,a.useRef)(0),t_=(0,a.useRef)(!1),tz=(0,a.useRef)([]),tW=(0,a.useRef)([]),tO=(0,a.useRef)([]),tD=(0,a.useRef)(null),tH=(0,a.useRef)(null),tU=(0,a.useRef)(Q),tB=(0,a.useRef)(ey),tq=(0,a.useRef)(eq),tV=(0,a.useRef)(0),tK=(0,a.useRef)(eK);tB.current=ey,tq.current=eq,tK.current=eK,(0,a.useImperativeHandle)(ei,()=>({insertIfEmpty(e){let t=tS.current;(t?t.value:ey).trim()||(tB.current=e,ew(e),ts(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,r,n=tS.current;if(!function(e,t,r,n=0){return!e.trim()&&0===t&&0===r&&0===n}(n?n.value:ey,tq.current.length,tV.current,tK.current.length))return;let a=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lu(t)?.message??t),i=uC("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,r=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof r)return[];let n={data:t,mimeType:r};return rW(n)?[n]:[]})),s=uI((r="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lu(r)?.documents??[]));tB.current=a,tq.current=i,tK.current=s,ew(a),ts(null),tp(!1),eV(e=>(e.forEach(uP),i)),eG(s),requestAnimationFrame(()=>{n&&(n.focus(),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tU.current!==e)return void d_(e,t);let r={value:tB.current,images:tq.current.map(uj),documents:tK.current.filter(e=>"ready"===e.status).map(uM)},n=d_(e,t,r)??{value:"",images:[],documents:[]},a=n.value===r.value&&n.images.length===r.images.length&&n.images.every((e,t)=>e.data===r.images[t]?.data&&e.mimeType===r.images[t]?.mimeType)&&n.documents.length===r.documents.length&&n.documents.every((e,t)=>e.name===r.documents[t]?.name&&e.mimeType===r.documents[t]?.mimeType&&e.size===r.documents[t]?.size&&e.text===r.documents[t]?.text&&e.attachmentId===r.documents[t]?.attachmentId);if(tU.current=t,a)return;let i=uC(n.images),s=uE(uI(n.documents),tK.current),o=n.value;tB.current=o,tq.current=i,tK.current=s,ew(o),eV(e=>(e.forEach(uP),i)),eG(s),ts(null),tp(!1)},restoreSubmission(e,t,r,n){if(!e.trim()&&!t?.length&&!r?.length)return;let a=tU.current,i=n??a,s=i===a,o=!s&&i?dL(i):null,l=dF(e,t,s?tB.current:o?.value??"",s?tq.current.map(uj):o?.images??[],r,s?tK.current.filter(e=>"ready"===e.status).map(uM):o?.documents??[]);if(i&&dA(i,l),!s)return;let c=t?.length?[...uC(t).slice(0,Math.max(0,10-tq.current.length)),...tq.current].slice(0,10):tq.current,d=uE(uI(l.documents),tK.current);tB.current=l.value,tq.current=c,tK.current=d,ew(l.value),ts(null),tp(!1),t?.length&&eV(e=>{let r=Math.max(0,10-e.length),n=uC(t).slice(0,r),a=n.length>0?[...n,...e]:e;return tq.current=a,a}),eG(d),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=tS.current;if(!t)return void ew(t=>t+(t?" ":"")+e);let r=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length,a=t.value.slice(0,r),i=t.value.slice(n),s=a.length>0&&!a.endsWith(" ")?" ":"",o=a+s+e+i;tB.current=o,ew(o),ts(null),requestAnimationFrame(()=>{if(!t)return;let n=r+s.length+e.length;t.setSelectionRange(n,n),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){t9(e)}}));let tG=(0,a.useCallback)(async e=>{let t=Math.max(0,10-tq.current.length-tV.current),r=e.filter(e=>e.size>0xa00000);r.length>0&&eZ(eg("chat.attachImageTooLarge",{name:r.map(e=>e.name).join(", "),limit:lp(0xa00000)}));let n=e.filter(e=>e.size<=0xa00000),a=n.slice(0,t);if(a.length<n.length&&eZ(eg("chat.attachImageLimit",{count:10})),a.length){tV.current+=a.length;try{let e=await Promise.all(a.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result.split(",")[1];t({data:r,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},n.onerror=r,n.readAsDataURL(e)})));eV(t=>{let r=e.slice(0,Math.max(0,10-t.length));e.slice(r.length).forEach(uP);let n=[...t,...r];return tq.current=n,n})}finally{tV.current-=a.length}}},[eg]),tJ=(0,a.useCallback)(async e=>{for(let t of e){let e=la(t);if(!e)continue;if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eZ(eg("chat.attachTooLarge",{name:t.name,limit:lp(8388608)}));continue}if(tK.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eZ(eg("chat.attachTotalTooLarge",{limit:lp(0x1000000)}));continue}let r={id:++ud,name:t.name,mimeType:lt[e],size:t.size,text:"",status:"extracting"},n=[...tK.current,r];tK.current=n,eG(n);try{let e=await lc(t);if(tK.current.reduce((e,t)=>e+(t.id===r.id?0:t.text.length),0)+e.text.length>24e4)throw new le("text_too_large","Total extracted text exceeds 240000 characters");let n=tK.current.map(t=>t.id===r.id?{...e,id:t.id,status:"ready"}:t);tK.current=n,eG(n)}catch(a){let e=tK.current.some(e=>e.id===r.id),n=tK.current.filter(e=>e.id!==r.id);if(tK.current=n,eG(n),!e)continue;a instanceof le?"text_too_large"===a.code?eZ(eg("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===a.code?eZ(eg("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===a.code?eZ(eg("chat.attachNoPdfText",{name:t.name})):"password_protected"===a.code?eZ(eg("chat.attachPasswordProtected",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name}))}}},[eg]),tZ=(0,a.useCallback)((e,t)=>{if(!tK.current.some(t=>t.id===e))return!1;let r=t?tK.current.map(r=>r.id===e?t:r):tK.current.filter(t=>t.id!==e);return tK.current=r,eG(r),!0},[]),tY=(0,a.useCallback)((e,t)=>{if(!tK.current.some(t=>t.attachmentId===e))return!1;let r=tK.current.map(r=>r.attachmentId===e?t(r):r);return tK.current=r,eG(r),!0},[]),tX=(0,a.useCallback)((e,t,r)=>{if(!e||e===tU.current)return;let n=dL(e);n?.documents.some(e=>e.attachmentId===t)&&dA(e,{...n,documents:uI(n.documents).map(e=>e.attachmentId===t?r(e):e).map(uM)})},[]),tQ=(0,a.useRef)(new Map),t0=(0,a.useRef)(new Map),t1=(0,a.useRef)(new Set),t2=(0,a.useCallback)((e,t,r)=>{if(!e.storedInfo)return null;let n=Math.min(12e4,24e4-r.reduce((t,r)=>t+(r.attachmentId===e.attachmentId?0:r.text.length),0)),a=lg({...e.storedInfo,transcript:t},n);return a.length>n?null:{...e,text:a,size:new TextEncoder().encode(a).byteLength,transcription:void 0}},[]),t8=(0,a.useCallback)(e=>e instanceof u$&&"media_tool_unavailable"===e.code?eg("chat.transcribeToolMissing"):e instanceof u$&&"fallback_confirmation_expired"===e.code?eg("chat.transcribeFallbackExpired"):e instanceof u$&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eg("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eg]),t4=(0,a.useCallback)(async(e,t)=>{let r=tU.current,n=tK.current.find(t=>t.attachmentId===e);if(!n?.storedInfo)return;let a=n.transcription?.state==="confirm"?n.transcription.plan:null;t0.current.get(e)?.abort();let i=new AbortController;t0.current.set(e,i),tY(e,e=>({...e,transcription:{state:"running",plan:a}}));try{let n=await uL(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:i.signal}));if("string"!=typeof n.transcript)throw new u$("Invalid transcription result",null,null,null);let a=n.transcript;tY(e,e=>t2(e,a,tK.current)??{...e,transcription:{state:"failed",error:eg("chat.transcribeTooLong")}})||tX(r,e,e=>t2(e,a,[])??e)}catch(n){if(i.signal.aborted)return void tY(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof u$&&"confirmation_required"===n.code)return void t5.current?.(e);let t=n instanceof u$?n.offer:null;if(t){let r={state:"fallback",reason:n instanceof Error?n.message:"",...t};tY(e,e=>({...e,transcription:r}))||uA(e,t.token);return}let r=t8(n);tY(e,e=>({...e,transcription:{state:"failed",error:r}}))}finally{t0.current.get(e)===i&&t0.current.delete(e)}},[eg,t8,tY,tX,t2]),t5=(0,a.useRef)(null),t6=(0,a.useCallback)(async e=>{let t;t0.current.get(e)?.abort();let r=new AbortController;t0.current.set(e,r),tY(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new u$("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await uL(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:r.signal})))}catch(t){if(r.signal.aborted)tY(e,e=>({...e,transcription:{state:"skipped"}}));else{let r=t8(t);tY(e,e=>({...e,transcription:{state:"failed",error:r}}))}return}finally{t0.current.get(e)===r&&t0.current.delete(e)}t.requiresConfirmation?tY(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await t4(e,{})},[t4,t8,tY]);t5.current=t6;let t3=(0,a.useCallback)(e=>{let t=t0.current.get(e);if(t)return void t.abort();let r=tK.current.find(t=>t.attachmentId===e)?.transcription;r?.state==="fallback"&&uA(e,r.token),tY(e,e=>({...e,transcription:{state:"skipped"}}))},[tY]),t7=(0,a.useCallback)(async(e,t)=>{let r=null;for(let n of e){if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}let e="file"===t&&n.size<=8388608,a={id:++ud,name:n.name,mimeType:"text/plain",size:e?n.size:0,text:"",status:e?"extracting":"uploading",sourceSize:n.size},i=[...tK.current,a];tK.current=i,eG(i);let s=(e,t)=>{let r=tK.current.filter(e=>e.id!==a.id);return e<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&r.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?lo("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?lo("utf-16be",t.subarray(2)):t.includes(0)?null:lo("utf-8",t)??lo("euc-kr",t)},()=>null);if(null!==e&&s(e.length,n.size)){tZ(a.id,{...a,text:e,status:"ready"});continue}}if(null===r&&(r=1048576*(await dX().catch(()=>dJ)).uploadLimitMb),n.size>r){tZ(a.id,null)&&eZ(eg("chat.attachStoredTooLarge",{name:n.name,limit:lp(r)}));continue}let o={...a,stored:t,status:"uploading",size:0};if(!tZ(a.id,o))continue;let l=tU.current??uR,c=await dD(l),d=null,u=new AbortController;tQ.current.set(a.id,u);try{if(t1.current.has(a.id))continue;let e=await lx(n,{sessionId:er,draftId:c.draftId,signal:u.signal}),r=tK.current.filter(e=>e.id!==a.id).reduce((e,t)=>e+t.text.length,0),i=lg({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-r)),p=new TextEncoder().encode(i).byteLength;if(!s(i.length,p)){tZ(a.id,null)&&eZ(eg("chat.attachTotalTooLarge",{limit:lp(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:i,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tZ(a.id,h))d=e.id;else if(!t1.current.has(a.id)&&l!==tU.current){let t=dL(l)??{value:"",images:[],documents:[]};dA(l,{...t,documents:[...t.documents,uM(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tZ(a.id,null)&&eZ(eg("chat.attachUploadFailed",{name:n.name,error:e instanceof Error?e.message:String(e)}))}finally{tQ.current.delete(a.id),c.end(d)}d&&"audio"===t&&tK.current.some(e=>e.attachmentId===d)&&t6(d)}},[tZ,t6,er,eg]),t9=(0,a.useCallback)(async e=>{eZ(null);let{images:t,documents:r,audio:n,files:a}=function(e){let t=[],r=[],n=[],a=[];for(let i of e)i.type.startsWith("image/")?t.push(i):null!==la(i)?r.push(i):ls(i)?n.push(i):a.push(i);return{images:t,documents:r,audio:n,files:a}}(e),i=r.filter(e=>e.size>8388608);await Promise.all([tG(t),tJ(r.filter(e=>e.size<=8388608)),t7(n,"audio"),t7([...a,...i],"file")])},[tJ,t7,tG]),re=(0,a.useCallback)(e=>{eV(t=>{let r=[...t],[n]=r.splice(e,1);return n&&uP(n),tq.current=r,r})},[]),rt=(0,a.useCallback)(e=>{let t=tK.current.find(t=>t.id===e);if(t1.current.add(e),tQ.current.get(e)?.abort(),t?.attachmentId){t0.current.get(t.attachmentId)?.abort(),t.transcription?.state==="fallback"&&uA(t.attachmentId,t.transcription.token);var r=t.attachmentId;for(let[e,t]of dk)t.delete(r)&&(0===t.size&&dk.delete(e),dK())}let n=tK.current.filter(t=>t.id!==e);tK.current=n,eG(n)},[]),rr=(0,a.useCallback)(()=>{tq.current=[],eV(e=>(e.forEach(uP),[]))},[]),rn=(0,a.useCallback)(()=>{tK.current=[],eG([])},[]),ra=(0,a.useCallback)(()=>{tB.current="",ew(""),ts(null),e7(null),tt(!1),tp(!1),Q&&dP(Q),tU.current&&tU.current!==Q&&dP(tU.current),rr(),rn(),eZ(null),tS.current&&(tS.current.style.height="auto")},[rn,rr,Q]);(0,a.useEffect)(()=>{Q&&tU.current===Q&&dA(Q,{value:ey,images:eq.map(uj),documents:eY.map(uM)})},[eq,Q,eY,ey]),(0,a.useEffect)(()=>{let e=tU.current;if(e===Q)return;e&&dA(e,{value:tB.current,images:tq.current.map(uj),documents:tK.current.filter(e=>"ready"===e.status).map(uM)});let t=Q?dL(Q):null;tU.current=Q;let r=t?.value??"",n=uC(t?.images),a=uI(t?.documents);tB.current=r,tq.current=n,tK.current=a,ew(r),ts(null),tp(!1),eV(e=>(e.forEach(uP),n)),eG(a)},[Q]),(0,a.useEffect)(()=>{let e=tS.current;e&&(e.style.height="auto",ey&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ey]),(0,a.useEffect)(()=>()=>{tq.current.forEach(uP)},[]);let ri=(0,a.useCallback)((e,t)=>{let r=function(e,t){let r=dz(t);if(0===r.length)return()=>{};let n=++dy;return db.set(n,{draftId:dW(e),ids:r}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=db.get(n);if(t){if(db.delete(n),"accepted"===e){let e=dj.get(t.draftId)??new Set;for(let r of t.ids)e.add(r);dj.set(t.draftId,e)}dK()}}}(tU.current??uR,e);Promise.resolve(t()).then(e=>r("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),rs=(0,a.useCallback)(async()=>{let t=ey.trim(),r=e0.trim(),n=r.startsWith("/")||r.startsWith("!")?r:t;if(!n&&!eq.length&&!eY.length||o||eX)return;Y?.();let a=eq.length?eq:void 0,i=eY.length?eY:void 0;if(n.startsWith("/")){await ur(n,q,G,t=>ri(i,()=>e(t,a,i)),eZ,!!(a||i),K)&&ra();return}ra(),ri(i,()=>e(n,a,i))},[ey,e0,eq,eY,eX,o,G,q,K,e,ra,Y,ri]),ro=!e0.startsWith("/")||e0.startsWith("//")||/\s/.test(e0.slice(1))?null:e0.slice(1).toLowerCase(),rl=(()=>{if(null===ro)return[];let e=[...o?[]:ug,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),r=uw(e,eg).toLowerCase();return t.includes(ro)||r.includes(ro)}).sort((e,t)=>{let r=uy(e,ro,eg)-uy(t,ro,eg);return 0!==r?r:ub[e.source]-ub[t.source]||uc.compare(e.name,t.name)}).filter(e=>{let r=e.name.toLowerCase();return!t.has(r)&&(t.add(r),!0)})})(),{commands:rc,groups:rd}=(es=0,{commands:(eo=ux.map(e=>{let t=rl.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!uk(e,tj)),...t.filter(e=>uk(e,tj))]:t;return{source:e,items:r.map(e=>({command:e,index:es++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:eo}),ru=1===rl.length?eg(ro?"chat.match":"chat.command"):eg(ro?"chat.matches":"chat.commands",{count:rl.length}),rp=!!ey.trim(),rh=!eX&&(rp||eq.length>0||eY.length>0),rm=(0,a.useCallback)((e,t)=>{let r=function(e,t){let r=Math.max(0,Math.min(e.length,t)),n=/(?:^|\s)(\/\/[^\s]*)$/.exec(e.slice(0,r));if(!n)return null;let a=r-n[1].length,i=/^\S*/.exec(e.slice(r))[0];return{start:a,end:r+i.length,query:e.slice(a+2,r)}}(e,t??e.length);if(e7(r?{value:e,draftKey:Q,token:r}:null),tn(!1),!ee)return void ts(null);let n=t??e.length;ts(d0(e.slice(0,n)))},[ee,Q]),rf=ti?.query??null,rg=a.useMemo(()=>null!==rf&&tf&&tf.cwd===ee?function(e,t,r=20){let n=t.toLowerCase();if(!n)return e.slice(0,r);let a=[];for(let t of e){let e=function(e,t){let r=e.path.toLowerCase(),n=0;if(t.includes("/"))r===t?n=100:r.startsWith(t)?n=80:r.includes(t)?n=50:d2(t,r)&&(n=10);else{let e=r.lastIndexOf("/"),a=-1===e?r:r.slice(e+1);a===t?n=100:a.startsWith(t)?n=80:a.includes(t)?n=50:r.includes(t)?n=30:d2(t,r)&&(n=10)}return e.isDir&&n>0&&(n+=10),n}(t,n);e>0&&a.push({entry:t,score:e})}return a.sort((e,t)=>t.score-e.score||d1(e.entry.path)-d1(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),a.slice(0,r).map(e=>e.entry)}(tf.entries,rf):[],[rf,tf,ee]),rx=!!(rf&&tf?.truncated&&tf.cwd===ee);(0,a.useEffect)(()=>{if(!rx||!ee||!rf)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(rf)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ty({cwd:ee,query:rf,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[rx,rf,ee]);let rv=rx&&null!==tb&&tb.cwd===ee&&tb.query===rf,rb=rv?tb.matches:rg,ry=null===ti?null:`${ti.start}:${+!!ti.quoted}:${ti.query}`;(0,a.useEffect)(()=>{if(null===ry){tl(!1),td(0);return}tl(!0),td(0)},[ry]);let rw=null!==ti,rk=d9(tL,tu,{viewportFraction:.44,cap:360}),rj=d9(tL,e8,{viewportFraction:.56,cap:460}),rS=d9(tL,to,{viewportFraction:.48,cap:400}),rC=d9(tL,te,{viewportFraction:.48,cap:400}),rN=e9?`${e9.start}:${e9.end}:${e9.query}`:null;(0,a.useEffect)(()=>{tt(null!==rN)},[rN]);let rT=(0,a.useCallback)((e,t,r,n=!1)=>{tB.current===e&&tU.current===Q&&(tB.current=t,ew(t),e7(null),tt(!1),tn(n),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(r,r),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[Q]);(0,a.useEffect)(()=>{if(!rw||!ee)return;let e=tD.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tH.current===ee||(tH.current=ee,tv(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tg({cwd:ee,entries:function(e){let t=new Set;for(let r of e){let e=r.indexOf("/");for(;-1!==e;)t.add(r.slice(0,e)),e=r.indexOf("/",e+1)}let r=[];for(let e of t)r.push({path:e,isDir:!0});for(let t of e)t&&r.push({path:t,isDir:!1});return r.sort((e,t)=>d1(e.path)-d1(t.path)||e.path.localeCompare(t.path)),r}(e.files??[]),truncated:!!e.truncated}),tD.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tD.current=null}).finally(()=>{tH.current=null,tv(!1)}))},[rw,ee]);let rI=(0,a.useCallback)(e=>{if(!ti)return;let t=tS.current,r=t?.selectionStart??ey.length,n=ey.slice(0,ti.start),a=ey.slice(r);ti.quoted&&a.startsWith('"')&&(a=a.slice(1));let i=function(e,t,r=!1){let n=t?`${e}/`:e,a=r||n.includes(" ");if(t){let e=a?`@"${n}"`:`@${n}`;return{text:e,cursorOffset:a?e.length-1:e.length}}let i=a?`@"${n}" `:`@${n} `;return{text:i,cursorOffset:i.length}}(e.path,e.isDir,ti.quoted),s=n+i.text+a,o=n.length+i.cursorOffset;ew(s),ts(d0(s.slice(0,o))),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[ti,ey]);(0,a.useEffect)(()=>{tc>=rb.length&&td(Math.max(0,rb.length-1))},[rb.length,tc]),(0,a.useEffect)(()=>{tW.current.length=rb.length},[rb.length]),(0,a.useEffect)(()=>{to&&tW.current[tc]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tc,to]),(0,a.useEffect)(()=>{th>=D.length&&tm(Math.max(0,D.length-1))},[D.length,th]),(0,a.useEffect)(()=>{tO.current.length=D.length},[D.length]),(0,a.useEffect)(()=>{tu&&tO.current[th]?.scrollIntoView({block:"nearest",inline:"nearest"})},[th,tu]);let rM=(0,a.useCallback)(e=>{tB.current=e,ew(e),tp(!1),tm(0),ts(null),requestAnimationFrame(()=>{let t=tS.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),rE=(0,a.useCallback)(e=>{let t=`/${e.name} `;tB.current=t,ew(t),e4(!1),e6(0),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),r$=(0,a.useCallback)(async e=>{let t=ey.trim(),n=e0.trim(),a=n.startsWith("/")||n.startsWith("!")?n:t,s=eX||!a&&0===eq.length&&0===eY.length?null:{message:a,images:eq.length?eq:void 0,documents:eY.length?eY:void 0};if(!s)return;Y?.();let o="steer"===e?"steer":"followUp";if(a.startsWith("/")){await ur(a,q,G,e=>{if(!X)throw Error("Cannot queue this command while the session is busy.");ri(s.documents,()=>X(e,o,s.images,s.documents))},eZ,!!(s.images?.length||s.documents?.length),K)&&ra();return}ra(),"steer"===e&&r?ri(s.documents,()=>r(s.message,s.images,s.documents)):"followup"===e&&i&&ri(s.documents,()=>i(s.message,s.images,s.documents))},[ey,e0,eq,eY,eX,q,K,G,X,r,i,ra,Y,ri]),rR=(0,a.useCallback)(e=>{let t=rc.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e5-1);if("right"===e)return Math.min(t,e5+1);let r=tz.current[e5];if(!r)return"down"===e?Math.min(t,e5+1):Math.max(0,e5-1);let n=r.getBoundingClientRect(),a=n.left+n.width/2,i=n.top+n.height/2,s=-1,o=1/0;for(let r=0;r<=t;r+=1){if(r===e5)continue;let t=tz.current[r];if(!t)continue;let n=t.getBoundingClientRect(),l=n.top+n.height/2-i;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(n.left+n.width/2-a);c<o&&(s=r,o=c)}return s>=0?s:"down"===e?Math.min(t,e5+1):Math.max(0,e5-1)},[rc.length,e5]),rL=(0,a.useCallback)(e=>{let n=e.nativeEvent,a=Date.now()-tF.current<100,s=tP.current||n.isComposing||229===n.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||a)){a&&e.preventDefault();return}if(tu&&!s){if("ArrowDown"===e.key){e.preventDefault(),tm(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tm(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tp(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[th]){e.preventDefault(),rM(D[th]);return}}if(!(te&&e9&&!s&&ta.current?.handleKeyDown(e))){if(e8&&null!==ro){if("ArrowDown"===e.key){e.preventDefault(),e6(rR("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e6(rR("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e6(rR("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e6(rR("left"));return}if("Escape"===e.key){e.preventDefault(),e4(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rc[e5]){e.preventDefault(),rE(rc[e5]);return}}if(to&&null!==ti&&!s){if("ArrowDown"===e.key){e.preventDefault(),td(e=>Math.min(Math.max(0,rb.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),td(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tl(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rb[tc]){e.preventDefault(),rI(rb[tc]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===ey.trim().length){e.preventDefault(),e4(!1),tl(!1),tm(D.length-1),tp(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(r||i)?r$(r?"steer":"followup"):rs())}},[o,r,i,t,e8,ro,rc,e5,rE,r$,rs,rR,to,ti,rb,tc,rI,tu,D,th,rM,ey,te,e9]),rA=(0,a.useCallback)(()=>{let e=tS.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),rP=(0,a.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let r=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&r.push(e)}return r}(e.clipboardData);t.length&&(e.preventDefault(),t9(t))},[t9]);(0,a.useEffect)(()=>{if(null===ro){e4(!1),e6(0),t_.current=!1;return}e4(!0),e6(0),!t_.current&&K&&(t_.current=!0,Promise.resolve(K()).catch(()=>{t_.current=!1}))},[ro,K]),(0,a.useEffect)(()=>{if(!e8||!ee)return;let e=!1;return tk({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let r={};for(let e of t.skills??[])r[e.name]=e.disableModelInvocation;tk({cwd:ee,values:r})}).catch(()=>{e||tk({cwd:ee,values:{}})}),()=>{e=!0}},[e8,ee]),(0,a.useEffect)(()=>{e5>=rc.length&&e6(Math.max(0,rc.length-1))},[rc.length,e5]),(0,a.useEffect)(()=>{tz.current.length=rc.length},[rc.length]),(0,a.useEffect)(()=>{e8&&tz.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e8]);let rF=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(up):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(up),r_=g??null,rz=nh.find(e=>e.alias===r_)?.provider??null,rO=rz?rF.filter(e=>e.provider===rz):rF,rD=(el=eN.trim().toLocaleLowerCase())?rO.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(el)):rO,rH=rO.length>8,rB=[];for(let e of rD){let t=rB.find(t=>t.provider===e.provider);t?t.options.push(e):rB.push({provider:e.provider,options:[e]})}let rq=rz?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),rV=l?rq.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,rK=eN.trim()?[]:rO.map((e,t)=>{var r,n;return{option:e,order:t,count:eI[r=e.provider,n=e.modelId,`${r}/${n}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),rG=(e,t,r)=>{let a=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,n.jsxs)("button",{onClick:()=>{if(ej(!1),eT(""),!a||c){var t,r;let n=function(e,t){let r={...e,[t]:(e[t]??0)+1},n=Object.keys(r);if(n.length<=30)return r;for(let e of(n.sort((e,t)=>r[e]-r[t]),n)){if(Object.keys(r).length<=30)break;e!==t&&delete r[e]}return r}(d6(),(t=e.provider,r=e.modelId,`${t}/${r}`));try{window.localStorage.setItem(d5,JSON.stringify(n))}catch{}eM(n),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:a?"var(--bg-selected)":"none",border:"none",color:a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:a?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:[a?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==r&&r>=2&&(0,n.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eg("chat.modelPickCount",{count:r})})]},`${t}:${e.provider}:${e.modelId}`)},rJ=l?rF.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,rZ=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,rY=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eg("chat.compacted")} ${rU(S.tokensBefore)} -> ${rU(S.estimatedTokensAfter)} tokens (${eg("chat.tokensSaved",{saved:rU(rZ)})})`:null,rX=e=>{let t=A?.[e];return null!=t&&t!==e?t:null},rQ="auto"===(ec=T??"auto")?$?`auto ≤ ${rX($)??$}`:"auto":A?A[ec]??ec:ec,r0=(T??"auto")==="auto"&&I&&"auto"!==I?A?.[I]??I:null,r1=R&&r0?eg("chat.currentReasoning",{level:r0}):null,r2=e=>!L||L.includes(e),r8=[{level:"auto",ceiling:null},...um.filter(r2).map(e=>({level:"auto",ceiling:e})),...uh.filter(e=>"auto"!==e&&r2(e)).map(e=>({level:e,ceiling:null}))],r4=Object.entries(ui).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,a.useEffect)(()=>{let e=e=>{tC.current&&!tC.current.contains(e.target)&&tN.current&&!tN.current.contains(e.target)&&(ej(!1),eT("")),tT.current&&!tT.current.contains(e.target)&&tI.current&&!tI.current.contains(e.target)&&eA(!1),tM.current&&!tM.current.contains(e.target)&&ez(!1),tE.current&&!tE.current.contains(e.target)&&eO(!1),t$.current&&!t$.current.contains(e.target)&&eB(!1),!tR.current||tR.current.contains(e.target)||tS.current?.contains(e.target)||tp(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,a.useEffect)(()=>{eb||eB(!1)},[eb]);let r5=(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eq.length||eK.length?" is-active":""}`,onClick:()=>tA.current?.click(),title:eg("chat.attachFile"),"aria-label":eg("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eq.length||eK.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=eq.length||eK.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eq.length||eK.length?"var(--accent)":"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,n.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,n.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),r6=f&&nh.length>0?(0,n.jsxs)("div",{ref:tT,style:{position:"relative",flexShrink:+!!eb,minWidth:0},children:[(0,n.jsxs)("button",{className:`${eb?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eF({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eg("chat.mainPreset"),"aria-label":eg("chat.mainPreset"),children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eb?null:(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eg("chat.mainPreset")})]}),eL&&eP&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eP.top,eP.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eP.top+6}:{top:eP.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eP.left,width:"max-content",minWidth:eP.width};return(0,n.jsx)("div",{ref:tI,role:"menu","aria-label":eg("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tT.current?.querySelector("button")?.focus())},style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:(0,n.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:nh.map(e=>{let t=e.alias===r_;return(0,n.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eA(!1),f({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("img",{className:"account-avatar",src:nU(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,n.jsx)("span",{children:nL(e.alias)}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,r3=R?(0,n.jsxs)("div",{ref:tE,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,n.jsxs)("button",{type:"button",className:`${eb?"composer-icon-button":"composer-chip"}${eW?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eH({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(!1),eO(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eW,onKeyDown:e=>{"Escape"===e.key&&eW&&(e.stopPropagation(),eO(!1))},title:eg("chat.changeReasoning",{level:rQ}),"aria-label":eg("chat.changeReasoning",{level:rQ}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eb?0:"8px 12px",height:32,background:eW?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eW?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,n.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eb?null:(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:rQ})]}),eW&&eD&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eD.top,eD.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eD.top+6}:{top:eD.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eD.left,width:"max-content",minWidth:Math.max(180,eD.width)};return(0,n.jsx)("div",{role:"menu","aria-label":eg("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eO(!1),tE.current?.querySelector("button")?.focus())},style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:r},children:r8.map(({level:e,ceiling:t})=>{let r=(T??"auto")===e&&("auto"!==e||($??null)===t),a=t??e,i="auto"===e&&null===t?null:rX(a),s=t?`auto ≤ ${i??t}`:i??e,o=t?eg("chat.thinkingAutoCapped",{level:i??t}):eg(uf[e]);return(0,n.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":r,onClick:()=>{eO(!1),R(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsxs)("span",{style:{flex:1},children:[s,null!==i&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",a,")"]})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,r7=_?(ed=F?eg("chat.fastModeBusy"):null===P?eg("chat.fastModeUnknown"):P.active?eg("chat.fastModeActive"):P.enabled?eg("chat.fastModeInactive"):eg("chat.fastModeOff"),eu=F||o||b,ep=P?.enabled===!0,(0,n.jsx)("button",{type:"button",className:`composer-icon-button${P?.active?" is-active":""}`,onClick:_,disabled:eu,"aria-pressed":null===P?void 0:P.enabled,"aria-busy":F||void 0,title:ed,"aria-label":ed,style:{flexShrink:0,opacity:o?.5:1},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:P?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===P?"3 2":void 0,style:{opacity:ep&&!P?.active?.6:1},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,r9=(0,n.jsxs)(n.Fragment,{children:[r&&(0,n.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>r$("steer"),disabled:!rh,title:eX?eg("chat.attachExtractingWait"):eg("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rh?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:rh?"var(--warning)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eg("chat.steer")]}),i&&(0,n.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>r$("followup"),disabled:!rh,title:eX?eg("chat.attachExtractingWait"):eg("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rh?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:rh?"var(--accent-hover)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,n.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,n.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eg("chat.followUp")]})]}),ne=void 0!==Z?(0,n.jsx)(de,{soundEnabled:J??!0,onToggle:Z}):null;return(0,n.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,n.jsx)("input",{ref:tA,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t9(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(u_,{error:p}),(0,n.jsx)(uz,{warnings:h}),O.length>0&&(0,n.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,n.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ex("delivery.title",{count:O.length})}),H&&ev&&(0,n.jsxs)("button",{onClick:H,title:eg("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,n.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eg("chat.recall")]})]}),(0,n.jsx)(c5,{rows:O,removeLabel:eg("chat.queueRemove"),onRemove:U?(e,t)=>U("steer"===e?"steering":"followUp",t):void 0})]}),W&&(0,n.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]}),eg("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,n.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),rY&&(0,n.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),rY]}),j&&(0,n.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eJ&&(0,n.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eJ}),(0,n.jsx)("button",{type:"button",onClick:()=>eZ(null),"aria-label":eg("i18n.close"),title:eg("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,n.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eq.length>0||eK.length>0)&&(0,n.jsxs)("div",{role:"list","aria-label":eg("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eq.map((e,t)=>(0,n.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,n.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,n.jsx)("button",{type:"button","aria-label":eg("chat.removeImage",{index:t+1}),onClick:()=>re(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,n.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eK.map(e=>(0,n.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||un(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,n.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):aT(e.name,14),(0,n.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,n.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,n.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eg("chat.attachKindAudio"):"file"===e.stored?eg("chat.attachKindFile"):uu[e.mimeType]," \xb7 ",lp(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eg("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eg("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eg("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"||e.transcription?.state==="fallback"?` \xb7 ${eg("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eg("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,n.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eg("chat.attachTranscribeFailed")}`})]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>rt(e.id),"aria-label":eg("chat.removeAttachment",{name:e.name}),title:eg("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,n.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eQ.length>0&&(0,n.jsx)("div",{role:"group","aria-label":eg("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eQ.map(e=>{let t,r,a,i,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?eg("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eg("chat.transcribeDurationUnknown"):(r=Math.floor((t=Math.round(c.durationSeconds))/3600),a=Math.floor(t%3600/60),i=String(t%60).padStart(2,"0"),r>0?`${r}:${String(a).padStart(2,"0")}:${i}`:`${a}:${i}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?eg("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="fallback"?eg("chat.transcribeFallbackTitle",{name:e.name}):l?.state==="running"?eg("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${eg("chat.transcribeChecking")}`:l?.state==="failed"?eg("chat.transcribeFailedRow",{name:e.name,error:l.error}):eg("chat.transcribeSkipped",{name:e.name});return(0,n.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,n.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,n.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[l.plan.notice&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeUsageNotice")})]}),l?.state==="fallback"&&(0,n.jsxs)(n.Fragment,{children:[l.reason&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.reason}),l.completedParts>0&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:eg("chat.transcribeFallbackProgress",{done:l.completedParts,total:l.parts})}),(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeFallbackUsageNotice")})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{confirmed:!0}),children:eg("chat.transcribeStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),l?.state==="fallback"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{fallbackToken:l.token,approve:!0}),children:eg("chat.transcribeFallbackStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void t6(o),children:eg(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,n.jsxs)("div",{ref:tL,style:{position:"relative",minWidth:0},children:[tu&&D.length>0&&(0,n.jsxs)("div",{ref:tR,style:{position:"absolute",left:0,right:0,...ul(rk.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rk.maxHeight},children:[(0,n.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,n.jsx)("path",{d:"M3 4v5h5"}),(0,n.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rk.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let r=t===th;return(0,n.jsxs)("button",{ref:e=>{tO.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rM(e)},onMouseEnter:()=>tm(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,n.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,n.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),tr&&(0,n.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:eg("savedPrompts.saved")}),te&&e9&&(0,n.jsx)(c3,{ref:ta,value:ey,token:e9,cwd:ee,sessionTitle:et,style:ul(rC.side),maxHeight:rC.maxHeight,onReplace:rT,onClose:()=>tt(!1)}),e8&&null!==ro&&(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ul(rj.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rj.maxHeight},children:[(0,n.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,n.jsx)("span",{children:V?eg("chat.loadingCommands"):eg("chat.slashCommands",{label:ru})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rj.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==rl.length?rd.map(e=>(0,n.jsxs)("section",{style:{marginBottom:12},children:[(0,n.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,n.jsx)("span",{children:eg(uv[e.source])}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let r=t===e5,a=uk(e,tj);return(0,n.jsxs)("button",{ref:e=>{tz.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rE(e)},onMouseEnter:()=>e6(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${r?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:r?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,n.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:a?"var(--text-dim)":void 0},children:["/",e.name,a&&(0,n.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eg("chat.dormant")})]}),uw(e,eg)&&(0,n.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uw(e,eg)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,n.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eg("chat.noCommands")})})]}),to&&null!==ti&&(eh=tx&&(!tf||tf.cwd!==ee),em=1===rb.length?eg("chat.match"):eg("chat.matches",{count:rb.length}),ef=tf?.truncated&&!rv?ti.query?eg("chat.searchingAll"):eg("chat.indexTruncated"):"",(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ul(rS.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rS.maxHeight},children:[(0,n.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,n.jsx)("span",{children:eh?eg("chat.loadingFiles"):eg("chat.files",{label:em,hint:ef})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rS.maxHeight-34),overflowY:"auto",padding:4},children:eh||0!==rb.length?rb.map((e,t)=>{let r=t===tc,a=e.path.split("/").pop()??e.path,i=e.path.slice(0,e.path.length-a.length);return(0,n.jsxs)("button",{ref:e=>{tW.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rI(e)},onMouseEnter:()=>td(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,n.jsx)(aS,{size:14}):aT(a,14)}),(0,n.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[i&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:i}),a,e.isDir&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,n.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:rx&&!rv?eg("chat.searching"):eg("chat.noMatchingFiles")})})]})),(0,n.jsxs)("div",{className:`chat-composer-field${e1?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${e1?"var(--tool-bg)":o&&(r||i)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,n.jsx)("textarea",{className:"chat-composer-textarea",ref:tS,"aria-controls":te?"saved-prompt-menu":void 0,value:ey,onChange:e=>{tB.current=e.target.value,ew(e.target.value),tp(!1),rm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;rm(t.value,t.selectionStart)},onKeyDown:rL,onCompositionStart:()=>{tP.current=!0},onCompositionEnd:e=>{tP.current=!1,tF.current=Date.now();let t=e.currentTarget;rm(t.value,t.selectionStart)},onInput:rA,onPaste:rP,placeholder:o&&(r||i)?eg("chat.steerPlaceholder"):o?eg("chat.agentPlaceholder"):eg("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),o?eb?null:(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:r9}):(0,n.jsxs)("button",{className:"chat-composer-send",onClick:rs,disabled:!rh,"aria-busy":eX||void 0,"aria-label":eb?eg("chat.send"):void 0,title:eX?eg("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eb?44:void 0,padding:eb?0:"7px 14px",background:rh?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:rh?"var(--accent-hover)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,n.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eb?null:eg("chat.send")]})]})]}),e1&&(0,n.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e2?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eg("chat.shell")," \xb7 ",e2?eg("chat.outputLocal"):eg("chat.outputModel")]}),(0,n.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("div",{style:{flex:eb?"1 1 0%":"0 0 auto",minWidth:eb?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eb||!o)&&r5,!eb&&r6,!(eb&&o)&&(rF.length>0||rJ||p)&&m&&(0,n.jsxs)("div",{ref:tC,style:{position:"relative",flex:eb?"1 1 0%":void 0,width:eb?0:void 0,minWidth:44*!!eb},children:[(0,n.jsxs)("button",{className:`composer-chip${ek?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eC({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(e=>(e&&eT(""),!e))},disabled:o||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eb?"flex-start":void 0,padding:eb?"8px 10px":"8px 12px",height:32,width:eb?"100%":void 0,maxWidth:eb?"100%":220,overflow:"hidden",background:ek?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ek?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":rF.length>0?"Change model":"No available models",children:[b?(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rJ??(rF.length>0?"Select model":"No models")})]}),ek&&eS&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eS.top,eS.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eS.top+6}:{top:eS.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eS.left,width:"max-content",minWidth:eS.width};return(0,n.jsxs)("div",{ref:tN,style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:[rH&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsx)("input",{value:eN,onChange:e=>eT(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eT(""),ej(!1))},placeholder:eg("chat.filterModels"),"aria-label":eg("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eb,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,n.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[rK.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eg("chat.frequentModels")}),rK.map(({option:e,count:t})=>rG(e,"frequent",t))]}),rq.length>0&&!eN.trim()&&v&&(0,n.jsxs)("div",{style:{borderTop:rK.length>0?"1px solid var(--border)":"none"},children:[(0,n.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eE,"aria-controls":"model-role-rows",onClick:eR,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,n.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eE?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,n.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,n.jsx)("span",{style:{textTransform:"uppercase"},children:eg("chat.modelRoles")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:rq.length}),rV&&(0,n.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:rV.tag??rV.role.toUpperCase()}),rV.name]})]}),(0,n.jsx)("div",{id:"model-role-rows",hidden:!eE,children:rq.map(e=>{let t=rV?.role===e.role,r=e.resolved?.name??e.resolved?.modelId??"";return(0,n.jsxs)("button",{onClick:()=>{ej(!1),eT(""),v(e.role)},title:e.selector??r,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,n.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[r,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eg("chat.allModels")})]}),0===rB.length?(0,n.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eN.trim()?eg("chat.noMatchingModels"):"No available models"}):rB.map((e,t)=>(0,n.jsxs)("div",{children:[rB.length>1&&(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>rG(e,"all"))]},e.provider))]})]})})()]}),eb&&o&&(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:r9}),!eb&&r3,!eb&&r7,!eb&&r1&&(0,n.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:r1}),!eb&&null!==M&&(0,n.jsx)("span",{title:eg(E?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:eg(E?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,n.jsx)(dp,{sessionId:er})]}),(0,n.jsxs)("div",{ref:t$,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eb?4:2},children:[eb?(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eU?" is-active":""}`,title:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,n.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eU?void 0:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:eg("chat.moreControls")}),(0,n.jsxs)("div",{role:"group","aria-label":eg("chat.moreControls"),style:{display:eU?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:eb?"flex-start":"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eb&&(0,n.jsxs)(n.Fragment,{children:[o&&r5,r6,r3,r7]}),!o&&N&&(0,n.jsxs)("div",{ref:tM,style:{position:"relative"},children:[(0,n.jsxs)("button",{className:`composer-chip${e_?" is-active":""}`,onClick:()=>!o&&ez(e=>!e),disabled:o,title:eg("chat.changeToolPreset")+`: ${r4}`,"aria-label":eg("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:e_?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=e_?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:r4})]}),e_&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:ua.map(e=>{let t=ui[e],r=(C??"default")===t,a="off"===e?eg("chat.noTools"):"default"===e?eg("chat.builtInTools",{tools:us}):eg("chat.allBuiltInTools",{tools:`${us} + ${uo}`});return(0,n.jsxs)("button",{onClick:()=>{ez(!1),r||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1},children:e}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:a})]},e)})})]}),!o&&y&&(0,n.jsx)("div",{children:(0,n.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eg("chat.stopCompaction"):eg("chat.compactContext"),"aria-label":k?eg("chat.stopCompaction"):eg("chat.compactContext"),children:k?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compacting")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compact")})]})})}),eb&&ne,eU&&(0,n.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eg("chat.collapseControls"),"aria-label":eg("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ez(!1),eO(!1),eB(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,n.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eg("chat.stopAgent"),"aria-label":eb?eg("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eb?44:void 0,padding:eb?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eb?null:eg("chat.stop")]}),(0,n.jsx)(dd,{sessionId:er,onEnsureSession:en,onTranscriptPersisted:ea}),!eb&&ne]})]})]})]})});function uO({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),r=e$(t);return(0,n.jsx)("div",{role:"status","aria-label":r,title:r,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eF(t).map((e,t)=>(0,n.jsx)("span",{style:e.style,children:e.text},t))})})}function uD({phases:e,flow:t,busy:r}){let{t:i}=(0,z.s)(),{st:s}=ag(),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(!1),h=(0,a.useId)(),m=e??[],{currentPhase:f,activeTask:g,remaining:x,completed:v,total:b,percent:y}=tL(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,r){if(!t||!e.current)return null;let n=r("flow.strip.running",{stage:r(`flow.stage.${e.current}`)});return e.attempt>1?`${n} \xb7 ${r("flow.attempt",{attempt:e.attempt})}`:n}(t,r,s);if(0===b&&null===j)return null;let S=b>0&&0===x;return(0,n.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,n.jsxs)("div",{className:"todo-strip-row",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,n.jsx)("span",{className:"todo-strip-lead",role:r?"status":void 0,children:j}),b>0&&(0,n.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!j&&f&&(0,n.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,n.jsx)("span",{className:"todo-strip-task",children:S?i("todo.allDone",{count:v}):g?.content??""}),(0,n.jsx)("span",{className:"todo-strip-count",children:S?i("todo.progressDone",{percent:y??0,completed:v,total:b}):i("todo.progress",{percent:y??0,completed:v,total:b,remaining:x})})]}),k&&(0,n.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,n.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,n.jsx)(oy,{flow:t,live:r,st:s,id:h}),o&&b>0&&(0,n.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let r=e.tasks.filter(e=>u||"completed"!==e.status);return 0===r.length?null:(0,n.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),r.map((e,t)=>(0,n.jsx)(aw,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,n.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:i(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function uH(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uU(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function uB(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let r={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let n=await t.getServiceWorkerRegistration();if(n)return await n.showNotification(e.title,{...r,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let n=t.createWindowNotification(e.title,r);return n.onclick=()=>{n.close(),e.onClick()},"window"}catch{return null}}class uq extends Error{constructor(e,t,r,n){super(e),this.status=t,this.code=r,this.accepted=n,this.name="AgentCommandError"}}async function uV(e,t){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok||n.error)throw new uq(n.error??`HTTP ${r.status}`,r.status,n.code,n.accepted);return n.data}let uK="ompweb-update-client-id",uG="ompweb-update-resume-intent-v2",uJ="ompweb-update-return-v1",uZ="cuelo-restart-return-v1",uY="ompweb-update-failure-return-v1",uX="ompweb:update-wake";function uQ(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function u0(){let e=sessionStorage.getItem(uK);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(uK,t),t}function u1(){sessionStorage.removeItem(uG)}function u2(){let e=sessionStorage.getItem(uJ);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function u8(e){let t=u2();if(!t||t.requestId!==e)return t;let r={...t,dismissed:!0};try{sessionStorage.setItem(uJ,JSON.stringify(r))}catch{}return r}async function u4(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:u0(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function u5(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let r=await t.json().catch(()=>null);!function(e){let t=u2();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let r={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(uJ,JSON.stringify(r))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u1();let n=r?.wake;e.sessionId&&(n?.wake===!0||n?.reason==="already-claimed"||n?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(uX,{detail:{sessionId:e.sessionId}}))}async function u6(e){let t=function(e){let t=sessionStorage.getItem(uY);if(!t)return null;sessionStorage.removeItem(uY);try{let r=JSON.parse(t);if(1!==r.schemaVersion||r.requestId!==e.requestId||r.stageHash!==e.stageHash||r.clientId!==e.clientId)return null;return{wake:!0===r.wake}}catch{return null}}(e);return t?(u1(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(uX,{detail:{sessionId:e.sessionId}})),"failed"):(await u5(e),"resumed")}function u3(e,t){let r=new Map(e.map(e=>[e.id,e]));for(let e of t)r.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(r.get(e.id),e));let n=[...r.values()];return[...n.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...n.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function u7(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function u9(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function pe(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function pt(e){return t=>{let r=e?.isCompacting?e.compaction:null;if(!r)return t;let n=Date.now()-r.elapsedMs;return{startedAt:t?Math.min(t.startedAt,n):n,reason:t?.reason??r.reason}}}function pr(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],a=t[r];if(!n||!a||n.name!==a.name||n.tasks.length!==a.tasks.length)return!1;for(let e=0;e<n.tasks.length;e+=1){let t=n.tasks[e],r=a.tasks[e];if(!t||!r||t.content!==r.content||t.status!==r.status||t.blocker!==r.blocker||(t.dependsOn?.length??0)!==(r.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==r.dependsOn?.[t]))return!1}}return!0}function pn(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function pa(e,t){for(let r=e.length-1;r>=0;r--){let n=t[r]??null;if(!tn(n??void 0))return{message:e[r],entryId:n}}return null}let pi=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class ps extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function po(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pl(e){return new Promise(t=>setTimeout(t,e))}function pc(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,r)=>r===t?{...e,exiting:!0}:e)}function pd(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:pc(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:pc(e.visible)};case"remove":return function(e,t){let r=e,n=t;for(;n.length>0&&r.length<5;){let[e,...t]=n;r=[...r,e],n=t}return n.length>0&&!r.some(e=>e.exiting)&&(r=pc(r)),{visible:r,pending:n}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function pu(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function pp(e){let t,r=e.content;return"string"==typeof r?JSON.stringify({text:r,images:[]}):Array.isArray(r)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:r.map(pu).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function ph(e){return"user"===e.role?`user:${pp(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function pm(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function pf(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function pg(e){rN(e),e.clear()}function px(e,t,r){for(let n of r??[]){let r=rC(t,n);r&&e.add(r)}}function pv(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let pb=!1,py={width:0,height:0},pw=new Set,pk=null;function pj(){let e=window.visualViewport,t=pv();py.width!==window.innerWidth?py={width:window.innerWidth,height:window.innerHeight}:t||(py.height=Math.max(py.height,window.innerHeight));let r=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:r,viewportScale:n,baselineHeight:a}){return!(!e||Math.abs(n-1)>=.01)&&(t-r>120||a-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:py.height});if(r!==pb)for(let e of(pb=r,pw))e()}function pS(e){if(pw.add(e),!pk){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,pj()})},r=window.visualViewport;r?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),pj(),pk=()=>{r?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{pw.delete(e),0===pw.size&&pk&&(pk(),pk=null)}}function pC(){return(0,a.useSyncExternalStore)(pS,()=>pb,()=>!1)}let pN={count:50,end:null};function pT(e,t){let r=Math.max(e,0),n=null===t.end?r:Math.min(Math.max(t.end,0),r),a=Math.min(Math.max(t.count,0),n),i=n-a;return{startIndex:i,endIndex:n,hasMore:i>0,hasLater:n<r}}function pI(e,t,r){let{startIndex:n,endIndex:a}=pT(e,r);if(t>=n&&t<a)return r;let i=Math.max(0,t-10),s=Math.max(t+1,i+50);return s>=e?{count:e-i,end:null}:{count:s-i,end:s}}function pM({sticker:e,text:t,tag:r,followRef:i}){let s=(0,a.useRef)(null);return((0,a.useEffect)(()=>{(!i||i.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,n.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,n.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:r8[r]}),t&&(0,n.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,n.jsx)(cm(),{id:"71a4a7cebbc6c842",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function pE(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),r=(lu(t)?.message??t).trim();return r.length>0?r:null}function p$(e){return`omp-cues:${e}`}function pR(e,t){let r=[];for(let n of t)n.sessionId===e&&null!==n.anchorEntryId&&r.push({id:n.id,anchorEntryId:n.anchorEntryId,sticker:n.sticker,text:n.text,tag:n.tag});try{window.localStorage.setItem(p$(e),JSON.stringify(r.slice(-200)))}catch{}}let pL=[];function pA(e){return`omp-web:interrupted-dismissed:${e}`}let pP=(0,a.memo)(function({messages:e,entryIds:t,toolResultsMap:r,modelNames:i,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,main:g,process:x,dispatchSlots:v,compactedDispatch:b,openRequest:y,startIndex:w,endIndex:k,sentinelRef:j,laterSentinelRef:S,flashItem:C,t:N,onProcessLogChange:T,cues:I,cueFollowRef:M}){(0,a.useEffect)(()=>{T({groups:x,messages:e,entryIds:t,toolResults:r,modelNames:i,cwd:s,sessionId:f})},[T,x,e,t,r,i,s,f]);let E=(0,a.useMemo)(()=>(function(e){let t=new Map;for(let r=0;r<e.length;r++){let n=tt(e,r);n>=0&&t.set(n,function(e){let t="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");if(!t.startsWith("[interpreter] "))return t;let r=t.indexOf("\n\n");return r<0?t:t.slice(r+2)}(e[r]))}return t})(e),[e]),$=(0,a.useMemo)(()=>{let t=new Map;for(let[n,a]of function(e,t,r,n){let a=new Map;e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.idx,t)});let i=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=r[o.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(o.blocks?a.get(o.idx):void 0)??o.afterMainIndex??-1),l=t;!function(e,t,r){for(let n of e){if("toolCall"!==n.type||"learn"!==n.toolName&&"manage_skill"!==n.toolName)continue;let e=t?.get(n.toolCallId);if(!e||e.isError)continue;let a=n.input??{};if("manage_skill"===n.toolName){let e=to(a.action);if(!0===ts[e]){let t={kind:"skill",action:e,name:to(a.name)};r(JSON.stringify(t),t)}continue}let i=to(a.memory),s=a.skill,o=s?{action:to(s.action),name:to(s.name)}:void 0;r(JSON.stringify({kind:"lesson",memory:i,skill:o}),{kind:"lesson",memory:i.length>160?`${i.slice(0,160)}…`:i,...o?{skill:o}:{}})}}(o.blocks??e.content??[],n,(e,t)=>{if(l.has(e))return;l.add(e);let r=i.get(s);r?r.push(t):i.set(s,[t])})}}return i}(g,x,e,r)){let e=a.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(n,{role:"custom",customType:e9,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,r,N]),R=(0,a.useMemo)(()=>{let n=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(n=t.idx);return function(e,t,r,n,a,i,s=[]){let o=function(e,t,r){let n=new Map,a=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&sD(t,e.idx)===e.idx).map(e=>e.idx),i=null===r?null:sD(t,r),s=new Map;for(let[r,o]of(e.forEach((e,r)=>{"answer"===e.kind&&s.set(sD(t,e.anchorIdx),r)}),s)){if(r===i)continue;let e=a.find(e=>e>r);n.set(o,{from:r+1,to:e??t.length})}return n}(e,t,r),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,r]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(sU(t,n,r.from,u,d),u=Math.max(u,r.from),0===r.from&&i){let a=r.to-1;for(;a>=r.from&&tn(s[a]);)a-=1;if(s[a]!==i.throughEntryId)continue;let o=sW(t,r.from,r.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sH(t,n,r.from,r.to);c.set(e,{...i.summary,...p?{remaining:s_(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...i.ciHeads),u=r.to;continue}c.set(e,{...function(e,t,r,n,a,i=[]){let s=sW(e,r,n),o=sH(e,t,r,n);return{...sz(s,t,a),remaining:o?s_(o):null,span:sB(e,r,n),flow:sP(s,t,!1,i,a,sO(e,r,n))}}(t,n,r.from,r.to,a,d),latest:e===l})}return c}(g,e,n,r,s,y,t)},[g,e,r,s,l,y,t]),L=w>0,A=k<g.length,P=(a,g={})=>{let x=g.messageOverride??e[a],v=a-1;for(;v>=0&&tn(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=a+1;t<e.length;t++){let r=e[t].role;if("user"===r)break;if("assistant"===r){w=!1;break}}w&&d&&a===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,n.jsx)(lL,{message:x,toolResults:r,modelNames:i,cwd:s,onOpenFile:o,entryId:t[a],onFork:l||c||0===a&&"user"===x.role?void 0:u,forking:p===t[a],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:a>0?e[a-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary,inputTranslation:"user"===x.role?E.get(a):void 0,recoveredError:eK(e,a)},`${y}-view-${a}`)},F=(t,r)=>{let a=g[t],i="message"===a.kind&&e[a.idx]?.role==="user";return(0,n.jsx)("div",{"data-chat-item":t,"data-chat-question":i?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:r})};return(0,n.jsxs)(n.Fragment,{children:[L&&(0,n.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((i,l)=>{let c=w+l,d=b?.position===c?(0,n.jsx)(o_,{calls:b.calls}):null,u="message"===i.kind?i.anchorIdx??i.idx:i.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(r=>{let n=null!==r.anchorEntryId?t.indexOf(r.anchorEntryId):Math.min(r.liveIndex??-1,e.length-1);return n>=i.idx&&n<m}).map(e=>(0,n.jsx)(pM,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),y=h!==u,k=$.get(c),j=k?(0,n.jsx)(lL,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=y?(0,n.jsx)(cw,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:o}):null;if("message"===i.kind)return(0,n.jsxs)(a.Fragment,{children:[d,F(c,P(i.idx)),j,S,x]},`message-${i.idx}`);let C=tN(i.precedingBlocks,r,s);return(0,n.jsxs)(a.Fragment,{children:[d,F(c,P(i.idx,{keyPrefix:`answer-${i.runIndex}`,messageOverride:function(e,t){let r=eB(e,t);if(!e.replyTranslation)return r;let n=e.content.find(e=>"text"===e.type);return n&&t.includes(n)||(r.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(r.content=t.filter(e=>"text"!==e.type))),r}(e[i.idx],i.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:R.get(c)})),j,S,x]},`answer-${i.idx}-${i.runIndex}`)}),b?.position===g.length&&k===g.length&&(0,n.jsx)(o_,{calls:b.calls}),A&&(0,n.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function pF({session:e,newSessionCwd:t,initialSessionData:i,transitioning:s=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onLabWidgetsChange:y,onOpenWorkspaceView:w,onOpenSessionList:k,onOpenMaker:j,selectedMaker:S,onProcessLogChange:C,onOpenFile:N,transcriptReplacement:T,onComposerFocusChange:I,onSessionBusyChange:M,onWaitingChange:E,onAttentionChange:$,soundEnabled:R=!0,onSoundToggle:L,playCueSound:A=async()=>({sticker:null,text:null}),preloadCueSound:P,unlockAudio:F,jumpRequest:_=null,onJumpHandled:W}){var O,D;let H,U,V,{t:K}=(0,z.s)(),G=pC(),J=B(),Z=(0,a.useRef)(A);Z.current=A;let Y=(0,a.useRef)(null),X=(0,a.useRef)(P);X.current=P;let[Q,et]=(0,a.useState)([]),er=(0,a.useRef)(Q);er.current=Q;let en=(0,a.useRef)(0),ea=(0,a.useRef)([]),ei=(0,a.useRef)([]),es=(0,a.useRef)(null),eo=(0,a.useRef)(0),el=(0,a.useRef)(-1),ec=(0,a.useRef)(-1),ed=(0,a.useCallback)(()=>{let e=es.current?.current;return e?{sessionId:e,turn:eo.current}:null},[]),eu=(0,a.useCallback)(e=>es.current?.current===e.sessionId&&eo.current===e.turn,[]),ep=(0,a.useCallback)((e,t,r,n)=>{if(!e.sticker&&!e.text)return;en.current=Math.max(en.current+1,Date.now());let a={id:en.current,sticker:e.sticker,text:e.text,tag:t,sessionId:r.sessionId},i="entry"===n.kind?{...a,anchorEntryId:n.entryId}:{...a,anchorEntryId:null,liveIndex:n.liveIndex,intent:n.intent};et(e=>{let t=[...e,i];return null!==i.anchorEntryId&&pR(r.sessionId,t),t})},[]),eh=(0,a.useCallback)((e,t,r,n)=>{let a=()=>eu(r)&&("working"!==t||ec.current!==r.turn);a()&&Z.current(e,t,a).then(e=>{null!==t&&null!==n&&a()&&ep(e,t,r,n)}).catch(()=>{})},[eu,ep]),em=(0,a.useCallback)(async(e,t,r,n)=>{let a=(await ap(e,t,r,n))?.alias??null;return a&&X.current?.(a),a},[]),ef=(0,a.useCallback)((e,t,r,n,a)=>{let i=function(e,t){let r=e.length-1;if(r<0)return null;let n=Math.min(e.length,t.length);if(r<n)return{kind:"entry",entryId:t[r]};let a=ni(e[r]),i=0;for(let t=n;t<=r;t++)ni(e[t])===a&&(i+=1);return{kind:"pending",liveIndex:r,intent:{baseEntryId:n>0?t[n-1]:null,identity:a,occurrence:i}}}(ea.current,ei.current);em(t.sessionId,r,n,a).then(r=>{eh(r,e,t,i)})},[eh,em]),[eg,ex]=(0,a.useState)(0),ev=(0,a.useRef)([]),eb=(0,a.useCallback)(e=>{if(eo.current+=1,null!==r3(e.outcome)){let t=e.sessionId;ev.current.push({completion:e,trigger:t?{sessionId:t,turn:eo.current}:null}),ex(e=>e+1)}o?.(e)},[o]);(0,a.useEffect)(()=>{for(let{completion:e,trigger:t}of ev.current.splice(0)){let r=r3(e.outcome),n="neutral"===r?null:r;t?ef(n,t,e.provider,e.credentialId,e.model):Z.current(null,n).catch(()=>{})}},[eg,ef]);let ey=(0,a.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ew,error:ek,messages:ej,entryIds:eS,streamState:eC,agentRunning:eN,bashRunning:eT,pendingBash:eI,modelNames:eM,modelList:eE,modelError:eR,modelScopeWarnings:eL,modelThinkingLevels:eA,modelThinkingLevelMaps:eP,modelRoles:eF,toolPreset:e_,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eO,fastMode:eD,fastModeBusy:eH,handleFastModeToggle:eU,retryInfo:eq,contextUsage:eZ,forkingEntryId:eY,isCompacting:e0,compaction:e1,compactError:e8,compactResult:e4,displayModel:e9,modelSwitching:ts,sessionStats:to,runStateKnown:tc,compactedWork:td,slashCommands:tu,slashCommandsLoading:tp,deliveryRows:th,subagents:tm,todoPhases:tf,notices:tg,extensionDialog:tx,extensionResponse:tv,extensionCustomUi:tb,extensionStatuses:ty,extensionWidgets:tw,respondToExtensionUi:tk,sendExtensionCustomInput:tj,isAutoModelSelection:tS,agentPhase:tC,isNew:tN,autoFollowPaused:tT,resumeAutoFollow:tI,pauseAutoFollow:tM,goalStatus:tE,sessionIdRef:tR,messagesEndRef:tL,scrollContainerRef:tA,handleSend:tP,handleAbort:t_,handleFork:tz,handleNavigate:tW,handleModelChange:tO,handleRoleModelChange:tD,handleMainPresetChange:tH,newSessionAccount:tU,handleCompact:tB,handleSteer:tq,handleFollowUp:tV,handlePromptWithStreamingBehavior:tK,handleAbortCompaction:tG,handleRecallQueue:tJ,handleRemoveQueuedMessage:tZ,handleBuiltinSlashCommand:tY,handleToolPresetChange:tX,handleThinkingLevelChange:tQ,loadSlashCommands:t0,ensureNewSession:t1,refreshLiveTranscript:t2}=function(e){let{session:t,newSessionCwd:n,initialData:i,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==n,f=i&&i.sessionId===t?.id?i:null,[g,x]=(0,a.useState)(f),[v,b]=(0,a.useState)(!m&&!f),[y,w]=(0,a.useState)(null),[k,j]=(0,a.useState)(f?.leafId??null),[S,C]=(0,a.useState)(f?.context.messages??[]),[N,T]=(0,a.useState)(f?.context.entryIds??[]),[I,M]=(0,a.useState)(f?.context.compactedWork??null),[E,$]=(0,a.useReducer)(u7,{isStreaming:!1,streamingMessage:null}),[R,L]=(0,a.useState)(!1),[A,P]=(0,a.useState)(!1),[F,_]=(0,a.useState)(null),[z,W]=(0,a.useState)({}),[O,D]=(0,a.useState)([]),[H,U]=(0,a.useState)(null),[B,q]=(0,a.useState)([]),[V,K]=(0,a.useState)({}),[G,J]=(0,a.useState)({}),[Z,Y]=(0,a.useState)([]),[X,Q]=(0,a.useState)(null),[ee,et]=(0,a.useState)(null),[er,en]=(0,a.useState)(null),[ea,ei]=(0,a.useState)("default"),[es,eo]=(0,a.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[el,ec]=(0,a.useState)(),[ed,eu]=(0,a.useState)(null),[ep,eh]=(0,a.useState)(null),[em,ef]=(0,a.useState)(!1),eg=(0,a.useRef)(0),ex=(0,a.useRef)(0),ev=(0,a.useRef)(""),[eb,ey]=(0,a.useState)(null),[ew,ek]=(0,a.useState)(f?.contextUsage??null),[ej,eS]=(0,a.useState)(null),[eC,eN]=(0,a.useState)(null),[eT,eI]=(0,a.useState)(null),[eM,eE]=(0,a.useState)(null),[eR,eL]=(0,a.useState)(!1),[eA,eP]=(0,a.useState)(!1),[eF,e_]=(0,a.useState)(null),[ez,eW]=(0,a.useState)(null),[eO,eD]=(0,a.useState)(null),eH=(0,a.useRef)(null),[eU,eB]=(0,a.useState)(!1),[eq,eV]=(0,a.useState)(null),[eK,eG]=(0,a.useState)([]),[eJ,eZ]=(0,a.useState)(!1),[eY,eX]=(0,a.useReducer)(pd,{visible:[],pending:[]}),[eQ,e0]=(0,a.useState)(null),[e1,e2]=(0,a.useState)(null),[e8,e4]=(0,a.useState)(null),e5=(0,a.useRef)(null),[e6,e3]=(0,a.useState)(null),[e9,te]=(0,a.useState)([]),[tt,ti]=(0,a.useState)([]),[ts,to]=(0,a.useState)({steering:[],followUp:[]}),[tl,tc]=(0,a.useState)([]),[td,tu]=(0,a.useReducer)(ia,[]),tp=(0,a.useRef)(0);(0,a.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,a.useEffect)(()=>{R||tu({type:"idle"})},[R]),(0,a.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,a.useMemo)(()=>(function(e,t){let r=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${it(t)}`;r.set(e,(r.get(e)??0)+1)}let n=[],a=(e,t)=>{t.forEach((t,a)=>{let i=`${e}\u0000${ie(t)}`,s=r.get(i)??0;s>0?r.set(i,s-1):n.push({key:`queue-${e}-${a}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let r of(a("steer",t?.steering??[]),a("followUp",t?.followUp??[]),e))n.push({key:`sent-${r.id}`,kind:r.kind,text:r.text,images:r.images,stage:r.stage,removable:r.inQueue});return n})(td,ts),[td,ts]),[tm,tf]=(0,a.useState)(null),tg=(0,a.useRef)(null),tx=(0,a.useRef)(null),tv=(0,a.useRef)(null),tb=(0,a.useRef)(null),ty=(0,a.useRef)(null),tw=(0,a.useRef)(0),tk=(0,a.useRef)(!1),tj=(0,a.useRef)(t?.id??null),tS=(0,a.useRef)(f?.leafId??null),tC=(0,a.useRef)(S),tN=(0,a.useRef)(N);tC.current=S,tN.current=N;let tT=(0,a.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tI=(0,a.useRef)(!1),tM=(0,a.useRef)(new Set);(0,a.useEffect)(()=>()=>pg(tM.current),[]);let tE=(0,a.useRef)(!1),t$=(0,a.useRef)(!1),tR=(0,a.useRef)(-1),tL=(0,a.useRef)("unknown"),tA=(0,a.useRef)(null),tP=(0,a.useRef)(null),tF=(0,a.useRef)(0),t_=(0,a.useRef)(!1),tz=(0,a.useRef)(0),tW=(0,a.useRef)(null),tO=(0,a.useRef)(null),tD=(0,a.useRef)(null),tH=(0,a.useRef)(!1),tU=(0,a.useRef)(!0),[tB,tq]=(0,a.useState)(!1),[tV,tK]=(0,a.useState)(null),tG=(0,a.useRef)(void 0),tJ=(0,a.useRef)(0),tZ=(0,a.useRef)(null),tY=(0,a.useRef)(0),tX=(0,a.useRef)(()=>{}),tQ=(0,a.useRef)(null),t0=(0,a.useRef)(null),t1=(0,a.useRef)(null),t2=(0,a.useRef)(null),t8=(0,a.useRef)(!1),t4=(0,a.useRef)(null),t5=(0,a.useRef)(null),t6=(0,a.useRef)(null),t3=(0,a.useRef)(null),t7=(0,a.useRef)(0),t9=(0,a.useRef)(null),re=(0,a.useRef)(null),rt=(0,a.useRef)(!1);rt.current=e.transitioning??!1;let rr=(0,a.useRef)(Date.now()),rn=(0,a.useRef)(0),ra=(0,a.useRef)(0),ri=(0,a.useRef)(null),rs=(0,a.useRef)(!1),ro=(0,a.useRef)(Promise.resolve()),rl=e.setToolPreset??ei,rc=eT??g?.context.model??eM??null,rd=m?X??er:rc,ru=(0,a.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},r=0,n=0,a=0,i=0,s=0;for(let t of S){if("user"===t.role&&(n+=1),"toolResult"===t.role&&(i+=1),"assistant"!==t.role)continue;a+=1;let o=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,r+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:n,assistantMessages:a,toolCalls:s,toolResults:i,totalMessages:S.length,tokens:e,cost:r,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),rp=(0,a.useRef)(0),rh=(0,a.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(rp.current+=1,tf(r=>r?.sid===e&&pr(r.phases,t)?r:{sid:e,phases:t}))},[]),rm=(0,a.useCallback)((e,t,r)=>{tj.current===e&&rp.current===r&&Array.isArray(t)&&tf(r=>r?.sid===e&&pr(r.phases,t)?r:{sid:e,phases:t})},[]),rf=(0,a.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),rg=(0,a.useCallback)(e=>{tN.current=e,T(e)},[]),rx=(0,a.useCallback)(async(e,t=!1,r=!1,n)=>{let a=!1;try{t&&b(!0);let i=n??null;if(!i){let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),n=await fetch(`/api/sessions/${encodeURIComponent(e)}?${r}`);if(404===n.status)return t&&(x(null),j(null),rf([]),M(null),w(null)),null;if(!n.ok)throw Error(`HTTP ${n.status}`);i=await n.json()}if(tj.current!==e)return null;x(i),j(i.leafId),tS.current=i.leafId??null;let s=ta(i.context.messages,i.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);rf(s.messages),rg(s.entryIds),M(i.context.compactedWork??null),ek(i.contextUsage??null),eI(e=>rs.current?e:null),w(null);let o=!r&&t3.current===e;if(o||(eo(i.context.configuredThinkingLevel??i.context.thinkingLevel??"off"),ec(i.context.thinkingLevel)),eu(i.context.thinkingCeiling??null),a=!0,t&&b(!1),!r){if(o)try{let t=t7.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(r.ok&&tj.current===e){let n=await r.json();tj.current===e&&t7.current===t&&(n.state?.thinkingLevel!==void 0?(eo(n.state.configuredThinkingLevel??n.state.thinkingLevel),ec(n.state.thinkingLevel)):n.running||(t3.current=null,eo(i.context.configuredThinkingLevel??i.context.thinkingLevel??"off"),ec(i.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=rp.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();if(tj.current!==e)return null;let a=n.state;return a?(void 0!==a.contextUsage&&ek(a.contextUsage??null),void 0!==a.systemPrompt&&eS(a.systemPrompt??null),void 0!==a.thinkingLevel&&(t3.current=e,eo(a.configuredThinkingLevel??a.thinkingLevel),ec(a.thinkingLevel)),void 0!==a.thinkingCeiling&&eu(a.thinkingCeiling??null),void 0!==a.extensionStatuses&&te(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ti(a.extensionWidgets??[]),void 0!==a.queuedMessages&&to(u9(a.queuedMessages)),void 0!==a.subagents&&tc(e=>u3(e,a.subagents??[])),rm(e,a.todoPhases,t)):n.running||to({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!a&&b(!1)}},[rm,rg,rf]),rv=(0,a.useCallback)(e=>{let t=ro.current.then(async()=>{tj.current===e&&await rx(e)});return ro.current=t.catch(()=>{}),t},[rx]),rb=(0,a.useCallback)(async(e,t)=>{let r=++ex.current;try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let a=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,i=await fetch(a);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(ex.current!==r||tj.current!==e)return;tS.current=t;let o=ta(s.context.messages,s.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);rf(o.messages),rg(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[rg,rf]),ry=(0,a.useCallback)(async e=>{try{let t=await uV(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(r.bind(r,14755));rl(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[rl]),rk=(0,a.useCallback)((e=0,t="(no messages)")=>{let r=tj.current;m&&n&&r&&!t8.current&&(t8.current=!0,l?.({id:r,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,n,l]),rS=(0,a.useCallback)(async()=>{if(t1.current)return t1.current;let e=tj.current;if(e&&re.current!==e||!e&&(!m||!n))return e;let t=(async()=>{let t=e;if(!t){let e=t4.current,r=t6.current,a=t5.current;e&&eE(e);let i={cwd:n,type:"ensure_session",toolNames:(0,ue.xG)(ea),...e?{provider:e.provider,modelId:e.modelId}:{},...r?{thinkingLevel:r}:{},...e&&null!==a?{oauthPosition:a}:{}},s=JSON.stringify(i),o=t2.current,l=o?.body===s?o.createRequestId:po();t2.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,createRequestId:l})});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();t2.current=null,t=d.sessionId,tj.current=t,null!==t9.current&&(re.current=t),d.model&&t4.current===e&&(eE(d.model),e||en(d.model)),d.thinkingLevel&&t6.current===r&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;re.current===t;){let e=t9.current;await uV(t,{type:"set_thinking_ceiling",ceiling:e}),t9.current===e&&re.current===t&&(re.current=null)}return t})();t1.current=t;try{return await t}finally{t1.current=null}},[m,n,ea]),rT=(0,a.useCallback)(async()=>{let e=tj.current??await rS();if(!e)return eG([]),[];eZ(!0);try{let t=await uV(e,{type:"get_commands"}),r=t?.commands??[];return eG(r),r}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[rS]),rI=(0,a.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),rM=(0,a.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),rE=(0,a.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),r$=(0,a.useCallback)(e=>{rE();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let r=JSON.parse(t.data);"session_snapshot"===r.type?tW.current?.(r):"agent_start"===r.type&&tO.current?.(e)}catch{}}},[rE]),rR=(0,a.useCallback)(e=>{rM();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let r=new Promise(r=>{let n=!1,a=e=>{n||(n=!0,clearTimeout(i),tv.current?.source===t&&(tv.current.pending=!1),r({status:e,source:t}))},i=setTimeout(()=>a("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&a("connected"),tW.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(a("closed"),tg.current===t&&(tI.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tI.current||tk.current)&&rR(e)},1e3)}}});return tv.current={source:t,promise:r,pending:!0},r},[rM]),rL=(0,a.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let r=await rR(e);if("connected"!==r.status&&r.source.readyState!==EventSource.OPEN)throw tg.current===r.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===r.source&&(tv.current=null),r.source.close(),new ps(r.status)},[rR]),rA=(0,a.useCallback)(async(e,t)=>{let r=e5.current;if(r?.id===e.id&&"sending"===r.status)return;let n=tj.current,a=e=>{e5.current=e,e4(e)};if(!n)return void a({id:e.id,status:"failed",error:"no session"});a({id:e.id,status:"sending"});try{await uV(n,{type:"extension_ui_response",id:e.id,...t})}catch(t){a({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}a(null),e2(t=>t?.id===e.id?null:t)},[]),rP=(0,a.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{await uV(r,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rF=(0,a.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??po(),message:t,type:e.type??"info"}})},[]),r_=(0,a.useCallback)(e=>{let t={role:"custom",customType:e7,content:e$(e).trim(),display:!0,timestamp:Date.now()},r=tT.current,n=tj.current;r.sessionId!==n&&(r.sessionId=n,r.outputs=[]);let a=tN.current.slice(0,tC.current.length),i=null;for(let e=a.length-1;e>=0;e--)if(!tn(a[e])){i=a[e];break}r.seq+=1,r.outputs.push({entryId:`${tr}${r.seq}`,baseEntryId:i,message:t});let s=ta(tC.current,tN.current,r.outputs);rf(s.messages),rg(s.entryIds)},[rf,rg]),rz=(0,a.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e2(e=>e?.id===t.id?null:e),e5.current?.id===t.id&&(e5.current=null,e4(null));return}switch(uU(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":e2(t);break;case"notify":rF({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(e=>{let r=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...r,{key:t.statusKey,text:t.statusText}]:r});break;case"setWidget":ti(e=>{let r=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...r,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:r});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e3(e=>t.closed?e?.id===t.id?null:e:t)}},[rF,o,e.chatInputRef]),rW=(0,a.useCallback)(()=>{let e=tI.current;return tI.current=!1,L(!1),eV(null),pg(tM.current),ey(null),$({type:"end"}),e},[]),rO=(0,a.useCallback)(()=>{tL.current="unknown",tA.current=null;let e=pa(tC.current,tN.current);tP.current=e?{entryId:e.entryId,key:ph(e.message)}:null,tF.current+=1},[]),rD=(0,a.useCallback)(()=>{let e=tL.current,t=tA.current;if("unknown"===e){let r=pa(tC.current,tN.current),n=r?.message,a=tP.current;null!==r&&(null===a||(null!==r.entryId&&null!==a.entryId?r.entryId!==a.entryId:ph(r.message)!==a.key))&&n?.role==="assistant"&&n.stopReason&&(e=pn(n),t??={provider:n.provider,...n.model?{model:n.model}:{},...void 0!==n.credentialId?{credentialId:n.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),rH=(0,a.useCallback)(e=>{let t=rD();if("unknown"!==t.outcome||!e)return void s?.(t);let r=tF.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tF.current===r;s?.(e?rD():t)})},[s,rD]),rU=(0,a.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,rH(t),!0),[rH]),rB=(0,a.useCallback)(e=>{rI(),tk.current=!0;let t=tw.current,r=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let n=rp.current,a=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!a.ok)throw Error(`HTTP ${a.status}`);let i=await a.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=i.state;if(tc(e=>u3(e,s?.subagents??[])),rm(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tE.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tI.current=!0,L(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&s?.isCompacting){eP(!0),eD(pt(s)),ty.current=setTimeout(()=>void r(),600);return}if(i.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void r(),1e3);return}tk.current=!1,ty.current=null,rM()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void r(),600)}};ty.current=setTimeout(()=>void r(),3e4)},[rm,rI,rM]),rq=(0,a.useCallback)(async(e=tj.current,t=rn.current)=>{if(rn.current===t)try{e&&await rx(e)}finally{if(rn.current!==t)return;let r=t$.current,n=tE.current;t$.current=!1,tE.current=!1,ri.current=null;let a=rW();r?rU(t):n&&a&&rH(),e&&rB(e)}},[rx,rH,rU,rB,rW]),rV=(0,a.useCallback)(async(e,t)=>{await pl(800);let r=Date.now();for(;tI.current&&Date.now()-r<2e4;){if(void 0!==t&&rn.current!==t)return;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(r.ok){let n=await r.json(),a=n.state;if(!n.running||!a||!a.isStreaming&&!a.isPromptRunning)return void await rq(e,t)}}catch{}await pl(600)}},[rq]),rK=(0,a.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;t_.current&&tz.current===t&&tj.current===e;){await pl(1e3);try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)continue;let n=await r.json();if(n.state?.isBashRunning)continue;if(await rx(e),tz.current!==t||tj.current!==e)return;t_.current=!1,P(!1),_(null);return}catch{}}},[rx]),rG=(0,a.useCallback)(async e=>{if(!tI.current)return;let t=rn.current;try{let r=rp.current,n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let a=await n.json();if(rn.current!==t)return;let i=a.state;if(eP(i?.isCompacting??!1),eD(pt(i)),to(u9(i?.queuedMessages)),i?.contextUsage!==void 0&&ek(i.contextUsage??null),tc(e=>u3(e,i?.subagents??[])),rm(e,i?.todoPhases,r),a.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting||i.isHandoffRunning)||!tI.current)return;i&&(void 0!==i.systemPrompt&&eS(i.systemPrompt??null),void 0!==i.extensionStatuses&&te(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ti(i.extensionWidgets??[])),await rq(e,t)}catch{}},[rm,rq]),rJ=(0,a.useCallback)(async e=>{let t=await rx(e,!1,!0),r=t?.state;return!!t?.running&&!!r&&tj.current===e&&!tI.current&&!!(r.isStreaming||r.isPromptRunning||r.isHandoffRunning)&&(tE.current=!!r.isStreaming,t$.current=!!r.isPromptRunning,tI.current=!0,L(!0),eV(r.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),px(tM.current,e,r.pendingToolCalls),rR(e),!r.isStreaming&&r.isPromptRunning&&rV(e),!0)},[rR,rx,rV]),rZ=(0,a.useCallback)(async(e,t=rn.current)=>{let r=ra.current+1;ra.current=r;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let a=await n.json();if(r!==ra.current||tj.current!==e||rn.current!==t)return;a.state?.contextUsage!==void 0&&ek(a.state.contextUsage??null)}catch{}},[]);(0,a.useEffect)(()=>{if(!eA){eH.current=null,eD(null);return}eD(e=>e??{startedAt:Date.now(),reason:eH.current})},[eA]),(0,a.useEffect)(()=>{if(!R&&!eA)return;let e=()=>{let e=tj.current;e&&rZ(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[R,eA,rZ]),(0,a.useEffect)(()=>{if(!R)return;let e=()=>{let e=tj.current;e&&rG(e)},t=()=>{"visible"===document.visibilityState&&e()},r=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(r),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[R,rG]),(0,a.useEffect)(()=>{if(R)return;let e=()=>{let e=tj.current;e&&!tI.current&&rJ(e)},t=()=>{"visible"===document.visibilityState&&e()},r=e=>{let t=tj.current,r=e.detail?.sessionId;t&&r===t&&!tI.current&&rJ(t).then(e=>{e||tj.current!==t||tI.current||rx(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(uX,r),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(uX,r)}},[R,rJ,rx]),tO.current=e=>{if(tj.current!==e||tI.current||tg.current||tD.current)return;let t=rJ(e).then(async t=>{t||tj.current!==e||tI.current||await rx(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,a.useEffect)(()=>{tI.current=R},[R]),tW.current=(0,a.useCallback)(e=>{var t;switch(e.type){case"session_snapshot":{let t=function(e,t,r,n,a){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===r||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let i=e.context.messages,s=new Map;for(let e of i){let t=ph(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(n.length,a.length);for(let e of n.slice(0,o)){let t=ph(e),r=s.get(t)??0;r>0&&s.set(t,r-1)}let l=n.slice(o).filter(e=>{let t=ph(e),r=s.get(t)??0;return 0===r||(s.set(t,r-1),!1)});return{entryId:e.entryId,messages:[...i,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let r=ta(t.messages,t.entryIds,tT.current.sessionId===tj.current?tT.current.outputs:[]);rf(r.messages),rg(r.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tI.current;rI(),e&&rO(),tE.current=!0,tI.current=!0,L(!0),eV({kind:"waiting_model"}),$({type:"start"});break}case"agent_end":if(!tI.current)break;if(eV(null),pg(tM.current),ey(null),$({type:"end"}),tj.current){rx(tj.current);let e=rp.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eS(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&te(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ti(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>u3(e,t.state?.subagents??[])),tj.current&&rm(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),to(u9(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tE.current;if(tE.current=!1,!e||t$.current)break;let t=tj.current,r=rW();eP(!1);let n=t?rx(t):void 0;t&&rB(t),r&&rH(n);break}case"prompt_done":{let e=rn.current,t=t$.current;t$.current=!1,ri.current=null;let r=tR.current!==e;if(!t&&!r)break;let n=tj.current;rU(e,n?rx(n):void 0),!tE.current&&(rW(),n&&rB(n))}break;case"prompt_error":tL.current="failed",rF({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tL.current="failed",rF({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tI.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&$({type:"update",message:s2(t)}),eV(null);break}case"message_end":{if(!tI.current)break;let t=e.message;if(t?.role==="assistant"&&(tA.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tL.current=pn(t)),t&&"user"===t.role){let e=s2(t),r=pp(e),n=ri.current;ri.current=null,rf(t=>{let a=t[t.length-1];return n&&a?.role==="user"&&pp(a)===n?n===r?t:[...t.slice(0,-1),e]:[...t,e]}),n||tu({type:"user-message",kind:is(e),text:ii(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&rf(e=>[...e,s2(t)]);let r=tj.current;r&&rZ(r),$({type:"reset"}),eV(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,r=e.thinkingLevel;t&&void 0!==r&&(t3.current=t,t7.current+=1,eo(e.configured??r),ec(r));break}case"todo_changed":rh(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,r=e.toolName,n=e.args,a=rC(tj.current,t);a&&tM.current.add(a),eV(e=>{let a=e?.kind==="running_tools"?[...e.tools]:[];return a.some(e=>e.id===t)||a.push({id:t,name:r,args:n}),{kind:"running_tools",tools:a}});break}case"tool_execution_update":{let r=rC(tj.current,"string"==typeof e.toolCallId?e.toolCallId:null);r&&tM.current.has(r)&&"string"==typeof e.text&&(t=e.text,rw.get(r)!==t&&(rw.set(r,t),rj()));break}case"tool_execution_end":{let t=e.toolCallId,r=rC(tj.current,t);r&&tM.current.delete(r)&&rN([r]),eV(e=>{if(e?.kind!=="running_tools")return e;let r=e.tools.filter(e=>e.id!==t);return 0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";tc(r=>{let n=r.find(e=>e.id===t.id);return u3(r,[{id:t.id,index:t.index??n?.index??0,agent:t.agent??n?.agent??t.id,agentSource:t.agentSource??n?.agentSource??"bundled",description:t.description??n?.description,status:e,task:n?.task,assignment:n?.assignment,sessionFile:t.sessionFile??n?.sessionFile,parentToolCallId:t.parentToolCallId??n?.parentToolCallId,lastUpdate:Date.now(),progress:n?.progress?{...n.progress,status:e}:void 0}])});break}let r={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};tc(e=>u3(e,[r]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let r=t.progress,n={id:r.id,index:t.index??r.index,agent:t.agent??r.agent,agentSource:t.agentSource??"bundled",description:r.description,status:r.status,task:t.task??r.task,assignment:t.assignment??r.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:r};tc(e=>u3(e,[n]));break}case"queue_update":to({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eH.current=e.reason;let t=e.reason;eD(e=>e?{...e,reason:t}:e)}eP(!0),e_(null),eW(null);break;case"auto_compaction_end":case"compaction_end":if(eP(!1),e.errorMessage)e_(e.errorMessage),eW(null);else if(!e.aborted){eW(pm(e.result,e.reason??"auto"));let t=tj.current;t&&(rx(t),rZ(t))}break;case"extension_ui_request":rz(e)}},[rF,rh,rm,rI,rz,rx,rH,rU,rZ,rO,rB,rW,rg,rf]);let rY=(0,a.useCallback)(async(r,a,i)=>{let s=r.trim();if(!s&&!a?.length&&!i?.length)return"returned";if(tI.current||t_.current||rs.current)return"unknown";let o=ld(r,i??[]),l=!a?.length&&!i?.length&&s.startsWith("/");if(!a?.length&&!i?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tG.current?.(t,e),"accepted"):"unknown"}rO();let c=rn.current+1;rI(),t$.current=!0;let d=a?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...o.trim()?[{type:"text",text:o}]:[],...d]:o,timestamp:Date.now()};rf(e=>[...e,u]),ri.current=pp(u),rn.current=c,tI.current=!0,L(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),$({type:"start"}),tX.current(!0);let p=a?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1,g="unknown";try{if(m&&n){let e=tj.current??await t1.current,t=await rS();t&&(h=t,X&&(eE(X),e&&await uV(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await rL(t),f=!0,await uV(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),rk(1,r),g="accepted")}else t&&(h=t.id,await rL(t.id),f=!0,await uV(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&rV(h,c),g}catch(o){console.error("Failed to send message:",o);let n=o instanceof uq&&"update_draining"===o.code&&!1===o.accepted;if(!(!f||o instanceof uq&&"prompt_rejected"===o.code&&!1===o.accepted||n)&&h)return rV(h,c),"unknown";t$.current=!1,tI.current=!1,rM();let s=ri.current;return s&&rf(e=>{let t=e[e.length-1];return t?.role==="user"&&pp(t)===s?e.slice(0,-1):e}),rF({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(r,pf(a),i,t?.id??h??void 0),ri.current=null,L(!1),eV(null),$({type:"end"}),"returned"}},[m,n,X,t,rS,rL,rk,rV,rF,rI,rM,e.chatInputRef,rO,rf]);tG.current=(0,a.useCallback)(async(r,n)=>{if(tI.current||t_.current)return;let a=`${n?"!!":"!"}${r}`;t_.current=!0,tX.current(!0),_({command:r,excludeFromContext:n}),P(!0);try{let e=tj.current??t?.id??await rS();if(!e)throw Error("Unable to create a session for the shell command");await uV(e,{type:"bash",command:r,excludeFromContext:n}),await rx(e),rk(1,a)}catch(t){console.error("Failed to execute shell command:",t),rF({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(a)}finally{t_.current=!1,_(null),P(!1)}},[rF,rS,rx,e.chatInputRef,rk,t]);let rX=(0,a.useCallback)(async()=>{let e=tj.current;if(e){if(t_.current){try{await uV(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uV(e,{type:"abort"}),tL.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),rQ=(0,a.useCallback)(async e=>{if(t_.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eN(e??null);try{let{cancelled:r,newSessionId:n}=await uV(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!r&&n)return c?.(n),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eN(null)}},[c]),r0=(0,a.useCallback)(async e=>{if(t_.current)return;let t=tj.current;t&&(uV(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await rb(t,e))},[rb]),r1=(0,a.useCallback)(async e=>{if(t_.current)return;j(e);let t=tj.current;t&&(await rb(t,e),e&&uV(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[rb]),r2=(0,a.useCallback)(async(e,t)=>{if(m){let r={provider:e,modelId:t},n=t4.current?.provider===e;t4.current=r,n||(t5.current=null,et(null)),Q(r),eE(r);let a=tj.current??await t1.current;if(!a)return;try{await uV(a,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let r=tj.current;if(r&&!rs.current){rs.current=!0,eI({provider:e,modelId:t}),eL(!0);try{await uV(r,{type:"set_model",provider:e,modelId:t}),rs.current=!1,await rx(r)}catch(e){console.error("Failed to set model:",e),rs.current=!1,eI(eT),rF({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await rx(r)}finally{rs.current=!1,eL(!1)}}},[rF,eT,m,rx,Q]),r8=(0,a.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},r=e.oauthPosition,n={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==r?{oauthPosition:r}:{}},a=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(rs.current)return!1;rs.current=!0,eL(!0);let e=t4.current,i=t5.current,s=t6.current;try{t4.current=t,t5.current=r??null,t6.current="auto";let e=tj.current??await t1.current;return e&&await uV(e,n),Q(t),et(r??null),eE(t),eo("auto"),ec(void 0),e&&await rx(e),!0}catch(r){console.error("Failed to apply Main preset:",r),t4.current=e,t5.current=i,t6.current=s,rF({type:"error",message:a(r)});let t=tj.current;return t&&await rx(t),!1}finally{rs.current=!1,eL(!1)}}let i=tj.current;if(!i||rs.current)return!1;rs.current=!0,eI(t),eL(!0);try{return await uV(i,n),await rx(i),!0}catch(e){return console.error("Failed to apply Main preset:",e),eI(eT),rF({type:"error",message:a(e)}),await rx(i),!1}finally{rs.current=!1,eL(!1)}},[rF,eT,el,m,rx,Q,es]),r4=(0,a.useCallback)(async e=>{let t=Z.find(t=>t.role===e),r=t?.resolved;if(!r)return;if(m){let e={provider:r.provider,modelId:r.modelId},t=r.thinkingLevel;t6.current=t??null,eo(t??"auto"),ec(void 0),t4.current=e,t5.current=null,et(null),Q(e),eE(e)}let n=tj.current??(m?await t1.current:null);if(n)try{await uV(n,{type:"set_role_model",role:e}),m||eI({provider:r.provider,modelId:r.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,Q]),r5=(0,a.useCallback)(async()=>{let e=tj.current;if(e&&!eA){eH.current="manual",eP(!0),e_(null),eW(null);try{let t=await uV(e,{type:"compact"});eW(pm(t,"manual")),await rx(e,!0)}catch(e){e_(e instanceof Error?e.message:String(e)),eW(null)}finally{eP(!1)}}},[eA,rx]),r6=(0,a.useCallback)(async e=>{let r=n??t?.cwd??"",a=r?`/api/models?cwd=${encodeURIComponent(r)}`:"/api/models",i=await fetch(a,e?{signal:e}:void 0);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();W(s.models),U(s.modelError??null),q(s.modelScopeWarnings??[]),K(s.thinkingLevels??{}),J(s.thinkingLevelMaps??{}),Y(s.roles??[]);let o=s.modelList??[];if(D(o),m&&!tj.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];en(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t6.current&&eo(t??"auto")}},[m,n,t?.cwd]),r3=(0,a.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,r,n=""]=t,a=n.trim(),i=await rS(),s=e=>(e.handled&&(e.error?rF({type:"error",message:e.error}):"openSessionStats"!==e.action&&rF({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":{if(!i||eA)return s({handled:!0,error:"No active session to compact"});eH.current="manual",eP(!0),e_(null),eW(null);let e=await uV(i,{type:"compact",...a?{customInstructions:a}:{}});return eW(pm(e,"manual")),await rx(i,!0)&&rk(),s({handled:!0,message:"Compacted context"})}case"reload":if(!i)return s({handled:!0,error:"No active session to reload"});return await uV(i,{type:"reload"}),await Promise.all([rx(i,!1,!0),ry(i),rT(),r6()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!i)return s({handled:!0,error:"No active session to name"});if(!a)return s({handled:!0,error:"Usage: /name <name>"});return await uV(i,{type:"set_session_name",name:a}),await rx(i)&&rk(),s({handled:!0,message:`Session renamed to ${a}`});case"session":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"get_session_stats"});return e&&e0(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!i)return s({handled:!0,error:"No active session to fork"});let e=await rQ();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"goal",args:a});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(r_(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&rF({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!i)return s({handled:!0,error:"No active session"});if(tI.current||t_.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tI.current=!0,L(!0),eV({kind:"running_command"});try{await rL(i);let e=await uV(i,{type:"handoff",...a?{customInstructions:a}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await rx(i,!0)&&rk(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tI.current=!1,L(!1),eV(null),tj.current===i&&rB(i)}default:{if(!i)return s({handled:!0,error:"No active session"});let t=await uV(i,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let r=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(r&&r_(r),t.prompt)return{handled:!0,prompt:t.prompt};if(r)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&eP(!1)}},[rF,r_,rL,rS,rQ,eA,r6,rx,rT,ry,rk,h,rB]),r7=(0,a.useCallback)(async(t,r,n)=>{let a=tj.current;if(!a)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n),"returned";let i=ld(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:i,images:s?.length??0});try{return await uV(a,{type:"steer",message:i,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(i){return tu({type:"fail",id:o}),console.error("Failed to steer:",i),rF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n,a),"returned"}},[rF,e.chatInputRef]),r9=(0,a.useCallback)(async(t,r,n,a)=>{let i=tj.current;if(!i)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(n),a),"returned";let s=ld(t,a??[]),o=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:r,text:s,images:o?.length??0});try{return await uV(i,{type:"prompt",message:s,streamingBehavior:r,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(r){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",r),rF({type:"error",message:r instanceof Error?r.message:String(r)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(n),a,i),"returned"}},[rF,e.chatInputRef]),ne=(0,a.useCallback)(async(t,r,n)=>{let a=tj.current;if(!a)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n),"returned";let i=ld(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:i,images:s?.length??0});try{return await uV(a,{type:"follow_up",message:i,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(i){return tu({type:"fail",id:o}),console.error("Failed to follow up:",i),rF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n,a),"returned"}},[rF,e.chatInputRef]),nt=(0,a.useCallback)(async()=>{let e=tj.current;if(e)try{await uV(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nr=(0,a.useCallback)(async()=>{let t=tj.current;if(t)try{var r;let n=await uV(t,{type:"clear_queue"});tu({type:"withdraw"}),to({steering:[],followUp:[]});let a={text:(r=[...n?.steering??[],...n?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:r.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(a.text,a.images.length?a.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),rF({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,rF]),nn=(0,a.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{let n=await uV(r,{type:"remove_queued_message",message:t,queue:e});if(!n?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(r=>{let n=r[e].indexOf(t);return(n<0&&""===t.trim()&&(n=r[e].indexOf("[Image]")),n<0)?r:{...r,[e]:r[e].filter((e,t)=>t!==n)}})}catch(e){console.error("Failed to remove queued message:",e),rF({type:"error",message:"Failed to remove queued message"})}},[rF]),na=(0,a.useCallback)(async(e,t=null)=>{let r="auto"===e?t:null,n=r!==ed;eo(e),eu(r),m&&(!tj.current||re.current===tj.current)&&(t6.current=e,t9.current=r),ec(void 0);let a=tj.current??await t1.current;if(a)try{re.current===a?await rS():n&&await uV(a,{type:"set_thinking_ceiling",ceiling:r}),await uV(a,{type:"set_thinking_level",level:e}),await rx(a)}catch(e){console.error("Failed to set thinking level:",e),rF({type:"error",message:"Failed to set thinking level"}),await rx(a)}},[m,rx,rF,ed,rS]);ev.current=rd?`${rd.provider}/${rd.modelId}`:"";let ni=e=>e?`${e}|${ev.current}`:null,ns=t?.id??tj.current,no=ni(ns),nl=ep&&ep.key===no?ep.value:null;(0,a.useEffect)(()=>{let e=++eg.current;no&&ns&&!R&&!eR&&fetch(`/api/agent/${encodeURIComponent(ns)}`).then(e=>e.json()).then(t=>{eg.current===e&&ni(tj.current)===no&&eh({key:no,value:(t.running?pe(t.state):void 0)??null})}).catch(()=>{})},[no,R,eR]);let nc=(0,a.useCallback)(async()=>{let e=tj.current??await rS(),t=ni(tj.current);if(!e||!t)return;let r=++eg.current,n=()=>eg.current===r&&ni(tj.current)===t,a=e=>{n()&&eh({key:t,value:e})};ef(!0);try{let r=ep?.key===t?ep.value?.enabled:void 0;if(void 0===r){let t=pe(await uV(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");r=t.enabled}if(!n())return;let i=await uV(e,{type:"set_fast_mode",enabled:!r});a({enabled:i?.enabled===!0,active:i?.active===!0})}catch(t){if(!n())return;rF({type:"error",message:t instanceof Error?t.message:String(t)});try{a(pe(await uV(e,{type:"get_state"}))??null)}catch{a(null)}}finally{ef(!1)}},[rS,ep,rF]),nd=(0,a.useCallback)(async e=>{let t=(0,ue.xG)(e);rl(e);let r=tj.current??await t1.current;if(r)try{await uV(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[rl]),nu=(0,a.useCallback)(e=>{tU.current=e,tq(t=>!e===t?t:!e)},[]);tX.current=e=>{tZ.current=null,nu(e)};let np=(0,a.useCallback)((e="smooth")=>{tY.current=Date.now()+700,tQ.current?.scrollIntoView({behavior:e})},[]),nh=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,nu(!0),np("smooth")},[np,nu]),nm=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,nu(!1)},[nu]),nf=(0,a.useCallback)(()=>{if(!tZ.current)return;tZ.current=null;let e=t0.current;e&&nu(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[nu]),ng=(0,a.useCallback)(e=>{if(e instanceof PointerEvent&&"mouse"===e.pointerType&&1===e.button&&!(e.target instanceof Element&&e.target.closest("a[href], input, textarea"))&&!(e.target instanceof HTMLElement&&e.target.isContentEditable)){if(tZ.current)return void nf();nm();let e=t0.current;return void(tZ.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}nf(),e instanceof KeyboardEvent&&(!pi.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[nf,nm]),nx=(0,a.useCallback)(()=>{let e=t0.current;if(!e)return;let t=tZ.current;if(null!==t){let r=t.top;t.moved||=e.scrollTop!==r,t.top=e.scrollTop;return}if(!tI.current&&!t_.current)return;let r=e.scrollHeight-e.scrollTop-e.clientHeight,n=Date.now()<=tJ.current;if(!(!n&&Date.now()<tY.current)){if(r<=72)return void nu(!0);n&&nu(!1)}},[nu]);return(0,a.useEffect)(()=>(tj.current=t?.id??null,tT.current.sessionId!==tj.current&&(tT.current={sessionId:tj.current,outputs:[],seq:0}),t&&rx(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;r$(t.id),e?.running&&(ry(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tE.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tI.current=!0,L(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),px(tM.current,t.id,e.state.pendingToolCalls),rR(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&rV(t.id)),e.state?.isBashRunning&&(t_.current=!0,P(!0),rK(t.id)),(e.state?.subagents?.length??0)>0&&rR(t.id));let r=e?.state;r&&(void 0!==r.isCompacting&&eP(r.isCompacting),eD(pt(r)),void 0!==r.contextUsage&&ek(r.contextUsage??null),void 0!==r.systemPrompt&&eS(r.systemPrompt??null),void 0!==r.thinkingLevel&&(t3.current=t.id,eo(r.configuredThinkingLevel??r.thinkingLevel),ec(r.thinkingLevel)),void 0!==r.thinkingCeiling&&eu(r.thinkingCeiling??null),void 0!==r.extensionStatuses&&te(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&ti(r.extensionWidgets??[]),void 0!==r.queuedMessages&&to(u9(r.queuedMessages)),void 0!==r.subagents&&tc(e=>u3(e,r.subagents??[])),void 0!==r.goal&&tK(r.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,rI(),rM(),rE()}),[t?.id]),(0,a.useEffect)(()=>{p?.(ej)},[ej,p]),(0,a.useEffect)(()=>{u&&u(g?.tree??[],k,r1)},[g?.tree,k,r1,u]),(0,a.useEffect)(()=>{let e=e=>{let t=tZ.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t0.current?.contains(e.target))?nf():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",ng),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",ng)}},[nf,ng]),(0,a.useEffect)(()=>{let e=t0.current;if(!e)return;let t=()=>{tZ.current?.moved&&nf()};return e.addEventListener("pointerdown",ng,{passive:!0}),e.addEventListener("wheel",ng,{passive:!0}),e.addEventListener("touchstart",ng,{passive:!0}),e.addEventListener("scroll",nx,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",ng),e.removeEventListener("wheel",ng),e.removeEventListener("touchstart",ng),e.removeEventListener("scroll",nx),e.removeEventListener("scrollend",t)}},[S.length,v,nf,nx,ng]),(0,a.useEffect)(()=>{if(rt.current||!R&&!A||!tU.current)return;let e=t0.current;if(!e)return;let t=requestAnimationFrame(()=>{tU.current&&(tY.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[R,A,S.length,E.streamingMessage,eq,F,e.transitioning]),(0,a.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,np("instant");return}if(!rt.current&&tU.current){let e=Date.now()-rr.current<1500;np(tI.current||t_.current||e?"instant":"smooth")}}},[S.length,R,A,np,e.transitioning]),(0,a.useEffect)(()=>{let e=new AbortController;return r6(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[r6,d]),(0,a.useEffect)(()=>{if(!ez)return;let e=setTimeout(()=>eW(null),6e3);return()=>clearTimeout(e)},[ez]),(0,a.useEffect)(()=>{if(0===eY.visible.length)return;let e=eY.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eY.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eY.visible]),(0,a.useEffect)(()=>{e0(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:E,agentRunning:R,modelNames:z,modelList:O,modelError:H,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ea,thinkingLevel:es,effectiveThinkingLevel:el,thinkingCeiling:ed,retryInfo:eb,contextUsage:ew,systemPrompt:ej,forkingEntryId:eC,isCompacting:eA,compaction:eO,compactError:eF,compactResult:ez,currentModel:rc,displayModel:rd,modelSwitching:eR,sessionStats:ru,runStateKnown:eU,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:ts,deliveryRows:th,subagents:tl,todoPhases:tm&&tm.sid===tj.current?tm.phases:null,compactedWork:I,notices:eY.visible,extensionDialog:e1,extensionResponse:e8,extensionCustomUi:e6,extensionStatuses:e9,extensionWidgets:tt,respondToExtensionUi:rA,sendExtensionCustomInput:rP,isAutoModelSelection:m&&null===X,agentPhase:eq,isNew:m,autoFollowPaused:tB,resumeAutoFollow:nh,pauseAutoFollow:nm,goalStatus:tV,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tQ,scrollContainerRef:t0,handleSend:rY,handleAbort:rX,handleFork:rQ,handleNavigate:r0,handleModelChange:r2,handleRoleModelChange:r4,handleMainPresetChange:r8,newSessionAccount:ee,handleCompact:r5,handleSteer:r7,handleFollowUp:ne,handlePromptWithStreamingBehavior:r9,handleAbortCompaction:nt,handleRecallQueue:nr,handleRemoveQueuedMessage:nn,handleBuiltinSlashCommand:r3,handleToolPresetChange:nd,handleThinkingLevelChange:na,fastMode:nl,fastModeBusy:em,handleFastModeToggle:nc,loadTools:ry,loadSlashCommands:rT,ensureNewSession:rS,refreshLiveTranscript:rv,setActiveLeafId:j,setData:x,setMessages:C,dispatch:$,setAgentRunning:L,setForkingEntryId:eN,bashRunning:A,pendingBash:F,handleAgentEventRef:tW}}({session:e,newSessionCwd:t,initialData:i,transitioning:s,onAgentEnd:eb,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),t8=(0,a.useMemo)(()=>(function(e){let t=null,r=new Map;for(let n=0;n<e.length;n++){let a=e[n],i=e3(a);if(!i||"custom"!==a.role)continue;t??=[...e];let s=[];for(let t=0;t<n;t++){let n=e[t];if("assistant"!==n.role)continue;if(void 0===i.sourceHash){n.timestamp===i.sourceTimestamp&&s.push(t);continue}let a=r.get(t);void 0===a&&(a=function(e){let t=e6(e),r=5381;for(let e=0;e<t.length;e++)r=(r<<5)+r+t.charCodeAt(e)|0;return`${t.length}:${r}`}(n.content??[]),r.set(t,a)),a===i.sourceHash&&s.push(t)}s.length>1&&void 0!==i.sourceHash&&void 0!==i.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===i.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[n]={...a,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let r="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return r.startsWith(e5)?{kind:"translated",text:r.slice(e5.length),original:t}:r.startsWith("[번역 생략]")?{kind:"skipped",text:r,original:t}:{kind:"failed",text:r,original:t}}(a,e6(o.content??[]))}}return t??e})(ej),[ej]),t4=ah(e?.id,e9?.provider,void 0,e9?.modelId),t5=t4?.alias;(0,a.useEffect)(()=>{t5&&X.current?.(t5)},[t5]);let t6=(0,a.useMemo)(()=>{if(!e9)return null;let e=tN?tU:nh.find(e=>e.alias===t4?.alias)?.oauthPosition;return nh.find(t=>t.provider===e9.provider&&(void 0===t.oauthPosition?null===t4||t4.seed===t.seed:t.oauthPosition===e))?.alias??null},[e9,tN,tU,t4]),t3=eN||eT,t7=e?.id;ea.current=t8,ei.current=eS,es.current=tR;let t9=(0,a.useRef)(!0);t9.current=!tT;let re=(0,a.useRef)(!1);(0,a.useEffect)(()=>{eN&&!re.current&&(eo.current+=1),re.current=eN},[eN]),(0,a.useEffect)(()=>()=>{eo.current+=1},[]),(0,a.useEffect)(()=>{et(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(p$(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t7),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t7)])},[t7]),(0,a.useEffect)(()=>{let e=tR.current;e&&er.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let r=!1,n=[];for(let a of t){if(null!==a.anchorEntryId||!a.intent||a.sessionId!==e){n.push(a);continue}let i=function(e,t,r){let n=Math.min(t.length,r.length),a=0;if(null!==e.baseEntryId){let t=r.indexOf(e.baseEntryId);if(-1===t||t>=n)return{kind:"drop"};a=t+1}let i=0;for(let s=a;s<n;s++)if(ni(t[s])===e.identity&&(i+=1)===e.occurrence)return{kind:"entry",entryId:r[s]};return null}(a.intent,t8,eS);if(null===i){n.push(a);continue}r=!0,"drop"!==i.kind&&("working"===a.tag&&[...t,...n].some(e=>"working"===e.tag&&e.anchorEntryId===i.entryId)||n.push({id:a.id,anchorEntryId:i.entryId,sticker:a.sticker,text:a.text,tag:a.tag,sessionId:a.sessionId}))}return r?(pR(e,n),n):t})},[t8,eS,tR]);let rt=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=tR.current,t=rt.current;if(rt.current=e?{sessionId:e,entryIds:eS}:null,!e||!t||t.sessionId!==e)return;let r=function(e,t,r){if(0===e.length||t.length<=e.length)return[];for(let r=0;r<e.length;r++)if(e[r]!==t[r])return[];let n=[],a=Math.min(r.length,t.length);for(let i=e.length;i<a;i++){let e=r[i];"assistant"===e.role&&"web6"===e.provider&&e.model===no&&n.push(t[i])}return n}(t.entryIds,eS,t8),n=ed();if(0===r.length||!n)return;let a=au(e,"web6",void 0)?.alias??null;for(let e of r)er.current.some(t=>t.anchorEntryId===e)||eh(a,"done",n,{kind:"entry",entryId:e})},[eS,t8,tR,ed,eh]);let rr=eN&&tC?.kind==="running_tools"&&tC.tools.length>0&&tC.tools.every(e=>"wait"===e.name),rn=ew||s,{hideThinkingBlock:ra}=(O=t??e?.cwd??null,H=rX(),(0,a.useEffect)(()=>{rY(O).catch(()=>{})},[O]),H),ri=(0,a.useMemo)(()=>({hideThinking:ra}),[ra]);(0,a.useEffect)(()=>{var e;if(!tx||Y.current===tx.id)return;Y.current=tx.id;let t=ed();if(!t)return;ec.current=t.turn;let r=eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,n=ns(ea.current,r,e9?.provider,e9?.modelId);ef("select"===(e=tx.method)||"ask"===e||"form"===e?"choice":"approval",t,n.provider,n.credentialId,n.model)},[tx,eC.streamingMessage,e9?.provider,e9?.modelId,ed,ef]),(0,a.useEffect)(()=>(v=t3?t_:null,()=>void(v=null)),[t3,t_]),(0,a.useEffect)(()=>{M?.(t3)},[M,t3]),(0,a.useEffect)(()=>()=>M?.(!1),[M]),(0,a.useEffect)(()=>{E?.(rr)},[rr,E]),(0,a.useEffect)(()=>()=>E?.(!1),[E]),(0,a.useEffect)(()=>{$?.(null!==tx)},[$,tx]),(0,a.useEffect)(()=>()=>$?.(!1),[$]);let{main:rs,process:ro}=(0,a.useMemo)(()=>(function(e,t,r={}){let n=[],a=[],i=-1,s=null,o=(e,t,r)=>{if(0===t.length)return;let i=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},a.push(s)),s),o=n.length-1;for(let e of t)i.entries.push({...e,afterMainIndex:o});i.messageCount+=t.length,i.toolCallCount+=r},l=e2(e),c=new Map,d=(e,t)=>{let r=c.get(e)??0;c.set(e,r+1),n.push({kind:"answer",anchorIdx:i,idx:e,runIndex:r,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let a of t){if("answer"===a.kind){n.push(a);continue}if("process"===a.kind){o(a.anchorIdx,a.entries,a.toolCallCount);continue}let t=e[a.idx];if(!t)continue;if("user"===t.role){u(),i=a.idx,n.push(a);continue}if(te(t)){n.push(void 0!==a.anchorIdx||i<0?a:{...a,anchorIdx:i});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===e3(t)&&0>tt(e,a.idx)&&o(i,[{idx:a.idx}],0);continue}let s=eG(t,r);if(eV(t,r)&&eK(e,a.idx)){let e=s.flatMap(e=>e.blocks);o(i,[{idx:a.idx}],eJ(e)),l.collect(a.idx,e);continue}let c=!1;for(let e of s){if("answer"===e.kind){d(a.idx,e.blocks),c=!0;continue}o(i,[{idx:a.idx,blocks:e.blocks}],eJ(e.blocks)),l.collect(a.idx,e.blocks)}!c&&eV(t,r)&&d(a.idx,[])}return u(),{main:n,process:a}})(t8,function(e,t={}){let r=-1;for(let t=e.length-1;t>=0;t--)if(ti(e[t])){r=t;break}let n=[];for(let a=0;a<e.length;){if(!ti(e[a])){n.push({kind:"message",idx:a}),a+=1;continue}let i=a,s=i+1;for(;s<e.length&&!ti(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&i===r||!function(e,t,r){for(let n=t;n<r;n++)if(e[n]?.role==="assistant")return!0;return!1}(e,i+1,s)){for(let e=i;e<s;e++)n.push({kind:"message",idx:e});a=s;continue}for(let r of(n.push({kind:"message",idx:i}),function(e,t,r,n){let a=[],i=[],s=0,o=[],l=0,c=0,d=e2(e.slice(t+1,r)),u=()=>{0!==i.length&&(a.push({kind:"process",anchorIdx:t,idx:i[0].idx,groupIndex:c++,entries:i,messageCount:i.length,toolCallCount:s,turnHasAnswer:!1}),i=[],s=0)},p=(e,r)=>{u(),a.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(r),precedingBlocks:o}),o=[]};for(let l=t+1;l<r;l++){let r=e[l];if("assistant"!==r.role){if(null!==e3(r)||tt(e,l)>=0)continue;if(te(r)){u(),a.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==r.role&&i.push({idx:l});continue}let c=eG(r,n);if(eV(r,n)&&eK(e,l)){let e=c.flatMap(e=>e.blocks);for(let t of(i.push({idx:l}),s+=eJ(e),d.collect(l,e),c))"process"===t.kind&&o.push(...t.blocks);continue}let h=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){p(l,e.blocks);continue}for(let t of(i.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eJ(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eV(r,n)&&p(l,[])}u();let h=d.takeRemaining();h&&a.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let m=a.some(e=>"answer"===e.kind);for(let e of a)"process"===e.kind&&(e.turnHasAnswer=m);return a}(e,i,s,{hideThinking:t.hideThinking})))n.push(r);a=s}return n}(t8,{sessionBusy:t3,isStreaming:eC.isStreaming,hideThinking:ri.hideThinking}),ri),[t8,t3,eC.isStreaming,ri]),rl=(0,a.useMemo)(()=>(function(e,t,r=[]){let n=new Map,a=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===a.length)return n;let i=-1,s=-1;t.forEach((e,t)=>{let r=a2(e);if(r.length>0){let e=a.filter(e=>e.item.anchorIdx===i||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=n.get(l.position);e?e.calls.push(...r):n.set(l.position,{calls:[...r],placement:o?"after":"before"})}}"user"===e.role&&(i=t),ti(e)&&(s=t)});let{continuing:o}=a8(e,t,r);if(o){let e=n.get(o.position);e?e.calls.unshift(...o.calls):n.set(o.position,{calls:o.calls,placement:"before"})}return n})(rs,t8,td?.messages),[rs,t8,td]),rc=(0,a.useMemo)(()=>(function(e,t,r=[]){let{atCompaction:n}=a8(e,t,r);if(0===n.length)return null;let a=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(a=t)});let i=e.findIndex(e=>e.idx>a);return{position:-1===i?e.length:i,calls:n}})(rs,t8,td?.messages),[rs,t8,td]),[rd,ru]=(0,a.useState)(pN),{startIndex:rp,endIndex:rh,hasLater:rm}=pT(rs.length,rd),rf=null!==rd.end&&rm,rg=(0,a.useRef)(rs.length);rg.current=rs.length;let rx=(0,a.useRef)(null),rv=(0,a.useRef)(null),rb=(0,a.useRef)(null);(0,a.useEffect)(()=>{null!==rd.end&&rd.end>=rs.length&&ru(e=>({count:e.count,end:null}))},[rd.end,rs.length]),(0,a.useEffect)(()=>{let e=rx.current,t=tA.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(rb.current=t.scrollHeight-t.scrollTop,ru(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rd,rs.length,tA]),(0,a.useEffect)(()=>{if(null==rb.current)return;let e=tA.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-rb.current),rb.current=null}},[rd.count,tA]),(0,a.useEffect)(()=>{let e=rv.current,t=tA.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ru(e=>(function(e,t,r=50){if(null===t.end)return t;let{startIndex:n,endIndex:a}=pT(e,t),i=a+r;return i>=e?{count:e-n,end:null}:{count:i-n,end:i}})(rg.current,e))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rd,rs.length,tA]);let[ry,rk]=(0,a.useState)(null),[rS,rT]=(0,a.useState)(0),rI=(0,a.useRef)(null),rM=(0,a.useCallback)(e=>{tM(),rI.current=e,rk(null),ru(t=>pI(rg.current,e,t)),rT(e=>e+1)},[tM]);(0,a.useLayoutEffect)(()=>{let e=rI.current,t=tA.current;if(null===e||!t)return;let r=t.querySelector(`[data-chat-item="${e}"]`);if(!r)return;rI.current=null;let n=document.createRange();n.selectNodeContents(r),t.scrollTop+=n.getBoundingClientRect().top-t.getBoundingClientRect().top-24,rk(e)},[rS,rd,rs,tA]),(0,a.useEffect)(()=>{if(null===ry)return;let e=setTimeout(()=>rk(null),1800);return()=>clearTimeout(e)},[ry]);let rE=(0,a.useCallback)(()=>{(0,q.flushSync)(()=>ru(pN));let e=tA.current;e&&(e.scrollTop=e.scrollHeight)},[tA]),r$=(0,a.useCallback)(()=>{rf&&rE(),tI()},[rf,rE,tI]),rR=(0,a.useRef)(null),[rL,rA]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(!_||rR.current===_.id||_.sessionId!==e?.id||ew||0===t8.length)return;rR.current=_.id,W?.(_.id);let t=eS.indexOf(_.entryId);if(t<0)return void rA(!0);let r=0;for(let e=0;e<rs.length;e++){let n=rs[e].idx;if(n>t||(r=e,n===t))break}rM(r)},[_,e?.id,ew,t8.length,eS,rs,rM,W]),(0,a.useEffect)(()=>{if(!rL)return;let e=setTimeout(()=>rA(!1),6e3);return()=>clearTimeout(e)},[rL]);let[rP,rF]=(0,a.useState)(!1),[r_,rz]=(0,a.useState)(0),rW=(0,a.useMemo)(()=>rP?rs.map(e=>(function(e,t){if("answer"===e.kind)return tl(e.blocks);let r=t[e.idx];return r&&"content"in r?tl(r.content):""})(e,t8).toLowerCase()):pL,[rP,rs,t8]),rO=(0,a.useCallback)(e=>{tM(),ru(t=>pI(rg.current,e,t))},[tM]),rD=(0,a.useCallback)(()=>rF(!1),[]);(0,a.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tA.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let r=e.target instanceof Element?e.target:null;if(r?.closest("[data-capture-keys], [role='dialog']"))return;let n=r?.closest("input, textarea, select, [contenteditable='true']");(!n||n.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),rF(!0),rz(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tA]);let rH=(0,a.useMemo)(()=>{let e=[];return rs.forEach((t,r)=>{if("message"!==t.kind)return;let n=pE(t8[t.idx]);null!==n&&e.push({item:r,text:n})}),e},[rs,t8]),rU=`${rp}:${rh}`,rB=eS.length>0?eS[eS.length-1]:null,[rq,rV]=(0,a.useState)(null),rK=(0,a.useRef)(!1);(0,a.useEffect)(()=>{rK.current||!tc||ew||!e?.id||(rK.current=!0,t3||!rB||!function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role||"toolResult"===r.role)return!0;if("assistant"===r.role){if(!r.stopReason)return!0;if("aborted"===r.stopReason||"error"===r.stopReason||"length"===r.stopReason)break;return r.content.some(e=>"toolCall"===e.type)}}return!1}(t8)||function(e){try{return window.localStorage.getItem(pA(e))}catch{return null}}(e.id)!==rB&&rV(rB))},[tc,ew,e?.id,t3,rB,t8]);let rG=(0,a.useCallback)(()=>{e?.id&&rq&&function(e,t){try{window.localStorage.setItem(pA(e),t)}catch{}}(e.id,rq),rV(null)},[e?.id,rq]),rJ=null!==rq&&rq===rB&&!t3&&!rf,rZ=to?[to.sessionId,to.sessionFile??"",to.sessionName??"",to.userMessages,to.assistantMessages,to.toolCalls,to.toolResults,to.totalMessages,to.tokens.input,to.tokens.output,to.tokens.cacheRead,to.tokens.cacheWrite,to.tokens.total,to.cost??0,to.totalActiveMs??0].join("|"):null,rQ=(0,a.useRef)(to);rQ.current=to,(0,a.useEffect)(()=>{f?.(rQ.current)},[rZ,f]),(0,a.useEffect)(()=>()=>{f?.(null)},[f]);let r0=eZ?`${eZ.percent??"null"}|${eZ.contextWindow}|${eZ.tokens??"null"}`:null,r1=(0,a.useRef)(eZ);r1.current=eZ,(0,a.useEffect)(()=>{x?.(r1.current)},[r0,x]),(0,a.useEffect)(()=>()=>{x?.(null)},[x]),(0,a.useEffect)(()=>{b?.(tm)},[b,tm]),(0,a.useEffect)(()=>()=>{b?.([])},[b]);let{regular:r2,lab:r8}=(0,a.useMemo)(()=>(function(e){let t=[],r=[];for(let a of e){var n;((n=a.key).startsWith(cF)&&null!==c_(n)?r:t).push(a)}return{regular:t,lab:r}})(tw),[tw]),r4=e?.id??null;(0,a.useEffect)(()=>{y?.(r4,r8)},[y,r4,r8]),(0,a.useEffect)(()=>()=>{y?.(null,[])},[y]);let{isDragOver:r5,handleDragEnter:r6,handleDragOver:r7,handleDragLeave:r9,handleDrop:ne}=function(e){let[t,r]=(0,a.useState)(!1),n=(0,a.useRef)(0),i=(0,a.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),n.current+=1,r(!0))},[]),s=(0,a.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:i,handleDragOver:s,handleDragLeave:(0,a.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,r(!1))},[]),handleDrop:(0,a.useCallback)(t=>{t.preventDefault(),n.current=0,r(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,a.useCallback)(e=>{t3||p?.current?.addAttachments(e)},[t3,p])),nt=(0,a.useMemo)(()=>{var e;return e=td?.messages,e&&e.length>0?[...e,...t8]:t8},[td,t8]),nr=(0,a.useMemo)(()=>{let e=new Map;for(let t of nt)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[nt]),nn=(0,a.useMemo)(()=>{let e,t,r,n,a,i,s,o,l,c,d;return e=new Map,t=new Map,r=new Map,n=new Map,a=new Map,i=new Map,s=new Map,o=(e,n,a)=>{let i=r.get(e);i&&n&&t.set(i,{status:n,order:a})},l=new Set,c=(e,t)=>{let n=t?r.get(t):void 0,i=aK(e.status);if(!n||l.has(n)||"completed"!==i&&"failed"!==i&&"aborted"!==i)return;l.add(n);let s=aV(e);null!==s&&a.set(n,s)},d=(e,t,n)=>{let a=t?r.get(t):void 0,i=aV(e);a&&"number"==typeof n&&null!==i&&"running"===aK(e.status)&&s.set(a,Math.max(s.get(a)??-1/0,n-i))},nt.forEach((t,a)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=nr.get(e.toolCallId);if(t)for(let a of aJ(e,t)??[])r.set(a.agentId,a.key),"number"==typeof t.timestamp&&n.set(a.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let r=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let r=JSON.parse(aG(e.content));t=r?.ok===!0?r.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let r=t.verdict;if("accepted"!==r&&"rework"!==r&&"held"!==r)return null;let n=aq(t.assignmentId),a=n?.split("#")??[];if(a.length<3)return null;let i=a[a.length-1],s=a.slice(1,-1).join("#");return/^\d+$/.test(i)&&s?{key:`${s}#${i}`,record:{verdict:r,attempt:"number"==typeof t.attempt?t.attempt:null,reason:aq(t.reason)}}:null}(t);if(!r)return;let n=e.get(r.key)??[];n.push({...r.record,order:a,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(r.key,n);return}if("wait"===t.toolName){let e=new Set;for(let n of aB(t.details?.jobs)){if("task"!==n.type)continue;let i=aq(n.id);if(i&&o(i,aK(n.status),a),c(n,i),d(n,i,t.timestamp),i&&"running"===aK(n.status)){let t=r.get(i);t&&e.add(t)}}for(let t of e)for(let r of e){if(t===r)continue;let e=i.get(t);e||i.set(t,e=new Set),e.add(r)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of aG(t.content).matchAll(aZ)){let t=Object.fromEntries([...e[1].matchAll(aY)].map(e=>[e[1],e[2]]));t.id&&o(t.id,aK(t.status),a)}for(let e of aB(t.details?.jobs))"task"===e.type&&c(e,aq(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:r,spawnedAt:n,durations:a,parallelWith:i,runStartedAt:s}},[nt,nr]),na=(0,a.useMemo)(()=>({ledger:nn,subagents:tm,toolResults:nr,onOpenPanel:w,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:j,selectedMaker:S}),[nn,tm,nr,w,e?.id,e?.cwd,t,j,S]),nl=(0,a.useMemo)(()=>{let e=new Set,t=[];for(let r=t8.length-1;r>=0;r-=1){let n=pE(t8[r]);if(!(!n||e.has(n))&&(e.add(n),t.push(n),t.length>=50))break}return t.reverse()},[t8]),nc=(0,a.useMemo)(()=>t$(t8,nr,tf,td?.todoPhases??null),[t8,nr,tf,td]),nd=(0,a.useMemo)(()=>cN(eC.streamingMessage).join("|"),[eC.streamingMessage]),nu=(0,a.useMemo)(()=>JSON.stringify(cC(eC.streamingMessage)),[eC.streamingMessage]),np=(0,a.useMemo)(()=>JSON.stringify(cI(eC.streamingMessage)),[eC.streamingMessage]),nm=(0,a.useMemo)(()=>(function(e,t,r=[],n=[],a=[]){let i=function(e){let t=new Map;for(let r of e){if("toolResult"!==r.role||"write"!==r.toolName)continue;let e=r.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let n=e.message;if(!n||"object"!=typeof n||Array.isArray(n)||"send"!==n.op)continue;let a=Array.isArray(n.receipts)?n.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(r.toolCallId,{from:"string"==typeof n.from?n.from:void 0,receipts:a})}return t}(e),s=[],o=new Map,l=-1;for(let r=0;r<e.length;r+=1){let n=e[r];if("user"===n.role){l=r;continue}let a=cN(n),c=cI(n,i);if(0===a.length&&0===c.length||l<0)continue;let d=cC(n),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...a],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(r.length>0||a.length>0){let i=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){i=t;break}if(i>=0){let e=o.get(i);e||(e={index:i,entryId:t[i],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(i,e),s.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...r.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...n.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...a.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(t8,eS,nd.length>0?nd.split("|"):[],JSON.parse(nu),JSON.parse(np)),[t8,eS,nd,nu,np]),nf=e?.id??tR.current??void 0,ng=(U=c$(D=(0,a.useMemo)(()=>({sessionId:nf,sessionProvider:e9?.provider,turns:nm,messages:t8,subagents:tm}),[nf,e9?.provider,nm,t8,tm])),V=cP(D),(0,a.useMemo)(()=>(function(e){let t=new Map;for(let r of e){let e=t.get(r.turnIndex);e?e.push(r):t.set(r.turnIndex,[r])}return t})(function(e){let t=[];for(let r of e){let e=t[t.length-1];if(e&&e.speakerId===r.speakerId&&e.turnIndex===r.turnIndex&&e.text===r.text){t[t.length-1]=r;continue}t.push(r)}return t}([...U,...V])),[U,V])),nx=tN&&0===t8.length&&!eC.isStreaming&&!t3,nv=(0,a.useMemo)(()=>t8.filter(e=>"assistant"===e.role).length,[t8]),nb=function(e,t){let r=(0,a.useRef)(new Map),n=(0,a.useMemo)(()=>{if(!e)return r.current=new Map,0;let t=new Map,n=0;return(e.content??[]).forEach((e,a)=>{let i=eX(e);if(null===i)return;let s=eQ(r.current.get(a),i);t.set(a,{text:i,tokens:s}),n+=s}),r.current=t,n},[e]),i=(0,a.useRef)(n);i.current=n;let s=null!==e,o=e?.timestamp,[l,c]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(!s)return void c(null);let e=o??Date.now(),t=()=>{let t=(Date.now()-e)/1e3;c(t>=.5?i.current/t:0)};t();let r=setInterval(t,1e3);return()=>clearInterval(r)},[s,o,t]),s?l??0:null}(eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,nv),ny=(0,a.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("assistant"!==r.role)continue;let{usage:n,timestamp:a,completedAt:i}=r,s=n?.output??0;if(!(s<=0)&&a&&i&&!(i<=a))return s/((i-a)/1e3)}return null})(t8),[t8]),nw=e?.cwd??t??void 0,nk=e9?eA[`${e9.provider}:${e9.modelId}`]??null:null,nj=e9?eP[`${e9.provider}:${e9.modelId}`]??null:null,nS=(0,a.useRef)(null),nC=(0,a.useRef)(null),nN=(0,a.useCallback)(()=>{let e=nS.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,a.useEffect)(()=>(I?.(nN),()=>I?.(null)),[nN,I]),(0,a.useLayoutEffect)(()=>{let e=nC.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let r=tA.current?.clientHeight??0,n=()=>{let n=Math.ceil(e.getBoundingClientRect().height);n>0&&t.style.setProperty("--omp-dock-h",`${n}px`);let a=tA.current;if(!a)return;let i=r-a.clientHeight;r=a.clientHeight,i<=0||a.scrollHeight-a.scrollTop-a.clientHeight-i<=1&&(a.scrollTop+=i)};n();let a=new ResizeObserver(n);return a.observe(e),()=>a.disconnect()},[ew,tA]);let nT=(0,a.useCallback)((...e)=>(null!==rd.end&&rE(),tP(...e)),[tP,rd.end,rE]),nI=(0,n.jsx)("div",{ref:nS,"data-chat-composer":"",style:{display:"contents"},children:(0,n.jsx)(uW,{ref:p,sessionId:e?.id??tR.current??void 0,onEnsureSession:tN&&t?t1:void 0,onLiveTranscriptPersisted:t2,onSend:nT,onAbort:t_,onSteer:eN?tq:void 0,onFollowUp:eN?tV:void 0,onPromptWithStreamingBehavior:eN?tK:void 0,isStreaming:t3,model:e9,isAutoModelSelection:tS,modelNames:eM,modelList:eE,modelError:eR,modelScopeWarnings:eL,onModelChange:tO,onMainPresetChange:e||tN?tH:void 0,mainPresetActiveAlias:t6,modelRoles:eF,onRoleModelChange:tD,modelSwitching:ts,onCompact:e||tN?tB:void 0,onAbortCompaction:tG,isCompacting:e0,compactError:e8,compactResult:e4,toolPreset:e_,onToolPresetChange:e||tN?tX:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,outputTokensPerSecond:nb??ny,outputSpeedLive:null!==nb,thinkingCeiling:eO,onThinkingLevelChange:e||tN?tQ:void 0,fastMode:eD,fastModeBusy:eH,onFastModeToggle:e||tN?eU:void 0,availableThinkingLevels:nk,thinkingLevelMap:nj,retryInfo:eq,deliveryRows:th,inputHistory:nl,onRecallQueue:tJ,onRemoveQueuedMessage:tZ,slashCommands:tu,slashCommandsLoading:tp,onLoadSlashCommands:t0,onBuiltinCommand:tY,soundEnabled:R,onSoundToggle:L,onAudioUnlock:F,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name})}),nM=eC.streamingMessage,nE=(0,a.useMemo)(()=>nM?eG(nM,{isStreaming:!0}):[],[nM]),n$=(0,a.useMemo)(()=>nE.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[nE]),nR=(0,a.useMemo)(()=>nE.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[nE]),nL=nM?.role==="assistant"?nM:null,nA=(0,a.useMemo)(()=>{let e=-1;for(let t=t8.length-1;t>=0;t-=1)if("user"===t8[t].role){e=t;break}let t=e<0?-1:sD(t8,e);return{start:t,blocks:sW(t8,t+1,t8.length),priorCiHeads:sU(t8,nr,t+1),jobNotices:sO(t8,t+1,t8.length)}},[t8,nr]),nP=(0,a.useMemo)(()=>sP(nL?[...nA.blocks,...nL.content??[]]:nA.blocks,nr,t3,nA.priorCiHeads,nw,nA.jobNotices),[nA,nL,nr,t3,nw]),nF=(0,a.useMemo)(()=>t3?{...sz(nA.blocks,nr,nw),span:sB(t8,nA.start+1,t8.length)}:null,[t3,nA,nr,nw,t8]),n_=(0,a.useMemo)(()=>nF?{...nF,flow:nP,latest:!0}:null,[nF,nP]),nz=eN&&(tC?.kind==="running_tools"||(nL?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),nW=ns(t8,nL,e9?.provider,e9?.modelId),nO=nW.provider,nD=nW.model,nH=nW.credentialId;(0,a.useEffect)(()=>{if(!nz)return;let e=ed();e&&el.current!==e.turn&&ec.current!==e.turn&&(el.current=e.turn,ef("working",e,nO,nH,nD))},[nz,nO,nD,nH,ed,ef]);let[nU,nB]=(0,a.useState)(null),nq=(0,a.useCallback)(e=>{nB(e)},[]),nV=(0,a.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),nK=(0,a.useMemo)(()=>{let e=[eN&&!nM&&tC?function(e,t){if(e?.kind==="running_tools"){let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tC,K):null,eT&&!eI?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eN,nM,tC,eT,eI,K]);(0,a.useEffect)(()=>{if(!nU)return void C?.(null);let e=[],t=[],r=0;if(nM&&nR.length>0){let n=nU.messages.length+e.length;for(let a of(e.push(nM),nR))t.push({idx:n,blocks:a}),r+=eJ(a)}if(nV&&(t.push({idx:nU.messages.length+e.length}),e.push(nV)),0===t.length)return void C?.(nK?{...nU,status:nK}:nU);let n=-1;for(let e=nU.messages.length-1;e>=0;e--)if(ti(nU.messages[e])){n=e;break}let a=nU.groups.slice(),i=a.length>0?a[a.length-1]:void 0;i&&i.anchorIdx===n?a[a.length-1]={...i,entries:[...i.entries,...t],messageCount:i.messageCount+t.length,toolCallCount:i.toolCallCount+r}:a.push({anchorIdx:n,entries:t,messageCount:t.length,toolCallCount:r}),C?.({...nU,groups:a,messages:[...nU.messages,...e],status:nK})},[nU,nR,nM,nV,nK,C]),(0,a.useEffect)(()=>()=>C?.(null),[C]);let nG=r2.filter(e=>"belowEditor"!==e.placement),nJ=r2.filter(e=>"belowEditor"===e.placement);return ek?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ek}):(0,n.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":rn,"data-empty-start":nx&&!T?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:r6,onDragOver:r7,onDragLeave:r9,onDrop:ne,children:[rn?(0,n.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,n.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,r5&&!t3&&(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,n.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),tb&&(0,n.jsx)(pH,{request:tb,onInput:tj}),nx&&!T?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,n.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[860px] py-8",children:[(0,n.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,n.jsx)(ee,{})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.231"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.19.0"]})]})]})]}),nw&&(0,n.jsxs)("section",{className:"empty-workspace-context","aria-label":K("chat.emptyProjectLabel"),children:[(0,n.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,n.jsx)("span",{className:"empty-workspace-context-kicker",children:K("chat.emptyProjectLabel")}),(0,n.jsx)("strong",{children:tF(nw)||nw}),(0,n.jsx)("code",{title:nw,children:nw}),(0,n.jsx)("p",{children:K("chat.emptyProjectHint")})]}),k&&(0,n.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:k,children:K("chat.openSessionList")})]}),(0,n.jsx)(pW,{notices:tg,align:"right"})]})}):(0,n.jsxs)(n.Fragment,{children:[T&&(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:T}),(0,n.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!T,style:{display:T?"none":"flex"},children:[(0,n.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,n.jsx)(cs,{open:rP,onClose:rD,containerRef:tA,index:rW,renderedStart:rp,renderedEnd:rh,contentKey:t8,onReveal:rO,onProgrammaticScroll:tM,focusRequest:r_,t:K}),rL&&(0,n.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,n.jsx)(pW,{notices:tg,floating:!0,align:"right"})]})}),(0,n.jsx)("div",{ref:tA,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,n.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(pz,{widgets:nG}),(0,n.jsxs)(s7.Provider,{value:na,children:[(0,n.jsx)(cy,{utterances:ng,children:(0,n.jsx)(pP,{messages:t8,entryIds:eS,toolResultsMap:nr,modelNames:eM,messageCwd:nw,onOpenFile:N,sessionBusy:t3,isNew:tN,isStreaming:eC.isStreaming,handleFork:tz,forkingEntryId:eY,handleNavigate:tW,handleEditContent:ey,sessionId:e?.id??tR.current??void 0,main:rs,dispatchSlots:rl,compactedDispatch:rc,openRequest:td?.openRequest??null,process:ro,startIndex:rp,endIndex:rh,sentinelRef:rx,laterSentinelRef:rv,flashItem:ry,t:K,cues:Q,cueFollowRef:t9,onProcessLogChange:nq})}),!rf&&eC.isStreaming&&eC.streamingMessage&&n$.length>0&&(0,n.jsx)(lL,{message:eB(eC.streamingMessage,n$),sessionId:e?.id??tR.current??void 0,isStreaming:!0,modelNames:eM,cwd:nw,onOpenFile:N}),!rf&&n_&&(0,n.jsx)(o5,{summary:n_,live:!0,onOpenFile:N})]}),rJ&&(0,n.jsx)(cp,{onDismiss:rG,t:K}),(0,n.jsx)("div",{ref:tL})]})})}),(0,n.jsx)(co,{questions:rH,containerRef:tA,layoutKey:rU,onJump:rM,label:K("chat.questionRail")}),(t3&&tT||rf)&&(0,n.jsxs)("button",{type:"button",onClick:r$,"aria-label":K("chat.jumpToBottom"),title:K("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:J?44:void 0,borderRadius:"var(--seed-radius-full)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 5v14"}),(0,n.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,n.jsxs)("div",{ref:nC,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tx&&(0,n.jsx)("div",{style:{padding:"0 16px"},children:(0,n.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,n.jsx)(pD,{request:tx,onRespond:tk,onActivity:(e,t)=>void tj(e,t??"activity"),delivery:tv})})}),(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(cu,{compaction:e1,t:K}),(0,n.jsx)(p_,{goal:tE,t:K}),(0,n.jsx)(pz,{widgets:nJ}),(nc||nP.steps.length>0)&&!(G&&J)&&(0,n.jsx)(uD,{phases:nc,flow:nP,busy:t3})]})}),nI,(0,n.jsx)(uO,{statuses:ty})]})]})}function p_({goal:e,t}){if(!e)return null;let r=!e.enabled,a=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:rU(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:rU(e.tokensUsed)});return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:r?.7:1},children:[(0,n.jsx)("span",{style:{color:r?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,n.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:r?t("chat.goalPaused"):e.status}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:a})]})}function pz({widgets:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,n.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function pW({notices:e,floating:t=!1,align:r="left"}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===r?"flex-end":"stretch",marginBottom:10*!t},children:e.map((r,a)=>{let i="error"===r.type?"var(--danger)":"warning"===r.type?"var(--warning)":"success"===r.type?"var(--success)":"var(--accent)";return(0,n.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(a!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:r.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:i,flexShrink:0}}),(0,n.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.message})]},r.id)})})}function pO({focusKey:e,label:t,labelledBy:r,maxBlockSize:i="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,z.s)(),d=(0,a.useRef)(null),u=(0,a.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!d.current?.contains(t)?t:null}}return(0,a.useEffect)(()=>{let e=d.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let r=document.activeElement;(null===r||r===document.body||e?.contains(r))&&t.focus()}},[e]),(0,n.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":r,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:i},children:[o?(0,n.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function pD({request:e,onRespond:t,onActivity:r,delivery:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,a.useState)({selected:{},custom:{}}),[u,p]=(0,a.useState)(""),h=(0,a.useRef)(0),m=(0,a.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!r)return;let t=Date.now();t-h.current<1e3||(h.current=t,r(e))},[e,r]);(0,a.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let r of e)t[r.id]=void 0!==r.recommended&&void 0!==r.options[r.recommended]?[r.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("form"===e.method)return(0,n.jsx)(pO,{focusKey:e.id,label:s("chat.agentQuestion"),delivery:i,children:(0,n.jsx)(c2,{request:e,onRespond:t,onActivity:r,delivery:i},e.id)});if("ask"===e.method){var g;let r=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),a=()=>{if(r){var n;t(e,{value:(n=e.questions,JSON.stringify({kind:"submit",results:n.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,n.jsx)(pO,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,n.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,r)=>{let i=c.selected[t.id]??[];return(0,n.jsxs)("section",{style:{paddingTop:20*(0!==r),borderTop:0===r?"none":"1px solid var(--hairline)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,n.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[r+1,"/",e.questions.length]})]}),(0,n.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,n.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,r)=>{let a=i.includes(r),o=t.recommended===r;return(0,n.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":a,onClick:()=>{m(),d(e=>(function(e,t,r){let n=e.selected[t.id]??[];if(t.multi){let a=n.includes(r)?n.filter(e=>e!==r):[...n,r];return{...e,selected:{...e.selected,[t.id]:a}}}return{selected:{...e.selected,[t.id]:[r]},custom:{...e.custom,[t.id]:""}}})(e,t,r))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${a?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:a?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,n.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${a?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:a?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:a&&(t.multi?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,n.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,n.jsxs)("span",{style:{minWidth:0},children:[(0,n.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:a?600:500},children:e.label}),e.description&&(0,n.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),a&&e.preview&&(0,n.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${r}`)})}),(0,n.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let r=e.target.value;d(e=>{let n;return n={...e.custom,[t.id]:r},t.multi||0===r.trim().length?{...e,custom:n}:{selected:{...e.selected,[t.id]:[]},custom:n}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&a()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,n.jsx)("button",{type:"button",disabled:!r||i?.status==="sending",onClick:a,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:r&&i?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:r&&i?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:r&&i?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:i?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,n.jsx)(pO,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,n.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,n.jsx)(rb,{children:e.planContent})}),(0,n.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,n.jsx)(pO,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,n.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,n.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(r=>(0,n.jsx)("button",{onClick:()=>t(e,{value:r}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:r},r))}),"input"===e.method&&(0,n.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,n.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&f()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,n.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,n.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function pH({request:e,onInput:t}){let{t:r}=(0,z.s)(),i=(0,a.useRef)(null),s=(0,a.useRef)(!1),o=eP(e.lines);return(0,a.useEffect)(()=>{i.current?.focus()},[e.id]),(0,n.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||i.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,n.jsx)("textarea",{ref:i,"aria-label":r("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=ez[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":e_[e.key]??null}(r);n&&(r.preventDefault(),r.stopPropagation(),t(e,n))},onInput:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=r.currentTarget.value;r.currentTarget.value="",n&&t(e,n)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:r=>{s.current=!1;let n=r.currentTarget;queueMicrotask(()=>{let r=n.value;n.value="",r&&t(e,r)})},onPaste:r=>{r.preventDefault();let n=r.clipboardData.getData("text");n&&t(e,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:r("chat.extensionPanel")}),(0,n.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:r("chat.close")})]}),(0,n.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,r)=>{var i;return(0,n.jsxs)(a.Fragment,{children:[(i=`line-${t}`,eF(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},`${i}-${t}`):e.text)),t<r.length-1?"\n":null]},t)})})]})})}var pU=r(40960),pB=r.n(pU);function pq({sessionId:e,refreshKey:t,compact:r}){let{t:i}=(0,z.s)(),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(null),h=(0,a.useRef)(e);h.current=e;let m=(0,a.useRef)(0);(0,a.useEffect)(()=>{if(!e)return;let t=!1,r=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(n=>{if(t||r!==m.current)return;let a=n.running?n.state?.computerTakeover:null;l(a?{sessionId:e,state:{enabled:!0===a.enabled,available:!0===a.available}}:null),p(null)}).catch(()=>{}),()=>{t=!0}},[e,t]);let f=(0,a.useCallback)(async e=>{let t=h.current;if(t){d(!0),p(null);try{let r=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),n=await r.json();if(!r.ok)throw Error("shared_settings"===n.code?i("computerTakeover.shared"):n.error??r.statusText);h.current===t&&(m.current+=1,l({sessionId:t,state:{enabled:!0===n.enabled,available:!0!==n.enabled}}))}catch(e){h.current===t&&p(i("computerTakeover.failed",{error:e instanceof Error?e.message:String(e)}))}finally{d(!1)}}},[i]),g=o&&o.sessionId===e?o.state:null;if(!g||!g.enabled&&!g.available)return null;let x=g.enabled,v=x?i("computerTakeover.active"):i("computerTakeover.allow"),b=u??(x?i("computerTakeover.activeHint"):i("computerTakeover.allowHint"));return(0,n.jsxs)(s.r,{className:`workspace-header-action workspace-takeover${x?` ${pB().active}`:""}`,variant:x?"neutralWeak":"ghost",size:"small",type:"button",disabled:c,"aria-pressed":x,"aria-label":v,title:b,onClick:()=>void f(!x),children:[(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!r)&&(0,n.jsx)("span",{children:v})]})}function pV({onPick:e,t}){let[r,i]=(0,a.useState)(""),[s,o]=(0,a.useState)({kind:"idle"}),l=(0,a.useRef)(null),c=r.trim();(0,a.useEffect)(()=>{if(c.length<2)return void o({kind:"idle"});let e=new AbortController;o({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);o({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||o({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[c]);let d=e=>{let t=l.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,n.jsxs)("div",{className:"palette-search",children:[(0,n.jsx)("input",{type:"search",value:r,onChange:e=>i(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),d(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let r=u.hits[0],n=u.sessions[r.sessionId];n&&e(n,r,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,n.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,n.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,n.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((r,a)=>{let i=u.sessions[r.sessionId],s=r.matchStart+u.query.length;return(0,n.jsxs)("button",{type:"button",disabled:!i,onClick:()=>i&&e(i,r,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(a+("ArrowDown"===e.key?1:-1)))},children:[(0,n.jsxs)("span",{className:"palette-search-title",children:[(0,n.jsx)("span",{children:i?i.name?.trim()||i.firstMessage?.trim()||i.id:""}),(0,n.jsx)("small",{children:"user"===r.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,n.jsxs)("span",{className:"palette-search-snippet",children:[r.snippet.slice(0,r.matchStart),(0,n.jsx)("mark",{children:r.snippet.slice(r.matchStart,s)}),r.snippet.slice(s)]})]},`${r.sessionId}:${r.entryId}`)})})]})]})}var pK=r(50640),pG=r(73620);let pJ=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pZ(e){return function e(t,r){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(r.has(t))return"[Circular]";r.add(t);try{return t.map(t=>e(t,r)).filter(Boolean).join(", ")}finally{r.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let pY=["tags","categories","keywords","tag","category"];function pX({data:e}){var t;if(!e)return null;let r=Object.entries(e);if(0===r.length)return null;let a="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,i=pY.find(t=>Array.isArray(e[t])),s=i?e[i].map(pZ).filter(Boolean):[],o=r.filter(([e])=>e!==i&&("title"!==e||!a));return(0,n.jsxs)("div",{className:"markdown-frontmatter",children:[a&&(0,n.jsx)("div",{className:"markdown-frontmatter-title",children:a}),s.length>0&&(0,n.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,n.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,n.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,n.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,n.jsx)("dt",{children:e}),(0,n.jsx)("dd",{children:function(e){let t=pZ(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,n.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var pQ=r(8745);let p0=(0,a.createContext)(null),p1=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),p2=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),p8=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m10 3-5 5 5 5"})}),p4=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),p5=(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,n.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,n.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function p6({back:e,title:t,titleTooltip:r,titleRef:a,titleAdornment:i,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:m}){let{t:f}=(0,z.s)();return(0,n.jsxs)("header",{className:"panel-header",children:[e&&(0,n.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,n.jsx)(o.In,{size:"16px",svg:p8})}),(0,n.jsxs)("div",{className:"panel-header-heading",children:[(0,n.jsx)("h2",{className:"panel-header-title",title:r,ref:a,tabIndex:a?-1:void 0,children:t}),i,l&&("path"===d?(0,n.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,n.jsx)("bdi",{dir:"ltr",children:l})}):(0,n.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,n.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,n.jsxs)(pQ.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,n.jsxs)(pQ.A.Item,{value:e.value,title:e.title,children:[(0,n.jsx)(pQ.A.ItemHiddenInput,{}),e.label]},e.value)),(0,n.jsx)(pQ.A.Indicator,{})]}),h.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,n.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,n.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,n.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,n.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,n.jsx)(c.k.Trigger,{asChild:!0,children:(0,n.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,n.jsx)(o.In,{size:"16px",svg:p5})})}),(0,n.jsx)(c.k.Positioner,{children:(0,n.jsx)(c.k.Content,{"aria-label":f("panel.more"),children:(0,n.jsx)(c.k.ScrollArea,{children:(0,n.jsx)(c.k.Group,{children:h.map(e=>(0,n.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,n.jsx)(p3,{}),m&&(0,n.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:m.onClick,"aria-label":m.label,title:m.label,children:(0,n.jsx)(o.In,{size:"16px",svg:p4})})]})}function p3({className:e="panel-header-button"}){let{t}=(0,z.s)(),r=(0,a.useContext)(p0);if(!r)return null;let i=t(r.expanded?"panel.restore":"panel.expand");return(0,n.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":r.expanded,"aria-label":i,title:i,onClick:r.onToggle,children:(0,n.jsx)(o.In,{size:"16px",svg:r.expanded?p2:p1})})}let p7="cuelo-html-pick",p9="cuelo-html-pick-exit";function he(e,t){return"string"==typeof e&&e.length<=t}function ht(e){return"number"==typeof e&&Number.isFinite(e)}function hr({content:e,title:t,picking:r,onExitPick:i,onRequestEdit:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null),d=(0,a.useMemo)(()=>{if(!r)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var r;let n=`<script>${(r=t,`(function(){
|
|
20
|
+
${r}`:e:r,images:s,documents:o}}function d_(e,t,r){if(e===t)return r?d$(r):dL(t);let n=dL(e),a=r&&!dR(r)?d$(r):n??(r?d$(r):null),i=dL(t),s=dg.get(e);if(dg.delete(e),s&&!dg.has(t)&&dg.set(t,s),dP(e),!a)return i;let o=i?dF(i.value,i.images,a.value,a.images,i.documents,a.documents):a;return dA(t,o),d$(o)}function dz(e){let t=[];for(let r of e??[])r.attachmentId&&!t.includes(r.attachmentId)&&t.push(r.attachmentId);return t}function dW(e){dM();let t=dg.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let r=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}(),dg.set(e,t)),t}function dO(e){let t=dz(dh.get(e)?.documents),r=t.length?dW(e):dg.get(e);for(let[e,r]of dk){for(let e of t)r.delete(e);0===r.size&&dk.delete(e)}let n=`${r??""}|${t.join(",")}`;dS.get(e)!==n&&(0!==t.length||r?dS.set(e,n):dS.delete(e),dK())}async function dD(e){let t=dW(e);dw.set(t,(dw.get(t)??0)+1),await dC.get(t);let r=!1;return{draftId:t,end(e){if(r)return;r=!0;let n=(dw.get(t)??1)-1;if(n>0?dw.set(t,n):dw.delete(t),e){let r=dk.get(t)??new Set;r.add(e),dk.set(t,r)}dx.set(t,dv),dK()}}}function dH(e,t){let r=dj.get(e);if(!r)return[];for(let e of t)r.delete(e);return 0===r.size&&dj.delete(e),[...r].sort()}async function dU(){if(!dN)return;let e=[...function(){let e=new Map,t=(t,r)=>{let n=e.get(t)??new Set;for(let e of r)n.add(e);e.set(t,n)};for(let[e,r]of dg)t(r,dz(dh.get(e)?.documents));for(let{draftId:e,ids:r}of db.values())t(e,r);for(let[e,r]of dk)t(e,r);for(let e of dx.keys())t(e,[]);for(let e of dj.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dw.has(e))return!1;let r=dx.get(e);return dH(e,t).length>0||(0===t.length?void 0!==r:r!==t.join(","))}),t=dw.size>0,r=!1;for(let[n,a]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===a.length&&t)continue;let e=dH(n,a),i=dN(n,a,e).then(()=>{0===a.length?dx.delete(n):dx.set(n,a.join(","));let t=dj.get(n);if(t){for(let r of e)t.delete(r);0===t.size&&dj.delete(n)}},()=>{r=!0,a.length>0&&(t=!0)});dC.set(n,i),await i,dC.get(n)===i&&dC.delete(n)}r?function(){if(dV)return;dV=!0;let e=setTimeout(()=>{dV=!1,dK()},dq);"object"==typeof e&&"unref"in e&&e.unref(),dq=Math.min(2*dq,6e4)}():dq=dB}let dB=5e3,dq=5e3,dV=!1;function dK(){if(dN){if(dT){dI=!0;return}dT=Promise.resolve().then(dU).finally(()=>{dT=null,dI&&(dI=!1,dK())})}}let dG=Math.floor(Number.MAX_SAFE_INTEGER/1048576),dJ=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function dZ(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=dG}async function dY(e){let t,r=await e.json().catch(()=>null);if(!e.ok||!r||!dZ(r.uploadLimitMb)||"boolean"!=typeof r.autoCleanupEnabled)throw Error("string"==typeof r?.error?r.error:`HTTP ${e.status}`);return{uploadLimitMb:dZ((t=r&&"object"==typeof r?r:{}).uploadLimitMb)?t.uploadLimitMb:dJ.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:dJ.autoCleanupEnabled,orphanGraceDays:7}}async function dX(e={}){return dY(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function dQ(e){return dY(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function d0(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let r=/(?:^|\s)@([^\s"]*)$/.exec(e);return r?{start:e.length-(r[1].length+1),query:r[1],quoted:!1}:null}function d1(e){let t=0;for(let r=0;r<e.length;r++)"/"===e[r]&&t++;return t}function d2(e,t){if(!e)return!0;let r=0;for(let n=0;n<t.length&&r<e.length;n++)t[n]===e[r]&&r++;return r===e.length}function d8(e,t){let r=t?`${e}/`:e;return r.includes(" ")?`@"${r}" `:`@${r} `}function d4(e,t,r){let n=Math.max(1,Math.min(t,r)),a=Math.max(1,Math.max(t,r)),i=e.includes(" ")?`@"${e}"`:`@${e}`,s=n===a?`:${n}`:`:${n}-${a}`;return`${i}${s} `}let d5="omp-web:model-picks";function d6(){try{let e=JSON.parse(window.localStorage.getItem(d5)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[r,n]of Object.entries(e))"number"==typeof n&&Number.isFinite(n)&&n>0&&(t[r]=Math.floor(n));return t}catch{return{}}}function d3(e,t,r,n,a={}){let i=a.gap??8,s=a.margin??8,o=a.prefer??"above",l=Math.min(a.minHeight??120,Math.max(0,r-2*s)),c=Math.max(0,e-i-s),d=Math.max(0,r-t-i-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=n||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(n,h?u:p))}}function d7(e,t,r){return Math.min(e*t,r)}function d9(e,t,r){let{viewportFraction:n,cap:i,gap:s,margin:o,minHeight:l,prefer:c}=r,[d,u]=(0,a.useState)({side:c??"above",maxHeight:i}),p=(0,a.useCallback)(()=>{let t=e.current;if(!t)return;let r=window.visualViewport?.height??window.innerHeight,a=t.getBoundingClientRect(),d=d3(a.top,a.bottom,r,d7(r,n,i),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,i,s,o,l,c,n]);return(0,a.useEffect)(()=>{if(!t)return;p();let r=e.current,n=r?new ResizeObserver(p):null;return r&&n&&n.observe(r),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{n?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var ue=r(14755);let ut="omp-web:model-roles-expanded";async function ur(e,t,r,n,a,i,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...ug,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(i&&(!c||"builtin"===c.source))return a(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await r?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&n(d.prompt),!0}if(c&&"builtin"!==c.source)return n(e),!0;return a(`/${o} is not available in this web session.`),!1}catch(e){return a(e instanceof Error?e.message:String(e)),!1}}function un(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t||"fallback"===t}let ua=["off","default","full"],ui={off:"none",default:"default",full:"full"},us=ue.IN.join(" \xb7 "),uo=ue.C1.filter(e=>!ue.IN.includes(e)).join(" \xb7 ");function ul(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let uc=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),ud=0,uu={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function up(e,t){return uc.compare(e.name||e.modelId,t.name||t.modelId)||uc.compare(e.provider,t.provider)||uc.compare(e.modelId,t.modelId)}let uh=["auto","off","minimal","low","medium","high","xhigh","max"],um=["low","medium","high","xhigh"],uf={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},ug=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],ux=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uv={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},ub={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function uy(e,t,r){let n=e.name.toLowerCase(),a=uw(e,r).toLowerCase();return n===t?0:n.startsWith(t)?1:n.includes(t)?2:a.includes(t)?3:4}function uw(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uk(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uj(e){return{data:e.data,mimeType:e.mimeType}}function uS(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uC(e){return(e??[]).filter(rW).slice(0,10).map(uS)}let uN=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uT="\n\nTranscript of the audio ";function uI(e){return ll(e).map(e=>{let t=lf(e),r="audio"===t&&e.attachmentId&&!e.text.includes(uT)?uN.exec(e.text):null;return{...e,id:++ud,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...r?{storedInfo:{path:r[1],mimeType:r[2],size:Number(r[3])}}:{}}})}function uM({name:e,mimeType:t,size:r,text:n,attachmentId:a}){return a?{name:e,mimeType:t,size:r,text:n,attachmentId:a}:{name:e,mimeType:t,size:r,text:n}}function uE(e,t){let r=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?r.get(e.attachmentId):void 0;return t?(r.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class u$ extends Error{constructor(e,t,r,n,a=null){super(e),this.code=t,this.completedParts=r,this.parts=n,this.offer=a}}let uR="composer:unkeyed";async function uL(e){let t=await e.json().catch(()=>null),r=t&&"object"==typeof t?{...t}:{};if(e.ok)return r;let n="number"==typeof r.completedParts?r.completedParts:null,a="number"==typeof r.parts?r.parts:null,i="fallback_confirmation_required"===r.code&&"string"==typeof r.fallbackToken&&"string"==typeof r.notice&&null!==n&&null!==a?{token:r.fallbackToken,notice:r.notice,completedParts:n,parts:a}:null;throw new u$("string"==typeof r.error?r.error:`HTTP ${e.status}`,"string"==typeof r.code?r.code:null,n,a,i)}function uA(e,t){fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fallbackToken:t,approve:!1})}).catch(()=>void 0)}function uP(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function uF({tone:e,title:t,body:r}){let a="error"===e?"danger":"warning";return(0,n.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${a}-line)`,borderRadius:"var(--radius-control)",background:`var(--${a}-soft)`,color:`var(--${a})`,fontSize:11,lineHeight:1.45},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,n.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{fontWeight:600},children:t}),(0,n.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:r})]})]})}function u_({error:e}){return e?(0,n.jsx)(uF,{tone:"error",title:"Model error",body:e}):null}function uz({warnings:e}){return e&&0!==e.length?(0,n.jsx)(uF,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uW=(0,a.forwardRef)(function({onSend:e,onAbort:t,onSteer:r,onFollowUp:i,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:T,effectiveThinkingLevel:I,outputTokensPerSecond:M=null,outputSpeedLive:E=!1,thinkingCeiling:$,onThinkingLevelChange:R,availableThinkingLevels:L,thinkingLevelMap:A,fastMode:P=null,fastModeBusy:F=!1,onFastModeToggle:_,retryInfo:W,deliveryRows:O=[],inputHistory:D=[],onRecallQueue:H,onRemoveQueuedMessage:U,slashCommands:q,slashCommandsLoading:V,onLoadSlashCommands:K,onBuiltinCommand:G,soundEnabled:J,onSoundToggle:Z,onAudioUnlock:Y,onPromptWithStreamingBehavior:X,draftKey:Q,cwd:ee,sessionTitle:et,sessionId:er,onEnsureSession:en,onLiveTranscriptPersisted:ea},ei){let es,eo,el,ec,ed,eu,ep,eh,em,ef,{t:eg}=(0,z.s)();am();let{st:ex}=ag(),ev=O.some(e=>e.removable),eb=B(),[ey,ew]=(0,a.useState)(()=>Q?dL(Q)?.value??"":""),[ek,ej]=(0,a.useState)(!1),[eS,eC]=(0,a.useState)(null),[eN,eT]=(0,a.useState)(""),[eI,eM]=(0,a.useState)({});(0,a.useEffect)(()=>{ek&&eM(d6())},[ek]);let[eE,e$]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(ek)try{e$("1"===window.localStorage.getItem(ut))}catch{}},[ek]);let eR=()=>{e$(e=>{let t=!e;try{window.localStorage.setItem(ut,t?"1":"0")}catch{}return t})},[eL,eA]=(0,a.useState)(!1),[eP,eF]=(0,a.useState)(null),[e_,ez]=(0,a.useState)(!1),[eW,eO]=(0,a.useState)(!1),[eD,eH]=(0,a.useState)(null),[eU,eB]=(0,a.useState)(!1),[eq,eV]=(0,a.useState)(()=>Q?uC(dL(Q)?.images):[]),[eK,eG]=(0,a.useState)(()=>Q?uI(dL(Q)?.documents):[]),[eJ,eZ]=(0,a.useState)(null),eY=(0,a.useMemo)(()=>eK.filter(e=>"ready"===e.status),[eK]),eX=eK.some(e=>"ready"!==e.status||un(e)),eQ=eK.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uT))),e0=ey.trimStart(),e1=0===eq.length&&0===eK.length&&e0.startsWith("!"),e2=e1&&e0.startsWith("!!"),[e8,e4]=(0,a.useState)(!1),[e5,e6]=(0,a.useState)(0),[e3,e7]=(0,a.useState)(null),e9=e3?.value===ey&&e3.draftKey===Q?e3.token:null,[te,tt]=(0,a.useState)(!1),[tr,tn]=(0,a.useState)(!1),ta=(0,a.useRef)(null),[ti,ts]=(0,a.useState)(null),[to,tl]=(0,a.useState)(!1),[tc,td]=(0,a.useState)(0),[tu,tp]=(0,a.useState)(!1),[th,tm]=(0,a.useState)(0),[tf,tg]=(0,a.useState)(null),[tx,tv]=(0,a.useState)(!1),[tb,ty]=(0,a.useState)(null),[tw,tk]=(0,a.useState)(null),tj=ee&&tw?.cwd===ee?tw.values:{},tS=(0,a.useRef)(null),tC=(0,a.useRef)(null),tN=(0,a.useRef)(null),tT=(0,a.useRef)(null),tI=(0,a.useRef)(null),tM=(0,a.useRef)(null),tE=(0,a.useRef)(null),t$=(0,a.useRef)(null),tR=(0,a.useRef)(null),tL=(0,a.useRef)(null),tA=(0,a.useRef)(null),tP=(0,a.useRef)(!1),tF=(0,a.useRef)(0),t_=(0,a.useRef)(!1),tz=(0,a.useRef)([]),tW=(0,a.useRef)([]),tO=(0,a.useRef)([]),tD=(0,a.useRef)(null),tH=(0,a.useRef)(null),tU=(0,a.useRef)(Q),tB=(0,a.useRef)(ey),tq=(0,a.useRef)(eq),tV=(0,a.useRef)(0),tK=(0,a.useRef)(eK);tB.current=ey,tq.current=eq,tK.current=eK,(0,a.useImperativeHandle)(ei,()=>({insertIfEmpty(e){let t=tS.current;(t?t.value:ey).trim()||(tB.current=e,ew(e),ts(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,r,n=tS.current;if(!function(e,t,r,n=0){return!e.trim()&&0===t&&0===r&&0===n}(n?n.value:ey,tq.current.length,tV.current,tK.current.length))return;let a=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lu(t)?.message??t),i=uC("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,r=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof r)return[];let n={data:t,mimeType:r};return rW(n)?[n]:[]})),s=uI((r="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lu(r)?.documents??[]));tB.current=a,tq.current=i,tK.current=s,ew(a),ts(null),tp(!1),eV(e=>(e.forEach(uP),i)),eG(s),requestAnimationFrame(()=>{n&&(n.focus(),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tU.current!==e)return void d_(e,t);let r={value:tB.current,images:tq.current.map(uj),documents:tK.current.filter(e=>"ready"===e.status).map(uM)},n=d_(e,t,r)??{value:"",images:[],documents:[]},a=n.value===r.value&&n.images.length===r.images.length&&n.images.every((e,t)=>e.data===r.images[t]?.data&&e.mimeType===r.images[t]?.mimeType)&&n.documents.length===r.documents.length&&n.documents.every((e,t)=>e.name===r.documents[t]?.name&&e.mimeType===r.documents[t]?.mimeType&&e.size===r.documents[t]?.size&&e.text===r.documents[t]?.text&&e.attachmentId===r.documents[t]?.attachmentId);if(tU.current=t,a)return;let i=uC(n.images),s=uE(uI(n.documents),tK.current),o=n.value;tB.current=o,tq.current=i,tK.current=s,ew(o),eV(e=>(e.forEach(uP),i)),eG(s),ts(null),tp(!1)},restoreSubmission(e,t,r,n){if(!e.trim()&&!t?.length&&!r?.length)return;let a=tU.current,i=n??a,s=i===a,o=!s&&i?dL(i):null,l=dF(e,t,s?tB.current:o?.value??"",s?tq.current.map(uj):o?.images??[],r,s?tK.current.filter(e=>"ready"===e.status).map(uM):o?.documents??[]);if(i&&dA(i,l),!s)return;let c=t?.length?[...uC(t).slice(0,Math.max(0,10-tq.current.length)),...tq.current].slice(0,10):tq.current,d=uE(uI(l.documents),tK.current);tB.current=l.value,tq.current=c,tK.current=d,ew(l.value),ts(null),tp(!1),t?.length&&eV(e=>{let r=Math.max(0,10-e.length),n=uC(t).slice(0,r),a=n.length>0?[...n,...e]:e;return tq.current=a,a}),eG(d),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=tS.current;if(!t)return void ew(t=>t+(t?" ":"")+e);let r=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length,a=t.value.slice(0,r),i=t.value.slice(n),s=a.length>0&&!a.endsWith(" ")?" ":"",o=a+s+e+i;tB.current=o,ew(o),ts(null),requestAnimationFrame(()=>{if(!t)return;let n=r+s.length+e.length;t.setSelectionRange(n,n),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){t9(e)}}));let tG=(0,a.useCallback)(async e=>{let t=Math.max(0,10-tq.current.length-tV.current),r=e.filter(e=>e.size>0xa00000);r.length>0&&eZ(eg("chat.attachImageTooLarge",{name:r.map(e=>e.name).join(", "),limit:lp(0xa00000)}));let n=e.filter(e=>e.size<=0xa00000),a=n.slice(0,t);if(a.length<n.length&&eZ(eg("chat.attachImageLimit",{count:10})),a.length){tV.current+=a.length;try{let e=await Promise.all(a.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let r=n.result.split(",")[1];t({data:r,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},n.onerror=r,n.readAsDataURL(e)})));eV(t=>{let r=e.slice(0,Math.max(0,10-t.length));e.slice(r.length).forEach(uP);let n=[...t,...r];return tq.current=n,n})}finally{tV.current-=a.length}}},[eg]),tJ=(0,a.useCallback)(async e=>{for(let t of e){let e=la(t);if(!e)continue;if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eZ(eg("chat.attachTooLarge",{name:t.name,limit:lp(8388608)}));continue}if(tK.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eZ(eg("chat.attachTotalTooLarge",{limit:lp(0x1000000)}));continue}let r={id:++ud,name:t.name,mimeType:lt[e],size:t.size,text:"",status:"extracting"},n=[...tK.current,r];tK.current=n,eG(n);try{let e=await lc(t);if(tK.current.reduce((e,t)=>e+(t.id===r.id?0:t.text.length),0)+e.text.length>24e4)throw new le("text_too_large","Total extracted text exceeds 240000 characters");let n=tK.current.map(t=>t.id===r.id?{...e,id:t.id,status:"ready"}:t);tK.current=n,eG(n)}catch(a){let e=tK.current.some(e=>e.id===r.id),n=tK.current.filter(e=>e.id!==r.id);if(tK.current=n,eG(n),!e)continue;a instanceof le?"text_too_large"===a.code?eZ(eg("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===a.code?eZ(eg("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===a.code?eZ(eg("chat.attachNoPdfText",{name:t.name})):"password_protected"===a.code?eZ(eg("chat.attachPasswordProtected",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name}))}}},[eg]),tZ=(0,a.useCallback)((e,t)=>{if(!tK.current.some(t=>t.id===e))return!1;let r=t?tK.current.map(r=>r.id===e?t:r):tK.current.filter(t=>t.id!==e);return tK.current=r,eG(r),!0},[]),tY=(0,a.useCallback)((e,t)=>{if(!tK.current.some(t=>t.attachmentId===e))return!1;let r=tK.current.map(r=>r.attachmentId===e?t(r):r);return tK.current=r,eG(r),!0},[]),tX=(0,a.useCallback)((e,t,r)=>{if(!e||e===tU.current)return;let n=dL(e);n?.documents.some(e=>e.attachmentId===t)&&dA(e,{...n,documents:uI(n.documents).map(e=>e.attachmentId===t?r(e):e).map(uM)})},[]),tQ=(0,a.useRef)(new Map),t0=(0,a.useRef)(new Map),t1=(0,a.useRef)(new Set),t2=(0,a.useCallback)((e,t,r)=>{if(!e.storedInfo)return null;let n=Math.min(12e4,24e4-r.reduce((t,r)=>t+(r.attachmentId===e.attachmentId?0:r.text.length),0)),a=lg({...e.storedInfo,transcript:t},n);return a.length>n?null:{...e,text:a,size:new TextEncoder().encode(a).byteLength,transcription:void 0}},[]),t8=(0,a.useCallback)(e=>e instanceof u$&&"media_tool_unavailable"===e.code?eg("chat.transcribeToolMissing"):e instanceof u$&&"fallback_confirmation_expired"===e.code?eg("chat.transcribeFallbackExpired"):e instanceof u$&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eg("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eg]),t4=(0,a.useCallback)(async(e,t)=>{let r=tU.current,n=tK.current.find(t=>t.attachmentId===e);if(!n?.storedInfo)return;let a=n.transcription?.state==="confirm"?n.transcription.plan:null;t0.current.get(e)?.abort();let i=new AbortController;t0.current.set(e,i),tY(e,e=>({...e,transcription:{state:"running",plan:a}}));try{let n=await uL(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:i.signal}));if("string"!=typeof n.transcript)throw new u$("Invalid transcription result",null,null,null);let a=n.transcript;tY(e,e=>t2(e,a,tK.current)??{...e,transcription:{state:"failed",error:eg("chat.transcribeTooLong")}})||tX(r,e,e=>t2(e,a,[])??e)}catch(n){if(i.signal.aborted)return void tY(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof u$&&"confirmation_required"===n.code)return void t5.current?.(e);let t=n instanceof u$?n.offer:null;if(t){let r={state:"fallback",reason:n instanceof Error?n.message:"",...t};tY(e,e=>({...e,transcription:r}))||uA(e,t.token);return}let r=t8(n);tY(e,e=>({...e,transcription:{state:"failed",error:r}}))}finally{t0.current.get(e)===i&&t0.current.delete(e)}},[eg,t8,tY,tX,t2]),t5=(0,a.useRef)(null),t6=(0,a.useCallback)(async e=>{let t;t0.current.get(e)?.abort();let r=new AbortController;t0.current.set(e,r),tY(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new u$("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await uL(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:r.signal})))}catch(t){if(r.signal.aborted)tY(e,e=>({...e,transcription:{state:"skipped"}}));else{let r=t8(t);tY(e,e=>({...e,transcription:{state:"failed",error:r}}))}return}finally{t0.current.get(e)===r&&t0.current.delete(e)}t.requiresConfirmation?tY(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await t4(e,{})},[t4,t8,tY]);t5.current=t6;let t3=(0,a.useCallback)(e=>{let t=t0.current.get(e);if(t)return void t.abort();let r=tK.current.find(t=>t.attachmentId===e)?.transcription;r?.state==="fallback"&&uA(e,r.token),tY(e,e=>({...e,transcription:{state:"skipped"}}))},[tY]),t7=(0,a.useCallback)(async(e,t)=>{let r=null;for(let n of e){if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}let e="file"===t&&n.size<=8388608,a={id:++ud,name:n.name,mimeType:"text/plain",size:e?n.size:0,text:"",status:e?"extracting":"uploading",sourceSize:n.size},i=[...tK.current,a];tK.current=i,eG(i);let s=(e,t)=>{let r=tK.current.filter(e=>e.id!==a.id);return e<=12e4&&r.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&r.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await n.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?lo("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?lo("utf-16be",t.subarray(2)):t.includes(0)?null:lo("utf-8",t)??lo("euc-kr",t)},()=>null);if(null!==e&&s(e.length,n.size)){tZ(a.id,{...a,text:e,status:"ready"});continue}}if(null===r&&(r=1048576*(await dX().catch(()=>dJ)).uploadLimitMb),n.size>r){tZ(a.id,null)&&eZ(eg("chat.attachStoredTooLarge",{name:n.name,limit:lp(r)}));continue}let o={...a,stored:t,status:"uploading",size:0};if(!tZ(a.id,o))continue;let l=tU.current??uR,c=await dD(l),d=null,u=new AbortController;tQ.current.set(a.id,u);try{if(t1.current.has(a.id))continue;let e=await lx(n,{sessionId:er,draftId:c.draftId,signal:u.signal}),r=tK.current.filter(e=>e.id!==a.id).reduce((e,t)=>e+t.text.length,0),i=lg({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-r)),p=new TextEncoder().encode(i).byteLength;if(!s(i.length,p)){tZ(a.id,null)&&eZ(eg("chat.attachTotalTooLarge",{limit:lp(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:i,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tZ(a.id,h))d=e.id;else if(!t1.current.has(a.id)&&l!==tU.current){let t=dL(l)??{value:"",images:[],documents:[]};dA(l,{...t,documents:[...t.documents,uM(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tZ(a.id,null)&&eZ(eg("chat.attachUploadFailed",{name:n.name,error:e instanceof Error?e.message:String(e)}))}finally{tQ.current.delete(a.id),c.end(d)}d&&"audio"===t&&tK.current.some(e=>e.attachmentId===d)&&t6(d)}},[tZ,t6,er,eg]),t9=(0,a.useCallback)(async e=>{eZ(null);let{images:t,documents:r,audio:n,files:a}=function(e){let t=[],r=[],n=[],a=[];for(let i of e)i.type.startsWith("image/")?t.push(i):null!==la(i)?r.push(i):ls(i)?n.push(i):a.push(i);return{images:t,documents:r,audio:n,files:a}}(e),i=r.filter(e=>e.size>8388608);await Promise.all([tG(t),tJ(r.filter(e=>e.size<=8388608)),t7(n,"audio"),t7([...a,...i],"file")])},[tJ,t7,tG]),re=(0,a.useCallback)(e=>{eV(t=>{let r=[...t],[n]=r.splice(e,1);return n&&uP(n),tq.current=r,r})},[]),rt=(0,a.useCallback)(e=>{let t=tK.current.find(t=>t.id===e);if(t1.current.add(e),tQ.current.get(e)?.abort(),t?.attachmentId){t0.current.get(t.attachmentId)?.abort(),t.transcription?.state==="fallback"&&uA(t.attachmentId,t.transcription.token);var r=t.attachmentId;for(let[e,t]of dk)t.delete(r)&&(0===t.size&&dk.delete(e),dK())}let n=tK.current.filter(t=>t.id!==e);tK.current=n,eG(n)},[]),rr=(0,a.useCallback)(()=>{tq.current=[],eV(e=>(e.forEach(uP),[]))},[]),rn=(0,a.useCallback)(()=>{tK.current=[],eG([])},[]),ra=(0,a.useCallback)(()=>{tB.current="",ew(""),ts(null),e7(null),tt(!1),tp(!1),Q&&dP(Q),tU.current&&tU.current!==Q&&dP(tU.current),rr(),rn(),eZ(null),tS.current&&(tS.current.style.height="auto")},[rn,rr,Q]);(0,a.useEffect)(()=>{Q&&tU.current===Q&&dA(Q,{value:ey,images:eq.map(uj),documents:eY.map(uM)})},[eq,Q,eY,ey]),(0,a.useEffect)(()=>{let e=tU.current;if(e===Q)return;e&&dA(e,{value:tB.current,images:tq.current.map(uj),documents:tK.current.filter(e=>"ready"===e.status).map(uM)});let t=Q?dL(Q):null;tU.current=Q;let r=t?.value??"",n=uC(t?.images),a=uI(t?.documents);tB.current=r,tq.current=n,tK.current=a,ew(r),ts(null),tp(!1),eV(e=>(e.forEach(uP),n)),eG(a)},[Q]),(0,a.useEffect)(()=>{let e=tS.current;e&&(e.style.height="auto",ey&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ey]),(0,a.useEffect)(()=>()=>{tq.current.forEach(uP)},[]);let ri=(0,a.useCallback)((e,t)=>{let r=function(e,t){let r=dz(t);if(0===r.length)return()=>{};let n=++dy;return db.set(n,{draftId:dW(e),ids:r}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=db.get(n);if(t){if(db.delete(n),"accepted"===e){let e=dj.get(t.draftId)??new Set;for(let r of t.ids)e.add(r);dj.set(t.draftId,e)}dK()}}}(tU.current??uR,e);Promise.resolve(t()).then(e=>r("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),rs=(0,a.useCallback)(async()=>{let t=ey.trim(),r=e0.trim(),n=r.startsWith("/")||r.startsWith("!")?r:t;if(!n&&!eq.length&&!eY.length||o||eX)return;Y?.();let a=eq.length?eq:void 0,i=eY.length?eY:void 0;if(n.startsWith("/")){await ur(n,q,G,t=>ri(i,()=>e(t,a,i)),eZ,!!(a||i),K)&&ra();return}ra(),ri(i,()=>e(n,a,i))},[ey,e0,eq,eY,eX,o,G,q,K,e,ra,Y,ri]),ro=!e0.startsWith("/")||e0.startsWith("//")||/\s/.test(e0.slice(1))?null:e0.slice(1).toLowerCase(),rl=(()=>{if(null===ro)return[];let e=[...o?[]:ug,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),r=uw(e,eg).toLowerCase();return t.includes(ro)||r.includes(ro)}).sort((e,t)=>{let r=uy(e,ro,eg)-uy(t,ro,eg);return 0!==r?r:ub[e.source]-ub[t.source]||uc.compare(e.name,t.name)}).filter(e=>{let r=e.name.toLowerCase();return!t.has(r)&&(t.add(r),!0)})})(),{commands:rc,groups:rd}=(es=0,{commands:(eo=ux.map(e=>{let t=rl.filter(t=>t.source===e),r="skill"===e?[...t.filter(e=>!uk(e,tj)),...t.filter(e=>uk(e,tj))]:t;return{source:e,items:r.map(e=>({command:e,index:es++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:eo}),ru=1===rl.length?eg(ro?"chat.match":"chat.command"):eg(ro?"chat.matches":"chat.commands",{count:rl.length}),rp=!!ey.trim(),rh=!eX&&(rp||eq.length>0||eY.length>0),rm=(0,a.useCallback)((e,t)=>{let r=function(e,t){let r=Math.max(0,Math.min(e.length,t)),n=/(?:^|\s)(\/\/[^\s]*)$/.exec(e.slice(0,r));if(!n)return null;let a=r-n[1].length,i=/^\S*/.exec(e.slice(r))[0];return{start:a,end:r+i.length,query:e.slice(a+2,r)}}(e,t??e.length);if(e7(r?{value:e,draftKey:Q,token:r}:null),tn(!1),!ee)return void ts(null);let n=t??e.length;ts(d0(e.slice(0,n)))},[ee,Q]),rf=ti?.query??null,rg=a.useMemo(()=>null!==rf&&tf&&tf.cwd===ee?function(e,t,r=20){let n=t.toLowerCase();if(!n)return e.slice(0,r);let a=[];for(let t of e){let e=function(e,t){let r=e.path.toLowerCase(),n=0;if(t.includes("/"))r===t?n=100:r.startsWith(t)?n=80:r.includes(t)?n=50:d2(t,r)&&(n=10);else{let e=r.lastIndexOf("/"),a=-1===e?r:r.slice(e+1);a===t?n=100:a.startsWith(t)?n=80:a.includes(t)?n=50:r.includes(t)?n=30:d2(t,r)&&(n=10)}return e.isDir&&n>0&&(n+=10),n}(t,n);e>0&&a.push({entry:t,score:e})}return a.sort((e,t)=>t.score-e.score||d1(e.entry.path)-d1(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),a.slice(0,r).map(e=>e.entry)}(tf.entries,rf):[],[rf,tf,ee]),rx=!!(rf&&tf?.truncated&&tf.cwd===ee);(0,a.useEffect)(()=>{if(!rx||!ee||!rf)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(rf)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ty({cwd:ee,query:rf,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[rx,rf,ee]);let rv=rx&&null!==tb&&tb.cwd===ee&&tb.query===rf,rb=rv?tb.matches:rg,ry=null===ti?null:`${ti.start}:${+!!ti.quoted}:${ti.query}`;(0,a.useEffect)(()=>{if(null===ry){tl(!1),td(0);return}tl(!0),td(0)},[ry]);let rw=null!==ti,rk=d9(tL,tu,{viewportFraction:.44,cap:360}),rj=d9(tL,e8,{viewportFraction:.56,cap:460}),rS=d9(tL,to,{viewportFraction:.48,cap:400}),rC=d9(tL,te,{viewportFraction:.48,cap:400}),rN=e9?`${e9.start}:${e9.end}:${e9.query}`:null;(0,a.useEffect)(()=>{tt(null!==rN)},[rN]);let rT=(0,a.useCallback)((e,t,r,n=!1)=>{tB.current===e&&tU.current===Q&&(tB.current=t,ew(t),e7(null),tt(!1),tn(n),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(r,r),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[Q]);(0,a.useEffect)(()=>{if(!rw||!ee)return;let e=tD.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tH.current===ee||(tH.current=ee,tv(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tg({cwd:ee,entries:function(e){let t=new Set;for(let r of e){let e=r.indexOf("/");for(;-1!==e;)t.add(r.slice(0,e)),e=r.indexOf("/",e+1)}let r=[];for(let e of t)r.push({path:e,isDir:!0});for(let t of e)t&&r.push({path:t,isDir:!1});return r.sort((e,t)=>d1(e.path)-d1(t.path)||e.path.localeCompare(t.path)),r}(e.files??[]),truncated:!!e.truncated}),tD.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tD.current=null}).finally(()=>{tH.current=null,tv(!1)}))},[rw,ee]);let rI=(0,a.useCallback)(e=>{if(!ti)return;let t=tS.current,r=t?.selectionStart??ey.length,n=ey.slice(0,ti.start),a=ey.slice(r);ti.quoted&&a.startsWith('"')&&(a=a.slice(1));let i=function(e,t,r=!1){let n=t?`${e}/`:e,a=r||n.includes(" ");if(t){let e=a?`@"${n}"`:`@${n}`;return{text:e,cursorOffset:a?e.length-1:e.length}}let i=a?`@"${n}" `:`@${n} `;return{text:i,cursorOffset:i.length}}(e.path,e.isDir,ti.quoted),s=n+i.text+a,o=n.length+i.cursorOffset;ew(s),ts(d0(s.slice(0,o))),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[ti,ey]);(0,a.useEffect)(()=>{tc>=rb.length&&td(Math.max(0,rb.length-1))},[rb.length,tc]),(0,a.useEffect)(()=>{tW.current.length=rb.length},[rb.length]),(0,a.useEffect)(()=>{to&&tW.current[tc]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tc,to]),(0,a.useEffect)(()=>{th>=D.length&&tm(Math.max(0,D.length-1))},[D.length,th]),(0,a.useEffect)(()=>{tO.current.length=D.length},[D.length]),(0,a.useEffect)(()=>{tu&&tO.current[th]?.scrollIntoView({block:"nearest",inline:"nearest"})},[th,tu]);let rM=(0,a.useCallback)(e=>{tB.current=e,ew(e),tp(!1),tm(0),ts(null),requestAnimationFrame(()=>{let t=tS.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),rE=(0,a.useCallback)(e=>{let t=`/${e.name} `;tB.current=t,ew(t),e4(!1),e6(0),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),r$=(0,a.useCallback)(async e=>{let t=ey.trim(),n=e0.trim(),a=n.startsWith("/")||n.startsWith("!")?n:t,s=eX||!a&&0===eq.length&&0===eY.length?null:{message:a,images:eq.length?eq:void 0,documents:eY.length?eY:void 0};if(!s)return;Y?.();let o="steer"===e?"steer":"followUp";if(a.startsWith("/")){await ur(a,q,G,e=>{if(!X)throw Error("Cannot queue this command while the session is busy.");ri(s.documents,()=>X(e,o,s.images,s.documents))},eZ,!!(s.images?.length||s.documents?.length),K)&&ra();return}ra(),"steer"===e&&r?ri(s.documents,()=>r(s.message,s.images,s.documents)):"followup"===e&&i&&ri(s.documents,()=>i(s.message,s.images,s.documents))},[ey,e0,eq,eY,eX,q,K,G,X,r,i,ra,Y,ri]),rR=(0,a.useCallback)(e=>{let t=rc.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e5-1);if("right"===e)return Math.min(t,e5+1);let r=tz.current[e5];if(!r)return"down"===e?Math.min(t,e5+1):Math.max(0,e5-1);let n=r.getBoundingClientRect(),a=n.left+n.width/2,i=n.top+n.height/2,s=-1,o=1/0;for(let r=0;r<=t;r+=1){if(r===e5)continue;let t=tz.current[r];if(!t)continue;let n=t.getBoundingClientRect(),l=n.top+n.height/2-i;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(n.left+n.width/2-a);c<o&&(s=r,o=c)}return s>=0?s:"down"===e?Math.min(t,e5+1):Math.max(0,e5-1)},[rc.length,e5]),rL=(0,a.useCallback)(e=>{let n=e.nativeEvent,a=Date.now()-tF.current<100,s=tP.current||n.isComposing||229===n.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||a)){a&&e.preventDefault();return}if(tu&&!s){if("ArrowDown"===e.key){e.preventDefault(),tm(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tm(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tp(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[th]){e.preventDefault(),rM(D[th]);return}}if(!(te&&e9&&!s&&ta.current?.handleKeyDown(e))){if(e8&&null!==ro){if("ArrowDown"===e.key){e.preventDefault(),e6(rR("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e6(rR("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e6(rR("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e6(rR("left"));return}if("Escape"===e.key){e.preventDefault(),e4(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rc[e5]){e.preventDefault(),rE(rc[e5]);return}}if(to&&null!==ti&&!s){if("ArrowDown"===e.key){e.preventDefault(),td(e=>Math.min(Math.max(0,rb.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),td(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tl(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&rb[tc]){e.preventDefault(),rI(rb[tc]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===ey.trim().length){e.preventDefault(),e4(!1),tl(!1),tm(D.length-1),tp(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(r||i)?r$(r?"steer":"followup"):rs())}},[o,r,i,t,e8,ro,rc,e5,rE,r$,rs,rR,to,ti,rb,tc,rI,tu,D,th,rM,ey,te,e9]),rA=(0,a.useCallback)(()=>{let e=tS.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),rP=(0,a.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let r=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&r.push(e)}return r}(e.clipboardData);t.length&&(e.preventDefault(),t9(t))},[t9]);(0,a.useEffect)(()=>{if(null===ro){e4(!1),e6(0),t_.current=!1;return}e4(!0),e6(0),!t_.current&&K&&(t_.current=!0,Promise.resolve(K()).catch(()=>{t_.current=!1}))},[ro,K]),(0,a.useEffect)(()=>{if(!e8||!ee)return;let e=!1;return tk({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let r={};for(let e of t.skills??[])r[e.name]=e.disableModelInvocation;tk({cwd:ee,values:r})}).catch(()=>{e||tk({cwd:ee,values:{}})}),()=>{e=!0}},[e8,ee]),(0,a.useEffect)(()=>{e5>=rc.length&&e6(Math.max(0,rc.length-1))},[rc.length,e5]),(0,a.useEffect)(()=>{tz.current.length=rc.length},[rc.length]),(0,a.useEffect)(()=>{e8&&tz.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e8]);let rF=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(up):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(up),r_=g??null,rz=nh.find(e=>e.alias===r_)?.provider??null,rO=rz?rF.filter(e=>e.provider===rz):rF,rD=(el=eN.trim().toLocaleLowerCase())?rO.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(el)):rO,rH=rO.length>8,rB=[];for(let e of rD){let t=rB.find(t=>t.provider===e.provider);t?t.options.push(e):rB.push({provider:e.provider,options:[e]})}let rq=rz?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),rV=l?rq.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,rK=eN.trim()?[]:rO.map((e,t)=>{var r,n;return{option:e,order:t,count:eI[r=e.provider,n=e.modelId,`${r}/${n}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),rG=(e,t,r)=>{let a=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,n.jsxs)("button",{onClick:()=>{if(ej(!1),eT(""),!a||c){var t,r;let n=function(e,t){let r={...e,[t]:(e[t]??0)+1},n=Object.keys(r);if(n.length<=30)return r;for(let e of(n.sort((e,t)=>r[e]-r[t]),n)){if(Object.keys(r).length<=30)break;e!==t&&delete r[e]}return r}(d6(),(t=e.provider,r=e.modelId,`${t}/${r}`));try{window.localStorage.setItem(d5,JSON.stringify(n))}catch{}eM(n),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:a?"var(--bg-selected)":"none",border:"none",color:a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:a?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:[a?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==r&&r>=2&&(0,n.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eg("chat.modelPickCount",{count:r})})]},`${t}:${e.provider}:${e.modelId}`)},rJ=l?rF.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,rZ=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,rY=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eg("chat.compacted")} ${rU(S.tokensBefore)} -> ${rU(S.estimatedTokensAfter)} tokens (${eg("chat.tokensSaved",{saved:rU(rZ)})})`:null,rX=e=>{let t=A?.[e];return null!=t&&t!==e?t:null},rQ="auto"===(ec=T??"auto")?$?`auto ≤ ${rX($)??$}`:"auto":A?A[ec]??ec:ec,r0=(T??"auto")==="auto"&&I&&"auto"!==I?A?.[I]??I:null,r1=R&&r0?eg("chat.currentReasoning",{level:r0}):null,r2=e=>!L||L.includes(e),r8=[{level:"auto",ceiling:null},...um.filter(r2).map(e=>({level:"auto",ceiling:e})),...uh.filter(e=>"auto"!==e&&r2(e)).map(e=>({level:e,ceiling:null}))],r4=Object.entries(ui).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,a.useEffect)(()=>{let e=e=>{tC.current&&!tC.current.contains(e.target)&&tN.current&&!tN.current.contains(e.target)&&(ej(!1),eT("")),tT.current&&!tT.current.contains(e.target)&&tI.current&&!tI.current.contains(e.target)&&eA(!1),tM.current&&!tM.current.contains(e.target)&&ez(!1),tE.current&&!tE.current.contains(e.target)&&eO(!1),t$.current&&!t$.current.contains(e.target)&&eB(!1),!tR.current||tR.current.contains(e.target)||tS.current?.contains(e.target)||tp(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,a.useEffect)(()=>{eb||eB(!1)},[eb]);let r5=(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eq.length||eK.length?" is-active":""}`,onClick:()=>tA.current?.click(),title:eg("chat.attachFile"),"aria-label":eg("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eq.length||eK.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=eq.length||eK.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eq.length||eK.length?"var(--accent)":"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,n.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,n.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),r6=f&&nh.length>0?(0,n.jsxs)("div",{ref:tT,style:{position:"relative",flexShrink:+!!eb,minWidth:0},children:[(0,n.jsxs)("button",{className:`${eb?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eF({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eg("chat.mainPreset"),"aria-label":eg("chat.mainPreset"),children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eb?null:(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eg("chat.mainPreset")})]}),eL&&eP&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eP.top,eP.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eP.top+6}:{top:eP.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eP.left,width:"max-content",minWidth:eP.width};return(0,n.jsx)("div",{ref:tI,role:"menu","aria-label":eg("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tT.current?.querySelector("button")?.focus())},style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:(0,n.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:nh.map(e=>{let t=e.alias===r_;return(0,n.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eA(!1),f({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("img",{className:"account-avatar",src:nU(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,n.jsx)("span",{children:nL(e.alias)}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,r3=R?(0,n.jsxs)("div",{ref:tE,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,n.jsxs)("button",{type:"button",className:`${eb?"composer-icon-button":"composer-chip"}${eW?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eH({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(!1),eO(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eW,onKeyDown:e=>{"Escape"===e.key&&eW&&(e.stopPropagation(),eO(!1))},title:eg("chat.changeReasoning",{level:rQ}),"aria-label":eg("chat.changeReasoning",{level:rQ}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eb?0:"8px 12px",height:32,background:eW?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eW?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,n.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eb?null:(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:rQ})]}),eW&&eD&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eD.top,eD.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eD.top+6}:{top:eD.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eD.left,width:"max-content",minWidth:Math.max(180,eD.width)};return(0,n.jsx)("div",{role:"menu","aria-label":eg("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eO(!1),tE.current?.querySelector("button")?.focus())},style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:r},children:r8.map(({level:e,ceiling:t})=>{let r=(T??"auto")===e&&("auto"!==e||($??null)===t),a=t??e,i="auto"===e&&null===t?null:rX(a),s=t?`auto ≤ ${i??t}`:i??e,o=t?eg("chat.thinkingAutoCapped",{level:i??t}):eg(uf[e]);return(0,n.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":r,onClick:()=>{eO(!1),R(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsxs)("span",{style:{flex:1},children:[s,null!==i&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",a,")"]})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,r7=_?(ed=F?eg("chat.fastModeBusy"):null===P?eg("chat.fastModeUnknown"):P.active?eg("chat.fastModeActive"):P.enabled?eg("chat.fastModeInactive"):eg("chat.fastModeOff"),eu=F||o||b,ep=P?.enabled===!0,(0,n.jsx)("button",{type:"button",className:`composer-icon-button${P?.active?" is-active":""}`,onClick:_,disabled:eu,"aria-pressed":null===P?void 0:P.enabled,"aria-busy":F||void 0,title:ed,"aria-label":ed,style:{flexShrink:0,opacity:o?.5:1},children:(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:P?.active?"var(--accent)":"none",stroke:ep?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===P?"3 2":void 0,style:{opacity:ep&&!P?.active?.6:1},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,r9=(0,n.jsxs)(n.Fragment,{children:[r&&(0,n.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>r$("steer"),disabled:!rh,title:eX?eg("chat.attachExtractingWait"):eg("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rh?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:rh?"var(--warning)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eg("chat.steer")]}),i&&(0,n.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>r$("followup"),disabled:!rh,title:eX?eg("chat.attachExtractingWait"):eg("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:rh?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:rh?"var(--accent-hover)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,n.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,n.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eg("chat.followUp")]})]}),ne=void 0!==Z?(0,n.jsx)(de,{soundEnabled:J??!0,onToggle:Z}):null;return(0,n.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,n.jsx)("input",{ref:tA,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t9(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(u_,{error:p}),(0,n.jsx)(uz,{warnings:h}),O.length>0&&(0,n.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,n.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ex("delivery.title",{count:O.length})}),H&&ev&&(0,n.jsxs)("button",{onClick:H,title:eg("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,n.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eg("chat.recall")]})]}),(0,n.jsx)(c5,{rows:O,removeLabel:eg("chat.queueRemove"),onRemove:U?(e,t)=>U("steer"===e?"steering":"followUp",t):void 0})]}),W&&(0,n.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]}),eg("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,n.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),rY&&(0,n.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),rY]}),j&&(0,n.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eJ&&(0,n.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eJ}),(0,n.jsx)("button",{type:"button",onClick:()=>eZ(null),"aria-label":eg("i18n.close"),title:eg("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,n.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eq.length>0||eK.length>0)&&(0,n.jsxs)("div",{role:"list","aria-label":eg("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eq.map((e,t)=>(0,n.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,n.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,n.jsx)("button",{type:"button","aria-label":eg("chat.removeImage",{index:t+1}),onClick:()=>re(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,n.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eK.map(e=>(0,n.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||un(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,n.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):aT(e.name,14),(0,n.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,n.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,n.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eg("chat.attachKindAudio"):"file"===e.stored?eg("chat.attachKindFile"):uu[e.mimeType]," \xb7 ",lp(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eg("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eg("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eg("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"||e.transcription?.state==="fallback"?` \xb7 ${eg("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eg("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,n.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eg("chat.attachTranscribeFailed")}`})]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>rt(e.id),"aria-label":eg("chat.removeAttachment",{name:e.name}),title:eg("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,n.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eQ.length>0&&(0,n.jsx)("div",{role:"group","aria-label":eg("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eQ.map(e=>{let t,r,a,i,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?eg("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eg("chat.transcribeDurationUnknown"):(r=Math.floor((t=Math.round(c.durationSeconds))/3600),a=Math.floor(t%3600/60),i=String(t%60).padStart(2,"0"),r>0?`${r}:${String(a).padStart(2,"0")}:${i}`:`${a}:${i}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?eg("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="fallback"?eg("chat.transcribeFallbackTitle",{name:e.name}):l?.state==="running"?eg("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${eg("chat.transcribeChecking")}`:l?.state==="failed"?eg("chat.transcribeFailedRow",{name:e.name,error:l.error}):eg("chat.transcribeSkipped",{name:e.name});return(0,n.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,n.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,n.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[l.plan.notice&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeUsageNotice")})]}),l?.state==="fallback"&&(0,n.jsxs)(n.Fragment,{children:[l.reason&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.reason}),l.completedParts>0&&(0,n.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:eg("chat.transcribeFallbackProgress",{done:l.completedParts,total:l.parts})}),(0,n.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.notice}),(0,n.jsx)("div",{style:{color:"var(--text-dim)"},children:eg("chat.transcribeFallbackUsageNotice")})]})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{confirmed:!0}),children:eg("chat.transcribeStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),l?.state==="fallback"&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t4(o,{fallbackToken:l.token,approve:!0}),children:eg("chat.transcribeFallbackStart")}),(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(o),children:eg("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void t6(o),children:eg(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,n.jsxs)("div",{ref:tL,style:{position:"relative",minWidth:0},children:[tu&&D.length>0&&(0,n.jsxs)("div",{ref:tR,style:{position:"absolute",left:0,right:0,...ul(rk.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rk.maxHeight},children:[(0,n.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,n.jsx)("path",{d:"M3 4v5h5"}),(0,n.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rk.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let r=t===th;return(0,n.jsxs)("button",{ref:e=>{tO.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rM(e)},onMouseEnter:()=>tm(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,n.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,n.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),tr&&(0,n.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:eg("savedPrompts.saved")}),te&&e9&&(0,n.jsx)(c3,{ref:ta,value:ey,token:e9,cwd:ee,sessionTitle:et,style:ul(rC.side),maxHeight:rC.maxHeight,onReplace:rT,onClose:()=>tt(!1)}),e8&&null!==ro&&(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ul(rj.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rj.maxHeight},children:[(0,n.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,n.jsx)("span",{children:V?eg("chat.loadingCommands"):eg("chat.slashCommands",{label:ru})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rj.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==rl.length?rd.map(e=>(0,n.jsxs)("section",{style:{marginBottom:12},children:[(0,n.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,n.jsx)("span",{children:eg(uv[e.source])}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,n.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let r=t===e5,a=uk(e,tj);return(0,n.jsxs)("button",{ref:e=>{tz.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rE(e)},onMouseEnter:()=>e6(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${r?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:r?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,n.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:a?"var(--text-dim)":void 0},children:["/",e.name,a&&(0,n.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eg("chat.dormant")})]}),uw(e,eg)&&(0,n.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uw(e,eg)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,n.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eg("chat.noCommands")})})]}),to&&null!==ti&&(eh=tx&&(!tf||tf.cwd!==ee),em=1===rb.length?eg("chat.match"):eg("chat.matches",{count:rb.length}),ef=tf?.truncated&&!rv?ti.query?eg("chat.searchingAll"):eg("chat.indexTruncated"):"",(0,n.jsxs)("div",{style:{position:"absolute",left:0,right:0,...ul(rS.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:rS.maxHeight},children:[(0,n.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,n.jsx)("span",{children:eh?eg("chat.loadingFiles"):eg("chat.files",{label:em,hint:ef})}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,n.jsx)("div",{style:{maxHeight:Math.max(0,rS.maxHeight-34),overflowY:"auto",padding:4},children:eh||0!==rb.length?rb.map((e,t)=>{let r=t===tc,a=e.path.split("/").pop()??e.path,i=e.path.slice(0,e.path.length-a.length);return(0,n.jsxs)("button",{ref:e=>{tW.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),rI(e)},onMouseEnter:()=>td(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:r?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,n.jsx)(aS,{size:14}):aT(a,14)}),(0,n.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[i&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:i}),a,e.isDir&&(0,n.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,n.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:rx&&!rv?eg("chat.searching"):eg("chat.noMatchingFiles")})})]})),(0,n.jsxs)("div",{className:`chat-composer-field${e1?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${e1?"var(--tool-bg)":o&&(r||i)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,n.jsx)("textarea",{className:"chat-composer-textarea",ref:tS,"aria-controls":te?"saved-prompt-menu":void 0,value:ey,onChange:e=>{tB.current=e.target.value,ew(e.target.value),tp(!1),rm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;rm(t.value,t.selectionStart)},onKeyDown:rL,onCompositionStart:()=>{tP.current=!0},onCompositionEnd:e=>{tP.current=!1,tF.current=Date.now();let t=e.currentTarget;rm(t.value,t.selectionStart)},onInput:rA,onPaste:rP,placeholder:o&&(r||i)?eg("chat.steerPlaceholder"):o?eg("chat.agentPlaceholder"):eg("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),o?eb?null:(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:r9}):(0,n.jsxs)("button",{className:"chat-composer-send",onClick:rs,disabled:!rh,"aria-busy":eX||void 0,"aria-label":eb?eg("chat.send"):void 0,title:eX?eg("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eb?44:void 0,padding:eb?0:"7px 14px",background:rh?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:rh?"var(--accent-hover)":"var(--text-dim)",cursor:rh?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,n.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eb?null:eg("chat.send")]})]})]}),e1&&(0,n.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e2?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eg("chat.shell")," \xb7 ",e2?eg("chat.outputLocal"):eg("chat.outputModel")]}),(0,n.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,n.jsxs)("div",{style:{flex:eb?"1 1 0%":"0 0 auto",minWidth:eb?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eb||!o)&&r5,!eb&&r6,!(eb&&o)&&(rF.length>0||rJ||p)&&m&&(0,n.jsxs)("div",{ref:tC,style:{position:"relative",flex:eb?"1 1 0%":void 0,width:eb?0:void 0,minWidth:44*!!eb},children:[(0,n.jsxs)("button",{className:`composer-chip${ek?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eC({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(e=>(e&&eT(""),!e))},disabled:o||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eb?"flex-start":void 0,padding:eb?"8px 10px":"8px 12px",height:32,width:eb?"100%":void 0,maxWidth:eb?"100%":220,overflow:"hidden",background:ek?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||b?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ek?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":rF.length>0?"Change model":"No available models",children:[b?(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,n.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:rJ??(rF.length>0?"Select model":"No models")})]}),ek&&eS&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:r}=d3(eS.top,eS.bottom,e,d7(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eS.top+6}:{top:eS.bottom+6},i=eb?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eS.left,width:"max-content",minWidth:eS.width};return(0,n.jsxs)("div",{ref:tN,style:{position:"fixed",...a,...i,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:r,display:"flex",flexDirection:"column"},children:[rH&&(0,n.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,n.jsx)("input",{value:eN,onChange:e=>eT(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eT(""),ej(!1))},placeholder:eg("chat.filterModels"),"aria-label":eg("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eb,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,n.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[rK.length>0&&(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eg("chat.frequentModels")}),rK.map(({option:e,count:t})=>rG(e,"frequent",t))]}),rq.length>0&&!eN.trim()&&v&&(0,n.jsxs)("div",{style:{borderTop:rK.length>0?"1px solid var(--border)":"none"},children:[(0,n.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eE,"aria-controls":"model-role-rows",onClick:eR,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,n.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eE?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,n.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,n.jsx)("span",{style:{textTransform:"uppercase"},children:eg("chat.modelRoles")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:rq.length}),rV&&(0,n.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:rV.tag??rV.role.toUpperCase()}),rV.name]})]}),(0,n.jsx)("div",{id:"model-role-rows",hidden:!eE,children:rq.map(e=>{let t=rV?.role===e.role,r=e.resolved?.name??e.resolved?.modelId??"";return(0,n.jsxs)("button",{onClick:()=>{ej(!1),eT(""),v(e.role)},title:e.selector??r,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,n.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,n.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[r,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eg("chat.allModels")})]}),0===rB.length?(0,n.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eN.trim()?eg("chat.noMatchingModels"):"No available models"}):rB.map((e,t)=>(0,n.jsxs)("div",{children:[rB.length>1&&(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>rG(e,"all"))]},e.provider))]})]})})()]}),eb&&o&&(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:r9}),!eb&&r3,!eb&&r7,!eb&&r1&&(0,n.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:r1}),!eb&&null!==M&&(0,n.jsx)("span",{title:eg(E?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:eg(E?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,n.jsx)(dp,{sessionId:er})]}),(0,n.jsxs)("div",{ref:t$,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eb?4:2},children:[eb?(0,n.jsx)("button",{type:"button",className:`composer-icon-button${eU?" is-active":""}`,title:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,n.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,n.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,n.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,n.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,n.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eU?void 0:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:eg("chat.moreControls")}),(0,n.jsxs)("div",{role:"group","aria-label":eg("chat.moreControls"),style:{display:eU?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:eb?"flex-start":"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eb&&(0,n.jsxs)(n.Fragment,{children:[o&&r5,r6,r3,r7]}),!o&&N&&(0,n.jsxs)("div",{ref:tM,style:{position:"relative"},children:[(0,n.jsxs)("button",{className:`composer-chip${e_?" is-active":""}`,onClick:()=>!o&&ez(e=>!e),disabled:o,title:eg("chat.changeToolPreset")+`: ${r4}`,"aria-label":eg("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:e_?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=e_?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:r4})]}),e_&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:ua.map(e=>{let t=ui[e],r=(C??"default")===t,a="off"===e?eg("chat.noTools"):"default"===e?eg("chat.builtInTools",{tools:us}):eg("chat.allBuiltInTools",{tools:`${us} + ${uo}`});return(0,n.jsxs)("button",{onClick:()=>{ez(!1),r||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1},children:e}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:a})]},e)})})]}),!o&&y&&(0,n.jsx)("div",{children:(0,n.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eg("chat.stopCompaction"):eg("chat.compactContext"),"aria-label":k?eg("chat.stopCompaction"):eg("chat.compactContext"),children:k?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compacting")})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,n.jsx)("span",{style:{whiteSpace:"nowrap"},children:eg("chat.compact")})]})})}),eb&&ne,eU&&(0,n.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eg("chat.collapseControls"),"aria-label":eg("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ez(!1),eO(!1),eB(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,n.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,n.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eg("chat.stopAgent"),"aria-label":eb?eg("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eb?44:void 0,padding:eb?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eb?null:eg("chat.stop")]}),(0,n.jsx)(dd,{sessionId:er,onEnsureSession:en,onTranscriptPersisted:ea}),!eb&&ne]})]})]})]})});function uO({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),r=e$(t);return(0,n.jsx)("div",{role:"status","aria-label":r,title:r,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,n.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eF(t).map((e,t)=>(0,n.jsx)("span",{style:e.style,children:e.text},t))})})}function uD({phases:e,flow:t,busy:r}){let{t:i}=(0,z.s)(),{st:s}=ag(),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(!1),h=(0,a.useId)(),m=e??[],{currentPhase:f,activeTask:g,remaining:x,completed:v,total:b,percent:y}=tL(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,r){if(!t||!e.current)return null;let n=r("flow.strip.running",{stage:r(`flow.stage.${e.current}`)});return e.attempt>1?`${n} \xb7 ${r("flow.attempt",{attempt:e.attempt})}`:n}(t,r,s);if(0===b&&null===j)return null;let S=b>0&&0===x;return(0,n.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,n.jsxs)("div",{className:"todo-strip-row",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,n.jsx)("span",{className:"todo-strip-lead",role:r?"status":void 0,children:j}),b>0&&(0,n.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!j&&f&&(0,n.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,n.jsx)("span",{className:"todo-strip-task",children:S?i("todo.allDone",{count:v}):g?.content??""}),(0,n.jsx)("span",{className:"todo-strip-count",children:S?i("todo.progressDone",{percent:y??0,completed:v,total:b}):i("todo.progress",{percent:y??0,completed:v,total:b,remaining:x})})]}),k&&(0,n.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,n.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,n.jsx)(oy,{flow:t,live:r,st:s,id:h}),o&&b>0&&(0,n.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let r=e.tasks.filter(e=>u||"completed"!==e.status);return 0===r.length?null:(0,n.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,n.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),r.map((e,t)=>(0,n.jsx)(aw,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,n.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:i(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function uH(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uU(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function uB(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let r={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let n=await t.getServiceWorkerRegistration();if(n)return await n.showNotification(e.title,{...r,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let n=t.createWindowNotification(e.title,r);return n.onclick=()=>{n.close(),e.onClick()},"window"}catch{return null}}class uq extends Error{constructor(e,t,r,n){super(e),this.status=t,this.code=r,this.accepted=n,this.name="AgentCommandError"}}async function uV(e,t){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok||n.error)throw new uq(n.error??`HTTP ${r.status}`,r.status,n.code,n.accepted);return n.data}let uK="ompweb-update-client-id",uG="ompweb-update-resume-intent-v2",uJ="ompweb-update-return-v1",uZ="cuelo-restart-return-v1",uY="ompweb-update-failure-return-v1",uX="ompweb:update-wake";function uQ(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function u0(){let e=sessionStorage.getItem(uK);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(uK,t),t}function u1(){sessionStorage.removeItem(uG)}function u2(){let e=sessionStorage.getItem(uJ);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function u8(e){let t=u2();if(!t||t.requestId!==e)return t;let r={...t,dismissed:!0};try{sessionStorage.setItem(uJ,JSON.stringify(r))}catch{}return r}async function u4(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:u0(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function u5(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let r=await t.json().catch(()=>null);!function(e){let t=u2();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let r={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(uJ,JSON.stringify(r))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u1();let n=r?.wake;e.sessionId&&(n?.wake===!0||n?.reason==="already-claimed"||n?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(uX,{detail:{sessionId:e.sessionId}}))}async function u6(e){let t=function(e){let t=sessionStorage.getItem(uY);if(!t)return null;sessionStorage.removeItem(uY);try{let r=JSON.parse(t);if(1!==r.schemaVersion||r.requestId!==e.requestId||r.stageHash!==e.stageHash||r.clientId!==e.clientId)return null;return{wake:!0===r.wake}}catch{return null}}(e);return t?(u1(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(uX,{detail:{sessionId:e.sessionId}})),"failed"):(await u5(e),"resumed")}function u3(e,t){let r=new Map(e.map(e=>[e.id,e]));for(let e of t)r.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(r.get(e.id),e));let n=[...r.values()];return[...n.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...n.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function u7(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function u9(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function pe(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function pt(e){return t=>{let r=e?.isCompacting?e.compaction:null;if(!r)return t;let n=Date.now()-r.elapsedMs;return{startedAt:t?Math.min(t.startedAt,n):n,reason:t?.reason??r.reason}}}function pr(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],a=t[r];if(!n||!a||n.name!==a.name||n.tasks.length!==a.tasks.length)return!1;for(let e=0;e<n.tasks.length;e+=1){let t=n.tasks[e],r=a.tasks[e];if(!t||!r||t.content!==r.content||t.status!==r.status||t.blocker!==r.blocker||(t.dependsOn?.length??0)!==(r.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==r.dependsOn?.[t]))return!1}}return!0}function pn(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function pa(e,t){for(let r=e.length-1;r>=0;r--){let n=t[r]??null;if(!tn(n??void 0))return{message:e[r],entryId:n}}return null}let pi=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class ps extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function po(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pl(e){return new Promise(t=>setTimeout(t,e))}function pc(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,r)=>r===t?{...e,exiting:!0}:e)}function pd(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:pc(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:pc(e.visible)};case"remove":return function(e,t){let r=e,n=t;for(;n.length>0&&r.length<5;){let[e,...t]=n;r=[...r,e],n=t}return n.length>0&&!r.some(e=>e.exiting)&&(r=pc(r)),{visible:r,pending:n}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function pu(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function pp(e){let t,r=e.content;return"string"==typeof r?JSON.stringify({text:r,images:[]}):Array.isArray(r)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:r.map(pu).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function ph(e){return"user"===e.role?`user:${pp(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function pm(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function pf(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function pg(e){rN(e),e.clear()}function px(e,t,r){for(let n of r??[]){let r=rC(t,n);r&&e.add(r)}}function pv(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let pb=!1,py={width:0,height:0},pw=new Set,pk=null;function pj(){let e=window.visualViewport,t=pv();py.width!==window.innerWidth?py={width:window.innerWidth,height:window.innerHeight}:t||(py.height=Math.max(py.height,window.innerHeight));let r=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:r,viewportScale:n,baselineHeight:a}){return!(!e||Math.abs(n-1)>=.01)&&(t-r>120||a-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:py.height});if(r!==pb)for(let e of(pb=r,pw))e()}function pS(e){if(pw.add(e),!pk){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,pj()})},r=window.visualViewport;r?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),pj(),pk=()=>{r?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{pw.delete(e),0===pw.size&&pk&&(pk(),pk=null)}}function pC(){return(0,a.useSyncExternalStore)(pS,()=>pb,()=>!1)}let pN={count:50,end:null};function pT(e,t){let r=Math.max(e,0),n=null===t.end?r:Math.min(Math.max(t.end,0),r),a=Math.min(Math.max(t.count,0),n),i=n-a;return{startIndex:i,endIndex:n,hasMore:i>0,hasLater:n<r}}function pI(e,t,r){let{startIndex:n,endIndex:a}=pT(e,r);if(t>=n&&t<a)return r;let i=Math.max(0,t-10),s=Math.max(t+1,i+50);return s>=e?{count:e-i,end:null}:{count:s-i,end:s}}function pM({sticker:e,text:t,tag:r,followRef:i}){let s=(0,a.useRef)(null);return((0,a.useEffect)(()=>{(!i||i.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,n.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,n.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:r8[r]}),t&&(0,n.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,n.jsx)(cm(),{id:"71a4a7cebbc6c842",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function pE(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),r=(lu(t)?.message??t).trim();return r.length>0?r:null}function p$(e){return`omp-cues:${e}`}function pR(e,t){let r=[];for(let n of t)n.sessionId===e&&null!==n.anchorEntryId&&r.push({id:n.id,anchorEntryId:n.anchorEntryId,sticker:n.sticker,text:n.text,tag:n.tag});try{window.localStorage.setItem(p$(e),JSON.stringify(r.slice(-200)))}catch{}}let pL=[];function pA(e){return`omp-web:interrupted-dismissed:${e}`}let pP=(0,a.memo)(function({messages:e,entryIds:t,toolResultsMap:r,modelNames:i,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,main:g,process:x,dispatchSlots:v,compactedDispatch:b,openRequest:y,startIndex:w,endIndex:k,sentinelRef:j,laterSentinelRef:S,flashItem:C,t:N,onProcessLogChange:T,cues:I,cueFollowRef:M}){(0,a.useEffect)(()=>{T({groups:x,messages:e,entryIds:t,toolResults:r,modelNames:i,cwd:s,sessionId:f})},[T,x,e,t,r,i,s,f]);let E=(0,a.useMemo)(()=>(function(e){let t=new Map;for(let r=0;r<e.length;r++){let n=tt(e,r);n>=0&&t.set(n,function(e){let t="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");if(!t.startsWith("[interpreter] "))return t;let r=t.indexOf("\n\n");return r<0?t:t.slice(r+2)}(e[r]))}return t})(e),[e]),$=(0,a.useMemo)(()=>{let t=new Map;for(let[n,a]of function(e,t,r,n){let a=new Map;e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.idx,t)});let i=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=r[o.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(o.blocks?a.get(o.idx):void 0)??o.afterMainIndex??-1),l=t;!function(e,t,r){for(let n of e){if("toolCall"!==n.type||"learn"!==n.toolName&&"manage_skill"!==n.toolName)continue;let e=t?.get(n.toolCallId);if(!e||e.isError)continue;let a=n.input??{};if("manage_skill"===n.toolName){let e=to(a.action);if(!0===ts[e]){let t={kind:"skill",action:e,name:to(a.name)};r(JSON.stringify(t),t)}continue}let i=to(a.memory),s=a.skill,o=s?{action:to(s.action),name:to(s.name)}:void 0;r(JSON.stringify({kind:"lesson",memory:i,skill:o}),{kind:"lesson",memory:i.length>160?`${i.slice(0,160)}…`:i,...o?{skill:o}:{}})}}(o.blocks??e.content??[],n,(e,t)=>{if(l.has(e))return;l.add(e);let r=i.get(s);r?r.push(t):i.set(s,[t])})}}return i}(g,x,e,r)){let e=a.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(n,{role:"custom",customType:e9,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,r,N]),R=(0,a.useMemo)(()=>{let n=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(n=t.idx);return function(e,t,r,n,a,i,s=[]){let o=function(e,t,r){let n=new Map,a=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&sD(t,e.idx)===e.idx).map(e=>e.idx),i=null===r?null:sD(t,r),s=new Map;for(let[r,o]of(e.forEach((e,r)=>{"answer"===e.kind&&s.set(sD(t,e.anchorIdx),r)}),s)){if(r===i)continue;let e=a.find(e=>e>r);n.set(o,{from:r+1,to:e??t.length})}return n}(e,t,r),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,r]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(sU(t,n,r.from,u,d),u=Math.max(u,r.from),0===r.from&&i){let a=r.to-1;for(;a>=r.from&&tn(s[a]);)a-=1;if(s[a]!==i.throughEntryId)continue;let o=sW(t,r.from,r.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sH(t,n,r.from,r.to);c.set(e,{...i.summary,...p?{remaining:s_(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...i.ciHeads),u=r.to;continue}c.set(e,{...function(e,t,r,n,a,i=[]){let s=sW(e,r,n),o=sH(e,t,r,n);return{...sz(s,t,a),remaining:o?s_(o):null,span:sB(e,r,n),flow:sP(s,t,!1,i,a,sO(e,r,n))}}(t,n,r.from,r.to,a,d),latest:e===l})}return c}(g,e,n,r,s,y,t)},[g,e,r,s,l,y,t]),L=w>0,A=k<g.length,P=(a,g={})=>{let x=g.messageOverride??e[a],v=a-1;for(;v>=0&&tn(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=a+1;t<e.length;t++){let r=e[t].role;if("user"===r)break;if("assistant"===r){w=!1;break}}w&&d&&a===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,n.jsx)(lL,{message:x,toolResults:r,modelNames:i,cwd:s,onOpenFile:o,entryId:t[a],onFork:l||c||0===a&&"user"===x.role?void 0:u,forking:p===t[a],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:a>0?e[a-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary,inputTranslation:"user"===x.role?E.get(a):void 0,recoveredError:eK(e,a)},`${y}-view-${a}`)},F=(t,r)=>{let a=g[t],i="message"===a.kind&&e[a.idx]?.role==="user";return(0,n.jsx)("div",{"data-chat-item":t,"data-chat-question":i?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:r})};return(0,n.jsxs)(n.Fragment,{children:[L&&(0,n.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((i,l)=>{let c=w+l,d=b?.position===c?(0,n.jsx)(o_,{calls:b.calls}):null,u="message"===i.kind?i.anchorIdx??i.idx:i.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(r=>{let n=null!==r.anchorEntryId?t.indexOf(r.anchorEntryId):Math.min(r.liveIndex??-1,e.length-1);return n>=i.idx&&n<m}).map(e=>(0,n.jsx)(pM,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),y=h!==u,k=$.get(c),j=k?(0,n.jsx)(lL,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=y?(0,n.jsx)(cw,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:o}):null;if("message"===i.kind)return(0,n.jsxs)(a.Fragment,{children:[d,F(c,P(i.idx)),j,S,x]},`message-${i.idx}`);let C=tN(i.precedingBlocks,r,s);return(0,n.jsxs)(a.Fragment,{children:[d,F(c,P(i.idx,{keyPrefix:`answer-${i.runIndex}`,messageOverride:function(e,t){let r=eB(e,t);if(!e.replyTranslation)return r;let n=e.content.find(e=>"text"===e.type);return n&&t.includes(n)||(r.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(r.content=t.filter(e=>"text"!==e.type))),r}(e[i.idx],i.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:R.get(c)})),j,S,x]},`answer-${i.idx}-${i.runIndex}`)}),b?.position===g.length&&k===g.length&&(0,n.jsx)(o_,{calls:b.calls}),A&&(0,n.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function pF({session:e,newSessionCwd:t,initialSessionData:i,transitioning:s=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onLabWidgetsChange:y,onOpenWorkspaceView:w,onOpenSessionList:k,onOpenMaker:j,selectedMaker:S,onProcessLogChange:C,onOpenFile:N,transcriptReplacement:T,onComposerFocusChange:I,onSessionBusyChange:M,onWaitingChange:E,onAttentionChange:$,soundEnabled:R=!0,onSoundToggle:L,playCueSound:A=async()=>({sticker:null,text:null}),preloadCueSound:P,unlockAudio:F,jumpRequest:_=null,onJumpHandled:W}){var O,D;let H,U,V,{t:K}=(0,z.s)(),G=pC(),J=B(),Z=(0,a.useRef)(A);Z.current=A;let Y=(0,a.useRef)(null),X=(0,a.useRef)(P);X.current=P;let[Q,et]=(0,a.useState)([]),er=(0,a.useRef)(Q);er.current=Q;let en=(0,a.useRef)(0),ea=(0,a.useRef)([]),ei=(0,a.useRef)([]),es=(0,a.useRef)(null),eo=(0,a.useRef)(0),el=(0,a.useRef)(-1),ec=(0,a.useRef)(-1),ed=(0,a.useCallback)(()=>{let e=es.current?.current;return e?{sessionId:e,turn:eo.current}:null},[]),eu=(0,a.useCallback)(e=>es.current?.current===e.sessionId&&eo.current===e.turn,[]),ep=(0,a.useCallback)((e,t,r,n)=>{if(!e.sticker&&!e.text)return;en.current=Math.max(en.current+1,Date.now());let a={id:en.current,sticker:e.sticker,text:e.text,tag:t,sessionId:r.sessionId},i="entry"===n.kind?{...a,anchorEntryId:n.entryId}:{...a,anchorEntryId:null,liveIndex:n.liveIndex,intent:n.intent};et(e=>{let t=[...e,i];return null!==i.anchorEntryId&&pR(r.sessionId,t),t})},[]),eh=(0,a.useCallback)((e,t,r,n)=>{let a=()=>eu(r)&&("working"!==t||ec.current!==r.turn);a()&&Z.current(e,t,a).then(e=>{null!==t&&null!==n&&a()&&ep(e,t,r,n)}).catch(()=>{})},[eu,ep]),em=(0,a.useCallback)(async(e,t,r,n)=>{let a=(await ap(e,t,r,n))?.alias??null;return a&&X.current?.(a),a},[]),ef=(0,a.useCallback)((e,t,r,n,a)=>{let i=function(e,t){let r=e.length-1;if(r<0)return null;let n=Math.min(e.length,t.length);if(r<n)return{kind:"entry",entryId:t[r]};let a=ni(e[r]),i=0;for(let t=n;t<=r;t++)ni(e[t])===a&&(i+=1);return{kind:"pending",liveIndex:r,intent:{baseEntryId:n>0?t[n-1]:null,identity:a,occurrence:i}}}(ea.current,ei.current);em(t.sessionId,r,n,a).then(r=>{eh(r,e,t,i)})},[eh,em]),[eg,ex]=(0,a.useState)(0),ev=(0,a.useRef)([]),eb=(0,a.useCallback)(e=>{if(eo.current+=1,null!==r3(e.outcome)){let t=e.sessionId;ev.current.push({completion:e,trigger:t?{sessionId:t,turn:eo.current}:null}),ex(e=>e+1)}o?.(e)},[o]);(0,a.useEffect)(()=>{for(let{completion:e,trigger:t}of ev.current.splice(0)){let r=r3(e.outcome),n="neutral"===r?null:r;t?ef(n,t,e.provider,e.credentialId,e.model):Z.current(null,n).catch(()=>{})}},[eg,ef]);let ey=(0,a.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ew,error:ek,messages:ej,entryIds:eS,streamState:eC,agentRunning:eN,bashRunning:eT,pendingBash:eI,modelNames:eM,modelList:eE,modelError:eR,modelScopeWarnings:eL,modelThinkingLevels:eA,modelThinkingLevelMaps:eP,modelRoles:eF,toolPreset:e_,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eO,fastMode:eD,fastModeBusy:eH,handleFastModeToggle:eU,retryInfo:eq,contextUsage:eZ,forkingEntryId:eY,isCompacting:e0,compaction:e1,compactError:e8,compactResult:e4,displayModel:e9,modelSwitching:ts,sessionStats:to,runStateKnown:tc,compactedWork:td,slashCommands:tu,slashCommandsLoading:tp,deliveryRows:th,subagents:tm,todoPhases:tf,notices:tg,extensionDialog:tx,extensionResponse:tv,extensionCustomUi:tb,extensionStatuses:ty,extensionWidgets:tw,respondToExtensionUi:tk,sendExtensionCustomInput:tj,isAutoModelSelection:tS,agentPhase:tC,isNew:tN,autoFollowPaused:tT,resumeAutoFollow:tI,pauseAutoFollow:tM,goalStatus:tE,sessionIdRef:tR,messagesEndRef:tL,scrollContainerRef:tA,handleSend:tP,handleAbort:t_,handleFork:tz,handleNavigate:tW,handleModelChange:tO,handleRoleModelChange:tD,handleMainPresetChange:tH,newSessionAccount:tU,handleCompact:tB,handleSteer:tq,handleFollowUp:tV,handlePromptWithStreamingBehavior:tK,handleAbortCompaction:tG,handleRecallQueue:tJ,handleRemoveQueuedMessage:tZ,handleBuiltinSlashCommand:tY,handleToolPresetChange:tX,handleThinkingLevelChange:tQ,loadSlashCommands:t0,ensureNewSession:t1,refreshLiveTranscript:t2}=function(e){let{session:t,newSessionCwd:n,initialData:i,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==n,f=i&&i.sessionId===t?.id?i:null,[g,x]=(0,a.useState)(f),[v,b]=(0,a.useState)(!m&&!f),[y,w]=(0,a.useState)(null),[k,j]=(0,a.useState)(f?.leafId??null),[S,C]=(0,a.useState)(f?.context.messages??[]),[N,T]=(0,a.useState)(f?.context.entryIds??[]),[I,M]=(0,a.useState)(f?.context.compactedWork??null),[E,$]=(0,a.useReducer)(u7,{isStreaming:!1,streamingMessage:null}),[R,L]=(0,a.useState)(!1),[A,P]=(0,a.useState)(!1),[F,_]=(0,a.useState)(null),[z,W]=(0,a.useState)({}),[O,D]=(0,a.useState)([]),[H,U]=(0,a.useState)(null),[B,q]=(0,a.useState)([]),[V,K]=(0,a.useState)({}),[G,J]=(0,a.useState)({}),[Z,Y]=(0,a.useState)([]),[X,Q]=(0,a.useState)(null),[ee,et]=(0,a.useState)(null),[er,en]=(0,a.useState)(null),[ea,ei]=(0,a.useState)("default"),[es,eo]=(0,a.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[el,ec]=(0,a.useState)(),[ed,eu]=(0,a.useState)(null),[ep,eh]=(0,a.useState)(null),[em,ef]=(0,a.useState)(!1),eg=(0,a.useRef)(0),ex=(0,a.useRef)(0),ev=(0,a.useRef)(""),[eb,ey]=(0,a.useState)(null),[ew,ek]=(0,a.useState)(f?.contextUsage??null),[ej,eS]=(0,a.useState)(null),[eC,eN]=(0,a.useState)(null),[eT,eI]=(0,a.useState)(null),[eM,eE]=(0,a.useState)(null),[eR,eL]=(0,a.useState)(!1),[eA,eP]=(0,a.useState)(!1),[eF,e_]=(0,a.useState)(null),[ez,eW]=(0,a.useState)(null),[eO,eD]=(0,a.useState)(null),eH=(0,a.useRef)(null),[eU,eB]=(0,a.useState)(!1),[eq,eV]=(0,a.useState)(null),[eK,eG]=(0,a.useState)([]),[eJ,eZ]=(0,a.useState)(!1),[eY,eX]=(0,a.useReducer)(pd,{visible:[],pending:[]}),[eQ,e0]=(0,a.useState)(null),[e1,e2]=(0,a.useState)(null),[e8,e4]=(0,a.useState)(null),e5=(0,a.useRef)(null),[e6,e3]=(0,a.useState)(null),[e9,te]=(0,a.useState)([]),[tt,ti]=(0,a.useState)([]),[ts,to]=(0,a.useState)({steering:[],followUp:[]}),[tl,tc]=(0,a.useState)([]),[td,tu]=(0,a.useReducer)(ia,[]),tp=(0,a.useRef)(0);(0,a.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,a.useEffect)(()=>{R||tu({type:"idle"})},[R]),(0,a.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,a.useMemo)(()=>(function(e,t){let r=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${it(t)}`;r.set(e,(r.get(e)??0)+1)}let n=[],a=(e,t)=>{t.forEach((t,a)=>{let i=`${e}\u0000${ie(t)}`,s=r.get(i)??0;s>0?r.set(i,s-1):n.push({key:`queue-${e}-${a}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let r of(a("steer",t?.steering??[]),a("followUp",t?.followUp??[]),e))n.push({key:`sent-${r.id}`,kind:r.kind,text:r.text,images:r.images,stage:r.stage,removable:r.inQueue});return n})(td,ts),[td,ts]),[tm,tf]=(0,a.useState)(null),tg=(0,a.useRef)(null),tx=(0,a.useRef)(null),tv=(0,a.useRef)(null),tb=(0,a.useRef)(null),ty=(0,a.useRef)(null),tw=(0,a.useRef)(0),tk=(0,a.useRef)(!1),tj=(0,a.useRef)(t?.id??null),tS=(0,a.useRef)(f?.leafId??null),tC=(0,a.useRef)(S),tN=(0,a.useRef)(N);tC.current=S,tN.current=N;let tT=(0,a.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tI=(0,a.useRef)(!1),tM=(0,a.useRef)(new Set);(0,a.useEffect)(()=>()=>pg(tM.current),[]);let tE=(0,a.useRef)(!1),t$=(0,a.useRef)(!1),tR=(0,a.useRef)(-1),tL=(0,a.useRef)("unknown"),tA=(0,a.useRef)(null),tP=(0,a.useRef)(null),tF=(0,a.useRef)(0),t_=(0,a.useRef)(!1),tz=(0,a.useRef)(0),tW=(0,a.useRef)(null),tO=(0,a.useRef)(null),tD=(0,a.useRef)(null),tH=(0,a.useRef)(!1),tU=(0,a.useRef)(!0),[tB,tq]=(0,a.useState)(!1),[tV,tK]=(0,a.useState)(null),tG=(0,a.useRef)(void 0),tJ=(0,a.useRef)(0),tZ=(0,a.useRef)(null),tY=(0,a.useRef)(0),tX=(0,a.useRef)(()=>{}),tQ=(0,a.useRef)(null),t0=(0,a.useRef)(null),t1=(0,a.useRef)(null),t2=(0,a.useRef)(null),t8=(0,a.useRef)(!1),t4=(0,a.useRef)(null),t5=(0,a.useRef)(null),t6=(0,a.useRef)(null),t3=(0,a.useRef)(null),t7=(0,a.useRef)(0),t9=(0,a.useRef)(null),re=(0,a.useRef)(null),rt=(0,a.useRef)(!1);rt.current=e.transitioning??!1;let rr=(0,a.useRef)(Date.now()),rn=(0,a.useRef)(0),ra=(0,a.useRef)(0),ri=(0,a.useRef)(null),rs=(0,a.useRef)(!1),ro=(0,a.useRef)(Promise.resolve()),rl=e.setToolPreset??ei,rc=eT??g?.context.model??eM??null,rd=m?X??er:rc,ru=(0,a.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},r=0,n=0,a=0,i=0,s=0;for(let t of S){if("user"===t.role&&(n+=1),"toolResult"===t.role&&(i+=1),"assistant"!==t.role)continue;a+=1;let o=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,r+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:n,assistantMessages:a,toolCalls:s,toolResults:i,totalMessages:S.length,tokens:e,cost:r,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),rp=(0,a.useRef)(0),rh=(0,a.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(rp.current+=1,tf(r=>r?.sid===e&&pr(r.phases,t)?r:{sid:e,phases:t}))},[]),rm=(0,a.useCallback)((e,t,r)=>{tj.current===e&&rp.current===r&&Array.isArray(t)&&tf(r=>r?.sid===e&&pr(r.phases,t)?r:{sid:e,phases:t})},[]),rf=(0,a.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),rg=(0,a.useCallback)(e=>{tN.current=e,T(e)},[]),rx=(0,a.useCallback)(async(e,t=!1,r=!1,n)=>{let a=!1;try{t&&b(!0);let i=n??null;if(!i){let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),n=await fetch(`/api/sessions/${encodeURIComponent(e)}?${r}`);if(404===n.status)return t&&(x(null),j(null),rf([]),M(null),w(null)),null;if(!n.ok)throw Error(`HTTP ${n.status}`);i=await n.json()}if(tj.current!==e)return null;x(i),j(i.leafId),tS.current=i.leafId??null;let s=ta(i.context.messages,i.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);rf(s.messages),rg(s.entryIds),M(i.context.compactedWork??null),ek(i.contextUsage??null),eI(e=>rs.current?e:null),w(null);let o=!r&&t3.current===e;if(o||(eo(i.context.configuredThinkingLevel??i.context.thinkingLevel??"off"),ec(i.context.thinkingLevel)),eu(i.context.thinkingCeiling??null),a=!0,t&&b(!1),!r){if(o)try{let t=t7.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(r.ok&&tj.current===e){let n=await r.json();tj.current===e&&t7.current===t&&(n.state?.thinkingLevel!==void 0?(eo(n.state.configuredThinkingLevel??n.state.thinkingLevel),ec(n.state.thinkingLevel)):n.running||(t3.current=null,eo(i.context.configuredThinkingLevel??i.context.thinkingLevel??"off"),ec(i.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=rp.current,r=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();if(tj.current!==e)return null;let a=n.state;return a?(void 0!==a.contextUsage&&ek(a.contextUsage??null),void 0!==a.systemPrompt&&eS(a.systemPrompt??null),void 0!==a.thinkingLevel&&(t3.current=e,eo(a.configuredThinkingLevel??a.thinkingLevel),ec(a.thinkingLevel)),void 0!==a.thinkingCeiling&&eu(a.thinkingCeiling??null),void 0!==a.extensionStatuses&&te(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ti(a.extensionWidgets??[]),void 0!==a.queuedMessages&&to(u9(a.queuedMessages)),void 0!==a.subagents&&tc(e=>u3(e,a.subagents??[])),rm(e,a.todoPhases,t)):n.running||to({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!a&&b(!1)}},[rm,rg,rf]),rv=(0,a.useCallback)(e=>{let t=ro.current.then(async()=>{tj.current===e&&await rx(e)});return ro.current=t.catch(()=>{}),t},[rx]),rb=(0,a.useCallback)(async(e,t)=>{let r=++ex.current;try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&n.set("leafId",t);let a=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,i=await fetch(a);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(ex.current!==r||tj.current!==e)return;tS.current=t;let o=ta(s.context.messages,s.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);rf(o.messages),rg(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[rg,rf]),ry=(0,a.useCallback)(async e=>{try{let t=await uV(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(r.bind(r,14755));rl(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[rl]),rk=(0,a.useCallback)((e=0,t="(no messages)")=>{let r=tj.current;m&&n&&r&&!t8.current&&(t8.current=!0,l?.({id:r,path:"",cwd:n,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,n,l]),rS=(0,a.useCallback)(async()=>{if(t1.current)return t1.current;let e=tj.current;if(e&&re.current!==e||!e&&(!m||!n))return e;let t=(async()=>{let t=e;if(!t){let e=t4.current,r=t6.current,a=t5.current;e&&eE(e);let i={cwd:n,type:"ensure_session",toolNames:(0,ue.xG)(ea),...e?{provider:e.provider,modelId:e.modelId}:{},...r?{thinkingLevel:r}:{},...e&&null!==a?{oauthPosition:a}:{}},s=JSON.stringify(i),o=t2.current,l=o?.body===s?o.createRequestId:po();t2.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,createRequestId:l})});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();t2.current=null,t=d.sessionId,tj.current=t,null!==t9.current&&(re.current=t),d.model&&t4.current===e&&(eE(d.model),e||en(d.model)),d.thinkingLevel&&t6.current===r&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;re.current===t;){let e=t9.current;await uV(t,{type:"set_thinking_ceiling",ceiling:e}),t9.current===e&&re.current===t&&(re.current=null)}return t})();t1.current=t;try{return await t}finally{t1.current=null}},[m,n,ea]),rT=(0,a.useCallback)(async()=>{let e=tj.current??await rS();if(!e)return eG([]),[];eZ(!0);try{let t=await uV(e,{type:"get_commands"}),r=t?.commands??[];return eG(r),r}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[rS]),rI=(0,a.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),rM=(0,a.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),rE=(0,a.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),r$=(0,a.useCallback)(e=>{rE();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let r=JSON.parse(t.data);"session_snapshot"===r.type?tW.current?.(r):"agent_start"===r.type&&tO.current?.(e)}catch{}}},[rE]),rR=(0,a.useCallback)(e=>{rM();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let r=new Promise(r=>{let n=!1,a=e=>{n||(n=!0,clearTimeout(i),tv.current?.source===t&&(tv.current.pending=!1),r({status:e,source:t}))},i=setTimeout(()=>a("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&a("connected"),tW.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(a("closed"),tg.current===t&&(tI.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tI.current||tk.current)&&rR(e)},1e3)}}});return tv.current={source:t,promise:r,pending:!0},r},[rM]),rL=(0,a.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let r=await rR(e);if("connected"!==r.status&&r.source.readyState!==EventSource.OPEN)throw tg.current===r.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===r.source&&(tv.current=null),r.source.close(),new ps(r.status)},[rR]),rA=(0,a.useCallback)(async(e,t)=>{let r=e5.current;if(r?.id===e.id&&"sending"===r.status)return;let n=tj.current,a=e=>{e5.current=e,e4(e)};if(!n)return void a({id:e.id,status:"failed",error:"no session"});a({id:e.id,status:"sending"});try{await uV(n,{type:"extension_ui_response",id:e.id,...t})}catch(t){a({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}a(null),e2(t=>t?.id===e.id?null:t)},[]),rP=(0,a.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{await uV(r,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),rF=(0,a.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??po(),message:t,type:e.type??"info"}})},[]),r_=(0,a.useCallback)(e=>{let t={role:"custom",customType:e7,content:e$(e).trim(),display:!0,timestamp:Date.now()},r=tT.current,n=tj.current;r.sessionId!==n&&(r.sessionId=n,r.outputs=[]);let a=tN.current.slice(0,tC.current.length),i=null;for(let e=a.length-1;e>=0;e--)if(!tn(a[e])){i=a[e];break}r.seq+=1,r.outputs.push({entryId:`${tr}${r.seq}`,baseEntryId:i,message:t});let s=ta(tC.current,tN.current,r.outputs);rf(s.messages),rg(s.entryIds)},[rf,rg]),rz=(0,a.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e2(e=>e?.id===t.id?null:e),e5.current?.id===t.id&&(e5.current=null,e4(null));return}switch(uU(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":e2(t);break;case"notify":rF({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(e=>{let r=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...r,{key:t.statusKey,text:t.statusText}]:r});break;case"setWidget":ti(e=>{let r=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...r,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:r});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e3(e=>t.closed?e?.id===t.id?null:e:t)}},[rF,o,e.chatInputRef]),rW=(0,a.useCallback)(()=>{let e=tI.current;return tI.current=!1,L(!1),eV(null),pg(tM.current),ey(null),$({type:"end"}),e},[]),rO=(0,a.useCallback)(()=>{tL.current="unknown",tA.current=null;let e=pa(tC.current,tN.current);tP.current=e?{entryId:e.entryId,key:ph(e.message)}:null,tF.current+=1},[]),rD=(0,a.useCallback)(()=>{let e=tL.current,t=tA.current;if("unknown"===e){let r=pa(tC.current,tN.current),n=r?.message,a=tP.current;null!==r&&(null===a||(null!==r.entryId&&null!==a.entryId?r.entryId!==a.entryId:ph(r.message)!==a.key))&&n?.role==="assistant"&&n.stopReason&&(e=pn(n),t??={provider:n.provider,...n.model?{model:n.model}:{},...void 0!==n.credentialId?{credentialId:n.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),rH=(0,a.useCallback)(e=>{let t=rD();if("unknown"!==t.outcome||!e)return void s?.(t);let r=tF.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tF.current===r;s?.(e?rD():t)})},[s,rD]),rU=(0,a.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,rH(t),!0),[rH]),rB=(0,a.useCallback)(e=>{rI(),tk.current=!0;let t=tw.current,r=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let n=rp.current,a=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!a.ok)throw Error(`HTTP ${a.status}`);let i=await a.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=i.state;if(tc(e=>u3(e,s?.subagents??[])),rm(e,s?.todoPhases,n),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tE.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tI.current=!0,L(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&s?.isCompacting){eP(!0),eD(pt(s)),ty.current=setTimeout(()=>void r(),600);return}if(i.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void r(),1e3);return}tk.current=!1,ty.current=null,rM()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void r(),600)}};ty.current=setTimeout(()=>void r(),3e4)},[rm,rI,rM]),rq=(0,a.useCallback)(async(e=tj.current,t=rn.current)=>{if(rn.current===t)try{e&&await rx(e)}finally{if(rn.current!==t)return;let r=t$.current,n=tE.current;t$.current=!1,tE.current=!1,ri.current=null;let a=rW();r?rU(t):n&&a&&rH(),e&&rB(e)}},[rx,rH,rU,rB,rW]),rV=(0,a.useCallback)(async(e,t)=>{await pl(800);let r=Date.now();for(;tI.current&&Date.now()-r<2e4;){if(void 0!==t&&rn.current!==t)return;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(r.ok){let n=await r.json(),a=n.state;if(!n.running||!a||!a.isStreaming&&!a.isPromptRunning)return void await rq(e,t)}}catch{}await pl(600)}},[rq]),rK=(0,a.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;t_.current&&tz.current===t&&tj.current===e;){await pl(1e3);try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)continue;let n=await r.json();if(n.state?.isBashRunning)continue;if(await rx(e),tz.current!==t||tj.current!==e)return;t_.current=!1,P(!1),_(null);return}catch{}}},[rx]),rG=(0,a.useCallback)(async e=>{if(!tI.current)return;let t=rn.current;try{let r=rp.current,n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let a=await n.json();if(rn.current!==t)return;let i=a.state;if(eP(i?.isCompacting??!1),eD(pt(i)),to(u9(i?.queuedMessages)),i?.contextUsage!==void 0&&ek(i.contextUsage??null),tc(e=>u3(e,i?.subagents??[])),rm(e,i?.todoPhases,r),a.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting||i.isHandoffRunning)||!tI.current)return;i&&(void 0!==i.systemPrompt&&eS(i.systemPrompt??null),void 0!==i.extensionStatuses&&te(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ti(i.extensionWidgets??[])),await rq(e,t)}catch{}},[rm,rq]),rJ=(0,a.useCallback)(async e=>{let t=await rx(e,!1,!0),r=t?.state;return!!t?.running&&!!r&&tj.current===e&&!tI.current&&!!(r.isStreaming||r.isPromptRunning||r.isHandoffRunning)&&(tE.current=!!r.isStreaming,t$.current=!!r.isPromptRunning,tI.current=!0,L(!0),eV(r.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),px(tM.current,e,r.pendingToolCalls),rR(e),!r.isStreaming&&r.isPromptRunning&&rV(e),!0)},[rR,rx,rV]),rZ=(0,a.useCallback)(async(e,t=rn.current)=>{let r=ra.current+1;ra.current=r;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let a=await n.json();if(r!==ra.current||tj.current!==e||rn.current!==t)return;a.state?.contextUsage!==void 0&&ek(a.state.contextUsage??null)}catch{}},[]);(0,a.useEffect)(()=>{if(!eA){eH.current=null,eD(null);return}eD(e=>e??{startedAt:Date.now(),reason:eH.current})},[eA]),(0,a.useEffect)(()=>{if(!R&&!eA)return;let e=()=>{let e=tj.current;e&&rZ(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[R,eA,rZ]),(0,a.useEffect)(()=>{if(!R)return;let e=()=>{let e=tj.current;e&&rG(e)},t=()=>{"visible"===document.visibilityState&&e()},r=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(r),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[R,rG]),(0,a.useEffect)(()=>{if(R)return;let e=()=>{let e=tj.current;e&&!tI.current&&rJ(e)},t=()=>{"visible"===document.visibilityState&&e()},r=e=>{let t=tj.current,r=e.detail?.sessionId;t&&r===t&&!tI.current&&rJ(t).then(e=>{e||tj.current!==t||tI.current||rx(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(uX,r),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(uX,r)}},[R,rJ,rx]),tO.current=e=>{if(tj.current!==e||tI.current||tg.current||tD.current)return;let t=rJ(e).then(async t=>{t||tj.current!==e||tI.current||await rx(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,a.useEffect)(()=>{tI.current=R},[R]),tW.current=(0,a.useCallback)(e=>{var t;switch(e.type){case"session_snapshot":{let t=function(e,t,r,n,a){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===r||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let i=e.context.messages,s=new Map;for(let e of i){let t=ph(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(n.length,a.length);for(let e of n.slice(0,o)){let t=ph(e),r=s.get(t)??0;r>0&&s.set(t,r-1)}let l=n.slice(o).filter(e=>{let t=ph(e),r=s.get(t)??0;return 0===r||(s.set(t,r-1),!1)});return{entryId:e.entryId,messages:[...i,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let r=ta(t.messages,t.entryIds,tT.current.sessionId===tj.current?tT.current.outputs:[]);rf(r.messages),rg(r.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tI.current;rI(),e&&rO(),tE.current=!0,tI.current=!0,L(!0),eV({kind:"waiting_model"}),$({type:"start"});break}case"agent_end":if(!tI.current)break;if(eV(null),pg(tM.current),ey(null),$({type:"end"}),tj.current){rx(tj.current);let e=rp.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eS(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&te(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ti(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>u3(e,t.state?.subagents??[])),tj.current&&rm(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),to(u9(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tE.current;if(tE.current=!1,!e||t$.current)break;let t=tj.current,r=rW();eP(!1);let n=t?rx(t):void 0;t&&rB(t),r&&rH(n);break}case"prompt_done":{let e=rn.current,t=t$.current;t$.current=!1,ri.current=null;let r=tR.current!==e;if(!t&&!r)break;let n=tj.current;rU(e,n?rx(n):void 0),!tE.current&&(rW(),n&&rB(n))}break;case"prompt_error":tL.current="failed",rF({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tL.current="failed",rF({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tI.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&$({type:"update",message:s2(t)}),eV(null);break}case"message_end":{if(!tI.current)break;let t=e.message;if(t?.role==="assistant"&&(tA.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tL.current=pn(t)),t&&"user"===t.role){let e=s2(t),r=pp(e),n=ri.current;ri.current=null,rf(t=>{let a=t[t.length-1];return n&&a?.role==="user"&&pp(a)===n?n===r?t:[...t.slice(0,-1),e]:[...t,e]}),n||tu({type:"user-message",kind:is(e),text:ii(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&rf(e=>[...e,s2(t)]);let r=tj.current;r&&rZ(r),$({type:"reset"}),eV(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,r=e.thinkingLevel;t&&void 0!==r&&(t3.current=t,t7.current+=1,eo(e.configured??r),ec(r));break}case"todo_changed":rh(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,r=e.toolName,n=e.args,a=rC(tj.current,t);a&&tM.current.add(a),eV(e=>{let a=e?.kind==="running_tools"?[...e.tools]:[];return a.some(e=>e.id===t)||a.push({id:t,name:r,args:n}),{kind:"running_tools",tools:a}});break}case"tool_execution_update":{let r=rC(tj.current,"string"==typeof e.toolCallId?e.toolCallId:null);r&&tM.current.has(r)&&"string"==typeof e.text&&(t=e.text,rw.get(r)!==t&&(rw.set(r,t),rj()));break}case"tool_execution_end":{let t=e.toolCallId,r=rC(tj.current,t);r&&tM.current.delete(r)&&rN([r]),eV(e=>{if(e?.kind!=="running_tools")return e;let r=e.tools.filter(e=>e.id!==t);return 0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";tc(r=>{let n=r.find(e=>e.id===t.id);return u3(r,[{id:t.id,index:t.index??n?.index??0,agent:t.agent??n?.agent??t.id,agentSource:t.agentSource??n?.agentSource??"bundled",description:t.description??n?.description,status:e,task:n?.task,assignment:n?.assignment,sessionFile:t.sessionFile??n?.sessionFile,parentToolCallId:t.parentToolCallId??n?.parentToolCallId,lastUpdate:Date.now(),progress:n?.progress?{...n.progress,status:e}:void 0}])});break}let r={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};tc(e=>u3(e,[r]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let r=t.progress,n={id:r.id,index:t.index??r.index,agent:t.agent??r.agent,agentSource:t.agentSource??"bundled",description:r.description,status:r.status,task:t.task??r.task,assignment:t.assignment??r.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:r};tc(e=>u3(e,[n]));break}case"queue_update":to({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eH.current=e.reason;let t=e.reason;eD(e=>e?{...e,reason:t}:e)}eP(!0),e_(null),eW(null);break;case"auto_compaction_end":case"compaction_end":if(eP(!1),e.errorMessage)e_(e.errorMessage),eW(null);else if(!e.aborted){eW(pm(e.result,e.reason??"auto"));let t=tj.current;t&&(rx(t),rZ(t))}break;case"extension_ui_request":rz(e)}},[rF,rh,rm,rI,rz,rx,rH,rU,rZ,rO,rB,rW,rg,rf]);let rY=(0,a.useCallback)(async(r,a,i)=>{let s=r.trim();if(!s&&!a?.length&&!i?.length)return"returned";if(tI.current||t_.current||rs.current)return"unknown";let o=ld(r,i??[]),l=!a?.length&&!i?.length&&s.startsWith("/");if(!a?.length&&!i?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tG.current?.(t,e),"accepted"):"unknown"}rO();let c=rn.current+1;rI(),t$.current=!0;let d=a?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...o.trim()?[{type:"text",text:o}]:[],...d]:o,timestamp:Date.now()};rf(e=>[...e,u]),ri.current=pp(u),rn.current=c,tI.current=!0,L(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),$({type:"start"}),tX.current(!0);let p=a?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1,g="unknown";try{if(m&&n){let e=tj.current??await t1.current,t=await rS();t&&(h=t,X&&(eE(X),e&&await uV(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await rL(t),f=!0,await uV(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),rk(1,r),g="accepted")}else t&&(h=t.id,await rL(t.id),f=!0,await uV(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&rV(h,c),g}catch(o){console.error("Failed to send message:",o);let n=o instanceof uq&&"update_draining"===o.code&&!1===o.accepted;if(!(!f||o instanceof uq&&"prompt_rejected"===o.code&&!1===o.accepted||n)&&h)return rV(h,c),"unknown";t$.current=!1,tI.current=!1,rM();let s=ri.current;return s&&rf(e=>{let t=e[e.length-1];return t?.role==="user"&&pp(t)===s?e.slice(0,-1):e}),rF({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(r,pf(a),i,t?.id??h??void 0),ri.current=null,L(!1),eV(null),$({type:"end"}),"returned"}},[m,n,X,t,rS,rL,rk,rV,rF,rI,rM,e.chatInputRef,rO,rf]);tG.current=(0,a.useCallback)(async(r,n)=>{if(tI.current||t_.current)return;let a=`${n?"!!":"!"}${r}`;t_.current=!0,tX.current(!0),_({command:r,excludeFromContext:n}),P(!0);try{let e=tj.current??t?.id??await rS();if(!e)throw Error("Unable to create a session for the shell command");await uV(e,{type:"bash",command:r,excludeFromContext:n}),await rx(e),rk(1,a)}catch(t){console.error("Failed to execute shell command:",t),rF({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(a)}finally{t_.current=!1,_(null),P(!1)}},[rF,rS,rx,e.chatInputRef,rk,t]);let rX=(0,a.useCallback)(async()=>{let e=tj.current;if(e){if(t_.current){try{await uV(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uV(e,{type:"abort"}),tL.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),rQ=(0,a.useCallback)(async e=>{if(t_.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eN(e??null);try{let{cancelled:r,newSessionId:n}=await uV(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!r&&n)return c?.(n),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eN(null)}},[c]),r0=(0,a.useCallback)(async e=>{if(t_.current)return;let t=tj.current;t&&(uV(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await rb(t,e))},[rb]),r1=(0,a.useCallback)(async e=>{if(t_.current)return;j(e);let t=tj.current;t&&(await rb(t,e),e&&uV(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[rb]),r2=(0,a.useCallback)(async(e,t)=>{if(m){let r={provider:e,modelId:t},n=t4.current?.provider===e;t4.current=r,n||(t5.current=null,et(null)),Q(r),eE(r);let a=tj.current??await t1.current;if(!a)return;try{await uV(a,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let r=tj.current;if(r&&!rs.current){rs.current=!0,eI({provider:e,modelId:t}),eL(!0);try{await uV(r,{type:"set_model",provider:e,modelId:t}),rs.current=!1,await rx(r)}catch(e){console.error("Failed to set model:",e),rs.current=!1,eI(eT),rF({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await rx(r)}finally{rs.current=!1,eL(!1)}}},[rF,eT,m,rx,Q]),r8=(0,a.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},r=e.oauthPosition,n={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==r?{oauthPosition:r}:{}},a=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(rs.current)return!1;rs.current=!0,eL(!0);let e=t4.current,i=t5.current,s=t6.current;try{t4.current=t,t5.current=r??null,t6.current="auto";let e=tj.current??await t1.current;return e&&await uV(e,n),Q(t),et(r??null),eE(t),eo("auto"),ec(void 0),e&&await rx(e),!0}catch(r){console.error("Failed to apply Main preset:",r),t4.current=e,t5.current=i,t6.current=s,rF({type:"error",message:a(r)});let t=tj.current;return t&&await rx(t),!1}finally{rs.current=!1,eL(!1)}}let i=tj.current;if(!i||rs.current)return!1;rs.current=!0,eI(t),eL(!0);try{return await uV(i,n),await rx(i),!0}catch(e){return console.error("Failed to apply Main preset:",e),eI(eT),rF({type:"error",message:a(e)}),await rx(i),!1}finally{rs.current=!1,eL(!1)}},[rF,eT,el,m,rx,Q,es]),r4=(0,a.useCallback)(async e=>{let t=Z.find(t=>t.role===e),r=t?.resolved;if(!r)return;if(m){let e={provider:r.provider,modelId:r.modelId},t=r.thinkingLevel;t6.current=t??null,eo(t??"auto"),ec(void 0),t4.current=e,t5.current=null,et(null),Q(e),eE(e)}let n=tj.current??(m?await t1.current:null);if(n)try{await uV(n,{type:"set_role_model",role:e}),m||eI({provider:r.provider,modelId:r.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,Q]),r5=(0,a.useCallback)(async()=>{let e=tj.current;if(e&&!eA){eH.current="manual",eP(!0),e_(null),eW(null);try{let t=await uV(e,{type:"compact"});eW(pm(t,"manual")),await rx(e,!0)}catch(e){e_(e instanceof Error?e.message:String(e)),eW(null)}finally{eP(!1)}}},[eA,rx]),r6=(0,a.useCallback)(async e=>{let r=n??t?.cwd??"",a=r?`/api/models?cwd=${encodeURIComponent(r)}`:"/api/models",i=await fetch(a,e?{signal:e}:void 0);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();W(s.models),U(s.modelError??null),q(s.modelScopeWarnings??[]),K(s.thinkingLevels??{}),J(s.thinkingLevelMaps??{}),Y(s.roles??[]);let o=s.modelList??[];if(D(o),m&&!tj.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];en(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t6.current&&eo(t??"auto")}},[m,n,t?.cwd]),r3=(0,a.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,r,n=""]=t,a=n.trim(),i=await rS(),s=e=>(e.handled&&(e.error?rF({type:"error",message:e.error}):"openSessionStats"!==e.action&&rF({type:"success",message:e.message??"Command completed"})),e);try{switch(r){case"compact":{if(!i||eA)return s({handled:!0,error:"No active session to compact"});eH.current="manual",eP(!0),e_(null),eW(null);let e=await uV(i,{type:"compact",...a?{customInstructions:a}:{}});return eW(pm(e,"manual")),await rx(i,!0)&&rk(),s({handled:!0,message:"Compacted context"})}case"reload":if(!i)return s({handled:!0,error:"No active session to reload"});return await uV(i,{type:"reload"}),await Promise.all([rx(i,!1,!0),ry(i),rT(),r6()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!i)return s({handled:!0,error:"No active session to name"});if(!a)return s({handled:!0,error:"Usage: /name <name>"});return await uV(i,{type:"set_session_name",name:a}),await rx(i)&&rk(),s({handled:!0,message:`Session renamed to ${a}`});case"session":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"get_session_stats"});return e&&e0(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!i)return s({handled:!0,error:"No active session to fork"});let e=await rQ();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!i)return s({handled:!0,error:"No active session"});let e=await uV(i,{type:"goal",args:a});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(r_(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&rF({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!i)return s({handled:!0,error:"No active session"});if(tI.current||t_.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tI.current=!0,L(!0),eV({kind:"running_command"});try{await rL(i);let e=await uV(i,{type:"handoff",...a?{customInstructions:a}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await rx(i,!0)&&rk(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tI.current=!1,L(!1),eV(null),tj.current===i&&rB(i)}default:{if(!i)return s({handled:!0,error:"No active session"});let t=await uV(i,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let r=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(r&&r_(r),t.prompt)return{handled:!0,prompt:t.prompt};if(r)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&eP(!1)}},[rF,r_,rL,rS,rQ,eA,r6,rx,rT,ry,rk,h,rB]),r7=(0,a.useCallback)(async(t,r,n)=>{let a=tj.current;if(!a)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n),"returned";let i=ld(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:i,images:s?.length??0});try{return await uV(a,{type:"steer",message:i,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(i){return tu({type:"fail",id:o}),console.error("Failed to steer:",i),rF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n,a),"returned"}},[rF,e.chatInputRef]),r9=(0,a.useCallback)(async(t,r,n,a)=>{let i=tj.current;if(!i)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(n),a),"returned";let s=ld(t,a??[]),o=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:r,text:s,images:o?.length??0});try{return await uV(i,{type:"prompt",message:s,streamingBehavior:r,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(r){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",r),rF({type:"error",message:r instanceof Error?r.message:String(r)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(n),a,i),"returned"}},[rF,e.chatInputRef]),ne=(0,a.useCallback)(async(t,r,n)=>{let a=tj.current;if(!a)return rF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n),"returned";let i=ld(t,n??[]),s=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:i,images:s?.length??0});try{return await uV(a,{type:"follow_up",message:i,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(i){return tu({type:"fail",id:o}),console.error("Failed to follow up:",i),rF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pf(r),n,a),"returned"}},[rF,e.chatInputRef]),nt=(0,a.useCallback)(async()=>{let e=tj.current;if(e)try{await uV(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nr=(0,a.useCallback)(async()=>{let t=tj.current;if(t)try{var r;let n=await uV(t,{type:"clear_queue"});tu({type:"withdraw"}),to({steering:[],followUp:[]});let a={text:(r=[...n?.steering??[],...n?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:r.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(a.text,a.images.length?a.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),rF({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,rF]),nn=(0,a.useCallback)(async(e,t)=>{let r=tj.current;if(r)try{let n=await uV(r,{type:"remove_queued_message",message:t,queue:e});if(!n?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(r=>{let n=r[e].indexOf(t);return(n<0&&""===t.trim()&&(n=r[e].indexOf("[Image]")),n<0)?r:{...r,[e]:r[e].filter((e,t)=>t!==n)}})}catch(e){console.error("Failed to remove queued message:",e),rF({type:"error",message:"Failed to remove queued message"})}},[rF]),na=(0,a.useCallback)(async(e,t=null)=>{let r="auto"===e?t:null,n=r!==ed;eo(e),eu(r),m&&(!tj.current||re.current===tj.current)&&(t6.current=e,t9.current=r),ec(void 0);let a=tj.current??await t1.current;if(a)try{re.current===a?await rS():n&&await uV(a,{type:"set_thinking_ceiling",ceiling:r}),await uV(a,{type:"set_thinking_level",level:e}),await rx(a)}catch(e){console.error("Failed to set thinking level:",e),rF({type:"error",message:"Failed to set thinking level"}),await rx(a)}},[m,rx,rF,ed,rS]);ev.current=rd?`${rd.provider}/${rd.modelId}`:"";let ni=e=>e?`${e}|${ev.current}`:null,ns=t?.id??tj.current,no=ni(ns),nl=ep&&ep.key===no?ep.value:null;(0,a.useEffect)(()=>{let e=++eg.current;no&&ns&&!R&&!eR&&fetch(`/api/agent/${encodeURIComponent(ns)}`).then(e=>e.json()).then(t=>{eg.current===e&&ni(tj.current)===no&&eh({key:no,value:(t.running?pe(t.state):void 0)??null})}).catch(()=>{})},[no,R,eR]);let nc=(0,a.useCallback)(async()=>{let e=tj.current??await rS(),t=ni(tj.current);if(!e||!t)return;let r=++eg.current,n=()=>eg.current===r&&ni(tj.current)===t,a=e=>{n()&&eh({key:t,value:e})};ef(!0);try{let r=ep?.key===t?ep.value?.enabled:void 0;if(void 0===r){let t=pe(await uV(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");r=t.enabled}if(!n())return;let i=await uV(e,{type:"set_fast_mode",enabled:!r});a({enabled:i?.enabled===!0,active:i?.active===!0})}catch(t){if(!n())return;rF({type:"error",message:t instanceof Error?t.message:String(t)});try{a(pe(await uV(e,{type:"get_state"}))??null)}catch{a(null)}}finally{ef(!1)}},[rS,ep,rF]),nd=(0,a.useCallback)(async e=>{let t=(0,ue.xG)(e);rl(e);let r=tj.current??await t1.current;if(r)try{await uV(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[rl]),nu=(0,a.useCallback)(e=>{tU.current=e,tq(t=>!e===t?t:!e)},[]);tX.current=e=>{tZ.current=null,nu(e)};let np=(0,a.useCallback)((e="smooth")=>{tY.current=Date.now()+700,tQ.current?.scrollIntoView({behavior:e})},[]),nh=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,nu(!0),np("smooth")},[np,nu]),nm=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,nu(!1)},[nu]),nf=(0,a.useCallback)(()=>{if(!tZ.current)return;tZ.current=null;let e=t0.current;e&&nu(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[nu]),ng=(0,a.useCallback)(e=>{if(e instanceof PointerEvent&&"mouse"===e.pointerType&&1===e.button&&!(e.target instanceof Element&&e.target.closest("a[href], input, textarea"))&&!(e.target instanceof HTMLElement&&e.target.isContentEditable)){if(tZ.current)return void nf();nm();let e=t0.current;return void(tZ.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}nf(),e instanceof KeyboardEvent&&(!pi.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[nf,nm]),nx=(0,a.useCallback)(()=>{let e=t0.current;if(!e)return;let t=tZ.current;if(null!==t){let r=t.top;t.moved||=e.scrollTop!==r,t.top=e.scrollTop;return}if(!tI.current&&!t_.current)return;let r=e.scrollHeight-e.scrollTop-e.clientHeight,n=Date.now()<=tJ.current;if(!(!n&&Date.now()<tY.current)){if(r<=72)return void nu(!0);n&&nu(!1)}},[nu]);return(0,a.useEffect)(()=>(tj.current=t?.id??null,tT.current.sessionId!==tj.current&&(tT.current={sessionId:tj.current,outputs:[],seq:0}),t&&rx(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;r$(t.id),e?.running&&(ry(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tE.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tI.current=!0,L(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),px(tM.current,t.id,e.state.pendingToolCalls),rR(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&rV(t.id)),e.state?.isBashRunning&&(t_.current=!0,P(!0),rK(t.id)),(e.state?.subagents?.length??0)>0&&rR(t.id));let r=e?.state;r&&(void 0!==r.isCompacting&&eP(r.isCompacting),eD(pt(r)),void 0!==r.contextUsage&&ek(r.contextUsage??null),void 0!==r.systemPrompt&&eS(r.systemPrompt??null),void 0!==r.thinkingLevel&&(t3.current=t.id,eo(r.configuredThinkingLevel??r.thinkingLevel),ec(r.thinkingLevel)),void 0!==r.thinkingCeiling&&eu(r.thinkingCeiling??null),void 0!==r.extensionStatuses&&te(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&ti(r.extensionWidgets??[]),void 0!==r.queuedMessages&&to(u9(r.queuedMessages)),void 0!==r.subagents&&tc(e=>u3(e,r.subagents??[])),void 0!==r.goal&&tK(r.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,rI(),rM(),rE()}),[t?.id]),(0,a.useEffect)(()=>{p?.(ej)},[ej,p]),(0,a.useEffect)(()=>{u&&u(g?.tree??[],k,r1)},[g?.tree,k,r1,u]),(0,a.useEffect)(()=>{let e=e=>{let t=tZ.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t0.current?.contains(e.target))?nf():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",ng),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",ng)}},[nf,ng]),(0,a.useEffect)(()=>{let e=t0.current;if(!e)return;let t=()=>{tZ.current?.moved&&nf()};return e.addEventListener("pointerdown",ng,{passive:!0}),e.addEventListener("wheel",ng,{passive:!0}),e.addEventListener("touchstart",ng,{passive:!0}),e.addEventListener("scroll",nx,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",ng),e.removeEventListener("wheel",ng),e.removeEventListener("touchstart",ng),e.removeEventListener("scroll",nx),e.removeEventListener("scrollend",t)}},[S.length,v,nf,nx,ng]),(0,a.useEffect)(()=>{if(rt.current||!R&&!A||!tU.current)return;let e=t0.current;if(!e)return;let t=requestAnimationFrame(()=>{tU.current&&(tY.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[R,A,S.length,E.streamingMessage,eq,F,e.transitioning]),(0,a.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,np("instant");return}if(!rt.current&&tU.current){let e=Date.now()-rr.current<1500;np(tI.current||t_.current||e?"instant":"smooth")}}},[S.length,R,A,np,e.transitioning]),(0,a.useEffect)(()=>{let e=new AbortController;return r6(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[r6,d]),(0,a.useEffect)(()=>{if(!ez)return;let e=setTimeout(()=>eW(null),6e3);return()=>clearTimeout(e)},[ez]),(0,a.useEffect)(()=>{if(0===eY.visible.length)return;let e=eY.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eY.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eY.visible]),(0,a.useEffect)(()=>{e0(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:E,agentRunning:R,modelNames:z,modelList:O,modelError:H,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ea,thinkingLevel:es,effectiveThinkingLevel:el,thinkingCeiling:ed,retryInfo:eb,contextUsage:ew,systemPrompt:ej,forkingEntryId:eC,isCompacting:eA,compaction:eO,compactError:eF,compactResult:ez,currentModel:rc,displayModel:rd,modelSwitching:eR,sessionStats:ru,runStateKnown:eU,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:ts,deliveryRows:th,subagents:tl,todoPhases:tm&&tm.sid===tj.current?tm.phases:null,compactedWork:I,notices:eY.visible,extensionDialog:e1,extensionResponse:e8,extensionCustomUi:e6,extensionStatuses:e9,extensionWidgets:tt,respondToExtensionUi:rA,sendExtensionCustomInput:rP,isAutoModelSelection:m&&null===X,agentPhase:eq,isNew:m,autoFollowPaused:tB,resumeAutoFollow:nh,pauseAutoFollow:nm,goalStatus:tV,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tQ,scrollContainerRef:t0,handleSend:rY,handleAbort:rX,handleFork:rQ,handleNavigate:r0,handleModelChange:r2,handleRoleModelChange:r4,handleMainPresetChange:r8,newSessionAccount:ee,handleCompact:r5,handleSteer:r7,handleFollowUp:ne,handlePromptWithStreamingBehavior:r9,handleAbortCompaction:nt,handleRecallQueue:nr,handleRemoveQueuedMessage:nn,handleBuiltinSlashCommand:r3,handleToolPresetChange:nd,handleThinkingLevelChange:na,fastMode:nl,fastModeBusy:em,handleFastModeToggle:nc,loadTools:ry,loadSlashCommands:rT,ensureNewSession:rS,refreshLiveTranscript:rv,setActiveLeafId:j,setData:x,setMessages:C,dispatch:$,setAgentRunning:L,setForkingEntryId:eN,bashRunning:A,pendingBash:F,handleAgentEventRef:tW}}({session:e,newSessionCwd:t,initialData:i,transitioning:s,onAgentEnd:eb,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),t8=(0,a.useMemo)(()=>(function(e){let t=null,r=new Map;for(let n=0;n<e.length;n++){let a=e[n],i=e3(a);if(!i||"custom"!==a.role)continue;t??=[...e];let s=[];for(let t=0;t<n;t++){let n=e[t];if("assistant"!==n.role)continue;if(void 0===i.sourceHash){n.timestamp===i.sourceTimestamp&&s.push(t);continue}let a=r.get(t);void 0===a&&(a=function(e){let t=e6(e),r=5381;for(let e=0;e<t.length;e++)r=(r<<5)+r+t.charCodeAt(e)|0;return`${t.length}:${r}`}(n.content??[]),r.set(t,a)),a===i.sourceHash&&s.push(t)}s.length>1&&void 0!==i.sourceHash&&void 0!==i.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===i.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[n]={...a,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let r="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return r.startsWith(e5)?{kind:"translated",text:r.slice(e5.length),original:t}:r.startsWith("[번역 생략]")?{kind:"skipped",text:r,original:t}:{kind:"failed",text:r,original:t}}(a,e6(o.content??[]))}}return t??e})(ej),[ej]),t4=ah(e?.id,e9?.provider,void 0,e9?.modelId),t5=t4?.alias;(0,a.useEffect)(()=>{t5&&X.current?.(t5)},[t5]);let t6=(0,a.useMemo)(()=>{if(!e9)return null;let e=tN?tU:nh.find(e=>e.alias===t4?.alias)?.oauthPosition;return nh.find(t=>t.provider===e9.provider&&(void 0===t.oauthPosition?null===t4||t4.seed===t.seed:t.oauthPosition===e))?.alias??null},[e9,tN,tU,t4]),t3=eN||eT,t7=e?.id;ea.current=t8,ei.current=eS,es.current=tR;let t9=(0,a.useRef)(!0);t9.current=!tT;let re=(0,a.useRef)(!1);(0,a.useEffect)(()=>{eN&&!re.current&&(eo.current+=1),re.current=eN},[eN]),(0,a.useEffect)(()=>()=>{eo.current+=1},[]),(0,a.useEffect)(()=>{et(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(p$(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t7),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t7)])},[t7]),(0,a.useEffect)(()=>{let e=tR.current;e&&er.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let r=!1,n=[];for(let a of t){if(null!==a.anchorEntryId||!a.intent||a.sessionId!==e){n.push(a);continue}let i=function(e,t,r){let n=Math.min(t.length,r.length),a=0;if(null!==e.baseEntryId){let t=r.indexOf(e.baseEntryId);if(-1===t||t>=n)return{kind:"drop"};a=t+1}let i=0;for(let s=a;s<n;s++)if(ni(t[s])===e.identity&&(i+=1)===e.occurrence)return{kind:"entry",entryId:r[s]};return null}(a.intent,t8,eS);if(null===i){n.push(a);continue}r=!0,"drop"!==i.kind&&("working"===a.tag&&[...t,...n].some(e=>"working"===e.tag&&e.anchorEntryId===i.entryId)||n.push({id:a.id,anchorEntryId:i.entryId,sticker:a.sticker,text:a.text,tag:a.tag,sessionId:a.sessionId}))}return r?(pR(e,n),n):t})},[t8,eS,tR]);let rt=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=tR.current,t=rt.current;if(rt.current=e?{sessionId:e,entryIds:eS}:null,!e||!t||t.sessionId!==e)return;let r=function(e,t,r){if(0===e.length||t.length<=e.length)return[];for(let r=0;r<e.length;r++)if(e[r]!==t[r])return[];let n=[],a=Math.min(r.length,t.length);for(let i=e.length;i<a;i++){let e=r[i];"assistant"===e.role&&"web6"===e.provider&&e.model===no&&n.push(t[i])}return n}(t.entryIds,eS,t8),n=ed();if(0===r.length||!n)return;let a=au(e,"web6",void 0)?.alias??null;for(let e of r)er.current.some(t=>t.anchorEntryId===e)||eh(a,"done",n,{kind:"entry",entryId:e})},[eS,t8,tR,ed,eh]);let rr=eN&&tC?.kind==="running_tools"&&tC.tools.length>0&&tC.tools.every(e=>"wait"===e.name),rn=ew||s,{hideThinkingBlock:ra}=(O=t??e?.cwd??null,H=rX(),(0,a.useEffect)(()=>{rY(O).catch(()=>{})},[O]),H),ri=(0,a.useMemo)(()=>({hideThinking:ra}),[ra]);(0,a.useEffect)(()=>{var e;if(!tx||Y.current===tx.id)return;Y.current=tx.id;let t=ed();if(!t)return;ec.current=t.turn;let r=eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,n=ns(ea.current,r,e9?.provider,e9?.modelId);ef("select"===(e=tx.method)||"ask"===e||"form"===e?"choice":"approval",t,n.provider,n.credentialId,n.model)},[tx,eC.streamingMessage,e9?.provider,e9?.modelId,ed,ef]),(0,a.useEffect)(()=>(v=t3?t_:null,()=>void(v=null)),[t3,t_]),(0,a.useEffect)(()=>{M?.(t3)},[M,t3]),(0,a.useEffect)(()=>()=>M?.(!1),[M]),(0,a.useEffect)(()=>{E?.(rr)},[rr,E]),(0,a.useEffect)(()=>()=>E?.(!1),[E]),(0,a.useEffect)(()=>{$?.(null!==tx)},[$,tx]),(0,a.useEffect)(()=>()=>$?.(!1),[$]);let{main:rs,process:ro}=(0,a.useMemo)(()=>(function(e,t,r={}){let n=[],a=[],i=-1,s=null,o=(e,t,r)=>{if(0===t.length)return;let i=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},a.push(s)),s),o=n.length-1;for(let e of t)i.entries.push({...e,afterMainIndex:o});i.messageCount+=t.length,i.toolCallCount+=r},l=e2(e),c=new Map,d=(e,t)=>{let r=c.get(e)??0;c.set(e,r+1),n.push({kind:"answer",anchorIdx:i,idx:e,runIndex:r,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let a of t){if("answer"===a.kind){n.push(a);continue}if("process"===a.kind){o(a.anchorIdx,a.entries,a.toolCallCount);continue}let t=e[a.idx];if(!t)continue;if("user"===t.role){u(),i=a.idx,n.push(a);continue}if(te(t)){n.push(void 0!==a.anchorIdx||i<0?a:{...a,anchorIdx:i});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===e3(t)&&0>tt(e,a.idx)&&o(i,[{idx:a.idx}],0);continue}let s=eG(t,r);if(eV(t,r)&&eK(e,a.idx)){let e=s.flatMap(e=>e.blocks);o(i,[{idx:a.idx}],eJ(e)),l.collect(a.idx,e);continue}let c=!1;for(let e of s){if("answer"===e.kind){d(a.idx,e.blocks),c=!0;continue}o(i,[{idx:a.idx,blocks:e.blocks}],eJ(e.blocks)),l.collect(a.idx,e.blocks)}!c&&eV(t,r)&&d(a.idx,[])}return u(),{main:n,process:a}})(t8,function(e,t={}){let r=-1;for(let t=e.length-1;t>=0;t--)if(ti(e[t])){r=t;break}let n=[];for(let a=0;a<e.length;){if(!ti(e[a])){n.push({kind:"message",idx:a}),a+=1;continue}let i=a,s=i+1;for(;s<e.length&&!ti(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&i===r||!function(e,t,r){for(let n=t;n<r;n++)if(e[n]?.role==="assistant")return!0;return!1}(e,i+1,s)){for(let e=i;e<s;e++)n.push({kind:"message",idx:e});a=s;continue}for(let r of(n.push({kind:"message",idx:i}),function(e,t,r,n){let a=[],i=[],s=0,o=[],l=0,c=0,d=e2(e.slice(t+1,r)),u=()=>{0!==i.length&&(a.push({kind:"process",anchorIdx:t,idx:i[0].idx,groupIndex:c++,entries:i,messageCount:i.length,toolCallCount:s,turnHasAnswer:!1}),i=[],s=0)},p=(e,r)=>{u(),a.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(r),precedingBlocks:o}),o=[]};for(let l=t+1;l<r;l++){let r=e[l];if("assistant"!==r.role){if(null!==e3(r)||tt(e,l)>=0)continue;if(te(r)){u(),a.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==r.role&&i.push({idx:l});continue}let c=eG(r,n);if(eV(r,n)&&eK(e,l)){let e=c.flatMap(e=>e.blocks);for(let t of(i.push({idx:l}),s+=eJ(e),d.collect(l,e),c))"process"===t.kind&&o.push(...t.blocks);continue}let h=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){p(l,e.blocks);continue}for(let t of(i.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eJ(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eV(r,n)&&p(l,[])}u();let h=d.takeRemaining();h&&a.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let m=a.some(e=>"answer"===e.kind);for(let e of a)"process"===e.kind&&(e.turnHasAnswer=m);return a}(e,i,s,{hideThinking:t.hideThinking})))n.push(r);a=s}return n}(t8,{sessionBusy:t3,isStreaming:eC.isStreaming,hideThinking:ri.hideThinking}),ri),[t8,t3,eC.isStreaming,ri]),rl=(0,a.useMemo)(()=>(function(e,t,r=[]){let n=new Map,a=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===a.length)return n;let i=-1,s=-1;t.forEach((e,t)=>{let r=a2(e);if(r.length>0){let e=a.filter(e=>e.item.anchorIdx===i||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=n.get(l.position);e?e.calls.push(...r):n.set(l.position,{calls:[...r],placement:o?"after":"before"})}}"user"===e.role&&(i=t),ti(e)&&(s=t)});let{continuing:o}=a8(e,t,r);if(o){let e=n.get(o.position);e?e.calls.unshift(...o.calls):n.set(o.position,{calls:o.calls,placement:"before"})}return n})(rs,t8,td?.messages),[rs,t8,td]),rc=(0,a.useMemo)(()=>(function(e,t,r=[]){let{atCompaction:n}=a8(e,t,r);if(0===n.length)return null;let a=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(a=t)});let i=e.findIndex(e=>e.idx>a);return{position:-1===i?e.length:i,calls:n}})(rs,t8,td?.messages),[rs,t8,td]),[rd,ru]=(0,a.useState)(pN),{startIndex:rp,endIndex:rh,hasLater:rm}=pT(rs.length,rd),rf=null!==rd.end&&rm,rg=(0,a.useRef)(rs.length);rg.current=rs.length;let rx=(0,a.useRef)(null),rv=(0,a.useRef)(null),rb=(0,a.useRef)(null);(0,a.useEffect)(()=>{null!==rd.end&&rd.end>=rs.length&&ru(e=>({count:e.count,end:null}))},[rd.end,rs.length]),(0,a.useEffect)(()=>{let e=rx.current,t=tA.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(rb.current=t.scrollHeight-t.scrollTop,ru(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rd,rs.length,tA]),(0,a.useEffect)(()=>{if(null==rb.current)return;let e=tA.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-rb.current),rb.current=null}},[rd.count,tA]),(0,a.useEffect)(()=>{let e=rv.current,t=tA.current;if(!e||!t)return;let r=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ru(e=>(function(e,t,r=50){if(null===t.end)return t;let{startIndex:n,endIndex:a}=pT(e,t),i=a+r;return i>=e?{count:e-n,end:null}:{count:i-n,end:i}})(rg.current,e))},{root:t,threshold:0});return r.observe(e),()=>r.disconnect()},[rd,rs.length,tA]);let[ry,rk]=(0,a.useState)(null),[rS,rT]=(0,a.useState)(0),rI=(0,a.useRef)(null),rM=(0,a.useCallback)(e=>{tM(),rI.current=e,rk(null),ru(t=>pI(rg.current,e,t)),rT(e=>e+1)},[tM]);(0,a.useLayoutEffect)(()=>{let e=rI.current,t=tA.current;if(null===e||!t)return;let r=t.querySelector(`[data-chat-item="${e}"]`);if(!r)return;rI.current=null;let n=document.createRange();n.selectNodeContents(r),t.scrollTop+=n.getBoundingClientRect().top-t.getBoundingClientRect().top-24,rk(e)},[rS,rd,rs,tA]),(0,a.useEffect)(()=>{if(null===ry)return;let e=setTimeout(()=>rk(null),1800);return()=>clearTimeout(e)},[ry]);let rE=(0,a.useCallback)(()=>{(0,q.flushSync)(()=>ru(pN));let e=tA.current;e&&(e.scrollTop=e.scrollHeight)},[tA]),r$=(0,a.useCallback)(()=>{rf&&rE(),tI()},[rf,rE,tI]),rR=(0,a.useRef)(null),[rL,rA]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(!_||rR.current===_.id||_.sessionId!==e?.id||ew||0===t8.length)return;rR.current=_.id,W?.(_.id);let t=eS.indexOf(_.entryId);if(t<0)return void rA(!0);let r=0;for(let e=0;e<rs.length;e++){let n=rs[e].idx;if(n>t||(r=e,n===t))break}rM(r)},[_,e?.id,ew,t8.length,eS,rs,rM,W]),(0,a.useEffect)(()=>{if(!rL)return;let e=setTimeout(()=>rA(!1),6e3);return()=>clearTimeout(e)},[rL]);let[rP,rF]=(0,a.useState)(!1),[r_,rz]=(0,a.useState)(0),rW=(0,a.useMemo)(()=>rP?rs.map(e=>(function(e,t){if("answer"===e.kind)return tl(e.blocks);let r=t[e.idx];return r&&"content"in r?tl(r.content):""})(e,t8).toLowerCase()):pL,[rP,rs,t8]),rO=(0,a.useCallback)(e=>{tM(),ru(t=>pI(rg.current,e,t))},[tM]),rD=(0,a.useCallback)(()=>rF(!1),[]);(0,a.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tA.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let r=e.target instanceof Element?e.target:null;if(r?.closest("[data-capture-keys], [role='dialog']"))return;let n=r?.closest("input, textarea, select, [contenteditable='true']");(!n||n.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),rF(!0),rz(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tA]);let rH=(0,a.useMemo)(()=>{let e=[];return rs.forEach((t,r)=>{if("message"!==t.kind)return;let n=pE(t8[t.idx]);null!==n&&e.push({item:r,text:n})}),e},[rs,t8]),rU=`${rp}:${rh}`,rB=eS.length>0?eS[eS.length-1]:null,[rq,rV]=(0,a.useState)(null),rK=(0,a.useRef)(!1);(0,a.useEffect)(()=>{rK.current||!tc||ew||!e?.id||(rK.current=!0,t3||!rB||!function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("user"===r.role||"toolResult"===r.role)return!0;if("assistant"===r.role){if(!r.stopReason)return!0;if("aborted"===r.stopReason||"error"===r.stopReason||"length"===r.stopReason)break;return r.content.some(e=>"toolCall"===e.type)}}return!1}(t8)||function(e){try{return window.localStorage.getItem(pA(e))}catch{return null}}(e.id)!==rB&&rV(rB))},[tc,ew,e?.id,t3,rB,t8]);let rG=(0,a.useCallback)(()=>{e?.id&&rq&&function(e,t){try{window.localStorage.setItem(pA(e),t)}catch{}}(e.id,rq),rV(null)},[e?.id,rq]),rJ=null!==rq&&rq===rB&&!t3&&!rf,rZ=to?[to.sessionId,to.sessionFile??"",to.sessionName??"",to.userMessages,to.assistantMessages,to.toolCalls,to.toolResults,to.totalMessages,to.tokens.input,to.tokens.output,to.tokens.cacheRead,to.tokens.cacheWrite,to.tokens.total,to.cost??0,to.totalActiveMs??0].join("|"):null,rQ=(0,a.useRef)(to);rQ.current=to,(0,a.useEffect)(()=>{f?.(rQ.current)},[rZ,f]),(0,a.useEffect)(()=>()=>{f?.(null)},[f]);let r0=eZ?`${eZ.percent??"null"}|${eZ.contextWindow}|${eZ.tokens??"null"}`:null,r1=(0,a.useRef)(eZ);r1.current=eZ,(0,a.useEffect)(()=>{x?.(r1.current)},[r0,x]),(0,a.useEffect)(()=>()=>{x?.(null)},[x]),(0,a.useEffect)(()=>{b?.(tm)},[b,tm]),(0,a.useEffect)(()=>()=>{b?.([])},[b]);let{regular:r2,lab:r8}=(0,a.useMemo)(()=>(function(e){let t=[],r=[];for(let a of e){var n;((n=a.key).startsWith(cF)&&null!==c_(n)?r:t).push(a)}return{regular:t,lab:r}})(tw),[tw]),r4=e?.id??null;(0,a.useEffect)(()=>{y?.(r4,r8)},[y,r4,r8]),(0,a.useEffect)(()=>()=>{y?.(null,[])},[y]);let{isDragOver:r5,handleDragEnter:r6,handleDragOver:r7,handleDragLeave:r9,handleDrop:ne}=function(e){let[t,r]=(0,a.useState)(!1),n=(0,a.useRef)(0),i=(0,a.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),n.current+=1,r(!0))},[]),s=(0,a.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:i,handleDragOver:s,handleDragLeave:(0,a.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,r(!1))},[]),handleDrop:(0,a.useCallback)(t=>{t.preventDefault(),n.current=0,r(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,a.useCallback)(e=>{t3||p?.current?.addAttachments(e)},[t3,p])),nt=(0,a.useMemo)(()=>{var e;return e=td?.messages,e&&e.length>0?[...e,...t8]:t8},[td,t8]),nr=(0,a.useMemo)(()=>{let e=new Map;for(let t of nt)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[nt]),nn=(0,a.useMemo)(()=>{let e,t,r,n,a,i,s,o,l,c,d;return e=new Map,t=new Map,r=new Map,n=new Map,a=new Map,i=new Map,s=new Map,o=(e,n,a)=>{let i=r.get(e);i&&n&&t.set(i,{status:n,order:a})},l=new Set,c=(e,t)=>{let n=t?r.get(t):void 0,i=aK(e.status);if(!n||l.has(n)||"completed"!==i&&"failed"!==i&&"aborted"!==i)return;l.add(n);let s=aV(e);null!==s&&a.set(n,s)},d=(e,t,n)=>{let a=t?r.get(t):void 0,i=aV(e);a&&"number"==typeof n&&null!==i&&"running"===aK(e.status)&&s.set(a,Math.max(s.get(a)??-1/0,n-i))},nt.forEach((t,a)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=nr.get(e.toolCallId);if(t)for(let a of aJ(e,t)??[])r.set(a.agentId,a.key),"number"==typeof t.timestamp&&n.set(a.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let r=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let r=JSON.parse(aG(e.content));t=r?.ok===!0?r.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let r=t.verdict;if("accepted"!==r&&"rework"!==r&&"held"!==r)return null;let n=aq(t.assignmentId),a=n?.split("#")??[];if(a.length<3)return null;let i=a[a.length-1],s=a.slice(1,-1).join("#");return/^\d+$/.test(i)&&s?{key:`${s}#${i}`,record:{verdict:r,attempt:"number"==typeof t.attempt?t.attempt:null,reason:aq(t.reason)}}:null}(t);if(!r)return;let n=e.get(r.key)??[];n.push({...r.record,order:a,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(r.key,n);return}if("wait"===t.toolName){let e=new Set;for(let n of aB(t.details?.jobs)){if("task"!==n.type)continue;let i=aq(n.id);if(i&&o(i,aK(n.status),a),c(n,i),d(n,i,t.timestamp),i&&"running"===aK(n.status)){let t=r.get(i);t&&e.add(t)}}for(let t of e)for(let r of e){if(t===r)continue;let e=i.get(t);e||i.set(t,e=new Set),e.add(r)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of aG(t.content).matchAll(aZ)){let t=Object.fromEntries([...e[1].matchAll(aY)].map(e=>[e[1],e[2]]));t.id&&o(t.id,aK(t.status),a)}for(let e of aB(t.details?.jobs))"task"===e.type&&c(e,aq(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:r,spawnedAt:n,durations:a,parallelWith:i,runStartedAt:s}},[nt,nr]),na=(0,a.useMemo)(()=>({ledger:nn,subagents:tm,toolResults:nr,onOpenPanel:w,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:j,selectedMaker:S}),[nn,tm,nr,w,e?.id,e?.cwd,t,j,S]),nl=(0,a.useMemo)(()=>{let e=new Set,t=[];for(let r=t8.length-1;r>=0;r-=1){let n=pE(t8[r]);if(!(!n||e.has(n))&&(e.add(n),t.push(n),t.length>=50))break}return t.reverse()},[t8]),nc=(0,a.useMemo)(()=>t$(t8,nr,tf,td?.todoPhases??null),[t8,nr,tf,td]),nd=(0,a.useMemo)(()=>cN(eC.streamingMessage).join("|"),[eC.streamingMessage]),nu=(0,a.useMemo)(()=>JSON.stringify(cC(eC.streamingMessage)),[eC.streamingMessage]),np=(0,a.useMemo)(()=>JSON.stringify(cI(eC.streamingMessage)),[eC.streamingMessage]),nm=(0,a.useMemo)(()=>(function(e,t,r=[],n=[],a=[]){let i=function(e){let t=new Map;for(let r of e){if("toolResult"!==r.role||"write"!==r.toolName)continue;let e=r.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let n=e.message;if(!n||"object"!=typeof n||Array.isArray(n)||"send"!==n.op)continue;let a=Array.isArray(n.receipts)?n.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(r.toolCallId,{from:"string"==typeof n.from?n.from:void 0,receipts:a})}return t}(e),s=[],o=new Map,l=-1;for(let r=0;r<e.length;r+=1){let n=e[r];if("user"===n.role){l=r;continue}let a=cN(n),c=cI(n,i);if(0===a.length&&0===c.length||l<0)continue;let d=cC(n),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...a],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(r.length>0||a.length>0){let i=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){i=t;break}if(i>=0){let e=o.get(i);e||(e={index:i,entryId:t[i],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(i,e),s.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...r.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...n.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...a.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(t8,eS,nd.length>0?nd.split("|"):[],JSON.parse(nu),JSON.parse(np)),[t8,eS,nd,nu,np]),nf=e?.id??tR.current??void 0,ng=(U=c$(D=(0,a.useMemo)(()=>({sessionId:nf,sessionProvider:e9?.provider,turns:nm,messages:t8,subagents:tm}),[nf,e9?.provider,nm,t8,tm])),V=cP(D),(0,a.useMemo)(()=>(function(e){let t=new Map;for(let r of e){let e=t.get(r.turnIndex);e?e.push(r):t.set(r.turnIndex,[r])}return t})(function(e){let t=[];for(let r of e){let e=t[t.length-1];if(e&&e.speakerId===r.speakerId&&e.turnIndex===r.turnIndex&&e.text===r.text){t[t.length-1]=r;continue}t.push(r)}return t}([...U,...V])),[U,V])),nx=tN&&0===t8.length&&!eC.isStreaming&&!t3,nv=(0,a.useMemo)(()=>t8.filter(e=>"assistant"===e.role).length,[t8]),nb=function(e,t){let r=(0,a.useRef)(new Map),n=(0,a.useMemo)(()=>{if(!e)return r.current=new Map,0;let t=new Map,n=0;return(e.content??[]).forEach((e,a)=>{let i=eX(e);if(null===i)return;let s=eQ(r.current.get(a),i);t.set(a,{text:i,tokens:s}),n+=s}),r.current=t,n},[e]),i=(0,a.useRef)(n);i.current=n;let s=null!==e,o=e?.timestamp,[l,c]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(!s)return void c(null);let e=o??Date.now(),t=()=>{let t=(Date.now()-e)/1e3;c(t>=.5?i.current/t:0)};t();let r=setInterval(t,1e3);return()=>clearInterval(r)},[s,o,t]),s?l??0:null}(eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,nv),ny=(0,a.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if("assistant"!==r.role)continue;let{usage:n,timestamp:a,completedAt:i}=r,s=n?.output??0;if(!(s<=0)&&a&&i&&!(i<=a))return s/((i-a)/1e3)}return null})(t8),[t8]),nw=e?.cwd??t??void 0,nk=e9?eA[`${e9.provider}:${e9.modelId}`]??null:null,nj=e9?eP[`${e9.provider}:${e9.modelId}`]??null:null,nS=(0,a.useRef)(null),nC=(0,a.useRef)(null),nN=(0,a.useCallback)(()=>{let e=nS.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,a.useEffect)(()=>(I?.(nN),()=>I?.(null)),[nN,I]),(0,a.useLayoutEffect)(()=>{let e=nC.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let r=tA.current?.clientHeight??0,n=()=>{let n=Math.ceil(e.getBoundingClientRect().height);n>0&&t.style.setProperty("--omp-dock-h",`${n}px`);let a=tA.current;if(!a)return;let i=r-a.clientHeight;r=a.clientHeight,i<=0||a.scrollHeight-a.scrollTop-a.clientHeight-i<=1&&(a.scrollTop+=i)};n();let a=new ResizeObserver(n);return a.observe(e),()=>a.disconnect()},[ew,tA]);let nT=(0,a.useCallback)((...e)=>(null!==rd.end&&rE(),tP(...e)),[tP,rd.end,rE]),nI=(0,n.jsx)("div",{ref:nS,"data-chat-composer":"",style:{display:"contents"},children:(0,n.jsx)(uW,{ref:p,sessionId:e?.id??tR.current??void 0,onEnsureSession:tN&&t?t1:void 0,onLiveTranscriptPersisted:t2,onSend:nT,onAbort:t_,onSteer:eN?tq:void 0,onFollowUp:eN?tV:void 0,onPromptWithStreamingBehavior:eN?tK:void 0,isStreaming:t3,model:e9,isAutoModelSelection:tS,modelNames:eM,modelList:eE,modelError:eR,modelScopeWarnings:eL,onModelChange:tO,onMainPresetChange:e||tN?tH:void 0,mainPresetActiveAlias:t6,modelRoles:eF,onRoleModelChange:tD,modelSwitching:ts,onCompact:e||tN?tB:void 0,onAbortCompaction:tG,isCompacting:e0,compactError:e8,compactResult:e4,toolPreset:e_,onToolPresetChange:e||tN?tX:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,outputTokensPerSecond:nb??ny,outputSpeedLive:null!==nb,thinkingCeiling:eO,onThinkingLevelChange:e||tN?tQ:void 0,fastMode:eD,fastModeBusy:eH,onFastModeToggle:e||tN?eU:void 0,availableThinkingLevels:nk,thinkingLevelMap:nj,retryInfo:eq,deliveryRows:th,inputHistory:nl,onRecallQueue:tJ,onRemoveQueuedMessage:tZ,slashCommands:tu,slashCommandsLoading:tp,onLoadSlashCommands:t0,onBuiltinCommand:tY,soundEnabled:R,onSoundToggle:L,onAudioUnlock:F,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name})}),nM=eC.streamingMessage,nE=(0,a.useMemo)(()=>nM?eG(nM,{isStreaming:!0}):[],[nM]),n$=(0,a.useMemo)(()=>nE.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[nE]),nR=(0,a.useMemo)(()=>nE.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[nE]),nL=nM?.role==="assistant"?nM:null,nA=(0,a.useMemo)(()=>{let e=-1;for(let t=t8.length-1;t>=0;t-=1)if("user"===t8[t].role){e=t;break}let t=e<0?-1:sD(t8,e);return{start:t,blocks:sW(t8,t+1,t8.length),priorCiHeads:sU(t8,nr,t+1),jobNotices:sO(t8,t+1,t8.length)}},[t8,nr]),nP=(0,a.useMemo)(()=>sP(nL?[...nA.blocks,...nL.content??[]]:nA.blocks,nr,t3,nA.priorCiHeads,nw,nA.jobNotices),[nA,nL,nr,t3,nw]),nF=(0,a.useMemo)(()=>t3?{...sz(nA.blocks,nr,nw),span:sB(t8,nA.start+1,t8.length)}:null,[t3,nA,nr,nw,t8]),n_=(0,a.useMemo)(()=>nF?{...nF,flow:nP,latest:!0}:null,[nF,nP]),nz=eN&&(tC?.kind==="running_tools"||(nL?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),nW=ns(t8,nL,e9?.provider,e9?.modelId),nO=nW.provider,nD=nW.model,nH=nW.credentialId;(0,a.useEffect)(()=>{if(!nz)return;let e=ed();e&&el.current!==e.turn&&ec.current!==e.turn&&(el.current=e.turn,ef("working",e,nO,nH,nD))},[nz,nO,nD,nH,ed,ef]);let[nU,nB]=(0,a.useState)(null),nq=(0,a.useCallback)(e=>{nB(e)},[]),nV=(0,a.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),nK=(0,a.useMemo)(()=>{let e=[eN&&!nM&&tC?function(e,t){if(e?.kind==="running_tools"){let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tC,K):null,eT&&!eI?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eN,nM,tC,eT,eI,K]);(0,a.useEffect)(()=>{if(!nU)return void C?.(null);let e=[],t=[],r=0;if(nM&&nR.length>0){let n=nU.messages.length+e.length;for(let a of(e.push(nM),nR))t.push({idx:n,blocks:a}),r+=eJ(a)}if(nV&&(t.push({idx:nU.messages.length+e.length}),e.push(nV)),0===t.length)return void C?.(nK?{...nU,status:nK}:nU);let n=-1;for(let e=nU.messages.length-1;e>=0;e--)if(ti(nU.messages[e])){n=e;break}let a=nU.groups.slice(),i=a.length>0?a[a.length-1]:void 0;i&&i.anchorIdx===n?a[a.length-1]={...i,entries:[...i.entries,...t],messageCount:i.messageCount+t.length,toolCallCount:i.toolCallCount+r}:a.push({anchorIdx:n,entries:t,messageCount:t.length,toolCallCount:r}),C?.({...nU,groups:a,messages:[...nU.messages,...e],status:nK})},[nU,nR,nM,nV,nK,C]),(0,a.useEffect)(()=>()=>C?.(null),[C]);let nG=r2.filter(e=>"belowEditor"!==e.placement),nJ=r2.filter(e=>"belowEditor"===e.placement);return ek?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ek}):(0,n.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":rn,"data-empty-start":nx&&!T?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:r6,onDragOver:r7,onDragLeave:r9,onDrop:ne,children:[rn?(0,n.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,n.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,r5&&!t3&&(0,n.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,n.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),tb&&(0,n.jsx)(pH,{request:tb,onInput:tj}),nx&&!T?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,n.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[860px] py-8",children:[(0,n.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,n.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,n.jsx)(ee,{})}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.232"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.20.0"]})]})]})]}),nw&&(0,n.jsxs)("section",{className:"empty-workspace-context","aria-label":K("chat.emptyProjectLabel"),children:[(0,n.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,n.jsx)("span",{className:"empty-workspace-context-kicker",children:K("chat.emptyProjectLabel")}),(0,n.jsx)("strong",{children:tF(nw)||nw}),(0,n.jsx)("code",{title:nw,children:nw}),(0,n.jsx)("p",{children:K("chat.emptyProjectHint")})]}),k&&(0,n.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:k,children:K("chat.openSessionList")})]}),(0,n.jsx)(pW,{notices:tg,align:"right"})]})}):(0,n.jsxs)(n.Fragment,{children:[T&&(0,n.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:T}),(0,n.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!T,style:{display:T?"none":"flex"},children:[(0,n.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,n.jsx)(cs,{open:rP,onClose:rD,containerRef:tA,index:rW,renderedStart:rp,renderedEnd:rh,contentKey:t8,onReveal:rO,onProgrammaticScroll:tM,focusRequest:r_,t:K}),rL&&(0,n.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,n.jsx)(pW,{notices:tg,floating:!0,align:"right"})]})}),(0,n.jsx)("div",{ref:tA,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,n.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(pz,{widgets:nG}),(0,n.jsxs)(s7.Provider,{value:na,children:[(0,n.jsx)(cy,{utterances:ng,children:(0,n.jsx)(pP,{messages:t8,entryIds:eS,toolResultsMap:nr,modelNames:eM,messageCwd:nw,onOpenFile:N,sessionBusy:t3,isNew:tN,isStreaming:eC.isStreaming,handleFork:tz,forkingEntryId:eY,handleNavigate:tW,handleEditContent:ey,sessionId:e?.id??tR.current??void 0,main:rs,dispatchSlots:rl,compactedDispatch:rc,openRequest:td?.openRequest??null,process:ro,startIndex:rp,endIndex:rh,sentinelRef:rx,laterSentinelRef:rv,flashItem:ry,t:K,cues:Q,cueFollowRef:t9,onProcessLogChange:nq})}),!rf&&eC.isStreaming&&eC.streamingMessage&&n$.length>0&&(0,n.jsx)(lL,{message:eB(eC.streamingMessage,n$),sessionId:e?.id??tR.current??void 0,isStreaming:!0,modelNames:eM,cwd:nw,onOpenFile:N}),!rf&&n_&&(0,n.jsx)(o5,{summary:n_,live:!0,onOpenFile:N})]}),rJ&&(0,n.jsx)(cp,{onDismiss:rG,t:K}),(0,n.jsx)("div",{ref:tL})]})})}),(0,n.jsx)(co,{questions:rH,containerRef:tA,layoutKey:rU,onJump:rM,label:K("chat.questionRail")}),(t3&&tT||rf)&&(0,n.jsxs)("button",{type:"button",onClick:r$,"aria-label":K("chat.jumpToBottom"),title:K("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:J?44:void 0,borderRadius:"var(--seed-radius-full)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,n.jsx)("path",{d:"M12 5v14"}),(0,n.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,n.jsxs)("div",{ref:nC,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tx&&(0,n.jsx)("div",{style:{padding:"0 16px"},children:(0,n.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,n.jsx)(pD,{request:tx,onRespond:tk,onActivity:(e,t)=>void tj(e,t??"activity"),delivery:tv})})}),(0,n.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,n.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,n.jsx)(cu,{compaction:e1,t:K}),(0,n.jsx)(p_,{goal:tE,t:K}),(0,n.jsx)(pz,{widgets:nJ}),(nc||nP.steps.length>0)&&!(G&&J)&&(0,n.jsx)(uD,{phases:nc,flow:nP,busy:t3})]})}),nI,(0,n.jsx)(uO,{statuses:ty})]})]})}function p_({goal:e,t}){if(!e)return null;let r=!e.enabled,a=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:rU(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:rU(e.tokensUsed)});return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:r?.7:1},children:[(0,n.jsx)("span",{style:{color:r?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,n.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:r?t("chat.goalPaused"):e.status}),(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:a})]})}function pz({widgets:e}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,n.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,n.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,n.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function pW({notices:e,floating:t=!1,align:r="left"}){return 0===e.length?null:(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===r?"flex-end":"stretch",marginBottom:10*!t},children:e.map((r,a)=>{let i="error"===r.type?"var(--danger)":"warning"===r.type?"var(--warning)":"success"===r.type?"var(--success)":"var(--accent)";return(0,n.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(a!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:r.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:i,flexShrink:0}}),(0,n.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r.message})]},r.id)})})}function pO({focusKey:e,label:t,labelledBy:r,maxBlockSize:i="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,z.s)(),d=(0,a.useRef)(null),u=(0,a.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!d.current?.contains(t)?t:null}}return(0,a.useEffect)(()=>{let e=d.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let r=document.activeElement;(null===r||r===document.body||e?.contains(r))&&t.focus()}},[e]),(0,n.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":r,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:i},children:[o?(0,n.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function pD({request:e,onRespond:t,onActivity:r,delivery:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,a.useState)({selected:{},custom:{}}),[u,p]=(0,a.useState)(""),h=(0,a.useRef)(0),m=(0,a.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!r)return;let t=Date.now();t-h.current<1e3||(h.current=t,r(e))},[e,r]);(0,a.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let r of e)t[r.id]=void 0!==r.recommended&&void 0!==r.options[r.recommended]?[r.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("form"===e.method)return(0,n.jsx)(pO,{focusKey:e.id,label:s("chat.agentQuestion"),delivery:i,children:(0,n.jsx)(c2,{request:e,onRespond:t,onActivity:r,delivery:i},e.id)});if("ask"===e.method){var g;let r=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),a=()=>{if(r){var n;t(e,{value:(n=e.questions,JSON.stringify({kind:"submit",results:n.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,n.jsx)(pO,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,n.jsxs)("div",{style:{minWidth:0},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,n.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,n.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,r)=>{let i=c.selected[t.id]??[];return(0,n.jsxs)("section",{style:{paddingTop:20*(0!==r),borderTop:0===r?"none":"1px solid var(--hairline)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,n.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[r+1,"/",e.questions.length]})]}),(0,n.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,n.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,r)=>{let a=i.includes(r),o=t.recommended===r;return(0,n.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":a,onClick:()=>{m(),d(e=>(function(e,t,r){let n=e.selected[t.id]??[];if(t.multi){let a=n.includes(r)?n.filter(e=>e!==r):[...n,r];return{...e,selected:{...e.selected,[t.id]:a}}}return{selected:{...e.selected,[t.id]:[r]},custom:{...e.custom,[t.id]:""}}})(e,t,r))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${a?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:a?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,n.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${a?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:a?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:a&&(t.multi?(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,n.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,n.jsxs)("span",{style:{minWidth:0},children:[(0,n.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:a?600:500},children:e.label}),e.description&&(0,n.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),a&&e.preview&&(0,n.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${r}`)})}),(0,n.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let r=e.target.value;d(e=>{let n;return n={...e.custom,[t.id]:r},t.multi||0===r.trim().length?{...e,custom:n}:{selected:{...e.selected,[t.id]:[]},custom:n}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&a()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,n.jsx)("button",{type:"button",disabled:!r||i?.status==="sending",onClick:a,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:r&&i?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:r&&i?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:r&&i?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:i?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,n.jsx)(pO,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,n.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,n.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,n.jsx)(rb,{children:e.planContent})}),(0,n.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,n.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,n.jsx)(pO,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,n.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,n.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,n.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,n.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,n.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(r=>(0,n.jsx)("button",{onClick:()=>t(e,{value:r}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:r},r))}),"input"===e.method&&(0,n.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,n.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&f()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,n.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,n.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,n.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function pH({request:e,onInput:t}){let{t:r}=(0,z.s)(),i=(0,a.useRef)(null),s=(0,a.useRef)(!1),o=eP(e.lines);return(0,a.useEffect)(()=>{i.current?.focus()},[e.id]),(0,n.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,n.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||i.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,n.jsx)("textarea",{ref:i,"aria-label":r("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=ez[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":e_[e.key]??null}(r);n&&(r.preventDefault(),r.stopPropagation(),t(e,n))},onInput:r=>{if(s.current||r.nativeEvent.isComposing)return;let n=r.currentTarget.value;r.currentTarget.value="",n&&t(e,n)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:r=>{s.current=!1;let n=r.currentTarget;queueMicrotask(()=>{let r=n.value;n.value="",r&&t(e,r)})},onPaste:r=>{r.preventDefault();let n=r.clipboardData.getData("text");n&&t(e,`\x1b[200~${n}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,n.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:r("chat.extensionPanel")}),(0,n.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:r("chat.close")})]}),(0,n.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,r)=>{var i;return(0,n.jsxs)(a.Fragment,{children:[(i=`line-${t}`,eF(e).map((e,t)=>Object.keys(e.style).length>0?(0,n.jsx)("span",{style:e.style,children:e.text},`${i}-${t}`):e.text)),t<r.length-1?"\n":null]},t)})})]})})}var pU=r(40960),pB=r.n(pU);function pq({sessionId:e,refreshKey:t,compact:r}){let{t:i}=(0,z.s)(),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(null),h=(0,a.useRef)(e);h.current=e;let m=(0,a.useRef)(0);(0,a.useEffect)(()=>{if(!e)return;let t=!1,r=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(n=>{if(t||r!==m.current)return;let a=n.running?n.state?.computerTakeover:null;l(a?{sessionId:e,state:{enabled:!0===a.enabled,available:!0===a.available}}:null),p(null)}).catch(()=>{}),()=>{t=!0}},[e,t]);let f=(0,a.useCallback)(async e=>{let t=h.current;if(t){d(!0),p(null);try{let r=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),n=await r.json();if(!r.ok)throw Error("shared_settings"===n.code?i("computerTakeover.shared"):n.error??r.statusText);h.current===t&&(m.current+=1,l({sessionId:t,state:{enabled:!0===n.enabled,available:!0!==n.enabled}}))}catch(e){h.current===t&&p(i("computerTakeover.failed",{error:e instanceof Error?e.message:String(e)}))}finally{d(!1)}}},[i]),g=o&&o.sessionId===e?o.state:null;if(!g||!g.enabled&&!g.available)return null;let x=g.enabled,v=x?i("computerTakeover.active"):i("computerTakeover.allow"),b=u??(x?i("computerTakeover.activeHint"):i("computerTakeover.allowHint"));return(0,n.jsxs)(s.r,{className:`workspace-header-action workspace-takeover${x?` ${pB().active}`:""}`,variant:x?"neutralWeak":"ghost",size:"small",type:"button",disabled:c,"aria-pressed":x,"aria-label":v,title:b,onClick:()=>void f(!x),children:[(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!r)&&(0,n.jsx)("span",{children:v})]})}function pV({onPick:e,t}){let[r,i]=(0,a.useState)(""),[s,o]=(0,a.useState)({kind:"idle"}),l=(0,a.useRef)(null),c=r.trim();(0,a.useEffect)(()=>{if(c.length<2)return void o({kind:"idle"});let e=new AbortController;o({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);o({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||o({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[c]);let d=e=>{let t=l.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,n.jsxs)("div",{className:"palette-search",children:[(0,n.jsx)("input",{type:"search",value:r,onChange:e=>i(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),d(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let r=u.hits[0],n=u.sessions[r.sessionId];n&&e(n,r,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,n.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,n.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,n.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((r,a)=>{let i=u.sessions[r.sessionId],s=r.matchStart+u.query.length;return(0,n.jsxs)("button",{type:"button",disabled:!i,onClick:()=>i&&e(i,r,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(a+("ArrowDown"===e.key?1:-1)))},children:[(0,n.jsxs)("span",{className:"palette-search-title",children:[(0,n.jsx)("span",{children:i?i.name?.trim()||i.firstMessage?.trim()||i.id:""}),(0,n.jsx)("small",{children:"user"===r.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,n.jsxs)("span",{className:"palette-search-snippet",children:[r.snippet.slice(0,r.matchStart),(0,n.jsx)("mark",{children:r.snippet.slice(r.matchStart,s)}),r.snippet.slice(s)]})]},`${r.sessionId}:${r.entryId}`)})})]})]})}var pK=r(50640),pG=r(73620);let pJ=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pZ(e){return function e(t,r){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(r.has(t))return"[Circular]";r.add(t);try{return t.map(t=>e(t,r)).filter(Boolean).join(", ")}finally{r.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let pY=["tags","categories","keywords","tag","category"];function pX({data:e}){var t;if(!e)return null;let r=Object.entries(e);if(0===r.length)return null;let a="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,i=pY.find(t=>Array.isArray(e[t])),s=i?e[i].map(pZ).filter(Boolean):[],o=r.filter(([e])=>e!==i&&("title"!==e||!a));return(0,n.jsxs)("div",{className:"markdown-frontmatter",children:[a&&(0,n.jsx)("div",{className:"markdown-frontmatter-title",children:a}),s.length>0&&(0,n.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,n.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,n.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,n.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,n.jsx)("dt",{children:e}),(0,n.jsx)("dd",{children:function(e){let t=pZ(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,n.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var pQ=r(8745);let p0=(0,a.createContext)(null),p1=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),p2=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),p8=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m10 3-5 5 5 5"})}),p4=(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,n.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),p5=(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,n.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,n.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,n.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function p6({back:e,title:t,titleTooltip:r,titleRef:a,titleAdornment:i,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:m}){let{t:f}=(0,z.s)();return(0,n.jsxs)("header",{className:"panel-header",children:[e&&(0,n.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,n.jsx)(o.In,{size:"16px",svg:p8})}),(0,n.jsxs)("div",{className:"panel-header-heading",children:[(0,n.jsx)("h2",{className:"panel-header-title",title:r,ref:a,tabIndex:a?-1:void 0,children:t}),i,l&&("path"===d?(0,n.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,n.jsx)("bdi",{dir:"ltr",children:l})}):(0,n.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,n.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,n.jsxs)(pQ.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,n.jsxs)(pQ.A.Item,{value:e.value,title:e.title,children:[(0,n.jsx)(pQ.A.ItemHiddenInput,{}),e.label]},e.value)),(0,n.jsx)(pQ.A.Indicator,{})]}),h.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,n.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,n.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,n.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,n.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,n.jsx)(c.k.Trigger,{asChild:!0,children:(0,n.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,n.jsx)(o.In,{size:"16px",svg:p5})})}),(0,n.jsx)(c.k.Positioner,{children:(0,n.jsx)(c.k.Content,{"aria-label":f("panel.more"),children:(0,n.jsx)(c.k.ScrollArea,{children:(0,n.jsx)(c.k.Group,{children:h.map(e=>(0,n.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,n.jsx)(c.k.ItemBody,{children:(0,n.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,n.jsx)(p3,{}),m&&(0,n.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:m.onClick,"aria-label":m.label,title:m.label,children:(0,n.jsx)(o.In,{size:"16px",svg:p4})})]})}function p3({className:e="panel-header-button"}){let{t}=(0,z.s)(),r=(0,a.useContext)(p0);if(!r)return null;let i=t(r.expanded?"panel.restore":"panel.expand");return(0,n.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":r.expanded,"aria-label":i,title:i,onClick:r.onToggle,children:(0,n.jsx)(o.In,{size:"16px",svg:r.expanded?p2:p1})})}let p7="cuelo-html-pick",p9="cuelo-html-pick-exit";function he(e,t){return"string"==typeof e&&e.length<=t}function ht(e){return"number"==typeof e&&Number.isFinite(e)}function hr({content:e,title:t,picking:r,onExitPick:i,onRequestEdit:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null),d=(0,a.useMemo)(()=>{if(!r)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var r;let n=`<script>${(r=t,`(function(){
|
|
21
21
|
var NONCE=${JSON.stringify(r)},TYPE=${JSON.stringify(p7)},EXIT=${JSON.stringify(p9)};
|
|
22
22
|
var host=window.parent;
|
|
23
23
|
if(document.currentScript)document.currentScript.remove();
|