cuelo 0.10.199 → 0.10.201
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 +58 -58
- 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/agent/[id]/account/route.js +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 +5 -5
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
- package/.next/server/app/index.segments/_full.segment.rsc +5 -5
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/page.js +5 -5
- 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 +58 -58
- package/.next/server/chunks/1008.js +2 -2
- package/.next/server/chunks/4831.js +1 -1
- package/.next/server/chunks/5228.js +1 -1
- package/.next/server/chunks/6429.js +1 -1
- package/.next/server/chunks/7015.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-9d5d4b7b367060a3.js → layout-b9595b7df7edd57d.js} +1 -1
- package/.next/static/chunks/app/page-1ae6fb3e07b3af13.js +77 -0
- package/.next/static/css/{08a6c792a820ad7f.css → 46bbf7d679c17856.css} +1 -1
- package/.next/trace +111 -111
- package/.next/trace-build +1 -1
- package/README.md +3 -2
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +3 -3
- package/Tools/OMP_Global_Config/agent/AGENTS.md +2 -2
- package/Tools/OMP_Global_Config/agent/RULES.md +4 -1
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/argon-preflight/plugin.json +4 -0
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/goal-lane/plugin.json +4 -0
- package/Tools/OMP_Global_Config/agent/cuelo-plugins/scan-nudge/plugin.json +4 -0
- package/Tools/OMP_Global_Config/agent/extensions/character-voice.ts +1 -1
- package/Tools/OMP_Global_Config/agent/extensions/lib/maker-routing.ts +8 -12
- package/Tools/OMP_Global_Config/agent/extensions/lib/turn-documents.ts +6 -6
- package/Tools/OMP_Global_Config/agent/extensions/lib/turn-publication.ts +180 -0
- package/Tools/OMP_Global_Config/agent/extensions/plugin-lab.ts +1 -0
- package/Tools/OMP_Global_Config/agent/extensions/turn-end-guard.ts +28 -7
- package/Tools/OMP_Global_Config/agent/prompt-copies/AGENTS.en.md +3 -3
- package/Tools/OMP_Global_Config/agent/prompt-copies/RULES.en.md +2 -2
- package/Tools/OMP_Global_Config/agent/rules/docs-handoff.md +1 -1
- package/Tools/OMP_Global_Config/agent/rules/harness-policy.json +2 -2
- package/Tools/OMP_Global_Config/agent/rules/rule-enforcement.md +3 -3
- package/Tools/OMP_Global_Config/agent/rules/subagent.md +4 -4
- package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +22 -7
- package/package.json +7 -7
- package/.next/static/chunks/app/page-2206726c93550b54.js +0 -77
- /package/.next/static/{DFQya0lPjJlyAXtmOS6bk → 67yzX7RAFdK1wgMWP0ybq}/_buildManifest.js +0 -0
- /package/.next/static/{DFQya0lPjJlyAXtmOS6bk → 67yzX7RAFdK1wgMWP0ybq}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2498:e=>{e.exports={view:"MemoryTraceView_view__62Ck_",body:"MemoryTraceView_body__gELit",message:"MemoryTraceView_message__pDO_k",errorText:"MemoryTraceView_errorText__GkoKJ",sectionTitle:"MemoryTraceView_sectionTitle__lmuuo",sectionCount:"MemoryTraceView_sectionCount__9yRSn",requests:"MemoryTraceView_requests__scPBk",requestScroller:"MemoryTraceView_requestScroller__4ALfU",requestList:"MemoryTraceView_requestList__rQ4G0",requestRow:"MemoryTraceView_requestRow__LZd3A",stationButton:"MemoryTraceView_stationButton__BztyW",requestIndex:"MemoryTraceView_requestIndex__TacwG",requestTime:"MemoryTraceView_requestTime__fJjQF",noticeChip:"MemoryTraceView_noticeChip__gz9AO",requestPreview:"MemoryTraceView_requestPreview__HwG7v",miniRail:"MemoryTraceView_miniRail__84C2v",flow:"MemoryTraceView_flow__UCgmI",titleText:"MemoryTraceView_titleText__38Tl7",flowPreview:"MemoryTraceView_flowPreview__HjgKe",rail:"MemoryTraceView_rail__HlWbE",station:"MemoryTraceView_station__ulNBH",stationStep:"MemoryTraceView_stationStep__CgFYZ",stationCount:"MemoryTraceView_stationCount__2_rrN",stationLabel:"MemoryTraceView_stationLabel__QGYpC",stationNote:"MemoryTraceView_stationNote__Jc30I",detail:"MemoryTraceView_detail__Rnn_d",stageEmpty:"MemoryTraceView_stageEmpty__x0H_J",group:"MemoryTraceView_group__1SCqK",bucket:"MemoryTraceView_bucket__Vmuau",groupTitle:"MemoryTraceView_groupTitle__6Q1oM",groupCode:"MemoryTraceView_groupCode__qgzOG",query:"MemoryTraceView_query__DK87N",items:"MemoryTraceView_items__D8Wz8",item:"MemoryTraceView_item__wyulb",idList:"MemoryTraceView_idList__mQArH",path:"MemoryTraceView_path__97O3u",itemHead:"MemoryTraceView_itemHead__B0bQo",memoryId:"MemoryTraceView_memoryId__5KjoX",itemMeta:"MemoryTraceView_itemMeta__wbj6K",itemText:"MemoryTraceView_itemText__O92R_",graph:"MemoryTraceView_graph__RHbn9",graphHead:"MemoryTraceView_graphHead__sEDhc",scopeSwitch:"MemoryTraceView_scopeSwitch__3HBI2",legend:"MemoryTraceView_legend__52_dq",legendMark:"MemoryTraceView_legendMark__hS7sK",legendTitle:"MemoryTraceView_legendTitle__z_lgW",legendMemory:"MemoryTraceView_legendMemory__mkYqP",graphCaption:"MemoryTraceView_graphCaption__ot7gW",captionKind:"MemoryTraceView_captionKind__e1fLD",graphFrame:"MemoryTraceView_graphFrame__SgiqG",graphSvg:"MemoryTraceView_graphSvg___JeWV",columnHeads:"MemoryTraceView_columnHeads__drsYb",edges:"MemoryTraceView_edges__4zMSL",node:"MemoryTraceView_node__ymwrL",hit:"MemoryTraceView_hit__HS6HS",mark:"MemoryTraceView_mark__WxCZl",arrow:"MemoryTraceView_arrow__oz9U4",nodeText:"MemoryTraceView_nodeText__Tp4ud",ring:"MemoryTraceView_ring___LM5n"}},2730:(e,t,n)=>{"use strict";function r(e,t,n,a={}){let i=n[e]?.[t]??n.en?.[t];return void 0===i?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(i,a)}n.d(t,{u0:()=>r})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>i,IN:()=>a,getPresetFromTools:()=>o,xG:()=>l});let r=[],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 n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...a].sort().join(",")?"default":n===[...i].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...i]:[...a]}},20098:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>yy});var r=n(95155),a=n(12115),i=n(73321),s=n(16871),o=n(81886),l=n(68890),c=n(66919);let d=["chat","process","subagents","files","resource","sidechat","efficiency","plugins","memory"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),m=Object.fromEntries(d.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let n,r=f(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=f(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function T(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let n=null;for(let[r,a]of Object.entries(t.opened))(e.opened[r]??-1/0)>=a||((n??={...e.opened})[r]=a);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function R(e,t,n){let r=Math.max(n,M(t)??0);return(e.opened[t.id]??-1/0)>=r?e:{since:e.since,opened:{...e.opened,[t.id]:r}}}let E=new Set;function L(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function $(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function P(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=$(e),a=t.get(r);(!a||n.modified>a.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function A(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set($(e.key),e.order);let r=[...e],a=new Set(e.map($));for(let e of t){let t=$(e.key);!t||a.has(t)||(r.push(e.path??e.key),a.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get($(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let 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[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var z=n(92176);let W=`(max-width: ${p.navigator-1}px)`;function O(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=O("(max-width: 640px)"),H=O(W);function U(){return!1}function B(){return(0,a.useSyncExternalStore)(D.subscribe,D.getSnapshot,U)}var q=n(47650);async function V(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function K(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function G(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function J({onCancel:e,onSelect:t,busy:n=!1,error: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),n=t.path??e??"/";d(n),p(t.parentPath??null),m(!0===t.upToDrives),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,a.useEffect)(()=>{l(document.body),C()},[C]);let N=f.trim()!==c,T=!!c&&!N&&!n,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,q.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!I,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:I?"pointer":"default",opacity:I?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(G,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(K,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||i)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??i})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!T,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:T?1:.6,cursor:T?"pointer":"default"},children:s(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Z=n(21443),Y=n.n(Z);async function X(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function Q({onCancel:e,onSelect:t,busy:n=!1,error: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),[R,E]=(0,a.useState)(50),L=p?.device?.state==="pending",$=n||S,P=(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 A(){j(!0),T(null);try{let{device:e}=await X("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){T(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function F(e){if(e.preventDefault(),v.trim()&&!$){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),P()},[P]),(0,a.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,a.useEffect)(()=>{let e;if(!L||d)return;let t=!1,n=async()=>{try{let e=await X("/api/github/projects");if(t)return;if(h(e),e.connected)return void await P();if(e.device?.state!=="pending")return}catch(e){t||T(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[L,d,P]),!l)return null;if(d)return(0,r.jsx)(J,{onCancel:()=>u(!1),onSelect:t,busy:n,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,r.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),$||e()},children:(0,r.jsxs)("form",{onSubmit:F,className:Y().form,children:[(0,r.jsxs)("header",{className:Y().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:Y().sources,children:[(0,r.jsx)("span",{className:Y().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:$,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:Y().body,children:[(0,r.jsxs)("section",{className:Y().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:y||$,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void A(),disabled:y||k||L||$,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:Y().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:Y().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>T(s("cloudProjects.copyFailure")))},children:I?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Y().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:Y().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:$}),y?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:Y().list,children:_.slice(0,R).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":v===e.fullName,disabled:$,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:Y().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:Y().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),_.length>R&&(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:Y().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:$,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),W&&(0,r.jsxs)("div",{className:Y().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:W}),(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:$,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:Y().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:Y().footer,children:[(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:$,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:Y().primary,disabled:$||!v.trim(),children:$?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function ee({label:e="CUELO",markSize:t=22,gap:n=10,style:a,labelStyle:i}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...a},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...i},children:e})]})}var et=n(2730);let 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."},er={...en,"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,ChatGPT 账号的 Codex 实时通话会把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","translator.open":"打开口译","translator.me":"我","translator.them":"对方","translator.myLanguage":"我的语言","translator.theirLanguage":"对方语言","translator.swap":"交换语言","translator.clear":"清除","translator.start":"开始口译","translator.stop":"结束口译","translator.empty":"按开始口译,把手机放在两人之间。无论谁说话,都会立即译成对方的语言说出来。","translator.connecting":"连接中…","translator.live":"正在听 \xb7 直接说话","translator.unsupported":"此浏览器不支持实时通话(WebRTC 和麦克风)。手机请用 Chrome 或 Safari 打开。","translator.insecure":"麦克风只能在 HTTPS 地址上使用。","translator.micDenied":"麦克风权限被阻止。请在浏览器设置中允许此地址使用麦克风。","translator.micUnavailable":"无法打开麦克风。请确认没有其他应用正在使用。","translator.auth":"Codex 登录不存在或已过期。请在模型设置中用 ChatGPT 账号重新登录。","translator.upstream":"Codex 实时连接已断开:{error}","translator.failed":"无法开始口译:{error}","translator.original":"原文","translator.translationPending":"口译中…","translator.conversation":"口译记录","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-29岁","translator.age.30s":"30-39岁","translator.age.40s":"40-49岁","translator.age.50s":"50-59岁","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":"语言与场景设置","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":"在嘈杂的地方降低麦克风的背景噪音,让翻译听得更清楚。如果声音发闷,请关闭。"},ea={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,"zh-CN":er};function ei(){let{locale:e}=(0,z.s)();return{tt:(0,a.useCallback)((t,n)=>(0,et.u0)(e,t,ea,n),[e]),locale:e}}let es="omp-web:unread-session-ids",eo="omp-web:pinned-session-ids",el="omp-web:removed-projects";function ec(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 ed(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eu({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function ep({open:e,children:t,style:n}){let[i,s]=(0,a.useState)(e),[o,l]=(0,a.useState)(e);return((0,a.useEffect)(()=>{let t,n;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),i)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let eh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function em(){let[e,t]=(0,a.useState)(!1),[n,i]=(0,a.useState)(!1),s=(0,a.useRef)(null),o=function(e,t){let[n,r]=(0,a.useState)(e),i=(0,a.useRef)(null),s=(0,a.useRef)(0);return(0,a.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,a=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:eh[Math.floor(Math.random()*eh.length)]).join("")),s.current<n?i.current=requestAnimationFrame(a):r(e)};return i.current=requestAnimationFrame(a),()=>{i.current&&cancelAnimationFrame(i.current)}},[e,t]),n}(e?"0.10.201/18.18.7":"CUELO",n),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,r.jsx)("button",{className:"navigator-brand",onClick:c,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(ee,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function ef(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 eg({selectedSessionId:e,optimisticSession:t,onSelectSession:n,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}=ei(),{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,en]=(0,a.useState)("projects"),[er,ea]=(0,a.useState)(()=>new Set),[eh,ev]=(0,a.useState)(()=>new Set),[ek,ej]=(0,a.useState)(null),[eS,eN]=(0,a.useState)(null),[eT,eI]=(0,a.useState)({version:1,projects:[]}),[eM,eR]=(0,a.useState)(!1),[eE,eL]=(0,a.useState)(!1),[e$,eP]=(0,a.useState)(!1),[eA,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),tn=(0,a.useRef)(null),tr=(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(es);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(eo);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{eR(!0)}},[]);(0,a.useEffect)(()=>{tj()},[tj,c]),(0,a.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(el)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await ef(n.map(e=>({key:$(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(el)}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 ef(e),await tj()}finally{ti.current=!1,eO(!1)}},[tj]);(0,a.useEffect)(()=>{eA&&tr.current?.select()},[eA]);let tC=(0,a.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();_(r.sessions),tw.current||tc(new Set(r.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 n=new Set(t);return n.delete(e),n}),tf(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tx(t=>t&&L(t,[e])),d?.(e),tC()},[tC,d]),[tT,tI]=(0,a.useState)(null),[tM,tR]=(0,a.useState)(!1),[tE,tL]=(0,a.useState)(null),t$=(0,a.useCallback)(()=>{tM||(tI(null),tL(null))},[tM]),tP=(0,a.useCallback)(async e=>{tR(!0),tL(null);let t=[],n=[],r=[];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){n.push(a.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(a.id)}catch{r.push(a.name?.trim()||a.id.slice(0,8))}if(n.length>0&&(tw.current=!0,tc(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(th(n),tf(n),tx(e=>e&&L(e,t)),t))d?.(e)}(await tC(),tR(!1),r.length>0)?tL(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tI(null)},[tC,d,b]),[tA,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{en(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=>{en(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(es):window.localStorage.setItem(es,JSON.stringify([...tp]))}catch{}},[tp]),(0,a.useEffect)(()=>{try{0===tm.size?window.localStorage.removeItem(eo):window.localStorage.setItem(eo,JSON.stringify([...tm]))}catch{}},[tm]),(0,a.useEffect)(()=>{if(tg)try{var e,t,n;let r,a,i=window.localStorage;i.setItem(N,(e=i.getItem(N),t=Date.now(),a=(r=Object.entries((n=I(tg,T(e,t))).opened)).length>500?r.sort((e,t)=>t[1]-e[1]).slice(0,500):r,JSON.stringify({since:n.since,opened:Object.fromEntries(a)})))}catch{}},[tg]);let tO=(0,a.useCallback)(e=>{tf(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,a.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},a=async()=>{if(e||"visible"!==document.visibilityState)return;let i=new AbortController;n?.abort(),n=i;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:i.signal});if(!t.ok)return;let r=await t.json();if(e||n!==i)return;tw.current=!0,tc(new Set(r.runningSessionIds??[])),tu(new Set(r.waitingSessionIds??[]))}catch{}finally{n===i&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void a(),2500))}},i=()=>{"visible"===document.visibilityState?a():(r(),n?.abort(),n=null)};return a(),document.addEventListener("visibilitychange",i),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",i)}},[]),(0,a.useEffect)(()=>{let t=ty.current,n=[...t].filter(t=>!tl.has(t)&&t!==e),r=[...tl].filter(e=>!t.has(e));(n.length>0||r.length>0)&&th(e=>{let t=new Set(e);return tl.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let a=r.some(e=>!F.some(t=>t.id===e));(n.length>0||a)&&tC(!1,!0),n.length>0&&h?.(),ty.current=tl},[tl,e,F,tC,h]),(0,a.useEffect)(()=>{e&&th(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[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&&R(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),n(e,!0);return}l?.()}if(!eM)return;let e=new Map(eT.projects.map(e=>[e.key,e])),t=A(F.length>0?P(F):[],eT.projects).filter(t=>!e.get($(t))?.hidden);t.length>0&&V(t[0])}},[F,q,s,o,n,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})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eG(n.error??b("workspace.unable"));let r=n.cwd??t,a=$(r),i=eT.projects.find(e=>e.key===a);if(i?.hidden===!0)try{await tS([{key:a,path:r,hidden:!1}])}catch{}V(r),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})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e6(n.error??`HTTP ${t.status}`);e2(!1),e4(""),e0(!1),eX(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),V(n.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 n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eY.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void te(e);e6(r.error??`HTTP ${n.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(""),ej(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tQ=(0,a.useCallback)(e=>{e.cwd&&V(e.cwd),n(e)},[n]),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=>{ev(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),t3=tB(q),t7=null===t3?null:$(t3),t9=(0,a.useMemo)(()=>new Map(eT.projects.map(e=>[e.key,e])),[eT.projects]),ne=P(W);if(null!==t3){let e=$(t3);ne.some(t=>$(t)===e)||ne.unshift(t3)}let nt=A(ne,eT.projects),nn=nt.filter(e=>eE||!t9.get($(e))?.hidden),nr=nt.some(e=>t9.get($(e))?.hidden),na=()=>{eN(null),e0(!1),e2(!1),e4(""),e6(null),te(null),eB("")},ni=async(e,t)=>{na();try{await tS([{key:$(e),path:e,hidden:t}]),t&&t7&&t7===$(e)&&V(null),t||nt.some(t=>$(t)!==$(e)&&t9.get($(t))?.hidden)||eL(!1)}catch{}},ns=async e=>{if(ta.current){ta.current=!1,eF(null);return}let t=e_.trim();if(t===(t9.get($(e))?.alias??""))return void eF(null);eH(null);try{await tS([{key:$(e),path:e,alias:t||null}]),eF(null)}catch{eH(b("sidebar.projectUpdateFailed"))}},no=async(e,t)=>{if(X)return;let n=nn.indexOf(e),r=n+t;if(n<0||r<0||r>=nn.length)return;let a=new Set(nn),i=nt.map((e,t)=>a.has(e)?t:-1).filter(e=>e>=0),s=[...nt],o=i[n],l=i[r];[s[o],s[l]]=[s[l],s[o]],na();try{await tS(s.map((e,t)=>({key:$(e),path:e,order:t})))}catch{}},nl=new Map;for(let e of W){let t=e.projectRoot??e.cwd;if(!t)continue;let n=$(t),r=nl.get(n);r?r.push(e):nl.set(n,[e])}let nc=(0,a.useMemo)(()=>{let e=new Map;for(let t of W){let n=t.projectRoot??t.cwd;if(!n)continue;let r=$(n),a=e.get(r);a||(a={running:0,unread:0},e.set(r,a)),tl.has(t.id)&&a.running++,tp.has(t.id)&&a.unread++}return e},[W,tl,tp]),nd=X.trim().toLowerCase(),nu=X.length>0,np=nn.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=$(e),r=t9.get(n),a=r?.alias??t,i=(nl.get(n)??[]).slice().sort((e,t)=>{let n=Number(tm.has(t.id))-Number(tm.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!nd)return[{project:e,key:n,name:a,sessions:i,hidden:r?.hidden===!0}];let s=a.toLowerCase().includes(nd)||t.toLowerCase().includes(nd),o=i.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(nd));return s||0!==o.length?[{project:e,key:n,name:a,sessions:s?i:o,hidden:r?.hidden===!0}]:[]}),nh=[],nm=[];for(let e of np){let t=e.key===t7||(nc.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?nm.push(e):nh.push(e)}let nf={running:0,unread:0};for(let e of nm){let t=nc.get(e.key);t&&(nf.running+=t.running,nf.unread+=t.unread)}let ng=nu||e$,nx=[...nh.map(e=>({kind:"project",group:e})),...nm.length>0?[{kind:"temporary"}]:[],...ng?nm.map(e=>({kind:"project",group:e})):[]],nv=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nx.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nb=(0,a.useMemo)(()=>tg?W.filter(e=>(function(e,t,n,r=E){if(e.transient||e.trial)return!1;if(r.has(e.id))return!0;if(t.has(e.id))return!1;let a=M(e);return null!==a&&a>(n.opened[e.id]??n.since)})(e,tl,tg,td)):[],[tg,tl,W,td]),ny=tv&&null!==tg,[nw,nk]=(0,a.useState)(null),nj=(0,a.useMemo)(()=>(function(e,t,n,r,a="Priority",i=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),c=l.filter(e=>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 n=new Date(e.modified);if(p>=o)continue;p+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),a=u.get(r);a?a.push(e):u.set(r,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:a,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,n){let[r,a,i]=e.split("-").map(Number),s=new Date(r,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(n,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:u.get(e)??[]});return h})(ny?W.filter(e=>e.id===nw&&!tl.has(e.id)||nb.includes(e)):W,tl,new Date,y,b("navigator.priority"),tm,b("sidebar.pinned"),ny?1/0:void 0),[nw,y,tm,nb,ny,tl,W,b]),nS=(0,a.useCallback)(e=>{nk(e.id),tQ(e)},[tQ]),nC=!!(eY?.isGit&&eY.isTopLevel&&q&&t3===eY.projectRoot),nN=eY?.worktrees.find(e=>e.path===q)??eY?.worktrees.find(e=>e.isMain),nT=(eY?.worktrees.length??0)>=8,nI=nT&&eU.trim()?(eY?.worktrees??[]).filter(e=>(e.branch??ed(e.path,K)).toLowerCase().includes(eU.trim().toLowerCase())):eY?.worktrees??[],nM=(()=>{if(!tT)return[];let e="project"===tT.kind?nl.get($(tT.project))??[]:nj.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nR=nM.filter(e=>!tl.has(e.id)),nE=e=>{let t=new Set;for(let n of e)n.transient||tl.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nL=void 0!==m&&f;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eq&&(0,r.jsx)(Z?Q:J,{busy:eJ,error:eK,onCancel:()=>{eV(!1),eG(null)},onSelect:e=>void tJ(e)}),tT&&(0,r.jsx)(ex,{scope:tT,eligible:nR.length,runningExcluded:nM.length-nR.length,busy:tM,error:tE,onCancel:t$,onConfirm:()=>void tP(nR)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(em,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${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,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),Z&&!nL&&(0,r.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,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),n=!nL&&et===e;return(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tW(e),nL&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":nL,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!nL),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:"var(--radius-control)",background:nL?"var(--bg-selected)":"transparent",color:nL?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nL?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!nL&&"projects"===et&&(0,r.jsx)("button",{type:"button",onClick:()=>eL(e=>!e),disabled:!nr,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eE,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eE?"var(--bg-selected)":"transparent",color:eE?"var(--accent)":"var(--text-dim)",cursor:nr?"pointer":"default",opacity:nr?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eE&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nL&&"projects"===et&&(0,r.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,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),nL&&m,!nL&&"projects"===et&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value: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}})]}),!nL&&"projects"===et&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(O||!eM)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),eD&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!O&&eM&&!H&&0===np.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nd?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!O&&eM&&!H&&nx.map(t=>{let n,a,i;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":ng,title:b("sidebar.temporaryProjects"),onClick:()=>eP(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:ng?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nm.length}),eC(nf,b)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t7,p=nv.has(l.toLowerCase())&&ed((a=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,a),K)||null,h=!eh.has(s)&&!nd,m=er.has(s),f=eA===s,g=nn.indexOf(s),x=eW||nu||g<=0,v=eW||nu||g>=nn.length-1,y=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let a=function(e){let r=n.get(e),a=new Set;for(;r&&!a.has(r);){if(a.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);a?t.get(a).children.push(e):r.push(e)}let a=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>a(e.children))};return a(r),r}(m?c:c.slice(0,5)),k=c.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:eS===s?tt:void 0,onMouseEnter:()=>ej(s),onMouseLeave:()=>ej(e=>e===s&&eS!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:"var(--radius-control)",background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>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,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:tr,value:e_,onChange:e=>ez(e.target.value),onBlur:()=>void ns(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,r.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,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),eC(nc.get(o),b)]}),(0,r.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:()=>ej(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eN(eS===s?null:s),e0(!1),e2(!1),e6(null),u||V(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":eS===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eS===s?"var(--bg-selected)":"transparent",color:u&&nN&&!nN.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ek===s||eS===s?1:0,pointerEvents:w||ek===s||eS===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ej(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(ep,{open:eS===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:[nC&&eY&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>e0(e=>!e),title:nN?b("sidebar.switchWorktreeTitle",{path:nN.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,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(ep,{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:[nT&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.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,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[nI.map(e=>{let t=e.path===q||e.isMain&&!eY.worktrees.some(e=>e.path===q);return e9===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void 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,r.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,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(eu,{text:e.branch??ed(e.path,K),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void 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,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nT&&0===nI.length&&eU.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e1?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:tn,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,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.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,r.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,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e2(!0),e6(null),setTimeout(()=>tn.current?.focus(),0)},title:b("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:b("sidebar.newWorktree")})]}),e5&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e5})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eW,onClick:()=>{let e;return e=t9.get($(s))?.alias??"",void(ta.current=!1,eH(null),ez(e),eF(s),na())},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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),b(t9.get($(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:nu?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void no(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:nu?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void no(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eW,onClick:()=>void ni(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,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(i=0===nE(nl.get(o)??[])||tM,(0,r.jsxs)("button",{type:"button",disabled:i,onClick:()=>{na(),tL(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,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(ew,{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,r.jsx)("button",{type:"button",onClick:()=>{ea(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)})]}),!nL&&(0,r.jsx)(ey,{refreshKey:tA,selectedSessionId:e,onSelectSession:tQ,onRestored:t_}),!nL&&"priority"===et&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[O&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),H&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:H}),!O&&!H&&(x=nE(nj.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:t1,onClick:()=>void t5(),title:b("sidebar.newScratchSessionTitle"),style:ec(t1,w),children:b("sidebar.newScratchSession")}),nj.length>0&&!ny&&(0,r.jsx)("button",{type:"button",disabled:0===x||tM,onClick:()=>{tL(null),tI({kind:"priority"})},style:ec(0===x||tM,w),children:b("sidebar.clearPriorityList")})]})),!O&&!H&&tg&&(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,r.jsxs)("button",{type:"button","aria-pressed":ny,"aria-label":b("navigator.resultsToCheckCount",{count:nb.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{nk(null),tb(e=>!e)},style:{...ec(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ny?"var(--border-strong)":"var(--border)",background:ny?"var(--bg-selected)":"transparent",color:ny||nb.length>0?"var(--text)":"var(--text-muted)",fontWeight:ny?600:500,whiteSpace:"nowrap"},children:[b("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:nb.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nb.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nb.length})]}),nb.some(e=>!td.has(e.id))&&(0,r.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{nk(null),tx(e=>e&&function(e,t,n){let r=e;for(let e of t)r=R(r,e,n);return r}(e,nb,Date.now()))},style:ec(!1,w),children:b("navigator.acknowledgeResults")})]}),t8&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:t8}),!O&&!H&&0===nj.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ny?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!O&&!H&&nj.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(eb,{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:ny?nS:tQ,onTogglePin:tO},t.id))]},t.key))]})]})}function ex({scope:e,eligible:t,runningExcluded:n,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,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let a=n[0],i=n[n.length-1];t.shiftKey&&(r===a||!e.contains(r))?(t.preventDefault(),i.focus()):t.shiftKey||r!==i&&e.contains(r)||(t.preventDefault(),a.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{i||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled: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,r.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 ev({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function eb({session:e,selected:t,running:n,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,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>o(e),title:`${d}
|
|
2
|
+
${e.cwd}
|
|
3
|
+
${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:d}),a&&(0,r.jsx)(ek,{}),n&&!a&&(0,r.jsx)(ej,{}),!n&&i&&(0,r.jsx)(eS,{})]}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:u})]}),(0,r.jsx)("button",{type:"button","aria-pressed":s,"aria-label":c(s?"sidebar.unpin":"sidebar.pin"),title:c(s?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:s?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(ev,{filled:s})})]})}function ey({refreshKey:e,selectedSessionId:t,onSelectSession:n,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 n=await t.json();e||d(n.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,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:o?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),s("sidebar.archived")," (",c.length,")"]}),o&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===c.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:s("sidebar.noArchivedSessions")}),c.map(e=>{let a=_(e.firstMessage)??e.firstMessage,i=e.name||a.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function ew({node:e,selectedSessionId:t,runningSessionIds:n,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,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(eN,{session:e.session,isSelected:e.session.id===t,isRunning:n.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,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ew,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:i,pinnedSessionIds:s,onSelectSession:o,onTogglePinnedSession:d,onRenamed:l,onSessionDeleted:c,onSessionArchived:u,depth:p+1},e.session.id))})]})}function ek(){let{t:e}=(0,z.s)();return(0,r.jsx)("span",{title:e("sidebar.waitingForAnswerHint"),style:{flexShrink:0,padding:"0 6px",borderRadius:"var(--radius-surface)",border:"1px solid var(--warning-line)",background:"var(--warning-soft)",color:"var(--warning)",fontSize:10.5,fontWeight:600,lineHeight:"16px",whiteSpace:"nowrap"},children:e("sidebar.waitingForAnswer")})}function ej(){let{t:e}=(0,z.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function eS(){let{t:e}=(0,z.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function eC(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,r.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function eN({session:e,isSelected:t,isRunning:n,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),R=(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]),E=(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]),L=(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]),$=(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]),P=(0,a.useCallback)(e=>{e.stopPropagation(),e.shiftKey?L():S(!0)},[L]),A=(0,a.useCallback)(e=>{e.stopPropagation(),L()},[L]),F=(0,a.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),W=(0,a.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${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,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:A,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick: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,r.jsx)("input",{ref:T,value:w,onChange:e=>k(e.target.value),onBlur:E,onKeyDown:e=>{"Enter"===e.key&&E(),"Escape"===e.key&&y(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[p>0&&(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),o()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(ej,{}),!n&&i&&(0,r.jsx)(eS,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{className:"navigator-session-action",onClick:e=>{e.stopPropagation(),l?.()},title:g(s?"sidebar.unpin":"sidebar.pin"),"aria-label":g(s?"sidebar.unpin":"sidebar.pin"),"aria-pressed":s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:s?"var(--bg-selected)":"transparent",border:"none",borderRadius:"var(--radius-control)",color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(ev,{filled:s})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:R,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:$,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:P,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let eT=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eI=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eM=/\x1B\[([0-9;]*)m/g,eR=/\x1B_pi:c\x07/g,eE=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eL=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function e$(e){return e.replace(eR,"").replace(eT,"")}function eP(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eI);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let a=String.fromCodePoint(r);t.push({start:n,end:n+a.length,char:a}),n+=a.length}return t}function eA(e,t){let n=eP(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eF(e){return eP(e)[0]?.char}function e_(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(eR,""),a=e$(e).trimEnd();if(t.test(a))continue;let i=e,s=eF(i);("│"===s||"┃"===s)&&" "===eF(i=eA(i,0))&&(i=eA(i,0));let o=function(e){let t=eP(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(i),l=o>=0?eP(i)[o]?.char:void 0;("│"===l||"┃"===l)&&(i=eA(i,o)),n.push(function(e){let t=e;for(;;){let e=eP(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(i))}for(;n.length>0&&""===e$(n[0]).trim();)n.shift();for(;n.length>0&&""===e$(n[n.length-1]).trim();)n.pop();return n.length?n:e}function ez(e){let t,n=[],r={},a=0;for(eM.lastIndex=0;null!==(t=eM.exec(e));)t.index>a&&n.push({text:e.slice(a,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=eE[r-30];else if(r>=90&&r<=97)n.color=eL[r-90];else if(r>=40&&r<=47)n.backgroundColor=eE[r-40];else if(r>=100&&r<=107)n.backgroundColor=eL[r-100];else if((38===r||48===r)&&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===r?n.color=`rgb(${a}, ${i}, ${s})`:n.backgroundColor=`rgb(${a}, ${i}, ${s})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let a=function(e){if(e>=0&&e<8)return eE[e];if(e>=8&&e<16)return eL[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),a=e=>0===e?0:55+40*e;return`rgb(${a(n)}, ${a(r)}, ${a(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);a&&(38===r?n.color=a:n.backgroundColor=a),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),a=t.index+t[0].length;return a<e.length&&n.push({text:e.slice(a),style:r}),n}let eW={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:""},eO={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eD={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"},eH={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 eU(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eB(e){return null!==(eD[eU(e)]??null)}function eq(e){let t;return null!==("pdf"===(t=eU(e))||"docx"===t?t:null)}function eV(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eK(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 eG(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eJ(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eK(e,t))}(e,t)){let e="image"===r.type||"text"===r.type&&r.text.trim().length>0?"answer":"process",t=n[n.length-1];t?.kind===e?t.blocks.push(r):n.push({kind:e,blocks:[r]})}return n}function eZ(e){return e.filter(e=>"toolCall"===e.type).length}let eY=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function eX(e){let t=0,n=0;for(let r of e)eY.test(r)?t++:n++;return t+n/4}function eQ(e){return"text"===e.type?e.text:"thinking"===e.type?e.thinking:"toolCall"===e.type?JSON.stringify(e.input??{})??"":null}function e0(e,t){if(!e)return eX(t);let n=Math.min(e.text.length,t.length),r=0;for(;r<n&&e.text.charCodeAt(r)===t.charCodeAt(r);)r++;let a=r>0?t.charCodeAt(r-1):0;return a>=55296&&a<=56319&&r--,e.tokens-eX(e.text.slice(r))+eX(t.slice(r))}function e1(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}let e2=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function e8(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,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 n=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===n.path;if("eval"===e.toolName){let e;return e=t.content?.at(-1),e?.type==="text"&&e2.test(e.text)}return"read"===e.toolName&&"string"==typeof n.path&&eB(n.path)}(i,t.get(i.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:i.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let e4=new Map,e5=new Map,e6="[한국어 번역]\n";function e3(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function e7(e){if("custom"!==e.role||"korean-reply-translation"!==e.customType)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let n="sourceTimestamp"in t&&"number"==typeof t.sourceTimestamp?t.sourceTimestamp:void 0,r="sourceHash"in t&&"string"==typeof t.sourceHash?t.sourceHash:void 0;return void 0===n&&void 0===r?null:{sourceTimestamp:n,sourceHash:r}}let e9="command",te="autolearn-saved";function tt(e){return"custom"===e.role&&(e.customType===e9||e.customType===te&&!1!==e.display)}function tn(e,t){let n=e[t];if(n?.role!=="custom"||"user-input-translation"!==n.customType)return -1;for(let n=t-1;n>=0;n--)if("user"===e[n].role)return n;return -1}let tr="local-command:";function ta(e){return e?.startsWith(tr)===!0}function ti(e,t,n){let r=new Set(n.map(e=>e.message)),a=[],i=[];for(let n=0;n<e.length;n++){let s=n<t.length;!(r.has(e[n])||s&&ta(t[n]))&&(a.push(e[n]),s&&i.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=i.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<a.length;){let e=a[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}a.splice(t,0,e.message),t<=i.length&&i.splice(t,0,e.entryId)}return{messages:a,entryIds:i}}function ts(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let to={create:!0,update:!0};function tl(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function tc(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let n of e)n&&"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&"string"==typeof n.text&&t.push(n.text);return t.join("\n")}function td(e,t){if(0===e.length)return -1;if(!t)return 0;let n=-1;for(let r=0;r<e.length;r++){let a=e[r];if(a.item===t.item){if(a.k===t.k)return r;n=r}}return -1===n?0:n}function tu(e){try{return decodeURIComponent(e)}catch{return e}}function tp(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function th(e){let t=tp(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),a=t.startsWith("/")&&!n&&!r,i=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){i.length>0&&".."!==i[i.length-1]?i.pop():a||n||r||i.push(e);continue}i.push(e)}let s=i.join("/");return n?s:r?`//${s}`:a?`/${s}`:s}function tm(e,t,n=t){let r,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=tu(l),p=u.startsWith("\\\\"),h=tp(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=tu(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(c=h,d="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(c=`${tp(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let f=th(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&n&&(r=th(f).replace(/\/+$/,""),a=th(n).replace(/\/+$/,""),s=(i=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(a))?r.toLowerCase():r,!(s===(o=i?a.toLowerCase():a)||s.startsWith(`${o}/`)))?null:f}function tf(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),a=e=>r?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)n=i;else if(i.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${i}`:i}else{if(!s)return null;n=`${s}/${i}`}return th(n)}function tg(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function tx(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 tv(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tb(e,t){if(!e||"object"!=typeof e||"delete"===e.op&&!t)return null;let n=e.path??e.resolvedPath;return"string"==typeof n&&n.length>0?n:null}function ty(e,t,n=!1){let r=t.details,a=tv(e);if(a)return!n&&r&&"object"==typeof r&&"delete"===r.op?[]:[a];if(!r||"object"!=typeof r)return[];if(Array.isArray(r.perFileResults))return r.perFileResults.map(e=>tb(e,n)).filter(e=>null!==e);let i=tb(r,n);return i?[i]:[]}function tw(e,t){let n=tv(e);return(t?ty(e,t,!0):n?[n]:[]).filter(tN)}function tk(e,t,n){let r=tw(e,t);return r.length>0&&r.every(e=>tC(e,n))}let tj=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])),tS=[/^\/(?: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 tC(e,t){let n=tf(e,t),r=t?tf(t)?.replace(/\/+$/,""):void 0,a=n??e.replace(/\\/g,"/"),i=/^(?:[a-zA-Z]:\/|\/\/|\/mnt\/[a-zA-Z](?:\/|$))/.test(a)||void 0!==r&&/^(?:[a-zA-Z]:\/|\/\/)/.test(r),s=e=>i?e.toLowerCase():e,o=null===n||void 0!==r&&(s(n)===s(r)||s(n).startsWith(`${s(r)}/`));return!!function(e,t){let n=(e,n)=>void 0!==e&&(t?e.toLowerCase()===n:e===n),r=e.findIndex(e=>n(e,".omp"));if(r<0||r===e.length-1)return!1;let a=e[r+1];if(n(a,"agent")||n(a,"wt")||n(a,"profiles")&&n(e[r+3],"agent"))return!1;let i=tj.get(a.toLowerCase());return!(void 0!==i&&(t||i===a))}((null!==n&&o&&void 0!==r?n.slice(r.length):a).split("/").filter(e=>""!==e&&"."!==e),i)||!o&&tS.some(e=>e.test(a))}function tN(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tT(e,t,n){let r=new Set,a=[];for(let s of e){var i;if("toolCall"!==s.type||!(tg(i=s.toolName)||tx(i)))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of ty(s.input,e)){if(!tN(t))continue;let e=tf(t,n);!(!e||tC(t,n))&&(r.has(e)||(r.add(e),a.push({filePath:e})))}}return a}function tI(e){let t=[];for(let n of e){if(!n||"object"!=typeof n||!("name"in n)||!("tasks"in n))return{phases:t,malformed:!0};let{name:e,tasks:r}=n;if("string"!=typeof e||!Array.isArray(r))return{phases:t,malformed:!0};let a=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;if("string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n)return[];let r="blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0,a="dependsOn"in e&&Array.isArray(e.dependsOn)?e.dependsOn.filter(e=>"string"==typeof e):[];return[{content:t,status:n,blocker:r,...a.length>0?{dependsOn:a}:{}}]}):[];if(a.length!==r.length)return{phases:t,malformed:!0};a.length>0&&t.push({name:e,tasks:a})}return{phases:t,malformed:!1}}function tM(e){if(!Array.isArray(e))return null;let{phases:t,malformed:n}=tI(e);return n?null:t}function tR(e,t){var n;let r;if(t){let e=t.details,n=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(n))return{kind:"unknown"};let{phases:r,malformed:a}=tI(n);return a?{kind:"unknown"}:{kind:"authoritative",phases:r}}let a=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return 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 tL(e,t,n=null,r=null){return n||(function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n],a=r.trackerTodos??[];for(let e=a.length-1;e>=0;e-=1){let t=tM(a[e]);if(t)return t}if("assistant"!==r.role)continue;let i=r.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let n=i[e];if("toolCall"!==n.type||!tE(n.toolName))continue;let r=tR(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function t$(e,t){if(!e.dependsOn?.length)return[];let n=new Set(t.flatMap(e=>e.tasks.filter(e=>"completed"===e.status).map(e=>e.content)));return e.dependsOn.filter(e=>!n.has(e))}function tP(e){let t=0,n=0,r=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&&(n+=1,t$(o,e).length>0?i||(i={phase:s,task:o}):"in_progress"===o.status?r||(r={phase:s,task:o}):"blocked"===o.status?i||(i={phase:s,task:o}):a||(a={phase:s,task:o}))}let s=r??a??i,o=t+n;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:n,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}function tA(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tF(e){return tA(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function t_(e){let t=tA(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tz(e,t){if(!t)return e;let n=tA(e),r=tA(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var tW=n(65063),tO=n(7644),tD=n(32316),tH=n(88374),tU=n(63280),tB=n(94764),tq=n(63835),tV=n(54152),tK=n(84678),tG=n(98164);let tJ={...tB.j,attributes:{...tB.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...tB.j.strip||[],"iframe","object","style","form"]};function tZ(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],a=null,i=0,s=null,o=new Map;for(let e=0;e<n.length;e++){var l;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;a?e===a.marker&&n>=a.size&&(a=null):a={marker:e,size:n},i=0,r.push(t);continue}if(a){r.push(t);continue}let d=t.match(/<(code|pre|script|style)\b/i);if(d){let e=d[1].toLowerCase(),n=t.slice((d.index??0)+d[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(s=e),i=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){i=0,r.push(t);continue}if(i||t.includes("`")){i=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let a=r-t;0===n?n=a:a===n&&(n=0),t=r}return n}(t,i),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>tX(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],a=m[2].trimEnd();if(a&&!a.includes("$$")){let i=tY(n,e+1,t,o);if(i){r.push(`${t}$$`,`${t}${a}`);for(let a=e+1;a<i.index;a++)r.push(tX(n[a],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],a=tY(n,e+1,t,o);if(a&&(a.glued||""!==t)){r.push(`${t}$$`);for(let i=e+1;i<a.index;i++)r.push(tX(n[i],t));a.content&&r.push(`${t}${a.content}`),r.push(`${t}$$`),e=a.index;continue}}r.push((l=t,/^\s{0,3}\[[^\]]+\]:/.test(l)||/]\s*\(/.test(l)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(l)||/\b(?:https?|file|mailto):/i.test(l)||/\b[A-Za-z]:\\/.test(l)?l:l.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function tY(e,t,n,r){let a=r.get(n);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=n)?/^ {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 r.set(n,a),null;let c=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==c)return{index:a,content:c,glued:!0}}return r.set(n,e.length),null}function tX(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let tQ={singleTilde:!1},t0=[[tV.A,["yaml"]],[tK.A,tQ],tG.A],t1=[[tV.A,["yaml"]],[tK.A,tQ],tG.A],t2=[tU.A,[tq.A,tJ],[tH.A,{throwOnError:!1,strict:!1}]],t8=[tU.A,[tq.A,tJ],[tH.A,{throwOnError:!1,strict:!1}]],t4="pi-theme",t5=["light","dark","auto"],t6={preference:"auto",theme:"light"},t3="omp-theme",t7=null,t9=0,ne=new Set,nt=null,nn=!1;function nr(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function na(e){return"auto"===e?nr():e}let ni="--omp-md-";function ns(e){let t=document.documentElement,n=t7?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let n=t.style.item(e);n.startsWith("--")&&!n.startsWith(ni)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(ni)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(t3,e)}catch{}}function no(){if(nt)return nt;let e=function(){try{let e=localStorage.getItem(t4);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(t3);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=na(e);return ns(t),nt={preference:e,theme:t}}function nl(e,t,n){if(ns(t),n)try{localStorage.setItem(t4,e)}catch{}nt={preference:e,theme:t},ne.forEach(e=>e())}function nc(){let e=no();if("auto"!==e.preference)return;let t=nr();t!==e.theme&&nl("auto",t,!1)}function nd(e){return ne.add(e),no(),nn||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",nc),window.addEventListener("focus",nc),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&nc()}),nn=!0),nc(),()=>{ne.delete(e)}}function nu(){return no()}function np(){return t6}async function nh(e){let t=++t9,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/theme${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Theme request failed (${r.status})`);let a=await r.json();if(t===t9){t7=a;try{localStorage.setItem("omp-theme-config",JSON.stringify(t7))}catch{}ns(no().theme)}}function nm(e){let t=(0,a.useSyncExternalStore)(nd,nu,np);(0,a.useEffect)(()=>{e?.syncWithOmp&&nh(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,a.useCallback)((e,t)=>{let n=na(e),r=()=>{nl(e,n,!0)},a=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||a)return void r();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(r).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(()=>{})},[]),r=(0,a.useCallback)(e=>{var t;let r;n((t=no().preference,r=t5.indexOf(t),t5[(r+1)%t5.length]),e)},[n]),i=(0,a.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:i,isDark:"dark"===t.theme}}function nf(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 ng={...tO.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tO.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function nx({code:e,isStreaming:t}){let{isDark:i}=nm(),{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(!0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1),h=`${i?"dark":"light"}
|
|
4
|
+
${e}`,m=o&&!t;(0,a.useEffect)(()=>{if(!m)return;let t=!1;return d({key:h,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328)),a=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${a}`,e),await document.fonts.ready,t)return;if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:i?"dark":"default",fontFamily:a}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let s="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await r.render(s,e);t||d({key:h,status:"ready",svg:o.svg})})().catch(()=>{t||d({key:h,status:"error"})}),()=>{t=!0}},[e,h,i,m]);let f=(0,a.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),disabled:t,title:t?s("i18n.previewAfterStreaming"):m?s("i18n.showMermaidSource"):s("i18n.previewMermaid"),className:["markdown-code-action",m?"is-active":""].filter(Boolean).join(" "),children:m?s("i18n.source"):s("i18n.preview")}),[t,m,s]);if(!m)return(0,r.jsx)(nb,{code:e,lang:"mermaid",headerAction:f,isStreaming:t});let g=c?.key===h&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==h||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!u&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openMermaidViewer"),"aria-label":s("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),u&&(0,r.jsx)(nv,{svg:c.svg,onClose:()=>p(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),f]}),g]})}function nv({svg:e,onClose:t}){let{t:n}=(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,r.jsx)("dialog",{ref:i,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:s>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>o(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let nb=(0,a.memo)(function({code:e,lang:t,headerAction:n,isStreaming:i}){let{isDark:s}=nm(),{t:o}=(0,z.s)(),[l,c]=(0,a.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{nf(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),i?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(tW.A,{language:t||"text",style:s?tO.xJ:ng,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 ny({children:e,className:t,isStreaming:n,cwd:i,onOpenFile:s}){let o=(0,a.useMemo)(()=>tZ(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,r.jsx)(nx,{code:s.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(nb,{code:s.replace(/\n$/,""),lang:i,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...a,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let a=s?tm(e,i):null;return a&&s?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(a))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let a="string"==typeof e?tm(e,i):null,s=a?`/api/files/${tF(a)}?type=read`:e;return(0,r.jsx)("img",{src:s,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[i,n,s]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(tD.oz,{remarkPlugins:t0,rehypePlugins:t2,components:l,children:o})})}function nw(e){let[t,n]=(0,a.useState)(()=>Date.now());return(0,a.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}let nk=new Map,nj=new Set;function nS(){nj.forEach(e=>e())}function nC(e){return nj.add(e),()=>{nj.delete(e)}}function nN(e,t){return e&&t?`${e}\u0000${t}`:null}function nT(e){let t=!1;for(let n of e)t=nk.delete(n)||t;t&&nS()}var nI=n(54265);let nM=(0,a.createContext)(null);function nR(e,t,n){return Math.min(n,Math.max(t,e))}function nE(e,t,n){let r=t.width>0?n.width/t.width:0,a=t.height>0?n.height/t.height:0;return{x:nR((e.x-t.left)*r,0,n.width),y:nR((e.y-t.top)*a,0,n.height)}}function nL(e){let t=nR(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let n$="#e5191f",nP="#ffffff";function nA(e){let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.toBlob(e=>e?n(e):r(Error("canvas encode failed")),"image/png"),t}function nF(e,t){let n=document.createElement("canvas");n.width=e,n.height=t;let r=n.getContext("2d");if(!r)throw Error("canvas 2d unavailable");return[n,r]}async function n_(e,t){let n=await createImageBitmap(e);try{let e={width:n.width,height:n.height},{inner:r,outer:a}=nL(e),i=Math.max(14,7*nL(e).inner),[s,o]=nF(e.width,e.height);o.drawImage(n,0,0),t.forEach((t,n)=>{let s=function(e,t){let{inner:n,outer:r}=nL(t),a=(n,r)=>{let a=nR(e.x-n,r,t.width-r),i=nR(e.y-n,r,t.height-r),s=nR(e.x+e.w+n,r,t.width-r);return{x:a,y:i,w:Math.max(0,s-a),h:Math.max(0,nR(e.y+e.h+n,r,t.height-r)-i)}};return{inner:a(n/2,n/2),outer:a(n+r/2,r/2)}}(t,e);o.lineJoin="miter",o.strokeStyle=nP,o.lineWidth=a,o.strokeRect(s.outer.x,s.outer.y,s.outer.w,s.outer.h),o.strokeStyle=n$,o.lineWidth=r,o.strokeRect(s.inner.x,s.inner.y,s.inner.w,s.inner.h);let l=String(n+1);o.font=`700 ${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-r),e.width-d),h=t.y-r-u,m=h>=0?h:Math.min(t.y,e.height-u);o.fillStyle=nP,o.fillRect(p-1,m-1,d+2,u+2),o.fillStyle=n$,o.fillRect(p,m,d,u),o.fillStyle=nP,o.textBaseline="middle",o.textAlign="center",o.fillText(l,p+d/2,m+u/2)});let l=await Promise.all(t.map(t=>{let r=function(e,t,n=.12){let r=Math.round(e.w*n),a=Math.round(e.h*n),i=nR(e.x-r,0,t.width),s=nR(e.y-a,0,t.height),o=nR(e.x+e.w+r,0,t.width);return{x:i,y:s,w:o-i,h:nR(e.y+e.h+a,0,t.height)-s}}(t,e),[a,i]=nF(r.w,r.h);return i.drawImage(n,r.x,r.y,r.w,r.h,0,0,r.w,r.h),nA(a)}));return{marked:await nA(s),crops:l}}finally{n.close()}}function nz({src:e,regions:t,max:n,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,n=u.current;return t&&n&&c?function(e,t,n,r){let a=nR(Math.min(e.x,t.x),n.left,n.left+n.width),i=nR(Math.max(e.x,t.x),n.left,n.left+n.width),s=nR(Math.min(e.y,t.y),n.top,n.top+n.height),o=nR(Math.max(e.y,t.y),n.top,n.top+n.height);if(i-a<6||o-s<6)return null;let l=nE({x:a,y:s},n,r),c=nE({x:i,y:o},n,r),d=Math.floor(l.x),u=Math.floor(l.y),p=Math.min(r.width,Math.ceil(c.x))-d,h=Math.min(r.height,Math.ceil(c.y))-u;return p>0&&h>0?{x:d,y:u,w:p,h}:null}(n.start,e,t.getBoundingClientRect(),c):null},f=(e,t)=>{if(u.current?.pointerId!==e.pointerId)return;let n=t?m({x:e.clientX,y:e.clientY}):null;u.current=null,h(null),n&&i(n)};return(0,r.jsxs)("div",{className:"tool-image-marker","data-drawing":c&&t.length<n?"true":void 0,onPointerDown:e=>{c&&!(t.length>=n)&&("mouse"!==e.pointerType||0===e.button)&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),u.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY}})},onPointerMove:e=>{u.current?.pointerId===e.pointerId&&h(m({x:e.clientX,y:e.clientY}))},onPointerUp:e=>f(e,!0),onPointerCancel:e=>f(e,!1),children:[(0,r.jsx)("img",{ref:l,className:"tool-image-full",src:e,alt:"",draggable:!1,onLoad:e=>{let t={width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight};d(t),s(t)}}),c&&t.map((e,t)=>(0,r.jsx)(nW,{region:e,natural:c,label:String(t+1),title:o(t+1)},`${t}-${e.x}-${e.y}`)),c&&p&&(0,r.jsx)(nW,{region:p,natural:c})]})}function nW({region:e,natural:t,label:n,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,r.jsx)("span",{className:"tool-image-region","data-draft":n?void 0:"true",role:n?"img":void 0,"aria-label":a,style:{left:`${i.left}%`,top:`${i.top}%`,width:`${i.width}%`,height:`${i.height}%`},children:n&&(0,r.jsx)("span",{className:"tool-image-region-number","aria-hidden":"true",children:n})})}function nO(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}function nD(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}let nH=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,nU=/(?:\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 nB(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let nq={hideThinkingBlock:!1},nV=new Set,nK=nq,nG=0;function nJ(e){return nV.add(e),()=>{nV.delete(e)}}function nZ(){return nK}function nY(){return nq}async function nX(e){let t=++nG,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/display-settings${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Display settings request failed (${r.status})`);let a=await r.json();t!==nG||a.hideThinkingBlock!==nK.hideThinkingBlock&&(nK={hideThinkingBlock:!0===a.hideThinkingBlock},nV.forEach(e=>e()))}function nQ(){return(0,a.useSyncExternalStore)(nJ,nZ,nY)}function n0(e){let t=new Date(e),n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}let n1=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","MITSU(미츠)","SHION(시온)","HIKARI(히카리)"],n2={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","MITSU(미츠)":"mitsu","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},n8=["approval","choice","done","failed","blocked","working"],n4={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},n5={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0},n6="/api/office-characters/",n3={voice:"/audio/completion/",sticker:"/stickers/"};function n7(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function n9(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(n4,e)?e:null}function re(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};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=n9(i);if(null===o)continue;let l=t+e.replace(/^\/+/,""),c=n.get(o);c?c.push(l):n.set(o,[l]),"string"==typeof s&&""!==s.trim()&&r.set(l,s.trim())}return{files:n,lines:r}}function rt(e,t=n3){let n=new Map;if("object"!=typeof e||null===e)return n;let{characters:r}=e;if(!Array.isArray(r))return n;for(let e of r){if("object"!=typeof e||null===e)continue;let{id:r,clips:a,stickers:i,captions:s}=e;if("string"!=typeof r||""===r)continue;let o=re(a,t.voice),l=re(i,t.sticker),c=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if("object"!=typeof n||null===n)continue;let{tag:e,ko:r}=n;if("string"!=typeof r||""===r.trim())continue;let a=n9(e);if(null===a)continue;let i=t.get(a);i?i.push(r.trim()):t.set(a,[r.trim()])}return t}(s),d=new Map;for(let e of n8){let t=o.files.get(e)??[],n=new Map;for(let e of t){let t=o.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:n,captions:c.get(e)??[]})}n.set(r,d)}return n}function rn(e,t,n){let r=t&&Object.hasOwn(n2,t)?n2[t]:null;return r?e.get(r)?.get(n)??null:null}function rr(e,t,n){return e.get(t)?.get(n)??null}async function ra(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return rt(await t.json())}catch{return new Map}}function ri(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),a=-1===r?e.length:e.length-1,i=Math.min(a-1,Math.max(0,Math.floor(n()*a)));return e[-1!==r&&i>=r?i+1:i]}function rs(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let n of e.content)if("text"===n.type)t.push(n.text.trim());else if("toolCall"===n.type){let e="id"in n&&"string"==typeof n.id?n.id:"";t.push(`toolCall:${n.toolCallId||e}`)}}let n="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,n,t.filter(Boolean)])}function ro(e,t,n,r){if(t&&("web6"!==t.provider||t.model!==rl))return{provider:t.provider,model:t.model,credentialId:t.credentialId};for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role)break;if("assistant"===n.role&&("web6"!==n.provider||n.model!==rl))return{provider:n.provider,model:n.model,credentialId:n.credentialId}}return{provider:n,model:r,credentialId:void 0}}let rl="ChatGPT 6PRO",rc="/api/sidecars/resource";function rd(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},n=e=>{let n=t[e];return"number"==typeof n&&Number.isFinite(n)?n:null},r=n("usedFraction");if(null!==r&&r>=1)return!0;let a=n("remainingFraction");if(null!==a&&a<=0)return!0;let i=n("used"),s=n("limit");if(null!==i&&null!==s&&i>=s)return!0;let o=n("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==i&&i>=100}let ru=[{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"}],rp={"gemini-4-argon":"HIKARI(히카리)"},rh=[{seed:3,alias:ru[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:ru[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:ru[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:ru[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:ru[2].alias,provider:"hive",model:"zai-org/glm-5.3-flash",voice:"부지런한 배달\xb7통통 튀는 보고\xb7끈질긴 재도전",summonExample:"미츠 불러와",switchExample:"미츠로 교체해"},{seed:6,alias:ru[6].alias,provider:"google-vertex",model:"gemini-4-argon",voice:"빠른 관찰\xb7톡 쏘는 한마디\xb7장난스러운 여유",summonExample:"히카리 불러와",switchExample:"히카리로 교체해"},{seed:5,alias:ru[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],rm=rh.filter(e=>null!==e.switchExample),rf={mode:"default",rosterAvailable:!1,seats:[]},rg=rf,rx=new Map,rv=new Map,rb=rh,ry=new Set,rw=null,rk=0,rj=new Map,rS=new Map,rC=null,rN=!1;function rT(e){let t="office"===e.mode?e.seats.filter(e=>!ru.some(t=>t.alias===e.alias)&&"MITSU(미츠)"!==e.seat):[];rk+=1;let n=JSON.stringify([e.mode,e.rosterAvailable,t]);if(n!==rC)for(let r of(rC=n,rg={...e,seats:t},rv=new Map([...rx=new Map(t.flatMap(e=>{let t=ru.findIndex(t=>t.alias===e.seat);return t>=0?[[t,e]]:[]}))].flatMap(([e,t])=>{let n=ru[e];return"provider"in n&&!("model"in n)?[[n.provider,{seed:e,alias:t.alias}]]:[]})),rj=new Map([...rx].flatMap(([e,t])=>{let n=ru[e];return"model"in n?[[`${n.provider}/${n.model}`,{seed:e,alias:t.alias}]]:[]})),rS=new Map(Object.entries(rp).flatMap(([e,t])=>{let n=ru.findIndex(e=>e.alias===t),r=rx.get(n);return r?[[e,{seed:n,alias:r.alias}]]:[]})),rb=0===rx.size?rh:rh.map(e=>{let t,n,r,a=rx.get(ru.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:`${r=(n=t.charCodeAt(t.length-1)-44032)>=0&&n<=11171?n%28:0,`${t}${0===r||8===r?"로":"으로"}`} 교체해`}):e}),ry))r()}function rI(){return rg}function rM(e){return ry.add(e),()=>{ry.delete(e)}}async function rR(e=fetch){let t=rk;try{let n=await e("/api/character-mode",{cache:"no-store"});if(!n.ok)return!1;let r=await n.json();if("object"!=typeof r||null===r)return!1;if(t!==rk)return!0;let{mode:a,rosterAvailable:i,seats:s}=r;return rT({mode:"office"===a?"office":"default",rosterAvailable:!0===i,seats:Array.isArray(s)?s:[]}),!0}catch{return!1}}let rE=new WeakMap;function rL(e){let t=rE.get(e);return t||(t=rt(e.manifest,{voice:n6,sticker:n6}),rE.set(e,t)),t}function r$(e){return e?rg.seats.find(t=>t.seat===e||t.alias===e)??null:null}function rP(e){return rg.seats.find(t=>t.seat===e)?.alias??e}let rA=ru.filter(e=>!("provider"in e)).length,rF=new Map(ru.flatMap((e,t)=>"provider"in e&&!("model"in e)?[[e.provider,t]]:[])),r_=new Map(ru.flatMap((e,t)=>"model"in e?[[`${e.provider}/${e.model}`,{seed:t,alias:e.alias}]]:[])),rz=new Map(Object.entries(rp).map(([e,t])=>[e,{seed:ru.findIndex(e=>e.alias===t),alias:t}])),rW=new Map([...rF].map(([e,t])=>[e,{seed:t,alias:ru[t].alias}])),rO=new Map(Object.entries({"google-antigravity":"HIKARI(히카리)"}).map(([e,t])=>[e,ru.findIndex(e=>e.alias===t)]));function rD(e,t){if(void 0===t)return null;let n=`${e}/${t}`;return rj.get(n)??rS.get(t)??r_.get(n)??rz.get(t)??null}function rH(e){return rv.get(e)??rW.get(e)??null}function rU(e){let t=e%ru.length;return rx.get(t)?.alias??ru[t].alias}function rB(e){let t=e%ru.length;return rx.get(t)?.faceUrl??`/avatars/${ru[t].file}`}function rq(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function rV(e){return({"openai-codex":"OpenAI Codex",anthropic:"Anthropic","google-gemini":"Google Gemini","github-copilot":"GitHub Copilot","opencode-go":"OpenCode Go",devin:"Devin","b-ai":"B.AI",web6:"WEB6"})[e]??e.replace(/(^|-)(\w)/g,(e,t,n)=>`${t?" ":""}${n.toUpperCase()}`)}function rK(e){let t=new Map;for(let n of e){if(!Number.isSafeInteger(n.oauthPosition)||n.oauthPosition<0)continue;let e=t.get(n.provider)??new Set;e.add(n.oauthPosition),t.set(n.provider,e)}return e.map(e=>{var n;let r=e.metadata?.email,a=e.metadata?.accountId,i="string"==typeof r&&r.length>0?r:"string"==typeof a?a:"",s=i.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return rq(e);let n=e.slice(t+1),r=n.lastIndexOf("."),a=r<0?n:n.slice(0,r),i=r<0?"":n.slice(r);return`${rq(e.slice(0,t))}@${0===a.length?"":`${a[0]}•••`}${i}`}(i):"",o=(n=e.provider,rF.get(n)??-1);if(o>=0)return{seed:o,alias:rU(o),masked:s,raw:i};let l=e.oauthPosition;if(!Number.isSafeInteger(l)||l<0){let n=t.get(e.provider)??new Set;for(l=0;n.has(l);)l++;n.add(l),t.set(e.provider,n)}let c=rO.get(e.provider)??-1;if(c>=0)return{seed:c,alias:`${rU(c)}${l+1}`,masked:s,raw:i};let d=l%rA,u=l<rA?rU(d):`${rU(d)}${l+1}`;return{seed:d,alias:u,masked:s,raw:i}})}class rG extends Error{constructor(e,t,n,r){super(e,r),this.kind=t,this.status=n,this.name="ResourceClientError",this.code=r?.code,this.outcomeUnknown=r?.outcomeUnknown}}function rJ(e,t){return`${rc}${e}${t?"?refresh=1":""}`}function rZ(e,t,n=!1){return e instanceof rG?e:t?new rG("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new rG("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new rG(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function rY(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function rX(e,t){let n,r=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&&(n=setTimeout(()=>{i=!0,a.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,n=await r(e,{signal:a.signal});try{t=await n.json()}catch(e){throw new rG("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",n.status,{cause:e})}let i=t&&"object"==typeof t?t:null,s="string"==typeof i?.error?i.error:null;if(!n.ok||s)throw new rG(s??`HTTP ${n.status}`,"http",n.status,{code:"string"==typeof i?.code?i.code:void 0,outcomeUnknown:i?.outcomeUnknown===!0});return t}catch(e){throw rZ(e,i,a.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",s)}}function rQ(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 r0(e={}){try{let t=await rX(rJ("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new rG("사용량 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:{...t,reports:t.reports.map(rQ)},error:null}}catch(t){return rY(e.previous,rZ(t,!1))}}async function r1(e,t={}){if(!e)return rY(void 0,new rG("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await rX(`/api/agent/${encodeURIComponent(e)}/account`,t),r=n?.state==="resolved"||n?.state==="unresolved"||n?.state==="not-running"||n?.state==="unsupported";if(!n||n.sessionId!==e||"number"!=typeof n.observedAt||!r||!Array.isArray(n.resetRecommendations))throw new rG("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return rY(void 0,rZ(e,!1))}}async function r2(e={}){try{let t=await rX(rJ("/models",!0===e.refresh),{...e,timeoutMs:e.timeoutMs??12e4});if(!t||!Array.isArray(t.models)||!Array.isArray(t.agents)||!Array.isArray(t.daily))throw new rG("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rY(e.previous,rZ(t,!1))}}async function r8(e={}){try{let t=await rX(`${rc}/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 rG("API 크레딧 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rY(e.previous,rZ(t,!1))}}async function r4(e,t={}){await r6({wallet:"hive",value:e},t)}async function r5(e,t,n={}){await r6({kind:"balance",wallet:e,value:t},n)}async function r6(e,t){await rX(`${rc}/credits/settings`,{...t,timeoutMs:t.timeoutMs??2e4,fetchImpl:async(n,r)=>{let a=new Headers(r?.headers);return a.set("Content-Type","application/json"),(t.fetchImpl??fetch)(n,{...r,method:"POST",headers:a,body:JSON.stringify(e)})}})}async function r3(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rG("credential id가 올바르지 않습니다.","invalid-response");let r=await rX(`${rc}/credential/${e}/${t?"enable":"disable"}`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,t)=>(n.fetchImpl??fetch)(e,{...t,method:"POST"})});if(!r||!0!==r.ok||r.credentialId!==e||!t!==r.disabled)throw new rG("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function r7(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rG("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new rG("credit id가 올바르지 않습니다.","invalid-response");let r=await rX(`${rc}/credential/${e}/reset`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,r)=>{let a=new Headers(r?.headers);return a.set("Content-Type","application/json"),(n.fetchImpl??fetch)(e,{...r,method:"POST",headers:a,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!r||"boolean"!=typeof r.ok||r.credentialId!==e||r.creditId!==t||"string"!=typeof r.code||r.ok!==("reset"===r.code))throw new rG("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function r9(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let ae={faces:new Map,pins:new Map},at=[],an=ae,ar=null,aa=at,ai=new Map,as=new Set;function ao(e){let t=(as.add(e),()=>{as.delete(e)}),n=rM(e);return()=>{t(),n()}}function al(e){an=e,as.forEach(e=>e())}function ac(e){return Number.isSafeInteger(e)&&e>0}function ad(e,t){return`${e}:${t}`}function au(e){let t=e??at;aa=t;let n=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===ar)return;ar=n;let r=rK(t),a=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!ac(n))return;let i=ad(e.provider,n);a.has(i)||a.set(i,{seed:r[t].seed,alias:r[t].alias})}),al({faces:a,pins:an.pins})}function ap(e,t,n,r){if(!t)return null;let a=rD(t,r);if(a)return a;if(ac(n)){let e=an.faces.get(ad(t,n));if(e)return e}let i=e?an.pins.get(e):void 0;if(i&&i.provider===t){let e=an.faces.get(ad(t,i.credentialId));if(e)return e}return rH(t)??("anthropic"!==t||ac(n)||i?.provider===t?null:rb.find(e=>e.provider===t&&0===e.oauthPosition)??null)}async function ah(e,t,n,r){if(!t||ac(n)||rH(t))return ap(e,t,n,r);try{let{data:n}=await r1(e);if(n?.state==="resolved"&&n.provider===t&&ac(n.credentialId)){let r=new Map(an.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),al({faces:an.faces,pins:r})}}catch{}return ap(e,t,void 0,r)}function am(e,t,n,r){let i=!!t&&!ac(n)&&!!e;return(0,a.useEffect)(()=>{i&&e&&t&&function(e,t){let n=Date.now(),r=an.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let a=`${e}\u0000${t}`,i=ai.get(a);void 0!==i&&n-i<3e4||(ai.set(a,n),r1(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:a}=n;if("string"!=typeof r||""===r||!ac(a))return;let i=new Map(an.pins);i.set(e,{provider:r,credentialId:a,observedAt:Date.now()}),al({faces:an.faces,pins:i})}).catch(()=>{}))}(e,t)},[i,e,t]),(0,a.useSyncExternalStore)(ao,()=>ap(e,t,n,r),()=>null)}function af(){return(0,a.useEffect)(()=>{if(!rN){rN=!0;let e=()=>{"visible"===document.visibilityState&&rR()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e)}null===rw&&(rw=rR().then(e=>{e||(rw=null)}))},[]),(0,a.useSyncExternalStore)(rM,rI,()=>rf)}rM(()=>{ar=null,au(aa)});let ag={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"},"zh-CN":{"dispatch.title":"{count} 个子代理","dispatch.tally":"运行中 {running} \xb7 运行完成 {done} \xb7 Main 已接受 {accepted}","dispatch.expand":"展开派发详情","dispatch.collapse":"收起派发详情","run.dispatching":"派发中","run.pending":"等待中","run.running":"运行中","run.completed":"运行完成","run.failed":"运行失败","run.aborted":"已中止","run.unobserved":"未观测到运行状态","verdict.accepted":"Main 已接受","verdict.rework":"Main 要求返工","verdict.held":"Main 暂缓","verdict.none":"未记录审查","verdict.attempt":"第 {attempt} 次","detail.stage":"当前步骤","detail.stageNone":"无记录","detail.model":"模型","detail.modelNone":"未观测","detail.fallback":"备用模型","detail.agentId":"代理 ID","detail.reason":"审查说明","detail.source.live":"实时观测","detail.source.record":"会话记录","detail.openSubagents":"打开子代理详情","detail.openProcess":"打开工作记录","summary.live":"进行中","summary.files":"变更文件 {count}","summary.checks":"检查 {count}","summary.files.one":"变更文件 {count}","summary.checks.one":"检查 {count}","summary.checksFailed":"失败 {count}","summary.unverified":"未确认 {count}","summary.verdictUnverified":"判定未确认 {count}","summary.verdictUnverified.one":"判定未确认 {count}","summary.expand":"展开本轮摘要","summary.collapse":"收起本轮摘要","result.label":"本次结果","result.open":"查看结果","result.openNamed":"查看结果:{name}","result.previewTitle":"{name} 预览","result.previewFailed":"无法加载预览。请点击“查看结果”打开。","result.more":"其他结果 {count}","result.previewLoading":"正在加载预览","result.kind.html":"页面","result.kind.pdf":"PDF","result.kind.document":"文档","result.kind.image":"图片","summary.heading.files":"变更文件","summary.heading.checks":"已运行的检查","summary.check.exit":"exit {code}","summary.makers":"Maker {count}","summary.makers.one":"Maker {count}","summary.remaining":"剩余 {count}","summary.heading.remaining":"剩余事项","summary.time.unobserved":"无时间记录","summary.time.running":"仍在运行","summary.todo.pending":"待办","summary.todo.in_progress":"进行中","summary.todo.blocked":"受阻","summary.todo.blocker":"受阻原因:{blocker}","summary.todo.none":"没有剩余事项","flow.heading":"工作流程","flow.aria":"本轮的工作阶段","flow.toggle":"工作流程","flow.stage.investigate":"调查","flow.stage.edit":"修改","flow.stage.check":"检查","flow.stage.review":"交叉评审","flow.stage.commit":"提交\xb7推送","flow.stage.ci":"CI","flow.stage.deploy":"部署","flow.state.waiting":"等待","flow.state.running":"进行中","flow.state.done":"完成","flow.state.redone":"再次修改","flow.state.passed":"通过","flow.state.unverified":"判定未确认","flow.state.failed":"失败","flow.state.unobserved":"结果未观测","flow.state.findings":"意见 {count} 条","flow.state.findings.one":"意见 {count} 条","flow.state.noFindings":"无意见","flow.state.open":"未解决 {count} 条","flow.state.reviewUnusable":"评审无效","flow.state.skipped":"已跳过","flow.state.notNeeded":"无需","flow.count.passed":"通过 {count}","flow.count.unverified":"判定未确认 {count}","flow.count.failed":"失败 {count}","flow.count.unobserved":"结果未观测 {count}","flow.count.running":"进行中 {count}","flow.earlier":"之前轮次 {count} 条","flow.attempt":"第 {attempt} 轮","flow.label.typecheck":"类型检查","flow.label.lint":"Lint","flow.label.test":"测试","flow.label.build":"构建","flow.label.verify":"验证","flow.label.smoke":"冒烟检查","flow.label.check":"检查","flow.label.ci":"CI 确认","flow.label.deploy":"部署执行","flow.label.review":"评审","flow.label.resolve":"处理意见","flow.label.commit":"提交\xb7推送","flow.details":"详情","flow.commandOmitted":"压缩请求的摘要中省略了命令正文。","flow.exit":"Shell 退出码 {code}","flow.exit.none":"没有退出码记录","flow.exit.error":"以错误结束","flow.evidence":"判定依据","flow.why.confirmed":"已确认","flow.why.missing":"缺少","flow.why.exitZero":"Shell 退出码 0","flow.why.check":"{label} 命令本身的退出码。后面接的命令(管道、;、|| 等)可能掩盖其结果,因此未计为通过。","flow.why.ci":"以退出码返回的 CI 结果。该命令不像 gh run watch --exit-status 那样返回结果,因此未计为通过。","flow.why.ciOtherRun":"这次运行属于此提交的记录。所等待的运行在记录中属于另一个提交 {sha}。","flow.why.ciPublishRun":"此提交 CI 运行的结果。该命令等待的是发布运行,因此未计为 CI 判定。","flow.why.watched.passed":"所等待的运行以通过结束","flow.why.watched.failed":"所等待的运行以失败结束","flow.why.watched.unjudged":"所等待的运行未产生判定即结束({conclusion})","flow.why.ciUnjudged":"此提交的 CI 判定。所等待的运行以 {conclusion} 结束,既非通过也非失败,因此该命令的失败未计为 CI 失败。","flow.why.deploy":"部署已完成的记录。该命令启动部署后立即返回,仅凭 Shell 退出码无法判断部署是否完成。","flow.strip.running":"{stage} 进行中","flow.loop.badge":"↻ 第 {attempt} 轮","flow.loop.failed":"{stage} 第 {attempt} 轮失败,回到修改","flow.loop.findings":"{stage} 第 {attempt} 轮有意见,回到修改","flow.state.stale":"修改前通过","flow.state.staleDone":"修改前完成","flow.count.stale":"修改前通过 {count}","flow.why.stale":"此结果之后又修改了文件,最新版本尚未检查。","flow.compound.failed":"组合命令失败","flow.why.compoundConfirmed":"{stages} 在一条命令中运行,整条命令失败","flow.why.compoundMissing":"具体哪个阶段失败","flow.why.next":"下一步","flow.why.check.syntax":"{label} 命令本身的退出码。命令中包含 $(…)、反引号、( ) 分组或 { } 大括号等 Shell 语法,此面板不追踪该退出码是否传递到 Shell 退出码,因此未计为通过。","flow.why.check.optional":"{label} 脚本实际运行的记录。使用 --if-present 时,如果脚本不存在,运行器不运行任何内容即以退出码 0 结束。","flow.why.noExit":"此调用的退出码。结果记录中没有退出码。","flow.why.noResult":"此调用的结果。没有该调用的结果记录。","flow.why.interrupted":"此调用的结果。调用在完成前被中断。","flow.why.noCompletion":"此调用的退出码。调用已转入后台任务,且该任务没有完成记录。","flow.next.rerun":"先查看此调用的完成记录和输出。只有在运行已结束且找不到检查命令本身的退出码时,才单独重新运行检查命令,不要使用管道、;、|| 或包裹语法。长输出请在结果 artifact 中查看,不要用 tail 或 grep 截断。","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":"同模型、同等级的过去首次尝试中,运行时间超过当前已用时间的那些实行的剩余时间分布(中间一半)。","eta.byTodo":"按待办约还需 {duration}({completed}/{total} 步)","eta.byTodoSoon":"按待办 1 分钟内({completed}/{total} 步)","eta.byTodoHint":"仅按 todo 完成比例估算。各步骤耗时不同,误差可能很大。","eta.rework":"返工第 {attempt} 次 \xb7 自首次派发 {duration}","eta.reworkAttempt":"返工第 {attempt} 次","eta.reworkHint":"返工尝试几乎没有耗时记录,因此不估算剩余时间和百分比。自首次派发起的时间包含各次尝试之间 Main 审查和等待的时间。","eta.rangeMinutes":"{low}~{high} 分钟","eta.range":"{low}~{high}","duration.seconds":"{seconds} 秒","duration.minutesSeconds":"{minutes} 分 {seconds} 秒","duration.minutes":"{minutes} 分钟","duration.hours":"{hours} 小时","duration.hoursMinutes":"{hours} 小时 {minutes} 分钟","duration.underMinute":"不到 1 分钟"}};function ax(){let{locale:e}=(0,z.s)();return{st:(0,a.useCallback)((t,n)=>(0,et.u0)(e,t,ag,n),[e]),locale:e}}function av({seed:e,size:t,provider:n}){af();let i=rB(e),[s,o]=(0,a.useState)(null),l=s===i,[c,d]=(0,a.useState)(!1);return l?(0,r.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:rU(e).slice(0,1)}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),d(!0)},"aria-label":rU(e),children:(0,r.jsx)("img",{className:"account-avatar",src:i,width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>o(i)})}),c&&(0,r.jsx)(ab,{seed:e,provider:n,onClose:()=>d(!1)})]})}function ab({seed:e,provider:t,onClose:n}){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=rU(e);return(0,q.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"account-avatar-dialog","aria-label":o,onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&n()},children:[(0,r.jsx)("img",{className:"account-avatar-full",src:rB(e),width:256,height:256,alt:o,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:o}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:rV(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:i("i18n.close")})]}),document.body)}function ay(e){let t,n=[],r=null,a=0,i=0,s=0,o=0,l=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){l=[],c=[];return}let e=Math.max(l.length,c.length);for(let t=0;t<e;t++){let e=l[t]?{lineNo:l[t].lineNo,text:l[t].text,type:"removed"}:d(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();r.rows.push({type:"line",left:e,right:n})}l=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(s>0||o>0)){if(d.startsWith("--- ")){u(),t=aw(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:aw(d.slice(4)),rows:[]},n.push(r);continue}}let e=d.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),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]),r.rows.push({type:"hunk",text:d});continue}if(!r)continue;if(d.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:d});continue}let p=d[0],h=d.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo: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(),r.rows.push({type:"hunk",text:d}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function aw(e){return e.split(" ")[0].trim()}function ak({task:e,phases:t}){let{t:n}=(0,z.s)(),a="completed"===e.status,i="abandoned"===e.status,s="in_progress"===e.status,o="blocked"===e.status,l=!t||a||i?[]:t$(e,t),c=l.length>0?n("todo.waiting",{tasks:l.join(", ")}):!t||a||i||o?null:n("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,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}${c?`; ${c}`:""}`,className:`todo-checklist-row ${u}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:d}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,o&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null,c&&(0,r.jsxs)("span",{className:`todo-checklist-readiness${l.length>0?" is-waiting":""}`,children:[" \xb7 ",c]})]})]})}let aj="/icons/catppuccin";function aS({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${aj}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${aj}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function aC({size:e=14,open:t=!1}){return(0,r.jsx)(aS,{name:t?"_folder_open":"_folder",size:e})}function aN({size:e=14}){return(0,r.jsx)(aS,{name:"_file",size:e})}let aT={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 aI(e,t=14){let n=e.toLowerCase(),a="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(a)return(0,r.jsx)(aS,{name:a,size:t});let i=aT[n.split(".").pop()??""];return i?(0,r.jsx)(aS,{name:i,size:t}):(0,r.jsx)(aN,{size:t})}function aM({files:e,onOpenFile:t}){let{t:n}=(0,z.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let a=t_(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("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:[aI(a,12),(0,r.jsx)("span",{children:a})]},e)})})}let aR=/^[\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),n=e;if(t){let r=t.index+t[0].length;"\r"===e[r]&&(r+=1),"\n"===e[r]&&(r+=1);let a=r;for(;r<e.length;){let t=e.indexOf("\n",r),n=-1===t?e.length:t,i=n>r&&"\r"===e[n-1]?n-1:n;if(!aR.test(e.slice(r,i)))break;a=i,r=-1===t?e.length:t+1}let i=t[0].length-t[0].trimStart().length;n=`${e.slice(0,t.index+i)}${e.slice(a)}`}let r=[...n.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===r.length&&r[0]&&r[0]===r[0].trim()&&/[가-힣]/u.test(r[0])?r[0]:null}function aL(e){let t=e.live,n=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,r=[t?.assignment,t?.progress?.assignment,t?.task].map(aE).find(e=>null!==e)??(n?.taskTitle?.trim()||null),a=t?.progress?.lastIntent?.trim()||"",i=t?.progress?.currentTool?.trim()||"";return{title:r??"담당 업무 미확인",stage:a&&i?`${a} \xb7 ${i}`:a||(i?`${i} 실행 중`:null),explicitTitle:null!==r}}function a$(e){let t=e.live?.progress,n="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,a="string"==typeof t?.resolvedThinkingLevel?t.resolvedThinkingLevel.trim():"",i="string"==typeof r?.thinkingLevel?r.thinkingLevel.trim():"";if(n){let e=n.split("/").pop()||n;return{model:n,modelShort:a&&e.endsWith(`:${a}`)?e.slice(0,-(a.length+1)):e,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:a||i||null}}let s="string"==typeof r?.model?r.model.trim():"";return{model:s||null,modelShort:s?s.split("/").pop()||s:null,modelIsFallback:!!s&&r?.modelIsFallback===!0,effort:i||null}}class aP extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function aA(e){try{return await e.json()}catch{throw new aP("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function aF(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 a_(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 az(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 aW(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 aO(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let n=async(t,n,r)=>{let a;try{a=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new aP(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let i=await aA(a);if(!a.ok)throw new aP("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:r}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!r||"object"!=typeof r)throw new aP("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new aP("http",r.error);if(!0!==r.running)return{runtime:"detached",subagents:[]};let a=r.state?.subagents;if(void 0!==a&&(!Array.isArray(a)||!a.every(az)))throw new aP("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:a??[]}},async getLiveTranscript(e,t,r,a){let{body:i}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:r}),signal:a},"live-unreachable");if(!i||"object"!=typeof i)throw new aP("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof i.error&&i.error)throw new aP("http",i.error);if(!0!==i.success||!i.data||"object"!=typeof i.data)throw new aP("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let s=i.data;if(!Array.isArray(s.entries)||!s.entries.every(aW)||"number"!=typeof s.fromByte||"number"!=typeof s.nextByte||"boolean"!=typeof s.reset)throw new aP("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:s.fromByte,nextByte:s.nextByte,reset:s.reset,entries:s.entries}},async getArchive(e,r){let a=`${t}/archive?session=${encodeURIComponent(e)}`,{body:i}=await n(a,{method:"GET",signal:r},"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(aF))throw new aP("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:i.sessionId,dir:i.dir,found:i.found,subagents:i.subagents,...!0===i.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,r,a=400,i){let s=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(r)}&limit=${encodeURIComponent(String(a))}`,{body:o}=await n(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(a_))throw new aP("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}let aD=["feature","maintenance","diagnostic"],aH=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function aU(e){if("string"!=typeof e)return null;let t=e.split(/\r?\n/),n=t.findIndex(e=>/^\s*TASK_GUARD\s*:\s*$/.test(e));if(n<0)return null;for(let e=n+1;e<t.length;e+=1){let n=aH.exec(t[e]);if(!n)break;if("WORK_CLASS"!==n[1])continue;let r=n[2].toLowerCase();return aD.includes(r)?r:null}return null}let aB={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function aq(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function aV(e){return"string"==typeof e&&e.trim()?e:null}function aK(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function aG(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 aJ(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function aZ(e,t){if(t?.isError)return null;let n=aq(e.input.tasks),r=aq(t?.details?.progress),a=Math.max(n.length,r.length),i=[];for(let s=0;s<a;s++){let a=r.find(e=>e.index===s)??r[s],o=n[s],l=aV(a?.id)??aV(o?.name);l&&i.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:l,agent:aV(a?.agent)??aV(o?.agent),task:aV(a?.task)??aV(o?.task)??"",workClass:aU(o?.task)??aU(a?.task),spawned:!!t})}return i}let aY=/<task-result\b([^>]*)>/g,aX=/(\w+)="([^"]*)"/g;function aQ(e,t,n){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&n.latestByAgent.get(e.agentId)===e.key)}function a0(e,t,n){var r;let a,i,s,o,l=aQ(e,t,n),c=l?{key:e.key,identity:"live",live:l.assignment?l:{...l,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},d=aL(c),u=n.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=n.verdicts.get(e.key),m=h&&h.length>0?h[h.length-1]:null,f=m?.at??null,g=null===f?null:(r=e.key,i=n.runStartedAt.get(r)??null,s=l?.progress?.durationMs,o=l&&("pending"===l.status||"running"===l.status)&&"number"==typeof s&&l.lastUpdate>0?l.lastUpdate-s:null,null===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?a$(c):null,run:a,runSource:p,verdict:x?null:m,priorVerdict:x?m:null,runTitle:x?aE(l?.progress?.task):null,observedParallelWith:n.parallelWith.get(e.key)}}function a1(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function a2(e,t){let n=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),r=new Map,a=[];for(let e of n){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?a.push(t):r.set(e.attempt,t)}return[...a,...[...r.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}function a8(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function a4(e,t,n){let r=-1;n.forEach((e,t)=>{"user"===e.role&&(r=t)});let a=n.slice(0,r+1).flatMap(a8),i=n.slice(r+1).flatMap(a8),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 a5="끊기기 전에 바깥에 영향을 주는 행동(커밋\xb7push, `git_finalize`\xb7`git_integrate`, 배포\xb7`update.sh`, CI 재실행, 이슈\xb7PR 댓글, 메시지 전송)을 하던 중이었다면 다시 하기 전에 그 결과가 이미 반영됐는지 `git log`\xb7`git status`\xb7원격 브랜치, `gh run list`, 배포 로그, 해당 페이지로 먼저 확인하고, 반영됐으면 되풀이하지 않는다. ",a6="[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+a5+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a3="[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. "+a5+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a7="[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+a5+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",a9=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 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."]),ie={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function it(e){return e.trim()}function ir(e){return it(e.text)||(e.images>0?"[Image]":"")}function ia(e){let t=e.filter(e=>!ie[e.stage]);if(t.length<=4)return e;let n=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!n.has(e.id))}function ii(e,t){switch(t.type){case"submit":return ia([...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 ia(e.map(e=>e.id===t.id&&ie[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,a=(e,t)=>{let n=`${e}\u0000${it(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)a("steer",e);for(let e of n)a("followUp",e);let i=!1,s=e.map(e=>{if(!ie[e.stage])return e;let t=`${e.kind}\u0000${ir(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-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 n=it(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(ie[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&it(e.text)===n&&e.images===t.images);if(!r)return e;return ia(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>ie[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=it(t.text),a=e.find(e=>n(e)&&e.kind===t.kind&&(it(e.text)===r||ir(e)===r));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 is(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 io(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}let il=["investigate","edit","check","review","commit","ci","deploy"];function ic(e,t){let n="",r=t;for(;r<e.length&&'"'!==e[r];){let t=e[r];if("\\"===t&&r+1<e.length){let a=e[r+1];"\n"!==a&&(n+='$`"\\'.includes(a)?a:t+a),r+=2}else if("$"===t&&"("===e[r+1]){let t=id(e,r+1);n+=e.slice(r,t),r=t}else if("`"===t){let t=iu(e,r+1);n+=e.slice(r,t),r=t}else n+=t,r+=1}return{text:n,end:Math.min(r+1,e.length)}}function id(e,t){let n=e[t],r="{"===n?"}":")",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=ic(e,i+1).end;else if("`"===t)i=iu(e,i+1);else{if(t===n)a+=1;else if(t===r&&0==--a)return i+1;i+=1}}return e.length}function iu(e,t){let n=t;for(;n<e.length&&"`"!==e[n];)n+="\\"===e[n]?2:1;return Math.min(n+1,e.length)}function ip(e){let{tokens:t,groups:n,expandingHeredoc:r}=function(e){let t=[],n=[],r=!1,a=[],i=[],s="",o=-1,l=!1,c=e=>{if(o<0)return;let n={value:s,start:o,end:e,risky:l};for(let e of(t.push(n),i.splice(0)))e.at===t.length-1&&(e.owner=n);s="",o=-1,l=!1},d=0;for(;d<e.length;){let u=e[d];if("\\"===u)"\n"!==e[d+1]&&(o<0&&(o=d),s+=e[d+1]??""),d+=2;else if("'"===u){o<0&&(o=d);let t=e.indexOf("'",d+1),n=t<0?e.length:t;s+=e.slice(d+1,n),d=n+1}else if('"'===u){o<0&&(o=d);let t=ic(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=id(e,d+1);s+=e.slice(d,t),l=!0,d=t}else if("`"===u){o<0&&(o=d);let t=iu(e,d+1);s+=e.slice(d,t),l=!0,d=t}else if("#"===u&&o<0){let t=e.indexOf("\n",d);d=t<0?e.length:t}else if(" "===u||" "===u||"\r"===u)c(d),d+=1;else if("\n"===u){c(d);let n=t[t.length-1];for(let s of("&&"!==n&&"||"!==n&&"|"!==n&&t.push(";"),d+=1,i.length=0,a.splice(0)))for(;d<e.length;){let t=e.indexOf("\n",d),n=t<0?e.length:t,a=e.slice(d,n);if(d=n+1,(s.stripTabs?a.replace(/^\t+/,""):a)===s.delimiter)break;!s.quoted&&/\$[({]|`/.test(a)&&(s.owner?s.owner.risky=!0:r=!0)}}else if("<"===u&&"<"===e[d+1]&&"<"!==e[d+2]){c(d);let n=d+2,r="-"===e[n];for(r&&(n+=1);" "===e[n]||" "===e[n];)n+=1;let s="",o=!1;for(;n<e.length&&!/[\s;&|<>()]/.test(e[n]);){let t=e[n];if("'"===t||'"'===t){o=!0;let r=e.indexOf(t,n+1),a=r<0?e.length:r;s+=e.slice(n+1,a),n=a+1}else"\\"===t&&(o=!0),s+="\\"===t?e[n+1]??"":t,n+="\\"===t?2:1}if(s){let e=t[t.length-1],n={delimiter:s,stripTabs:r,quoted:o,owner:void 0!==e&&"string"!=typeof e?e:null,at:t.length};a.push(n),n.owner||i.push(n)}d=n}else";"===u?(c(d),t.push(";"),d+=";"===e[d+1]?2:1):"&"===u?"&"===e[d+1]?(c(d),t.push("&&"),d+=2):(">"===e[d+1]||/[<>]$/.test(s)?(o<0&&(o=d),s+=u):(c(d),t.push("&")),d+=1):"|"===u?"|"===e[d+1]?(c(d),t.push("||"),d+=2):s.endsWith(">")?(s+=u,d+=1):(c(d),t.push("|"),d+="&"===e[d+1]?2:1):("("===u||")"===u?(c(d),n.push(d)):(o<0&&(o=d),("{"===u||"}"===u||"!"===u)&&(l=!0),s+=u),d+=1)}return c(e.length),{tokens:t,groups:n,expandingHeredoc:r}}(e),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 r=l[0].start,a=l[l.length-1].end,s=l.some(e=>e.risky)||n.some(e=>e>=r&&e<=a),c={words:t,text:e.slice(r,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:n.length>0||r||t.some(e=>"string"!=typeof e&&e.risky)}}function ih(e){return e.slice(e.lastIndexOf("/")+1)}let im={bash:!0,sh:!0,zsh:!0,dash:!0},ig={sudo:!0,env:!0,command:!0,exec:!0,nice:!0,nohup:!0,time:!0,timeout:!0,setsid:!0,"systemd-run":!0},ix={"-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},iv={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},ib={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function iy(e){let t=ij(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(im,ih(e[t]))||iw(e,t))return null;for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*c[a-zA-Z]*$/.test(e[n]))return e[n+1]??null;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return null}function iw(e,t){for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*n[a-zA-Z]*$/.test(e[n])||/^-[a-zA-Z]*o$/.test(e[n])&&"noexec"===e[n+1])return!0;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return!1}let ik={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function ij(e){let t=!1,n="";for(let r=0;r<e.length;r+=1){let a=e[r];if(!(/^[A-Za-z_]\w*=/.test(a)||!t&&Object.hasOwn(ib,a))){if(t&&(a.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(a))){if(Object.hasOwn(ik,n)&&ik[n].test(a))return -1;"command"!==n&&Object.hasOwn(ix,a)&&(r+=1);continue}if(!Object.hasOwn(ig,ih(a)))return r;t=!0,n=ih(a)}}return -1}let iS=/(?:^|\/)wsl\/update\.sh$/;function iC(e,t=0){let n=iy(e);if(null!==n)return t<3&&ip(n).commands.some(e=>iC(e.words,t+1));let r=ij(e);if(r<0)return!1;if(iS.test(e[r]))return!0;if(!Object.hasOwn(im,ih(e[r]))||iw(e,r))return!1;let a=e.slice(r+1).find(e=>!e.startsWith("-"));return void 0!==a&&iS.test(a)}function iN(e){let t=ij(e),n=t<0?e:e.slice(0,t),r=n.map(ih);return r.includes("systemd-run")?!n.some(e=>Object.hasOwn(iv,e)):!!(r.includes("sudo")&&n.some(e=>"--background"===e||/^-[a-zA-Z]*b[a-zA-Z]*$/.test(e)))||r.includes("setsid")&&!n.includes("-w")&&!n.includes("--wait")}function iT(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function iI(e){if(e.every(e=>/^[A-Za-z_]\w*=/.test(e)))return!0;let[t,...n]=e;return"cd"===t?n.length<=1:"export"===t?n.every(e=>/^[A-Za-z_]\w*=/.test(e)):"set"===t&&n.every(e=>/^[-+][a-zA-Z]+$/.test(e)&&!/^-[a-zA-Z]*n/.test(e)||"pipefail"===e)}let iM={tail:!0,head:!0,cat:!0,tee:!0},iR=/(?:^|[^\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},iL={"--help":!0,"-h":!0,"--version":!0},i$=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 iP(e){let t=ij(e);if(t<0)return!1;let n=ih(e[t]);if("test"===n||"["===n||e.slice(t+1).some(e=>Object.hasOwn(iL,e)))return!1;if(iR.test(n))return!0;if(!Object.hasOwn(iE,n))return!1;if("node"===n&&function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("--test"===t)return!0;if("--"===t||!t.startsWith("-"))break;Object.hasOwn(i$,t)&&(n+=1)}return!1}(e,t+1))return!0;let r=function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("-m"===t)return e[n+1];if(/^-[a-zA-Z]*[cep]/.test(t)||/^--(?:eval|print)(?:=|$)/.test(t))break;if(!t.startsWith("-")){if("run"===t||"exec"===t||"x"===t||"dlx"===t)return e.slice(n+1).find(e=>!e.startsWith("-"));return t}}}(e,t+1);return void 0!==r&&iR.test(r)}let iA={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},iF={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function i_(e){let t=ij(e);if(t<0||"git"!==ih(e[t]))return null;for(let n=t+1;n<e.length;n+=1)if(Object.hasOwn(iA,e[n]))n+=1;else if(!e[n].startsWith("-"))return{name:e[n],at:n};return null}function iz(e,t=0,n){let r=iy(e);if(null!==r)return t<3&&ip(r).commands.some(e=>iz(e.words,t+1,n));let a=i_(e);if(!a||"commit"!==a.name&&"push"!==a.name||void 0!==n&&a.name!==n)return!1;let i=iF[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 n of e.slice(1)){if("o".includes(n)||!/[a-zA-Z0-9]/.test(n))break;t+=n}return t}(e)))}function iW(e){return iI(e)||null!==i_(e)}let iO={check:({words:e})=>iP(e),commit:({words:e})=>iz(e),ci:({words:e})=>{let t=ij(e);return t>=0&&"gh"===ih(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>iC(e.words)},iD={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 iH(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 iU={"$?":!1,"${PIPESTATUS[0]}":!0};function iB(e,t){let n=i2(t);if("notRun"===n)return[];let r=n?void 0:t,a=ip(e),i=[];if(a.commands.some(({words:e})=>(function e(t,n=0){let r=iy(t);return null!==r?n<3&&ip(r).commands.some(t=>e(t.words,n+1)):iP(t)})(e))&&i.push("check"),a.commands.some(({words:e})=>iz(e))&&i.push("commit"),a.commands.some(({words:e})=>(function e(t,n=0){let r=iy(t);if(null!==r)return n<3&&ip(r).commands.some(t=>e(t.words,n+1));let a=ij(t);return a>=0&&"gh"===ih(t[a])&&"run"===t[a+1]&&["watch","view","list"].includes(t[a+2])})(e))&&i.push("ci"),a.commands.some(iO.deploy)&&i.push("deploy"),0===i.length)return[];let s=r?nD(r):null,o=null===s?!!r?.isError:0!==s,l=i.length>1?{stages:i,failed:o}:void 0,c=r?sh(r):"";return i.map(e=>{var t;let i,d,u,p="commit"===e?iW:iI,h=function e(t,n,r=iI,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?iy(p.words):null,m=null===h?null:e(ip(h),n,r,a+1);if(m&&m.decisive.length>0)s.push(...m.decisive);else if(n(p))s.push(p);else{let e=ij(p.words);u&&l&&e>=0&&Object.hasOwn(iM,ih(p.words[e]))||r(p.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let n=iT(e[t])?.words;return n?.[0]==="exit"&&(1===n.length||2===n.length&&"$?"===n[1])}(i,c)||(o=!0);continue}u=!0,(m?.reach==="masked"||d.negated||d.commands.length>1&&!l||t.operators.includes("||")||t.background||iN(p.words)||!function(e,t){if(t===e.length-1)return!0;let n=e[e.length-1],r=iT(n)?.words;return!!r&&"exit"===r[0]&&!n.background&&t===e.length-2&&(1===r.length||2===r.length&&"$?"===r[1])}(i,c))&&(o=!0)}}let d=iT(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,iO[e],p),m="check"===e&&h.decisive.some(({words:e})=>e.includes("--if-present")),f=r?(t=iO[e],i=new Map,d=a.lists.map(e=>(function(e){let t=e&&!e.background?iT(e)?.words:void 0;if(!t||"echo"!==t[0]||t.length<2)return null;let n=t.slice(1);if(n.some(e=>e.startsWith("-")||/^(?:\d*[<>]|&>)/.test(e)))return null;let r=n.join(" ");for(let[e,t]of Object.entries(iU)){let n=r.indexOf(e);if(n<0||r.indexOf(e,n+1)>=0)continue;let a=r.slice(0,n),i=r.slice(n+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,n)=>{let r=d[n+1];if(!r||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=r.first||1===a.commands.length?a.commands[0]:void 0;if(!o||!t(o)||iN(o.words)||o.uncertain)return;let l=d.filter(e=>e?.prefix===r.prefix&&e.suffix===r.suffix),c=RegExp(`^${r.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(-?\\d+)${r.suffix.trimEnd().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`),h=u.flatMap(e=>{let t=c.exec(e);return t?[{code:Number(t[1]),line:e}]:[]});if(h.length!==l.length)return;let m=d.slice(0,n+2).filter(e=>l.includes(e)).length-1;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"===n?"interrupted":r?"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:n}of e){let e=ij(n);n.forEach((n,r)=>{if(r!==e||"test"!==n)for(let e of n.replace(/^-+/,"").toLowerCase().split(":")){let n=Object.hasOwn(iD,e)?iD[e]:void 0;n&&!t.includes(n)&&t.push(n)}})}return t}(h.decisive):[],...l?{compound:l}:{},...x?{evidence:x.line}:{},...b?{reason:b}:{}}})}function iq(e,t){let n=iH(e),r=null===n?void 0:iB(n,t).find(e=>"check"===e.stage);return null!==n&&r?{toolCallId:e.toolCallId,command:n,state:r.state,exitCode:r.exitCode,labels:r.labels,...r.compound?{compound:r.compound}:{},...r.reason?{reason:r.reason}:{}}:null}let iV=/\.(?:md|mdx|markdown|txt)$/i,iK=/^docs?$/i;function iG(e){return iV.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>iK.test(e))}let iJ={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},iZ={multiedit:!0,notebookedit:!0,draft:!0},iY={rename:!0,rename_file:!0},iX={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function iQ(e){return e.split("\n")[0].trim()||void 0}let i0=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,i1=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function i2(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 i8=/\btool\.git_(?:finalize|integrate)\s*\(/,i4=/\b(?:Committed|Integrated \S+) and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,i5=/\bgit_(?:finalize|integrate) failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,i6=/\bstage["']?\s*:\s*["'](?:up-to-date|aborted)["']/,i3=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/;function i7(e,t){if("string"==typeof t.commitSha&&""!==t.commitSha.trim())return t.commitSha.trim();let n=i4.exec(sh(e));return n?.[1]??n?.[2]??null}let i9=/^bg_\d+$/;function se(e){let t=e.details,n=t&&"object"==typeof t&&"async"in t?t.async:null;if(n&&"object"==typeof n&&"jobId"in n&&"string"==typeof n.jobId&&i9.test(n.jobId))return n.jobId;let r=sh(e).trimStart();return r.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(r)?.[1]??null:null}function st(e,t){let n=/Command exited with code (-?\d+)\s*$/.exec(t.trimEnd());return{jobId:e,text:t,exitCode:n?Number(n[1]):null}}function sn(e){return"passed"===e||"failed"===e||"done"===e}function sr(e){let t=null;for(let n of e.values())"failed"===n.outcome&&(!t||n.order>t.order)&&(t=n);return t?.stage??null}function sa(e){return e.commandKey??JSON.stringify([e.cwd??"",e.command])}function si(e){let t=new Map;for(let n of e){if("check"!==n.stage)continue;let e=sa(n),r=t.get(e);(r?.outcome!=="failed"||sn(n.outcome))&&t.set(e,n)}return[...t.values()]}function ss(e){return"compound"in e&&e.compound?.failed===!0}let so={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function sl(e){return"stale"!==e&&(sn(e)||"running"===e)}function sc(e){if("ci"!==e.stage)return null;let t=ip(e.command).commands.flatMap(({words:e})=>sf(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?sb(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let sd={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},su={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},sp=/^[0-9a-f]{40}$/i;function sh(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 sm(e){let t=[];for(let n of e.split("\n")){let e,r=n.trim();if(r.startsWith("{")||r.startsWith("[")){try{e=JSON.parse(r)}catch{continue}for(let n of Array.isArray(e)?e:[e])n&&"object"==typeof n&&!Array.isArray(n)&&t.push(n)}}return t}function sf(e,t=0){let n=iy(e);if(null!==n)return t<3?ip(n).commands.flatMap(e=>sf(e.words,t+1)):[];let r=ij(e);return r>=0&&"gh"===ih(e[r])?[e.slice(r+1)]:[]}function sg(e,t){for(let n=0;n<e.length;n+=1)for(let r of t){if(e[n]===r)return e[n+1]??null;if(r.startsWith("--")&&e[n].startsWith(`${r}=`))return e[n].slice(r.length+1)}return null}let sx={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function sv(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(sx,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function sb(e){let t=sv(e);return null!==t&&/^\d+$/.test(t)?t:null}let sy=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function sw(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==nD(t))return[];let n=ip(e).commands.flatMap(({words:e})=>sf(e)).filter(e=>"run"===e[0]&&("list"===e[1]||"view"===e[1]));if(0===n.length)return[];let r=1===n.length?n[0]:null,a=r?.[1]==="list"?sg(r,["-c","--commit"])?.toLowerCase():void 0,i=a&&/^[0-9a-f]{7,40}$/.test(a)?a:null,s=sh(t);return i||s.includes("headSha")?sm(s).flatMap(e=>{let t="string"==typeof e.headSha?e.headSha.toLowerCase():i;if(null===t)return[];let n="string"==typeof e.url?sy.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):r?.[1]==="view"?sb(r):null,repo:(n??(r?sg(r,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:r?sg(r,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:r?sg(r,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let sk=/\b\d{9,12}\b/g,sj=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function sS(e,t){if(e?.type!=="toolCall")return[];let n=iH(e);return null===n?[]:sw(n,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(su,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let sC="Public tree already matches; nothing to publish";function sN(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function sT(e){let t="run"===e[0]&&"list"===e[1]?sg(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(sd,t)}function sI(e,t){let n=new Map,r=[];for(let{words:a}of ip(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],r=void 0===e?[]:ip(e).commands.flatMap(e=>sf(e.words));n.set(t[1],1===r.length&&sT(r[0]))}continue}for(let e of sf(a)){if(sT(e)){r.push({args:e,publish:!0});continue}let a="run"===e[0]&&("watch"===e[1]||"view"===e[1])?sv(e):null,i=sN(a),s=null!==i?!0===n.get(i):null!==a&&/^\d+$/.test(a)&&t(a);r.push({args:e,publish:s})}}return r}function sM(e,t){let n=sI(e,t);return n.length>0&&n.every(({publish:e})=>e)}function sR(e,t){if(!e||!t)return!1;let[n,r]=e.length<=t.length?[e.toLowerCase(),t.toLowerCase()]:[t.toLowerCase(),e.toLowerCase()];return n.length>=7&&/^[0-9a-f]+$/.test(r)&&r.startsWith(n)}function sE(e,t,n){if(sR(e.sha,t.step.commit))return!0;let{title:r}=t.step;return!!r&&!!e.title&&!!e.repo&&!(e.order<=t.order)&&!!e.workflow&&!!Object.hasOwn(su,e.workflow)&&[...n.publishRuns.values()].some(n=>n.order>t.order&&null!==n.sha&&sR(n.sha,t.step.commit)&&null!==n.repo&&n.repo!==e.repo)&&function(e,t){if(e===t)return!0;let n=e.endsWith("…")?e.slice(0,-1):null;return null!==n&&n.length>=20&&t.startsWith(n)}(e.title,r)}let sL={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},s$=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,sP=/^(\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 sF(e,t,n=!1,r=[],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,n=[]){let r=new Map,a=new Map,i=new Map;for(let e of n)null!==e.after&&i.set(e.after,[...i.get(e.after)??[],e]);let s=(e,t)=>{for(let n of e){let e=a.get(n.jobId);e&&(a.delete(n.jobId),r.set(e.toolCallId,{...e.result,isError:!1,content:[{type:"text",text:n.text}],details:{...null===n.exitCode?{}:{exitCode:n.exitCode},backgroundJob:{jobId:n.jobId,after:t}}}))}};for(let n of Array.isArray(e)?e:[]){if(!n||"toolCall"!==n.type)continue;let e=t.get(n.toolCallId);if(e){let t="bash"===n.toolName||"eval"===n.toolName?se(e):null;t?a.set(t,{toolCallId:n.toolCallId,result:e}):r.set(n.toolCallId,e),"wait"===n.toolName&&s(function(e){let t=e.details,n=t&&"object"==typeof t&&"jobs"in t?t.jobs:null,r=(Array.isArray(n)?n:[]).flatMap(e=>{if(!e||"object"!=typeof e||!("id"in e)||!("status"in e)||!("resultText"in e)||"string"!=typeof e.id||!i9.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[{...st(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(r.length>0)return r;let a=sh(e),i=[...a.matchAll(/^### (bg_\d+) \[\w+\] — (?:completed|failed)$/gm)];return i.map((e,t)=>{let n=(e.index??0)+e[0].length,r=a.slice(n,t+1<i.length?i[t+1].index:a.length),s=r.indexOf("\n```\n"),o=r.lastIndexOf("\n```");return st(e[1],s>=0&&o>s?r.slice(s+5,o):"")})}(e),n.toolCallId);let i="read"===n.toolName?function(e,t){let n=e.input.path,r="string"==typeof n?/^proc:\/\/(bg_\d+)$/.exec(n)?.[1]:void 0;if(!r)return null;let[a,...i]=sh(t).split("\n");return RegExp(`^1\\|${r} \\[\\w+\\] — (?:completed|failed)\\b`).test(a)?st(r,i.map(e=>e.replace(/^\d+\|/,"")).join("\n")):null}(n,e):null;i&&s([i],n.toolCallId)}for(let e of i.get(n.toolCallId)??[])s(function(e){let t=e.replace(/^\s*<system-notice>\s*\n?/,"").replace(/\s*<\/system-notice>\s*$/,""),n=/^Background job (bg_\d+) has (?:completed|failed)\b[^\n]*(?:\n|$)/.exec(t);if(n)return[st(n[1],t.slice(n[0].length))];let r=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return r.flatMap((e,n)=>{if(!i9.test(e[1]))return[];let a=(e.index??0)+e[0].length;return[st(e[1],t.slice(a,n+1<r.length?r[n+1].index:t.length).replace(/^\n/,""))]})}(e.text),n.toolCallId)}return r}(g,x,Array.isArray(i)?i:[]),b=[];g.forEach((e,t)=>{let r;if(!e||"toolCall"!==e.type)return;let i=v.get(e.toolCallId);for(let s of(!function(e,t,n,r){let a=iH(t);if(null===a||!a.includes("gh"))return;let i=(t,n)=>{let a=e.publishRuns.get(t);a&&(null===n.sha||null!==a.sha)||e.publishRuns.set(t,{...n,order:a?.order??r})};for(let t of sw(a,n))e.runs.push({...t,order:r}),t.id&&t.sha&&t.workflow&&Object.hasOwn(sd,t.workflow)&&i(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==nD(t))return[];let n=ip(e).commands.flatMap(({words:e})=>sf(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==n.length)return[];let r=sg(n[0],["-w","--workflow"])?.toLowerCase(),a=void 0!==r&&Object.hasOwn(sd,r),i=sg(n[0],["-R","--repo"])?.toLowerCase()??null;return sh(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let n=t.toLowerCase();if(!a&&!Object.keys(sd).some(e=>n.includes(e)))return[];let r=t.match(sk)??[];return 1===r.length?[{id:r[0],sha:sj.exec(n)?.[0]??null,repo:i}]:[]})}(a,n))i(e.id,e);for(let a of sS(t,n))e.ciHeads.push({...a,order:r});for(let t of function(e,t){let n=ip(e),r=n.commands.flatMap(({words:e})=>sf(e)).filter(e=>"api"===e[0]),a=!n.uncertain&&1===n.commands.length&&1===r.length,i=t&&!t.isError&&0===nD(t)?sh(t).trim():"",s=[];for(let e of r){let t=e.slice(1).find(e=>/^\/?repos\//.test(e)),n=t?/^\/?repos\/([^/]+\/[^/]+)\/commits\/([^/?\s]+)$/.exec(t):null;if(!n)continue;let r=sg(e,["-q","--jq"]),o=null;if(a&&".sha"===r)o=i.split("\n")[0]?.trim();else if(a&&null===r&&i.startsWith("{"))try{o=JSON.parse(i.slice(0,i.lastIndexOf("}")+1)).sha}catch{}let l="string"==typeof o&&sp.test(o)?o.toLowerCase():null;s.push({repo:n[1].toLowerCase(),ref:n[2],sha:l})}return s}(a,n))e.heads.push({...t,order:r});let s=function(e,t){if(!t||t.isError||0!==nD(t)||2!==e.split(sC).length)return null;let{lists:n}=ip(e),r=0;for(;r<n.length&&["set","cd"].includes(iT(n[r])?.words[0]??"");)r+=1;let a=r<n.length-1?function(e){let t=iT(e)?.words,n=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!n)return null;let r=ip(n[2]),a=1===r.lists.length?iT(r.lists[0]):null,i=a?.words[0]==="gh"?sf(a.words):[];if(1!==i.length||"run"!==i[0][0]||"list"!==i[0][1])return null;let s=sg(i[0],["-c","--commit"]),o=sg(i[0],["-w","--workflow"])?.toLowerCase();return s&&sp.test(s)&&o&&Object.hasOwn(sd,o)?{name:n[1],sha:s.toLowerCase()}:null}(n[r]):null;return a&&function(e,t){if(e.background||1!==e.pipelines.length)return!1;let[n]=e.pipelines,[r,a,...i]=n.commands;if(n.negated||!a||i.length>1||"gh"!==r.words[0])return!1;let s=sf(r.words);if(1!==s.length||"run"!==s[0][0]||"view"!==s[0][1]||!s[0].includes("--log"))return!1;let o=sv(s[0]);if(sN(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]!==sC)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))}(n[n.length-1],a.name)&&n.slice(r+1,-1).flatMap(e=>e.pipelines.flatMap(({commands:e})=>e)).every(({words:e})=>(function(e,t){let[n,...r]=e;if("["===n||"[["===n||"test"===n||"exit"===n||"true"===n||":"===n||"sleep"===n)return!0;if("echo"===n||"printf"===n)return r.every(e=>!/`|\$\(/.test(e)&&!/public|tree|already|matches|nothing|publish/i.test(e)&&[...e.matchAll(/\$\{?([A-Za-z_]\w*|[?])/g)].every(e=>e[1]===t||"?"===e[1]));if("gh"!==n)return!1;let a=sf(e);return 1===a.length&&"run"===a[0][0]&&"watch"===a[0][1]&&sN(sv(a[0]))===t})(e,a.name))&&sh(t).split("\n").some(e=>e.trim()===sC)?a.sha:null}(a,n);s&&e.nothingToPublish.push({sha:s,order:r})}(f,e,i,t),Array.isArray(r=function(e,t,n,r){if(!e.input||"object"!=typeof e.input||Array.isArray(e.input)||"string"!=typeof e.toolName)return null;let a=i2(t);if("notRun"===a)return null;let i={toolCallId:e.toolCallId,attempt:0},s=n&&!a?"running":"unobserved",o=iH(e);if(null!==o){var l;let n,a,c=(l=t,(a=(n=l?.details)&&"object"==typeof n&&"backgroundJob"in n?n.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 iB(o,t).map(n=>{var a,l,d,u;let p,h;if("commit"===n.stage){let e,r,l=t?"unobserved"===n.state&&function(e,t){if(t.isError)return!1;let{commands:n}=ip(e),r=sh(t),a=e=>n.some(({words:t})=>iz(t,0,e));return(!a("commit")||i0.test(r))&&(!a("push")||i1.test(r))}(o,t)?"done":iX[n.state]:s;return{...i,stage:"commit",..."done"===l?(e=(a=t)?sh(a):"",(r=i0.exec(e))?{commit:r[1],title:r[2].trim()}:{commit:i1.exec(e)?.[1]??null}):{commit:null},docsOnly:!1,outcome:l}}let m=n.evidence??(c&&null!==n.exitCode?`Command exited with code ${n.exitCode}`:void 0),f=m&&c?`${c.jobId} \xb7 ${m}`:m,g="ci"===n.stage&&"failed"===n.state&&t?function(e,t){let n=ip(e).commands.flatMap(({words:e})=>sf(e)),r=n.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),a=r?sv(r):null;if(null===a||!n.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&sv(e)===a))return null;let i=sm(sh(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(sL,s)?null:s}(o,t):null,x=g?"unverified":t?n.state:s,v="check"===n.stage&&x===n.state?n.reason:void 0;return{...i,stage:n.stage,command:o,..."check"===n.stage?{cwd:(l=e.input,d=r,u=e.toolCallId,p=d?tf(d)??d:void 0,(h="string"==typeof l.cwd?l.cwd:"")?tf(h,p)??(p?tf(`${p.replace(/\/+$/,"")}/${h}`):null)??`?${u}`:p??"")}:{},exitCode:n.exitCode,labels:n.labels,outcome:x,...n.compound?{compound:n.compound}:{},...f?{evidence:g?`${f} \xb7 ${g}`:f}:{},...g?{otherRun:{kind:"unjudged",conclusion:g}}:{},...v?{reason:v}:{}}})}let c=e.toolName.toLowerCase().split(/[.:/]/).pop()??"",d=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 n=Array.isArray(u.findings)?u.findings.length:null;if(null!==n&&n>0)return{...i,stage:"review",action:t,findings:n,outcome:"failed"};let r=Array.isArray(u.reviewers)?u.reviewers:[];return!1===u.passable||r.some(e=>!e||"object"!=typeof e||!("status"in e)||"ok"!==e.status)?{...i,stage:"review",action:t,findings:n,outcome:"unverified",unusable:!0}:{...i,stage:"review",action:t,findings:n,outcome:null===n?"unobserved":"done"}}if("git_finalize"===c){let t="string"==typeof e.input.message?iQ(e.input.message):void 0,n=t?{title:t}:{};if(!d)return{...i,stage:"commit",commit:null,docsOnly:!1,...n,outcome:s};let r=i7(d,u),a=d.isError||!1===u.ok,o=!a&&(!0===u.ok||null!==r),l=e.input.files,c=o&&Array.isArray(l)&&l.length>0&&l.every(e=>"string"==typeof e&&iG(e));return{...i,stage:"commit",commit:o?r:null,docsOnly:c,...n,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=i7(d,u),n=d.isError||!1===u.ok,r=!n&&null!==t,a=u.files,o=r&&Array.isArray(a)&&a.length>0&&a.every(e=>"string"==typeof e&&iG(e));return{...i,stage:"commit",commit:r?t:null,docsOnly:o,outcome:r?"done":n?"failed":"unobserved"}}if("eval"===c)return function(e,t,n){let r=function(e){if("string"==typeof e.code)return e.code;let t=e.cells;return Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"").join("\n"):""}(e.input);if(!i8.test(r))return null;let a=i3.exec(r)?.[2],i=void 0===a?void 0:iQ(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:n};let o=sh(t),l=i4.exec(o),c=l?(l[1]??l[2]).toLowerCase():null;if(!c&&i6.test(o))return null;let d=i5.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(iZ,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(iY,e.input.action);if(!tg(e.toolName)&&!tx(e.toolName))return!1;let n=e.input.file_path??e.input.path;return"string"!=typeof n||/^[a-zA-Z]:[\\/]/.test(n)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(n)}(e,c))return!a&&t?.isError?null:(tg(e.toolName)||tx(e.toolName))&&tk(e.input,d,r)?{...i,stage:"investigate",outcome:a?"unobserved":t||!n?"done":"running"}:{...i,stage:"edit",outcome:d?"done":s,..."task"===c?{dispatch:!0}:{},...!function(e,t,n){if(!t||!(tg(e.toolName)||tx(e.toolName)))return!1;let r=tw(e.input,t);return r.length>0&&r.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let n=t?tf(t)??t:void 0,r=tz(tf(e,t)??e,n);if(/^[\\/]/.test(r)||/^[a-zA-Z]:[\\/]/.test(r))return!1;let a=r.split(/[\\/]/).filter(e=>""!==e&&"."!==e);return"HANDOFF.md"===a.at(-1)||"doc"===a[0]&&"history"===a[1]&&a.length>2})(e,n))}(e,d,r)?{}:{recordOnly:!0}};return Object.hasOwn(iJ,c)?{...i,stage:"investigate",outcome:a?"unobserved":t||!n?"done":"running"}:null}(e,i,n,a))?r:r?[r]:[])){let n=i?void 0:x.get(e.toolCallId);"check"===s.stage&&"noResult"===s.reason&&n&&se(n)&&(s.reason="noCompletion"),b.push({step:s,order:t})}}),s=null,o=!1,b.forEach((e,t)=>{let{step:n,order:r}=e;if("commit"===n.stage&&"done"===n.outcome&&n.commit&&(s={step:{...n,commit:n.commit},order:r},o=!1),"edit"!==n.stage||"done"!==n.outcome||n.dispatch||n.recordOnly||(o=!0),"ci"!==n.stage||!s)return;let a=s,i=ip(n.command).commands.flatMap(({words:e})=>sf(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(i){let e,s=sb(i),l=e=>(f.publishRuns.get(e)?.order??1/0)<=r;if((e=sI(n.command,l).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){sM(n.command,l)||"passed"!==n.outcome&&"failed"!==n.outcome||(s&&"passed"===n.outcome&&f.watched.push({id:s,order:r}),b[t]={order:r,step:{...n,outcome:"unverified",evidence:void 0,otherRun:{kind:"publish",outcome:n.outcome}}});return}let c=s?f.runs.filter(e=>e.id===s):[],d=c.find(e=>null!==e.sha)?.sha;if(!d||c.some(e=>sE(e,a,f))){d&&o&&"passed"===n.outcome&&(b[t]={order:r,step:{...n,stale:!0}});return}if("passed"===n.outcome||"failed"===n.outcome){let e=d.slice(0,7);b[t]={order:r,step:{...n,outcome:"unverified",evidence:`run ${s} \xb7 ${e}`,otherRun:{kind:"commit",sha:e,outcome:n.outcome}}}}return}if("unverified"!==n.outcome)return;let l=f.runs.find(e=>e.order===r&&null!==e.workflow&&Object.hasOwn(su,e.workflow)&&sE(e,a,f));if(!l||"completed"!==l.status||"string"!=typeof l.conclusion)return;let c="success"===l.conclusion?"passed":Object.hasOwn(sL,l.conclusion)?"failed":null;c&&(b[t]={order:r,step:{...n,outcome:c,evidence:`run ${l.id??"?"} \xb7 ${l.status} ${l.conclusion}`,..."passed"===c&&o?{stale:!0}:{}}})}),b.forEach((e,t)=>{let{step:n,order:r}=e;if("deploy"!==n.stage||"unverified"!==n.outcome&&"unobserved"!==n.outcome)return;let a=function(e){let t=[],n=(e,r)=>{let a=iy(e);if(null!==a){if(r<3)for(let e of ip(a).commands)n(e.words,r+1);return}if(!iC(e))return;let i=ij(e),s=iS.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 ip(e).commands)n(t,0);return 1===t.length?t[0]:null}(n.command),i=x.get(n.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=r;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 sh(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=s$.exec(i);if(s&&Date.parse(s[1])>=l&&sR(s[2],a)){b[t]={order:r,step:{...n,outcome:"passed",evidence:`${s[1]} READY ${s[2].slice(0,12)}`}};return}let o=sP.exec(i);if(o&&Date.parse(o[1])>=l){b[t]={order:r,step:{...n,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 n=e;if("ci"===n.stage){let e=ip(n.command).commands.flatMap(({words:e})=>sf(e)).find(e=>"run"===e[0]&&"watch"===e[1]),r=e?sb(e):null;r&&"passed"===n.outcome&&f.watched.push({id:r,order:t}),!n.compound&&sM(n.command,e=>y(e,t))&&(n={toolCallId:n.toolCallId,attempt:n.attempt,stage:"investigate",outcome:"passed"===n.outcome||"unverified"===n.outcome?"done":n.outcome})}if("edit"!==n.stage||"done"!==n.outcome||n.dispatch){if("check"===n.stage||"review"===n.stage||"ci"===n.stage){let e="check"===n.stage?`check:${sa(n)}`:n.stage,t=u.get(e);(t?.outcome!=="failed"||sn(n.outcome))&&u.set(e,{stage:n.stage,outcome:n.outcome,order:l.length})}}else{let e=sr(u);e&&(c.push({from:e,attempt:d}),d+=1),u=new Map,p=l.length,n.recordOnly||(h=l.length)}n.attempt=d,m.set(n,t),l.push(n)}let w=!1;l.forEach((e,t)=>{t<("commit"===e.stage||w&&("ci"===e.stage||"deploy"===e.stage)?h:p)&&"investigate"!==e.stage&&"edit"!==e.stage&&("passed"===e.outcome||"done"===e.outcome)&&(e.stale=!0),"commit"===e.stage&&"done"===e.outcome&&(w=!0)});let k=l.filter(e=>"commit"===e.stage&&"done"===e.outcome&&e.attempt===d).at(-1),j=k?m.get(k)??-1:-1,S=k&&!k.stale&&k.commit&&sp.test(k.commit)?{sha:k.commit.toLowerCase(),order:j}:null,C=S?function(e,t,n){let r=e.watched.find(({id:n,order:r})=>{let a=e.publishRuns.get(n);return r>t.order&&a?.sha===t.sha&&a.order>t.order&&a.order<=r});if(!r)return null;let a=new Map;for(let t of e.heads)t.order>r.order&&a.set(`${t.repo}#${t.ref}`,t);let i=[...n,...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:r.id};return null}(f,S,r)??(f.nothingToPublish.some(({sha:e,order:t})=>e===S.sha&&t>S.order)?{kind:"nothingToPublish",commit:S.sha}:null):null;if(C?.kind==="nothingToPublish"){let e=C.commit;l.forEach((t,n)=>{var r;let 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)&&(r=t.command,!((a=ip(r).commands.flatMap(({words:e})=>sf(e))).length>0&&a.every(t=>"run"===t[0]&&"list"===t[1]&&sg(t,["-c","--commit"])?.toLowerCase()===e))))return;let s={toolCallId:t.toolCallId,attempt:t.attempt,stage:"investigate",outcome:"done"};l[n]=s,m.set(s,i)})}let N=il.map(e=>{let t=l.filter(t=>t.stage===e),n="investigate"===e?t:t.filter(e=>e.attempt===d);return{stage:e,status:function(e,t){if(0===t.length)return"waiting";if("check"!==e){let e=new Set,n=null;for(let r of t){let t=r.stale?"stale":r.outcome;if("failed"!==n||sn(r.outcome)){if(null!==n&&!("ci"!==r.stage||sl(t))&&!ip(r.command).commands.some(({words:e})=>sf(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===n&&(sc(r)?.every(t=>e.has(t))??!1);if(sl(n)||t)continue}if(n=t,"stale"===t||"passed"===r.outcome||"failed"===r.outcome)for(let t of sc(r)??[])e.add(t)}}return n??"waiting"}let n="done";for(let e of si(t)){let t=e.stale?"stale":e.outcome;so[t]>so[n]&&(n=t)}return n}(e,n),steps:n,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),T=N[il.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[il.indexOf("ci")],R=M.steps.some(e=>(m.get(e)??1/0)>j);C&&("waiting"===M.status||("unverified"===M.status||"stale"===M.status)&&!R)?M.status="notNeeded":C=null;let E=-1;N.forEach((e,t)=>{"waiting"!==e.status&&"failed"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status&&"stale"!==e.status&&e.steps.some(e=>!e.stale&&"failed"!==e.outcome&&!ss(e))&&(E=t)});let L=null;if(n&&l.length>0)if(sr(u))L={stage:"edit",returning:!0};else if(E<0)L={stage:N.find(e=>"waiting"!==e.status)?.stage??il[0],returning:!1};else{let e=N[E].steps.at(-1);if(e?.stage==="review"&&e.unusable)L={stage:"review",returning:!1};else{let e=N.slice(E+1).find(e=>"skipped"!==e.status&&"notNeeded"!==e.status);L=e?{stage:e.stage,returning:!1}:null}}if(N.forEach((e,t)=>{t<E&&"waiting"===e.status&&(e.status="skipped")}),!n&&l.length>0){let e=!I;for(let t of N)"waiting"===t.status&&(t.status=e&&("ci"===t.stage||"deploy"===t.stage)?"notNeeded":"skipped")}return{steps:l,attempt:d,loops:c,stages:N,current:function(e,t,n){let r=e.at(-1);if(!r)return null;if(!n||n.stale)return r.stage;let 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(s_,e.status));return i?.stage??a.at(-1)?.stage??r.stage}(l,N,k),reached:E<0?null:il[E],next:L,publication:C}}let s_={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0};function sz(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 sW(e,t,n){let r=[],a=[],i=null;for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){a.push(n);continue}if(tE(n.toolName)){let e=tR(n,t.get(n.toolCallId));"authoritative"===e.kind&&(i=e.phases);continue}let e=iq(n,t.get(n.toolCallId));e&&r.push(e)}return{checks:r,dispatchCalls:a,files:tT(e,t,n),remaining:i?sz(i):null}}function sO(e,t,n){let r=[];for(let a=Math.max(0,t);a<Math.min(e.length,n);a++){let t=e[a];"assistant"===t.role&&r.push(...t.content??[])}return r}function sD(e,t,n){let r=[],a=null;for(let i=Math.max(0,t);i<Math.min(e.length,n);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");r.push({text:e,after:a})}}return r}function sH(e,t){var n;let r=t;for(;r>=0&&(n=e[r],n?.role==="custom"?"compaction"===n.customType:n?.role==="user"&&("steer"===io(n)||function(e){if(e===a6||e===a3||e===a7||a9.has(e))return!0;let[t,n]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==n&&n.startsWith("requestId=")}(is(n))));){let t=r-1;for(;t>=0&&"user"!==e[t].role;)t-=1;r=t}return r}function sU(e,t,n,r){let a=Math.min(e.length,r),i=new Map;for(let t=Math.max(0,n);t<a;t++){let n=e[t];"toolResult"===n.role&&i.set(n.toolCallId,t)}let s=[];for(let r=Math.max(0,n-1);r<a;r++){let a=e[r];if(r>=n&&"assistant"===a.role)for(let e of a.content??[]){if("toolCall"!==e.type||!tE(e.toolName))continue;let n=tR(e,t.get(e.toolCallId));"authoritative"===n.kind&&s.push({at:i.get(e.toolCallId)??r,phases:n.phases})}for(let e of a.trackerTodos??[]){let t=tM(e);t&&s.push({at:r+.5,phases:t})}}let o=null;for(let e of s)(!o||e.at>=o.at)&&(o=e);return o?o.phases:null}function sB(e,t,n,r=0,a=[]){for(let i=Math.max(0,r);i<Math.min(e.length,n);i++){let n=e[i];if("assistant"===n.role)for(let e of n.content??[])"toolCall"===e.type&&a.push(...sS(e,t.get(e.toolCallId)))}return a}function sq(e,t,n){let r=null,a=null;for(let i=Math.max(0,t-1);i<Math.min(e.length,n);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===r||e<r)&&(r=e),(null===a||e>a)&&(a=e))}return{startedAt:r,endedAt:a}}function sV(e,t){if(0===e.length)return null;let n=[...e].sort((e,t)=>e-t),r=(n.length-1)*t,a=Math.floor(r),i=Math.ceil(r);return n[a]+(n[i]-n[a])*(r-a)}let sK=["investigate","implement","verify","report"],sG={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},sJ={bash:!0,eval:!0};function sZ(e){let t=[],n=new Map;for(let r of e)if("toolResult"===r.role&&n.set(r.toolCallId,r),"assistant"===r.role&&Array.isArray(r.content))for(let e of r.content)"toolCall"===e.type&&t.push(e);return{blocks:t,results:n}}function sY(e,t,n,r){return!0===sG[t]&&!tk(e.input,n.get(e.toolCallId),r)}function sX(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function sQ(e){return"yield"===sX(e)&&!Array.isArray(e.input?.type)}function s0(e,t){if(0===e.length)return null;let{blocks:n,results:r}=sZ(e),a=-1;n.forEach((e,t)=>{sQ(e)&&(a=t)});let i=a>=0&&a===n.length-1,s=i?n.findLastIndex((e,t)=>t<a&&sQ(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 n.slice(s)){let n=sX(e);if(sY(e,n,r,t))"verify"===o.phase&&(o.reedits+=1),l=!0,o.phase="implement",o.verifiedAfterEdit=!1;else if(sJ[n]){if(o.phase=l?"verify":"investigate",l){o.verifiedAfterEdit=!0;let t=iq(e,r.get(e.toolCallId));t?.state==="passed"?o.checks.passed+=1:t?.state==="failed"?o.checks.failed+=1:t&&(o.checks.unknown+=1)}}else"yield"===n&&(o.phase="report",l=!1);o.calls[o.phase]+=1}return o}function s1(e,t){if(!e)return{run:null,stations:sK.map(e=>({phase:e,state:"unobserved",calls:0}))};let n=t&&e.ended?{calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:!1,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1}:e,r=t?sK.indexOf(n.phase):sK.findLastIndex(e=>n.calls[e]>0),a=sK.map((e,a)=>{let i,s=n.calls[e];return i=t&&e===n.phase?"active":s>0?"verify"!==e||n.verifiedAfterEdit?"done":"stale":a<r?"skipped":t?"waiting":"none",{phase:e,state:i,calls:s}});return{run:n,stations:a}}function s2(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function s8(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:n}}function s4(e){return"pending"===e||"running"===e}let s5=new Map;function s6(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function s3(e){return e instanceof aP&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function s7(e,{sessionId:t,client:n,enabled:r}){let[i,s]=(0,a.useState)(s5),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 n=!1,r=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&&(n=!0),r.set(a,s)}return r.size!==t.size&&(n=!0),n?r:t})},[]),d=e.map(e=>`${e.key}|${s6(e)}`).join("\n");return(0,a.useEffect)(()=>{if(!r)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=s6(e);s.get(e.key)?.signature!==t&&s.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(r,a,i,s)=>{if(!r.archiveName){a.state={kind:"empty",source:"live",note:s};return}try{let o=await n.getArchiveTranscript(t,r.archiveName,400,i);if(e)return;0===a.collected.length&&(a.collected=o.entries.flatMap((e,t)=>{let n=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:n,message:e.message}]:e.irc?[{id:n,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),a.state=0===o.entries.length?{kind:"empty",source:"archive",note:s}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:s}}catch(n){if(e||i.aborted)return;let t=s3(n);a.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(r,a)=>{let i=s.get(r.key);if(i){if(!r.liveId)return void await u(r,i,a);try{var o,l;let s=await n.getLiveTranscript(t,r.liveId,i.nextByte,a);if(e)return;let c=(o=s.entries,l=s.fromByte,o.flatMap((e,t)=>{let n=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:n,message:s8(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:n,irc:{from:"string"==typeof t.from?t.from:void 0,message:"string"==typeof t.message?t.message:void 0}}]}return[]}));s.reset||0===s.fromByte?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(r,i,a)}catch(t){if(e||a.aborted)return;if(r.archiveName){let e=s3(t);await u(r,i,a,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=s3(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=>s4(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)}},[n,r,c,t,d]),i}let s9=(0,a.createContext)({ledger:aB,subagents:[],toolResults:new Map}),oe="omp-web:flow-motion",ot=new Set,on=null;function or(){if(null===on)try{on="paused"===window.localStorage.getItem(oe)}catch{on=!1}return on}function oa(e){return ot.add(e),()=>{ot.delete(e)}}function oi(){return(0,a.useSyncExternalStore)(oa,or,()=>!1)}function os({paused:e}){let{st:t}=ax();return(0,r.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){on=e;try{e?window.localStorage.setItem(oe,"paused"):window.localStorage.removeItem(oe)}catch{}for(let e of ot)e()})(!e),children:t("graph.motion.pause")})}function oo(e,t,n){return n&&t.current===e.stage?"active":"waiting"===e.status?"deploy"===e.stage?"approval":"waiting":"skipped"===e.status||"notNeeded"===e.status?"skipped":"stale"===e.status?"stale":"done"===e.status||"passed"===e.status?"done":"failed"===e.status||"running"===e.status?e.status:"unverified"}function ol(e){return e.stale?"stale":e.outcome}let oc=(0,r.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})});function od({look:e}){return(0,r.jsxs)("span",{className:"flow-node","aria-hidden":"true",children:[("done"===e||"stale"===e)&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:"stale"===e?"3 4":void 0,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}),"unverified"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"6",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"18",x2:"12",y2:"18.5"})]}),"failed"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"7",y1:"7",x2:"17",y2:"17"}),(0,r.jsx)("line",{x1:"17",y1:"7",x2:"7",y2:"17"})]}),"skipped"===e&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:(0,r.jsx)("line",{x1:"6",y1:"12",x2:"18",y2:"12"})})]})}function ou({outcome:e}){let t={className:"flow-check-icon",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"stale"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l4 2"})]}):"passed"===e||"done"===e?(0,r.jsx)("svg",{...t,strokeWidth:2.5,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}):"failed"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2.5,children:[(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"}),(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"})]}):"running"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0"}),(0,r.jsx)("path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0"}),(0,r.jsx)("path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7"}),(0,r.jsx)("path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8"}),(0,r.jsx)("path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69"}),(0,r.jsx)("path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8"}),(0,r.jsx)("path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69"}),(0,r.jsx)("path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7"})]}):(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,r.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}function op({step:e,st:t}){let n=t(`flow.state.${e.outcome}`);if(e.stale)n=t("passed"===e.outcome?"flow.state.stale":"flow.state.staleDone");else if("review"===e.stage&&"failed"===e.outcome&&null!==e.findings){let r=1===e.findings?"flow.state.findings.one":"flow.state.findings";n=t("resolve"===e.action?"flow.state.open":r,{count:e.findings})}else"review"===e.stage&&e.unusable?n=t("flow.state.reviewUnusable"):"review"===e.stage&&"done"===e.outcome&&(n=t("flow.state.noFindings"));return(0,r.jsxs)("span",{className:"flow-tone","data-tone":ol(e),children:[n,"commit"===e.stage&&e.commit&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsxs)("span",{className:"flow-sha-tail",children:["\xb7\xa0",(0,r.jsx)("code",{className:"flow-sha",children:e.commit.slice(0,7)})]})]})]})}let oh={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"},om={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 of({step:e,label:t,st:n}){let a=ss(e),i=e.compound?.stages.map(e=>n(`flow.stage.${e}`)).join("\xb7")??"",s=e.otherRun,o=e.reason?oh[e.reason]:void 0,l=a?n("flow.why.compoundConfirmed",{stages:i}):s?.kind==="unjudged"?n("flow.why.watched.unjudged",{conclusion:s.conclusion}):s?n(`flow.why.watched.${s.outcome}`):n("flow.why.exitZero"),c=a?n("flow.why.compoundMissing"):o?n(o,{label:t}):"check"===e.stage?n("flow.why.check",{label:t}):s?.kind==="commit"?n("flow.why.ciOtherRun",{sha:s.sha}):s?.kind==="publish"?n("flow.why.ciPublishRun"):s?.kind==="unjudged"?n("flow.why.ciUnjudged",{conclusion:s.conclusion}):n(`flow.why.${e.stage}`),d=e.reason?n(om[e.reason]):a?n("flow.next.compound"):null,u="unverified"===e.outcome||"unobserved"===e.outcome&&void 0!==e.reason,p=null!==e.exitCode?n("flow.exit",{code:e.exitCode}):n("failed"===e.outcome?"flow.exit.error":"running"===e.outcome?"flow.state.running":"flow.exit.none");return(0,r.jsxs)("div",{className:"flow-raw",children:[u&&(0,r.jsxs)("p",{className:"flow-why",children:["unverified"===e.outcome&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("b",{children:n("flow.why.confirmed")})," ",l,(0,r.jsx)("br",{})]}),(0,r.jsx)("b",{children:n("flow.why.missing")})," ",c,d&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("br",{}),(0,r.jsx)("b",{children:n("flow.why.next")})," ",d]})]}),e.stale&&(0,r.jsx)("p",{className:"flow-why",children:n("flow.why.stale")}),void 0===e.commandKey?(0,r.jsx)("code",{className:"flow-raw-command",children:e.command}):(0,r.jsx)("p",{className:"flow-why",children:n("flow.commandOmitted")}),(0,r.jsx)("div",{className:"flow-exit",children:p}),e.evidence&&(0,r.jsxs)("div",{className:"flow-exit",children:[n("flow.evidence")," ",(0,r.jsx)("code",{className:"flow-evidence",children:e.evidence})]})]})}function og({steps:e,st:t,attempts:n=!1}){return(0,r.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=ol(e),s=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ou,{outcome:i}),(0,r.jsx)(op,{step:e,st:t}),(0,r.jsxs)("span",{className:"flow-check-label",children:[n?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${a}`:a,ss(e)&&(0,r.jsx)("span",{className:"flow-compound",children:t("flow.compound.failed")})]})]});return"check"!==e.stage&&"ci"!==e.stage&&"deploy"!==e.stage?(0,r.jsx)("li",{className:"flow-check","data-result":i,children:(0,r.jsx)("div",{className:"flow-check-head",children:s})},e.toolCallId):(0,r.jsx)("li",{className:"flow-check","data-result":i,children:(0,r.jsxs)("details",{children:[(0,r.jsxs)("summary",{className:"flow-check-head",children:[s,(0,r.jsxs)("span",{className:"flow-disclose",children:[t("flow.details"),oc]})]}),(0,r.jsx)(of,{step:e,label:a,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function ox({steps:e,st:t}){return 0===e.length?null:(0,r.jsxs)("details",{className:"flow-earlier",children:[(0,r.jsxs)("summary",{className:"flow-earlier-toggle",children:[t("flow.earlier",{count:e.length}),oc]}),(0,r.jsx)(og,{steps:e,st:t,attempts:!0})]})}function ov({view:e,steps:t,st:n}){if(0===t.length)return null;if("check"!==e.stage)return(0,r.jsx)(og,{steps:t,st:n});let a=si(t),i=e=>{let t=ob.indexOf(ol(e));return t<0?ob.length:t},s=[...a].sort((e,t)=>i(e)-i(t)),o=t.filter(e=>!a.includes(e));return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(og,{steps:s,st:n}),o.length>0&&(0,r.jsxs)("details",{className:"flow-earlier",children:[(0,r.jsxs)("summary",{className:"flow-earlier-toggle",children:[n("flow.repeats",{count:o.length}),oc]}),(0,r.jsx)(og,{steps:o,st:n})]})]})}let ob=["failed","unverified","unobserved","stale","running","passed"];function oy({view:e,flow:t,live:n,st:a,compact:i=!1}){if(n&&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 n of si(e.steps))t.set(ol(n),(t.get(ol(n))??0)+1);return ob.filter(e=>t.has(e)).map((e,n)=>(0,r.jsxs)("span",{children:[n>0&&" \xb7 ",(0,r.jsx)("span",{className:"flow-tone","data-tone":e,children:a(`flow.count.${e}`,{count:t.get(e)??0})})]},e))}return"check"===e.stage||"edit"===e.stage?(0,r.jsx)("span",{className:"flow-tone","data-tone":e.status,children:a(`flow.state.${e.status}`)}):(0,r.jsx)(op,{step:s,st:a})}function ow({flow:e,live:t,st:n,id:a}){let i=e.loops[e.loops.length-1],s=i?e.steps.filter(e=>e.stage===i.from):[],o=n("flow.loop.badge",{attempt:e.attempt});return(0,r.jsxs)("div",{className:"flow-chain-panel",id:a,children:[(0,r.jsxs)("div",{className:"flow-chain-wrap","data-loop":i?"":void 0,style:i?{"--loop-from":il.indexOf(i.from)}:void 0,children:[(0,r.jsx)("ol",{className:"flow-chain","aria-label":n("flow.aria"),children:e.stages.map(a=>{let i=oo(a,e,t);return(0,r.jsxs)("li",{className:"flow-link","data-state":i,"aria-current":"active"===i?"step":void 0,children:[(0,r.jsx)(od,{look:i}),(0,r.jsx)("span",{className:"flow-link-name",children:n(`flow.stage.${a.stage}`)}),(0,r.jsx)("span",{className:"flow-link-state",children:(0,r.jsx)(oy,{view:a,flow:e,live:t,st:n,compact:!0})})]},a.stage)})}),i&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flow-loop","aria-hidden":"true",children:[(0,r.jsx)("svg",{width:"22",height:"15",viewBox:"0 0 22 15",children:(0,r.jsx)("polyline",{points:"3 12 11 3 19 12",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,r.jsx)("span",{className:"flow-loop-count",children:o})]}),(0,r.jsxs)("p",{className:"flow-loop-caption",children:[(0,r.jsx)("span",{className:"flow-loop-caption-count",children:o}),n("review"===i.from?"flow.loop.findings":"flow.loop.failed",{stage:n(`flow.stage.${i.from}`),attempt:i.attempt})]})]})]}),s.length>0&&(0,r.jsx)("div",{className:"flow-chain-attempts",children:(0,r.jsx)(og,{steps:s,st:n,attempts:!0})})]})}function ok({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:i=!0,cwd:s}){let o=(0,a.useMemo)(()=>t.filter(e=>s4(e.status)),[t]),l=r&&!!e&&o.length>0,c=s7((0,a.useMemo)(()=>o.map(e=>({key:e.id,liveId:e.id,status:e.status})),[o]),{sessionId:e??"",client:n,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 n=new AbortController,r=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([n.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!n.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),i=r.some(e=>!s.histories[e]))}catch{}finally{if(!n.signal.aborted){let e=i&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{n.abort(),window.clearTimeout(t)}},[p,l,e]),(0,a.useMemo)(()=>{let t=new Map;if(!l)return t;let n=d&&d.sessionId===e?d.histories:void 0;for(let e of o){let r=(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:n,results:r}=sZ(e),a="investigate",i=!1;for(let e of n){let n=sX(e);sY(e,n,r,t)?(i=!0,a="implement"):sJ[n]?a=i?"verify":"investigate":"yield"===n&&(a="report",i=!1)}return a}(r,s),trace:s0(r,s),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=tL([...e],t);if(!n)return null;let r=tP(n);return 0===r.total||null===r.percent?null:{completed:r.completed,total:r.total,percent:r.percent,activeTask:r.activeTask?.content??null}}(r),history:n?.[e.id]??null})}return t},[o,s,d,l,c,e,i])}function oj(e,t){let n=s2(t);return n?0===n.hours?e("duration.minutes",{minutes:n.minutes}):0===n.minutes?e("duration.hours",{hours:n.hours}):e("duration.hoursMinutes",{hours:n.hours,minutes:n.minutes}):e("duration.underMinute")}function oS(e,t){let n=Math.floor(t/1e3);return n<60?e("duration.seconds",{seconds:n}):n<3600?e("duration.minutesSeconds",{minutes:Math.floor(n/60),seconds:n%60}):oj(e,t)}function oC({phase:e}){let{st:t}=ax();return(0,r.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,r.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,r.jsx)("span",{"aria-hidden":"true",children:sK.map((n,a)=>(0,r.jsxs)("span",{children:[a>0&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,r.jsx)("span",{"data-current":n===e?"":void 0,style:n===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${n}`)})]},n))})]})}let oN={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function oT(e,t){let n=t.passed+t.failed+t.unknown,a=t.failed>0?"failed":t.unknown>0?"unverified":"passed";return(0,r.jsx)("span",{className:"flow-tone","data-tone":a,children:e("subflow.checks",{passed:t.passed,total:n})})}function oI({flow:e,live:t,verdict:n,attempts:a}){let{st:i}=ax(),s=oi(),o=e.stations.findIndex(e=>"active"===e.state),l=sK.indexOf("implement"),c=a.filter(e=>"rework"===e.verdict).length,d=n?"accepted"===n.verdict?"done":"unverified":"waiting",u=n?`${i(`verdict.${n.verdict}`)}${null!==n.attempt&&n.attempt>1?` \xb7 ${i("verdict.attempt",{attempt:n.attempt})}`:""}`:i(t?"flow.state.waiting":"verdict.none");return(0,r.jsxs)("div",{className:"subagent-flow",children:[t&&o>=0&&(0,r.jsx)(os,{paused:s}),(0,r.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,n)=>{let a=oN[t.state];return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":t.phase,"data-state":a,"data-loop":c>0&&n>=l?"":void 0,"aria-current":"active"===t.state?"step":void 0,style:{"--col":n+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:i(`phase.${t.phase}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(od,{look:a}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:function(e,t,n){let a="verify"===t.phase&&null!==n&&n.checks.passed+n.checks.failed+n.checks.unknown>0;switch(t.state){case"active":return a&&n?(0,r.jsxs)(r.Fragment,{children:[e("flow.state.running")," \xb7 ",oT(e,n.checks)]}):e("flow.state.running");case"waiting":return e("flow.state.waiting");case"skipped":return e("flow.state.skipped");case"none":return e("detail.stageNone");case"unobserved":return e("subflow.unobserved");case"stale":return e(n&&n.checks.passed>0?"flow.state.stale":"flow.state.staleDone");case"done":if("report"===t.phase)return e("subflow.reported");if(a&&n)return oT(e,n.checks);if("implement"===t.phase&&n&&n.reedits>0)return`${e("subflow.calls",{count:t.calls})} \xb7 ${e("subflow.reedits",{count:n.reedits})}`;return e("subflow.calls",{count:t.calls})}}(i,t,e.run)})]})]})},t.phase)}),(0,r.jsx)("li",{className:"flow-graph-station","data-stage":"verdict","data-state":d,style:{"--col":sK.length+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:i("graph.join")}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(od,{look:d}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:u})]})]})}),c>0&&(0,r.jsxs)("li",{className:"flow-graph-return",style:{"--from":l+1,"--to":sK.length+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsx)("span",{className:"flow-graph-return-text",children:i("subflow.rework",{count:c})})]})]})]})}function oM(e,t){let n=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${n} \xb7 ${t.activeTask}`:n}function oR({snapshot:e,view:t,id:n}){var a,i,s;let o,l,c,{st:d}=ax(),u=nw(5e3),p="number"!=typeof(o=e.progress?.durationMs)?null:o+(("pending"===e.status||"running"===e.status)&&e.lastUpdate>0?Math.max(0,u-e.lastUpdate):0);if(null===p)return null;let h=function(e,t){if(!e||e.rework||null===t||e.durationsSec.length<3)return null;let n=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(n.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:n.length};let r=sV(n,.5)??0;return{kind:"remaining",p25Ms:sV(n,.25)??0,medianMs:r,p75Ms:sV(n,.75)??0,samples:n.length,percent:Math.round(t/(t+r)*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,r.jsxs)("span",{id:n,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,r.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:d("eta.elapsed",{duration:oS(d,p)})}),g?.rework&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:d("eta.reworkHint"),children:null!==x&&x>=0?d("eta.rework",{attempt:g.attempt,duration:oS(d,x)}):d("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{title:d("eta.hint"),children:d("eta.remaining",{range:(i=h.p25Ms,s=h.p75Ms,l=s2(i),c=s2(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:oj(d,i),high:oj(d,s)})),samples:h.samples})})," \xb7 ",(0,r.jsx)("span",{style:f,children:d("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:{color:"var(--warning)"},title:d("eta.hint"),children:0===h.longerRuns?d("eta.overrun",{longest:oj(d,h.longestMs)}):d("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==m&&t.todo&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:d("eta.byTodoHint"),children:m<6e4?d("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):d("eta.byTodo",{duration:oj(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"},oL={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function o$({maker:e,st:t}){let n=e.verdict?.verdict??"none",a=e.verdict?.attempt;return(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(oE[e.run])}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":n,children:[t(oL[n]),null!=a&&a>1?` \xb7 ${t("verdict.attempt",{attempt:a})}`:null]})]})}function oP(e,t){let n=[],r=new Map;for(let t of e)"message"in t&&("assistant"===t.message.role?n.push(...t.message.content??[]):"toolResult"===t.message.role&&r.set(t.message.toolCallId,t.message));return sW(n,r,t)}function oA(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function oF(e,t){let n=e?.state;return n?.kind!=="ready-live"?null:s0(n.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function o_({maker:e,st:t}){let n=e.runTitle??e.title;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:n,children:n}),e.priorVerdict&&!e.runTitle&&(0,r.jsx)("span",{className:"answer-dispatch-title-note",children:t("subflow.firstTitle")})]})}function oz({calls:e}){let{ledger:t,subagents:n,toolResults:i,onOpenPanel:s,sessionId:o,cwd:l,onOpenMaker:c,selectedMaker:d}=(0,a.useContext)(s9),{st:u}=ax(),{t:p}=(0,z.s)(),[h,m]=(0,a.useState)(!1),f=(0,a.useId)(),g=(0,a.useMemo)(()=>aO(),[]),x=(0,a.useMemo)(()=>e.flatMap(e=>aZ(e,i.get(e.toolCallId))??[]).map(e=>a0(e,n,t)),[e,i,n,t]),v=(0,a.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=aQ(e.member,n,t);return r?[r]:[]}),[x,n,t]),b=ok({sessionId:o,snapshots:v,client:g,enabled:!0,transcripts:h,cwd:l}),y=(0,a.useMemo)(()=>new Map(x.flatMap(e=>{let t=a1(e.member,n);return t?[[e.member.key,t]]:[]})),[x,n]),w=(0,a.useMemo)(()=>h?[...y].filter(([,e])=>!s4(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:oA(t)})):[],[y,h]),k=s7(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,r.jsxs)("section",{className:"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":h,"aria-controls":f,title:u(h?"dispatch.collapse":"dispatch.expand"),onClick:()=>m(e=>!e),children:[(0,r.jsx)("span",{className:"answer-dispatch-heading",children:u("dispatch.title",{count:x.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:u("dispatch.tally",{running:N,done:T,accepted:I})}),(0,r.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,r.jsx)("ul",{className:"answer-dispatch-list",id:f,"aria-label":h?p("dispatchLane.label"):void 0,children:x.map(e=>{var n;let 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?s1(f?o?.trace??null:oF(k.get(e.member.key),l),f):null,x=h?a2(e.member,t):[];return(0,r.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":m?"":void 0,children:[h?(0,r.jsx)(oW,{maker:e,phase:f&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,n){if(!t)return{kind:"unobserved"};if(s4(t.status))return{kind:"running"};let r=e?.state;if(!r||"loading"===r.kind)return{kind:"loading"};if("ready-live"===r.kind){let{checks:e}=oP(r.entries,n);return{kind:"counted",passed:e.filter(e=>"passed"===e.state).length,total:e.length}}return"empty"===r.kind&&"live"===r.source?{kind:"counted",passed:0,total:0}:{kind:"unobserved"}}(k.get(e.member.key),p,l),onOpen:p&&c?()=>c({key:`live:${p.id}`,toolCallId:e.member.toolCallId,origin:e.member.key,status:{run:e.run,verdict:e.verdict}}):null}):(0,r.jsxs)("div",{className:"answer-dispatch-line",children:[(0,r.jsx)(o_,{maker:e,st:u}),(0,r.jsx)(o$,{maker:e,st:u})]}),g&&(0,r.jsx)(oI,{flow:g,live:f,verdict:e.verdict,attempts:x}),h&&(0,r.jsx)(oD,{attempts:x}),s&&o&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[o.todo?`${oM(u,o.todo)} \xb7 `:null,(0,r.jsx)(oR,{snapshot:s,view:o})]}),h&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[i&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??u("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.model")}),(0,r.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${u("detail.fallback")}`:""}`:u("detail.modelNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${u("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("subflow.prior")}),(0,r.jsx)("dd",{children:(a=null!==(n=e.priorVerdict).attempt&&n.attempt>1?` \xb7 ${u("verdict.attempt",{attempt:n.attempt})}`:"",`${u(oL[n.verdict])}${a}${n.reason?` \xb7 ${n.reason}`:""}`)})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u(e.runTitle?"subflow.firstTitle":"subflow.runTitle")}),(0,r.jsx)("dd",{children:e.runTitle?e.title:u("detail.stageNone")})]}),e.verdict?.reason&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),h&&s&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:u("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:u("detail.openProcess")})]})]})}function oW({maker:e,phase:t,checks:n,onOpen:a}){let{st:i}=ax(),{t:s}=(0,z.s)(),o=e.verdict?.verdict??"none",l=i(oE[e.run]),c="running"===n.kind?null:"counted"===n.kind?s("dispatchLane.checks",{passed:n.passed,total:n.total}):s("loading"===n.kind?"dispatchLane.checksLoading":"dispatchLane.checksUnobserved");return(0,r.jsxs)("div",{className:"answer-dispatch-line is-lane",children:[(0,r.jsx)(o_,{maker:e,st:i}),(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?s("dispatchLane.runPhase",{run:l,phase:t}):l}),c&&(0,r.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===n.kind&&n.passed<n.total?"failed":n.kind,children:c}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsx)("span",{className:"answer-status-verdict","data-verdict":o,children:i(oL[o])})]}),a?(0,r.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,r.jsx)("span",{className:"answer-dispatch-unavailable",title:s("makerDetail.unavailable"),children:s("dispatchLane.unavailable")})]})}function oO({maker:e}){let{ledger:t,subagents:n,sessionId:i,cwd:s}=(0,a.useContext)(s9),o=(0,a.useMemo)(()=>aO(),[]),l="pending"===e.run||"running"===e.run,c=l&&"live"===e.runSource,d=l?aQ(e.member,n,t):void 0,u=ok({sessionId:i,snapshots:(0,a.useMemo)(()=>d?[d]:[],[d]),client:o,enabled:!0,transcripts:!0,cwd:s}),p=a1(e.member,n),h=(0,a.useMemo)(()=>p&&!s4(p.status)?[{key:e.member.key,liveId:p.id,status:p.status,archiveName:oA(p)}]:[],[p,e.member.key]),m=s7(h,{sessionId:i??"",client:o,enabled:!!i&&h.length>0}),f=d?u.get(d.id):void 0,g=s1(c?f?.trace??null:oF(m.get(e.member.key),s),c),x=a2(e.member,t);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oI,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,r.jsx)(oD,{attempts:x})]})}function oD({attempts:e}){let{t}=(0,z.s)();return e.length<2?null:(0,r.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":t("dispatchLane.label"),children:e.map((e,n)=>(0,r.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[n>0&&(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→ "}),null===e.attempt?t("dispatchLane.attemptUnknown"):t("dispatchLane.attempt",{attempt:e.attempt})," ",t(`dispatchLane.verdict.${e.verdict}`)]},`${e.attempt??"n"}-${n}`))})}let oH={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},oU={html:0,document:1,image:2},oB=/\.(?:md|mdx|markdown|txt)$/i;function oq(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function oV(e,t,n){return"investigate"!==e.stage&&("edit"===e.stage?n>0||e.earlier.length>0:e.steps.length>0||e.earlier.length>0||"ci"===e.stage&&null!==t.publication)}function oK({entry:e,st:t}){let n="running"===e.maker.run||"pending"===e.maker.run||"dispatching"===e.maker.run;return e.bar&&null!==e.durationMs?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"flow-graph-track","aria-hidden":"true",children:(0,r.jsx)("span",{className:"flow-graph-bar",style:{left:oq(e.bar.offset),width:oq(e.bar.width)}})}),(0,r.jsx)("span",{className:"flow-graph-time",children:oS(t,e.durationMs)})]}):(0,r.jsx)("span",{className:"flow-graph-time-missing",children:t(n?"summary.time.running":"summary.time.unobserved")})}function oG({entry:e,together:t,batch:n=!1,st:a}){let i=e.maker.member.workClass;return(0,r.jsxs)("span",{className:"flow-graph-maker-tags",children:[(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":i?void 0:"",children:a(`graph.kind.${i??"unknown"}`)}),n&&e.batchSize>1&&(0,r.jsx)("span",{className:"flow-graph-chip",children:a("graph.parallel.batch")}),t&&(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":"unknown"===e.concurrency?"":void 0,"data-concurrency":e.concurrency,children:a(`graph.concurrency.${e.concurrency}`)})]})}function oJ({selectable:e,selected:t,detailId:n,onSelect:a,className:i,children:s,style:o}){return e?(0,r.jsx)("button",{type:"button",className:i,style:o,"aria-pressed":t,"aria-controls":n,onClick:a,children:s}):(0,r.jsx)("div",{className:i,style:o,children:s})}function oZ({summary:e,makers:t,timings:n,live:i=!1,onOpenFile:s}){let o,l,c,{subagents:d,onOpenMaker:u}=(0,a.useContext)(s9),{st:p}=ax(),h=(0,a.useId)(),{flow:m}=e,f=(0,a.useMemo)(()=>(function(e,t,n,r){let a=function(e,t){let n=t.map(e=>null!==e.startedAt&&null!==e.durationMs?{start:e.startedAt,end:e.startedAt+e.durationMs}:null),r=e.startedAt,a=e.endedAt;for(let e of n)e&&((null===r||e.start<r)&&(r=e.start),(null===a||e.end>a)&&(a=e.end));let i=null!==r&&null!==a?a-r:0;return n.map(e=>e?i<=0||null===r?{offset:0,width:1}:{offset:(e.start-r)/i,width:(e.end-e.start)/i}:null)}(n,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((n,r)=>{let o="unknown";for(let t=0;t<e.length;t+=1)if(t!==r&&(i[r]&&i[t]||n.observedParallelWith?.has(e[t].member.key))){o="overlapped";break}return{maker:n,bar:a[r],durationMs:t[r]?.durationMs??null,concurrency:o,batchSize:s.get(n.member.toolCallId)??1,liveRunning:i[r]}});return{makers:o,parallel:o.some(e=>"overlapped"===e.concurrency)?"observed":o.some(e=>e.batchSize>1)?"batch":"none",files:r.filter(e=>!oB.test(e.filePath)),docs:r.filter(e=>oB.test(e.filePath))}})(t,n,e.span,e.files),[t,n,e.span,e.files]),[g,x]=(0,a.useState)(void 0),v=oi(),b=e.files.length,y=i&&m.current?m.stages.find(e=>e.stage===m.current):void 0,w=void 0===g?y&&oV(y,m,b)?`stage:${y.stage}`:(o=m.stages.filter(e=>oV(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?il.indexOf(k.from):-1,S=il.indexOf("edit"),C=y?il.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,n,r){let a=il.indexOf("edit"),i=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,s=[],o=n,l=e=>{let t=il.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=il.indexOf(c.from);for(let n of e)il.indexOf(n.stage)<=t&&(i(n)||n.earlier.length>0||n.stage===c.from)&&l(n);for(let t of(o&&(s.push("branch"),o=!1),s.push("return"),e))il.indexOf(t.stage)>=a&&i(t)&&l(t)}else for(let t of e)i(t)&&l(t);return o&&s.push("branch"),r&&s.push("outputs"),s}(m.stages,m.loops,f.makers.length>0,T),[i,m.stages,m.loops,f.makers.length,T]),[M,R]=(0,a.useState)(null),E=null!==M&&M<I.length?M:null;(0,a.useEffect)(()=>{if(null===E)return;let e=window.setTimeout(()=>R(E+1<I.length?E+1:null),800);return()=>window.clearTimeout(e)},[E,I.length]);let L=e=>{if(null!==E&&I.includes(e))return I[E]===e?"now":I.slice(0,E).includes(e)?"past":"ahead"},$=new Map;for(let e of f.makers){let t=e.maker.verdict?.verdict??"none";$.set(t,($.get(t)??0)+1)}let P=1===$.size&&$.has("accepted"),A=m.stages[S+1],F=A?oo(A,m,i):"skipped",_=f.makers.length>0&&(0,r.jsxs)("li",{className:"flow-graph-branch","data-loop":k&&j>S?"":void 0,"data-merge":"skipped"===F||"waiting"===F||"approval"===F?"quiet":void 0,"data-beat":L("branch"),children:[(0,r.jsxs)("p",{className:"flow-graph-branch-head",children:[(0,r.jsx)("span",{children:p(1===f.makers.length?"graph.branch.one":"graph.branch",{count:f.makers.length})}),"none"!==f.parallel&&(0,r.jsx)("span",{className:"flow-graph-chip","data-parallel":f.parallel,children:p(`graph.parallel.${f.parallel}`)})]}),(0,r.jsx)("ul",{className:"flow-graph-lanes",children:f.makers.map(e=>{let t=`maker:${e.maker.member.key}`;return(0,r.jsx)("li",{className:"flow-graph-lane","data-run":e.maker.run,"data-live":e.liveRunning?"":void 0,children:(0,r.jsxs)(oJ,{selectable:!0,selected:w===t,detailId:h,onSelect:()=>x(w===t?null:t),className:"flow-graph-maker",children:[(0,r.jsx)("span",{className:"flow-graph-maker-name",title:e.maker.title,children:e.maker.title}),(0,r.jsx)(oG,{entry:e,together:f.makers.length>1,st:p}),(0,r.jsx)("span",{className:"flow-graph-maker-time",children:(0,r.jsx)(oK,{entry:e,st:p})}),(0,r.jsx)(o$,{maker:e.maker,st:p})]})},e.maker.member.key)})}),(0,r.jsxs)("p",{className:"flow-graph-join","data-state":P?"done":"unverified",children:[(0,r.jsx)(od,{look:P?"done":"unverified"}),(0,r.jsx)("span",{className:"flow-graph-join-label",children:p("graph.join")}),(0,r.jsx)("span",{className:"flow-graph-join-counts",children:["accepted","rework","held","none"].filter(e=>$.has(e)).map(e=>(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":e,children:[p(oL[e])," ",$.get(e)]},e))})]})]},"branch"),z=k&&(0,r.jsxs)("li",{className:"flow-graph-return","data-beat":L("return"),style:{"--from":S+1,"--to":j+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsxs)("span",{className:"flow-graph-return-text",children:[(0,r.jsx)("b",{children:p("flow.loop.badge",{attempt:m.attempt})})," ",p("review"===k.from?"flow.loop.findings":"flow.loop.failed",{stage:p(`flow.stage.${k.from}`),attempt:k.attempt})]})]},"return"),W=m.stages.map((e,t)=>{let n=oo(e,m,i),a=`stage:${e.stage}`,s=e.steps.some(ss);return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":e.stage,"data-state":n,"data-again":e.earlier.length>0?"":void 0,"data-loop":k&&t>=S&&t<j?"":void 0,"data-beat":L(e.stage),"aria-current":"active"===n?"step":void 0,style:{"--col":t+1},children:(0,r.jsxs)(oJ,{selectable:oV(e,m,b),selected:w===a,detailId:h,onSelect:()=>x(a),className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:p(`flow.stage.${e.stage}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(od,{look:n}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:(0,r.jsx)(oy,{view:e,flow:m,live:i,st:p})})]}),s&&(0,r.jsx)("span",{className:"flow-compound",children:p("flow.compound.failed")})]})},e.stage)}),O=[];W.forEach((e,t)=>{O.push(e),t===S&&_&&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 n="ci"===t.stage&&null!==m.publication&&"notNeeded"===t.status,a="edit"===t.stage||n?[]:t.steps;D=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:p(`flow.stage.${t.stage}`)}),"ci"===t.stage&&m.publication&&(0,r.jsx)("p",{className:"flow-graph-note",children:"nothingToPublish"===m.publication.kind?p("flow.ci.nothingToPublish",{sha:m.publication.commit.slice(0,7)}):p("flow.ci.notNeeded",{run:m.publication.runId,repo:m.publication.repo,ref:m.publication.ref,sha:m.publication.sha.slice(0,7)})}),"edit"===t.stage&&(0,r.jsx)(aM,{files:e.files,onOpenFile:s}),(0,r.jsx)(ov,{view:t,steps:a,st:p}),(0,r.jsx)(ox,{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=a1(e.maker.member,d);D=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,r.jsx)(oG,{entry:e,together:f.makers.length>1,batch:!0,st:p}),(0,r.jsx)("p",{className:"flow-graph-detail-line",children:(0,r.jsx)(o$,{maker:e.maker,st:p})}),(0,r.jsx)("div",{className:"flow-graph-maker-time",children:(0,r.jsx)(oK,{entry:e,st:p})}),(0,r.jsx)(oO,{maker:e.maker}),t&&u?(0,r.jsx)("button",{type:"button",className:"flow-graph-open",onClick:()=>u({key:`live:${t.id}`,toolCallId:e.maker.member.toolCallId,origin:e.maker.member.key,status:{run:e.maker.run,verdict:e.maker.verdict}}),children:p("graph.maker.open")}):(0,r.jsx)("p",{className:"flow-graph-note",children:p("graph.maker.unavailable")})]})}}else("files"===w||"docs"===w)&&(D=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:"files"===w?p(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length}):p(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})}),(0,r.jsx)(aM,{files:"files"===w?f.files:f.docs,onOpenFile:s})]}));return(0,r.jsxs)("section",{className:"flow-section",children:[(0,r.jsxs)("div",{className:"flow-graph-head",children:[(0,r.jsx)("h4",{className:"flow-heading",children:p("flow.heading")}),(C>=0||N)&&(0,r.jsx)(os,{paused:v}),I.length>1&&(0,r.jsx)("button",{type:"button",className:"flow-graph-replay",onClick:()=>R(null===E?0:null),children:p(null===E?"graph.replay":"graph.replay.stop")})]}),(0,r.jsx)("div",{className:"flow-graph-frame",children:(0,r.jsxs)("ol",{className:"flow-graph","aria-label":p("flow.aria"),"data-live":i?"":void 0,"data-motion":v?"paused":void 0,"data-replay":null===E?void 0:"",children:[O,T&&(0,r.jsxs)("li",{className:"flow-graph-outputs","data-beat":L("outputs"),children:[(0,r.jsx)("span",{className:"flow-graph-outputs-label",children:p("graph.outputs")}),f.files.length>0&&(0,r.jsx)(oJ,{selectable:!0,selected:"files"===w,detailId:h,onSelect:()=>x("files"),className:"flow-graph-output",children:p(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length})}),f.docs.length>0&&(0,r.jsx)(oJ,{selectable:!0,selected:"docs"===w,detailId:h,onSelect:()=>x("docs"),className:"flow-graph-output",children:p(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})})]})]})}),D&&(0,r.jsx)("div",{className:"flow-graph-detail",id:h,role:"region","aria-label":p("graph.detail.aria"),children:D})]})}function oY(e,t,n){let r=new URLSearchParams({type:t});return n&&r.set("sessionId",n),`/api/files/${tF(e)}?${r}`}function oX(e,t){let[n,r]=(0,a.useState)({kind:"loading"});return(0,a.useEffect)(()=>{let n=new AbortController;return r({kind:"loading"}),fetch(e,{method:"head"===t?"HEAD":"GET",cache:"no-store",signal:n.signal}).then(async e=>{if(!e.ok)return null;if("head"===t)return"";if("text"===t)return e.text();let n=await e.json();return"string"==typeof n.content?n.content:null}).then(e=>{n.signal.aborted||r(null===e?{kind:"failed"}:{kind:"ready",content:e})}).catch(()=>{n.signal.aborted||r({kind:"failed"})}),()=>n.abort()},[e,t]),n}function oQ({messageKey:e}){let{st:t}=ax();return(0,r.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function o0({deliverable:e,sessionId:t,title:n}){let{filePath:a,kind:i}=e;if("image"===i){let e=oY(a,"read",t);return(0,r.jsx)(o4,{src:e,title:n},e)}if("html"===i){let e=oY(a,"read",t);return(0,r.jsx)(o1,{url:e,title:n},e)}if(a.toLowerCase().endsWith(".pdf")){let e=oY(a,"read",t);return(0,r.jsx)(o2,{url:e,title:n},e)}let s=oY(a,"preview",t);return(0,r.jsx)(o8,{url:s,title:n},s)}function o1({url:e,title:t}){let n=oX(e,"json");return"ready"!==n.kind?(0,r.jsx)(oQ,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-scripts",title:t,scrolling:"no",inert:!0})}function o2({url:e,title:t}){let n=oX(e,"head");return"ready"!==n.kind?(0,r.jsx)(oQ,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",src:`${e}#toolbar=0&view=FitH`,title:t,inert:!0})}function o8({url:e,title:t}){let n=oX(e,"text");return"ready"!==n.kind?(0,r.jsx)(oQ,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-same-origin",title:t,inert:!0})}function o4({src:e,title:t}){let[n,i]=(0,a.useState)("loading");return"failed"===n?(0,r.jsx)(oQ,{messageKey:"result.previewFailed"}):(0,r.jsxs)(r.Fragment,{children:["loading"===n?(0,r.jsx)(oQ,{messageKey:"result.previewLoading"}):null,(0,r.jsx)("img",{className:"answer-result-media","data-fit":"contain",src:e,alt:t,draggable:!1,hidden:"loading"===n,onLoad:()=>i("ready"),onError:()=>i("failed")})]})}function o5({deliverables:e,onOpenFile:t}){let{sessionId:n}=(0,a.useContext)(s9),{st:i}=ax(),[o,l]=function(){let e=(0,a.useRef)(null),[t,n]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{let r=e.current;if(!r||t)return;if("u"<typeof IntersectionObserver)return void n(!0);let a=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n(!0)},{rootMargin:"200px 0px"});return a.observe(r),()=>a.disconnect()},[t]),[e,t]}(),[c,...d]=e;if(!c)return null;let u=t_(c.filePath),p=i("result.previewTitle",{name:u}),h=t?()=>t(c.filePath):void 0;return(0,r.jsxs)("section",{className:"answer-result","aria-label":i("result.label"),children:[(0,r.jsxs)("div",{ref:o,className:"answer-result-frame","data-kind":c.kind,children:[l&&(0,r.jsx)(o0,{deliverable:c,sessionId:n,title:p}),h&&(0,r.jsx)("button",{type:"button",className:"answer-result-cover",tabIndex:-1,"aria-hidden":"true",onClick:h})]}),(0,r.jsxs)("div",{className:"answer-result-bar",children:[(0,r.jsxs)("span",{className:"answer-result-title",children:[(0,r.jsx)("span",{className:"answer-result-kind",children: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,r.jsx)("span",{className:"answer-result-name",title:c.filePath,children:u})]}),h&&(0,r.jsx)(s.r,{className:"answer-result-open",variant:"neutralSolid",size:"medium",onClick:h,"aria-label":i("result.openNamed",{name:u}),children:i("result.open")})]}),d.length>0&&(0,r.jsxs)("div",{className:"answer-result-more",children:[(0,r.jsx)("span",{className:"answer-result-more-label",children:i("result.more",{count:d.length})}),(0,r.jsx)(aM,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}function o6({summary:e,live:t=!1,onOpenFile:n}){let{ledger:i,subagents:s,toolResults:o}=(0,a.useContext)(s9),{st:l}=ax(),c=(0,a.useMemo)(()=>t?[]:function(e){let t=[];for(let n of e){if(function(e){let t=e.toLowerCase().replace(/\\/g,"/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e];if(Object.hasOwn(oH,n)||n.startsWith(".next")||"doc"===n&&"history"===t[e+1])return!0}return!1}(n.filePath))continue;let e=function(e){let t=eU(e);return"html"===t||"htm"===t?"html":eq(e)?"document":eB(e)?"image":null}(n.filePath);e&&t.push({filePath:n.filePath,kind:e})}return t.map((e,t)=>({deliverable:e,index:t})).sort((e,t)=>oU[e.deliverable.kind]-oU[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=>aZ(e,o.get(e.toolCallId))??[]).map(e=>a0(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=si(g.steps),b=v.filter(e=>"failed"===e.outcome).length,y=v.filter(e=>"failed"===e.outcome||"unobserved"===e.outcome).length,w=v.filter(e=>e.compound?.failed).length,k=v.filter(e=>"unverified"===e.outcome&&!e.compound?.failed).length,j=v.filter(e=>e.stale).length,S=y+m.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted").length;if(0===g.steps.length&&(t||0===e.files.length&&0===e.checks.length&&0===m.length&&!x?.length))return null;let C=[l(1===e.files.length?"summary.files.one":"summary.files",{count:e.files.length}),l(1===v.length?"summary.checks.one":"summary.checks",{count:v.length})];t&&C.unshift(l("summary.live")),b>0&&C.push(l("summary.checksFailed",{count:b})),w>0&&C.push(l("summary.compoundFailed",{count:w})),m.length>0&&C.push(l(1===m.length?"summary.makers.one":"summary.makers",{count:m.length})),x&&C.push(l("summary.remaining",{count:x.length})),!t&&S>0&&C.push(l("summary.unverified",{count:S})),k>0&&C.push(l(1===k?"summary.verdictUnverified.one":"summary.verdictUnverified",{count:k})),j>0&&C.push(l("summary.stale",{count:j}));let N=!t&&S>0||b>0||k>0||w>0||j>0;return(0,r.jsxs)("div",{className:"answer-summary","data-open":p?"":void 0,"data-live":t?"":void 0,"data-result":c.length>0?"":void 0,children:[c.length>0&&(0,r.jsx)(o5,{deliverables:c,onOpenFile:n}),(0,r.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":p,"aria-controls":h,title:l(p?"summary.collapse":"summary.expand"),onClick:()=>u(!p),children:[(0,r.jsx)("span",{className:"answer-summary-text","data-unverified":N?"":void 0,children:C.join(" \xb7 ")}),(0,r.jsx)("svg",{className:"answer-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),p&&(0,r.jsxs)("div",{className:"answer-summary-body",id:h,children:[g.steps.length>0&&(0,r.jsx)(oZ,{summary:e,makers:m,timings:f,live:t,onOpenFile:n}),x&&(0,r.jsxs)("section",{className:"flow-remaining",children:[(0,r.jsx)("h4",{className:"flow-heading",children:l("summary.heading.remaining")}),0===x.length?(0,r.jsx)("p",{className:"answer-summary-empty",children:l("summary.todo.none")}):(0,r.jsx)("ul",{className:"flow-remaining-list",children:x.map((e,t)=>(0,r.jsxs)("li",{className:"answer-remaining","data-status":e.status,title:e.phase||void 0,children:[(0,r.jsx)("span",{className:"answer-remaining-status",children:l(`summary.todo.${e.status}`)}),(0,r.jsx)("span",{className:"answer-remaining-text",children:e.content}),e.blocker&&(0,r.jsx)("span",{className:"answer-remaining-blocker",children:l("summary.todo.blocker",{blocker:e.blocker})})]},`${e.phase}#${t}`))})]})]})]})}let o3=/^att_[0-9a-f]{32}$/,o7=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function o9(e){return"string"==typeof e&&o3.test(e)}function le(e){return"string"==typeof e&&o7.test(e)}class lt extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let ln={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},lr={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},la={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function li(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let n=t.lastIndexOf(".");if(n>0&&lr[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&la[r]?"text":null}let ls={".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 lo(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?ls[t.slice(n)]:void 0;if(r)return r;let a=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return a?.startsWith("audio/")?a:null}function ll(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function lc(e){if(!Array.isArray(e))return[];let t=[],n=0,r=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;!(n+a.size>0x1000000)&&(r+a.text.length>24e4||(t.push({name:a.name,mimeType:a.mimeType,size:a.size,text:a.text,...o9(a.attachmentId)?{attachmentId:a.attachmentId}:{}}),n+=a.size,r+=a.text.length))}}return t}async function ld(e){let t,n=li(e);if(!n)throw new lt("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new lt("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await ly(e);else{try{t=await e.text()}catch(e){throw new lt("read_failed",e instanceof Error?e.message:String(e))}lw(t)}return{name:e.name,mimeType:ln[n],size:e.size,text:t}}function lu(e,t){let n=lc(t);if(0===n.length)return e;let r={userMessageLength:e.length,documents:n.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,textLength:r.length}))},a=`${lk}${JSON.stringify(r)}${lj}
|
|
5
|
+
${lS}${e}${lC}`;return n.forEach((e,t)=>{a+=lN(t,e),a+=e.text,a+=lT(t)}),a}function lp(e){let t;if(!e.startsWith(lk))return null;let n=e.indexOf("\n");if(n<0)return null;let r=e.slice(0,n);if(!r.endsWith(lj))return null;try{t=JSON.parse(r.slice(lk.length,-lj.length))}catch{return null}if(!function(e){if(!e||"object"!=typeof e||!Number.isSafeInteger(e.userMessageLength)||(e.userMessageLength??-1)<0||!Array.isArray(e.documents)||0===e.documents.length||e.documents.length>3)return!1;let t=0,n=0;for(let r of e.documents){if(!r||"object"!=typeof r||"string"!=typeof r.name||0===r.name.length||"text/markdown"!==r.mimeType&&"text/plain"!==r.mimeType&&"application/pdf"!==r.mimeType||!Number.isSafeInteger(r.size)||(r.size??-1)<0||(r.size??0)>8388608||!Number.isSafeInteger(r.textLength)||(r.textLength??-1)<0||(r.textLength??0)>12e4)return!1;t+=r.size??0,n+=r.textLength??0}return t<=0x1000000&&n<=24e4}(t))return null;let a=n+1;if(!e.startsWith(lS,a))return null;let i=(a+=lS.length)+t.userMessageLength;if(i>e.length)return null;let s=e.slice(a,i);if(a=i,!e.startsWith(lC,a))return null;a+=lC.length;let o=[];for(let n=0;n<t.documents.length;n+=1){let r=t.documents[n],i=lN(n,r);if(!e.startsWith(i,a))return null;let s=(a+=i.length)+r.textLength;if(s>e.length)return null;let l=e.slice(a,s);a=s;let c=lT(n);if(!e.startsWith(c,a))return null;a+=c.length,o.push({name:r.name,mimeType:r.mimeType,size:r.size,text:l})}return a===e.length?{message:s,documents:o}:null}function lh(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:`${(e/1048576).toFixed(1)} MB`}let lm="\n[transcript truncated to fit the attachment limit]",lf="File saved at: ";function lg(e){return"application/pdf"===e.mimeType?"pdf":"text/markdown"===e.mimeType?"markdown":e.text.startsWith(lf)?lo({name:e.name,type:""})?"audio":"file":"text"}function lx(e,t=12e4){let n=`${lf}${e.path}
|
|
6
|
+
(${e.mimeType}, ${e.size} bytes) Open it with a tool when its contents are needed.`;if(void 0!==e.transcript){let r=`${n}
|
|
7
|
+
|
|
8
|
+
Transcript of the audio (speech-to-text; may contain recognition errors):
|
|
9
|
+
`,a=r+e.transcript;return a.length<=t?a:r+e.transcript.slice(0,Math.max(0,t-r.length-lm.length))+lm}return e.transcriptError?`${n}
|
|
10
|
+
The audio could not be transcribed: ${e.transcriptError}`:n}async function lv(e,{sessionId:t,draftId:n,signal:r}={}){let a=new FormData;t&&a.append("sessionId",t),n&&a.append("draftId",n),a.append("file",e,e.name);let i=await fetch("/api/attachments",{method:"POST",body:a,signal:r}),s=await i.json().catch(()=>null);if(!i.ok||"string"!=typeof s?.path||"number"!=typeof s.size||"string"!=typeof s.mimeType||!o9(s.id)||!le(s.draftId))throw Error("string"==typeof s?.error?s.error:`HTTP ${i.status}`);return{path:s.path,size:s.size,mimeType:s.mimeType,id:s.id,draftId:s.draftId}}async function lb(e,t,{sentAttachmentIds:n,signal:r}={}){let a=await fetch("/api/attachments/draft",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({draftId:e,attachmentIds:t,...n?.length?{sentAttachmentIds:n}:{}}),signal:r}),i=await a.json().catch(()=>null);if(!a.ok||!le(i?.draftId)||!Array.isArray(i.attachmentIds)||!i.attachmentIds.every(o9))throw Error("string"==typeof i?.error?i.error:`HTTP ${a.status}`);return{draftId:i.draftId,attachmentIds:i.attachmentIds}}async function ly(e){let t;try{t=await fetch("/api/document-text",{method:"POST",headers:{"Content-Type":"application/pdf"},body:e})}catch(e){throw new lt("read_failed",e instanceof Error?e.message:String(e))}let n=await t.json().catch(()=>null);if(!t.ok){var r;throw new lt("string"==typeof n?.code&&("unsupported"===(r=n.code)||"file_too_large"===r||"text_too_large"===r||"too_many_pages"===r||"no_extractable_text"===r||"password_protected"===r||"invalid_pdf"===r||"read_failed"===r)?n.code:"invalid_pdf","string"==typeof n?.error?n.error:`Unable to read ${e.name}`)}if("string"!=typeof n?.text)throw new lt("invalid_pdf",`Unable to read ${e.name}`);return lw(n.text),n.text}function lw(e){if(e.length>12e4)throw new lt("text_too_large","Document exceeds the extracted text limit")}let lk="\x3c!-- omp-web-document-context-v1:",lj=" --\x3e",lS="User message:\n",lC="\n\nAttached documents (locally extracted text supplied by the user):\n";function lN(e,t){return`
|
|
11
|
+
--- Begin attached document ${e+1}: ${JSON.stringify(t.name)} (${t.mimeType}, ${t.size} bytes) ---
|
|
12
|
+
`}function lT(e){return`
|
|
13
|
+
--- End attached document ${e+1} ---`}let lI=new Map;function lM({children:e,className:t,...n}){let{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(ny,{className:t,...n,children:e});if(!s){var l;return(0,r.jsxs)("button",{onClick:()=>o(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",i("i18n.largeMessageReveal",{size:(l=e.length)>=1e6?`${(l/1e6).toFixed(1)} MB`:l>=1e3?`${Math.round(l/1e3)} KB`:`${l} B`})]})}return(0,r.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:12,lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:e})})}let lR=null,lE=null,lL=null;function l$(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),a=(lR??=new Intl.DateTimeFormat([],{hour:"2-digit",minute:"2-digit"})).format(t);if(r)return a;let i=t.getFullYear()!==n.getFullYear()?(lL??=new Intl.DateTimeFormat([],{month:"short",day:"numeric",year:"numeric"})).format(t):(lE??=new Intl.DateTimeFormat([],{month:"short",day:"numeric"})).format(t);return`${i} ${a}`}let lP=(0,a.memo)(function({message:e,isStreaming:t,toolResults:n,modelNames:a,cwd:i,onOpenFile:s,entryId:o,onFork:l,forking:c,onNavigate:d,prevAssistantEntryId:u,onEditContent:p,showTimestamp:h,prevTimestamp:m,sessionId:f,writtenFiles:g,dispatchSlot:x,turnSummary:v,inputTranslation:b}){return"user"===e.role?(0,r.jsx)(lA,{message:e,cwd:i,onOpenFile:s,entryId:o,onFork:l,forking:c,onNavigate:d,prevAssistantEntryId:u,onEditContent:p,inputTranslation:b}):"assistant"===e.role?(0,r.jsx)(l_,{message:e,isStreaming:t,toolResults:n,modelNames:a,cwd:i,onOpenFile:s,showTimestamp:h,prevTimestamp:m,sessionId:f,entryId:o,writtenFiles:g,dispatchSlot:x,turnSummary:v}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(l3,{message:e}):(0,r.jsx)(ce,{message:e,cwd:i,onOpenFile:s}):"bashExecution"===e.role?(0,r.jsx)(cr,{message:e,sessionId:f}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.entryId===t.entryId&&e.onFork===t.onFork&&e.forking===t.forking&&e.onNavigate===t.onNavigate&&e.prevAssistantEntryId===t.prevAssistantEntryId&&e.onEditContent===t.onEditContent&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.sessionId===t.sessionId&&e.dispatchSlot===t.dispatchSlot&&e.turnSummary===t.turnSummary&&e.inputTranslation===t.inputTranslation);function lA({message:e,cwd:t,onOpenFile:n,entryId:i,onFork:s,forking:o,onNavigate:l,prevAssistantEntryId:c,onEditContent:d,inputTranslation:u}){let{t:p}=(0,z.s)(),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),x="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),v=lp(x),b=v?.message??x,y=v?.documents??[],w="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),k=l$(e.timestamp),j=!!i&&!!s,S=!!c&&!!l;return(0,r.jsxs)("div",{className:"message-user",style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsxs)("div",{className:"message-user-bubble",style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--accent-line)",borderRadius:"var(--seed-radius-r3)",padding:"8px 12px",fontSize:14,lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:[w.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:w.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t)})}),y.length>0&&(0,r.jsx)("div",{role:"list","aria-label":p("chat.attachments"),style:{display:"flex",flexDirection:"column",gap:5,marginBottom:8*!!b},children:y.map((e,t)=>{var n;return(0,r.jsxs)("div",{role:"listitem",style:{display:"flex",alignItems:"center",gap:7,minWidth:0,padding:"5px 7px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"color-mix(in srgb, var(--user-bg) 70%, var(--bg-panel))"},children:[aI(e.name,14),(0,r.jsx)("span",{title:e.name,style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:[(n=lg(e),"pdf"===n?"PDF":"markdown"===n?"Markdown":"audio"===n?p("chat.attachKindAudio"):"file"===n?p("chat.attachKindFile"):"Text")," \xb7 ",lh(e.size)]})]},`${e.name}-${t}`)})}),b&&(0,r.jsx)(lM,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:b})]})}),void 0!==u&&(0,r.jsx)(lF,{text:u,cwd:t,onOpenFile:n}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!h,pointerEvents:h?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{className:"message-meta-action",onClick:()=>{nf(function(e){let t=lp(e);if(!t)return e;let n=t.documents.map(e=>e.name).join(", ");return t.message.trim()?`${t.message}
|
|
14
|
+
|
|
15
|
+
Attached: ${n}`:`Attached: ${n}`}(x)).then(()=>{g(!0),setTimeout(()=>g(!1),1500)})},title:p("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:f?"var(--accent)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{f||(e.currentTarget.style.color="var(--text-muted)")},children:[f?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),f?p("i18n.copied"):p("i18n.copy")]})}),(j||S)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:h||o?1:0,pointerEvents:h||o?"auto":"none",transition:"opacity 0.12s"},children:[S&&(0,r.jsxs)("button",{onClick:()=>{l(c),d?.(e)},title:p("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]}),p("i18n.editFromHere")]}),j&&(0,r.jsxs)("button",{onClick:()=>{s(i)},disabled:o,title:o?p("i18n.creatingSession"):p("i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:o?"var(--accent)":"var(--text-dim)",cursor:o?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{o||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),o?p("i18n.creating"):p("i18n.newSession")]})]}),k&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-muted)"},children:k})]})]})}function lF({text:e,cwd:t,onOpenFile:n}){let{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(!1),l=(0,a.useId)();return(0,r.jsxs)("div",{className:"message-user-translation",style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4,maxWidth:"85%",marginTop:3},children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>!e),"aria-expanded":s,"aria-controls":s?l:void 0,style:{padding:"2px 0",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:i(s?"i18n.hideInputTranslation":"i18n.showInputTranslation")}),s&&(0,r.jsx)("div",{id:l,lang:"en",className:"message-user-translation-body",style:{alignSelf:"stretch",paddingLeft:10,borderLeft:"2px solid var(--border)"},children:(0,r.jsx)(lM,{cwd:t,onOpenFile:n,children:e})})]})}function l_({message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:s,onOpenFile:o,showTimestamp:l,prevTimestamp:c,sessionId:d,entryId:u,writtenFiles:p,dispatchSlot:h,turnSummary:m}){var f;let g,{t:x}=(0,z.s)(),{hideThinkingBlock:v}=nQ(),b=l?l$(e.timestamp):null,y=am(d,e.provider,e.credentialId,e.model),w=e.liveSpeaker?rb.find(t=>t.alias===e.liveSpeaker?.alias)??rh.find(t=>t.alias===e.liveSpeaker?.alias):void 0,k=w?{seed:w.seed,alias:rP(w.alias)}:y,j=!!w&&e.liveSpeaker?.mode==="native",{st:S}=ax(),C=i?.[`${e.provider}:${e.model}`]??i?.[e.model]??e.model,N=(0,a.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!eK(e,{isStreaming:t,hideThinking:v})),[e.content,t,v]),T=(0,a.useMemo)(()=>N.map(({block:e})=>e),[N]),I=eG(e,{isStreaming:t}),[M,R]=(0,a.useState)(!1),[E,L]=(0,a.useState)(!1),[$,P]=(0,a.useState)(!1),A=(0,a.useRef)(null),[F,_]=(0,a.useState)(null),W=(0,a.useRef)(N);W.current=N;let O=(0,a.useRef)(new Map),D=(0,a.useMemo)(()=>{if(!t)return O.current=new Map,0;let e=new Map,n=0;for(let{block:t,originalIndex:r}of N){let a=eQ(t);if(null===a)continue;let i=e0(O.current.get(r),a);e.set(r,{text:a,tokens:i}),n+=i}return O.current=e,n},[N,t]),H=(0,a.useRef)(D);H.current=D;let U=(0,a.useRef)(new Map),[B,q]=(0,a.useState)(new Map),V=(0,a.useMemo)(()=>{if(!e.timestamp||!c)return;let t=Math.round((e.timestamp-c)/1e3);return t>0?t:void 0},[e.timestamp,c]),K=(0,a.useMemo)(()=>(function(e,t){let n=new Map,r=e.completedAt;if(!t||!r)return n;for(let[e,a]of t){if(!a.timestamp||a.details?.executed===!1)continue;let t=Math.round((a.timestamp-r)/1e3);t>0&&n.set(e,t)}return n})(e,n),[e,n]),G=e.replyTranslation,J=G?.kind==="translated"?G:void 0,Z=J?N.findIndex(({block:e})=>"text"===e.type):-1,Y=J?J.text:T.filter(e=>"text"===e.type).map(e=>e.text).join("\n");return((0,a.useEffect)(()=>{if(!t){let e=new Date().getTime();q(t=>{let n=new Map(t);for(let[t,r]of U.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),A.current=null,_(null);return}let e=setInterval(()=>{let e=W.current,t=Date.now();e.forEach(({originalIndex:e})=>{U.current.has(e)||U.current.set(e,t)}),q(n=>{let r=!1,a=new Map(n);for(let n=0;n<e.length-1;n++){let i=e[n].originalIndex,s=e[n+1].originalIndex;if(!a.has(i)&&U.current.has(i)){let e=U.current.get(i),n=U.current.get(s)??t;a.set(i,Math.round((n-e)/1e3)),r=!0}}return r?a:n});let n=H.current;if(0===n)return;null===A.current&&(A.current=t);let r=(t-A.current)/1e3;r>.5&&_(n/r)},300);return()=>clearInterval(e)},[t]),0!==T.length||t||I)?(0,r.jsxs)("div",{className:`message-assistant${t?" is-streaming":""}`,style:{marginBottom:16},onMouseEnter:()=>R(!0),onMouseLeave:()=>R(!1),children:[(0,r.jsx)("div",{className:"message-assistant-role",style:{fontSize:11,color:"var(--text-dim)",marginBottom:2,display:"flex",alignItems:"center",gap:9,...k?{minHeight:40}:null},children:e.provider&&(0,r.jsxs)(r.Fragment,{children:[k&&(0,r.jsx)(av,{seed:k.seed,size:40,provider:e.provider}),k&&(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:k.alias}),j&&(0,r.jsx)("span",{children:S("live.nativeVoice")}),(0,r.jsx)("span",{children:`${function(e,t){if("anthropic"===e.provider){let n=e.usage?.credentialKind;if("oauth"===n)return t("i18n.providerAnthropicSubscription");if("api-key"===n)return t("i18n.providerAnthropicApi")}return rV(e.provider)}(e,x)} \xb7 ${C}`})]})}),h?.placement==="before"&&(0,r.jsx)(oz,{calls:h.calls}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[N.map(({block:a,originalIndex:i},l)=>J&&"text"===a.type?l===Z?(0,r.jsx)(lz,{translation:J.text,original:J.original,cwd:s,onOpenFile:o},`${u??"stream"}-${i}`):null:(0,r.jsx)(lW,{block:a,toolResults:n,isStreaming:t,streamingDuration:B.get(i)??("thinking"===a.type?V:void 0),toolCallDurations:K,runStartedAt:e.completedAt,cwd:s,onOpenFile:o,sessionId:d,entryId:u,blockIndex:i},`${u??"stream"}-${i}`)),G&&!J&&(0,r.jsx)("div",{className:"reply-translation-note",style:{fontSize:12,color:"var(--text-dim)"},children:G.text})]}),h?.placement==="after"&&(0,r.jsx)(oz,{calls:h.calls}),I&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(T.length>0),padding:"7px 10px",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",background:"var(--danger-soft)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",I]}),m?(0,r.jsx)(o6,{summary:m,onOpenFile:o}):p&&p.length>0&&(0,r.jsx)(aM,{files:p,onOpenFile:o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,r.jsx)("button",{type:"button",className:"message-meta-action",onClick:()=>P(e=>!e),onFocus:()=>R(!0),onBlur:()=>R(!1),"aria-expanded":$,title:x("i18n.messageUsageTitle"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:$?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:M||$?1:0,pointerEvents:M||$?"auto":"none",transition:"opacity 0.12s, color 0.12s"},children:$?(f=e.usage,g=[],f.input&&g.push(`${f.input.toLocaleString()} in`),f.output&&g.push(`${f.output.toLocaleString()} out`),f.cacheRead&&g.push(`${f.cacheRead.toLocaleString()} cache R`),f.cacheWrite&&g.push(`${f.cacheWrite.toLocaleString()} cache W`),f.cost?.total&&g.push(`$${f.cost.total.toFixed(4)}`),g.join(" \xb7 ")):x("i18n.messageUsage")}),t&&Math.round(D)>0&&(0,r.jsx)("button",{type:"button",className:"message-meta-action",onClick:()=>P(e=>!e),"aria-expanded":$,title:x("i18n.estimatedTokens"),style:{padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:$?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:$?`~${Math.round(D)}${null!==F?` \xb7 ${F.toFixed(1)} t/s`:""}`:x("i18n.messageUsage")}),Y&&!t&&(0,r.jsxs)("button",{className:"message-meta-action",onClick:()=>{nf(Y).then(()=>{L(!0),setTimeout(()=>L(!1),1500)})},title:x("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:"var(--radius-control)",color:E?"var(--accent)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!M,pointerEvents:M?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{E||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{E||(e.currentTarget.style.color="var(--text-muted)")},children:[E?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),x(E?"i18n.copied":"i18n.copy")]}),b&&!t&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-muted)",marginLeft:"auto"},children:b})]})]}):null}function lz({translation:e,original:t,cwd:n,onOpenFile:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(!1);return(0,r.jsxs)("div",{className:"reply-translation",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(lM,{cwd:n,onOpenFile:i,children:e}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,style:{alignSelf:"flex-start",padding:"2px 0",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:s(o?"i18n.hideOriginalReply":"i18n.showOriginalReply")}),o&&(0,r.jsx)("div",{className:"reply-translation-original",style:{paddingLeft:10,borderLeft:"2px solid var(--border)",color:"var(--text-muted)"},children:(0,r.jsx)(lM,{cwd:n,onOpenFile:i,children:t})})]})}function lW({block:e,toolResults:t,isStreaming:n,streamingDuration:a,toolCallDurations:i,runStartedAt:s,cwd:o,onOpenFile:l,sessionId:c,entryId:d,blockIndex:u}){if("text"===e.type)return(0,r.jsx)(lB,{block:e,isStreaming:n,cwd:o,onOpenFile:l});if("thinking"===e.type)return(0,r.jsx)(lq,{block:e,duration:a,sessionId:c,entryId:d,blockIndex:u});if("toolCall"===e.type){let n=t?.get(e.toolCallId),a=i?.get(e.toolCallId);return(0,r.jsx)(lV,{block:e,result:n,duration:a,runStartedAt:s,sessionId:c})}if("image"===e.type)return"image"===e.type&&"toolImage"in e?c?(0,r.jsx)(lD,{sessionId:c,toolCallId:e.toolImage.toolCallId}):null:(0,r.jsx)(lO,{block:e});return null}function lO({block:e}){let t=cn(e);return t?(0,r.jsx)("img",{src:t,alt:"",style:{maxWidth:"100%",maxHeight:420,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}}):null}function lD({sessionId:e,toolCallId:t}){let{t:n}=(0,z.s)(),[i,s]=(0,a.useState)(()=>e4.get(`${e}
|
|
16
|
+
${t}`)),[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)(()=>new Set);if((0,a.useEffect)(()=>{if(void 0!==i)return;let n=!0;return(function(e,t){let n=`${e}
|
|
17
|
+
${t}`,r=e4.get(n);if(void 0!==r)return Promise.resolve(r);let a=e5.get(n);if(a)return a;let i=fetch(e1(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),r=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return e4.set(n,r),r}).catch(()=>0).finally(()=>e5.delete(n));return e5.set(n,i),i})(e,t).then(e=>{n&&s(e)}),()=>{n=!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,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(a=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>l(a),children:(0,r.jsx)("img",{src:e1(e,t,a),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(a))})},a)),null!==o&&(0,r.jsx)(lU,{src:e1(e,t,o),fileName:`screen-${t.slice(-8)}-${o+1}`,onClose:()=>l(null)})]})}let lH={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function lU({src:e,fileName:t,onClose:n}){let{t:i}=(0,z.s)(),o=(0,a.useContext)(nM),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(),n()},b=async()=>{let r,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 n=await fetch(e,{signal:s.signal});if(!n.ok)throw Error(`HTTP ${n.status}`);let o=await n.blob(),l=lH[o.type];if(!l)throw Error(`unsupported ${o.type}`);if(0!==h.length&&f){let e=await n_(o,h);r=[new File([e.marked],`${t}-marked.png`,{type:"image/png"}),...e.crops.map((e,n)=>new File([e],`${t}-region-${n+1}.png`,{type:"image/png"}))];let n=1===h.length?"1":`1~${h.length}`;a=[i("toolImage.locatorIntro",{range:n}),...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 r=[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(r,a)){d(!1),p(i("toolImage.noComposer"));return}n()}};return(0,q.createPortal)((0,r.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,r.jsx)(nz,{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,r.jsx)("p",{role:"alert",className:"tool-image-error",children:u}):(0,r.jsx)("p",{className:"tool-image-hint","data-hidden":h.length>0&&h.length<9?"true":void 0,children:h.length>=9?i("toolImage.markLimit",{count:9}):i("toolImage.markHint")}),(0,r.jsxs)("div",{className:"tool-image-actions",children:[(0,r.jsx)(s.r,{variant:"neutralSolid",size:"medium",loading:c,onClick:()=>void b(),title:i("toolImage.requestEditHint"),children:i("toolImage.requestEdit")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",disabled:0===h.length,onClick:()=>m([]),children:i("toolImage.clearMarks")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",onClick:v,children:i("i18n.close")})]})]}),document.body)}function lB({block:e,isStreaming:t,cwd:n,onOpenFile:a}){return(0,r.jsx)(lM,{isStreaming:t,cwd:n,onOpenFile:a,children:e.text})}function lq({block:e,duration:t,sessionId:n,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 n&&i?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,a=lI.get(r);if(a)return lI.delete(r),lI.set(r,a),a;let i=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw lI.delete(r),e});if(lI.set(r,i),lI.size>100){let e=lI.keys().next().value;e&&lI.delete(e)}return i})(n,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,n,o]);let m=e.deferred?l:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":o("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:d?(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,r.jsx)(ny,{className:"markdown-thinking-body",children:m}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&f&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function lV({block:e,result:t,duration:n,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:nN(s,e.toolCallId),(0,a.useSyncExternalStore)(nC,()=>o?nk.get(o)??null:null,()=>null)),f=e.toolName.toLowerCase(),g=JSON.stringify(e.input,null,2),x="todo"===f||f.endsWith(".todo")||f.endsWith("_todo"),v="bash"===f||f.startsWith("bash ")||f.endsWith(".bash")||f.endsWith("_bash"),b=t&&!t.isError?function(e){var t;let n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let a="string"==typeof n.diff?n.diff:null;return a?{text:a}:null}(t):null,y=x?"unknown"===(l=tR(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?nD(t):null,C=t?t.isError||null!==S&&0!==S?"failed":"done":"running",N="failed"===C,T=p??N;if(x&&y)return(0,r.jsx)(lQ,{phases:y});let I=v&&"string"==typeof e.input.command?e.input.command:"",M=function(e,t,n){let r,a=t.html;if(!("ask"===(r=e.trim().toLowerCase())||r.endsWith(".ask")||r.endsWith("_ask"))||"string"!=typeof a)return null;let i="object"==typeof n&&null!==n?n:{},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),R=null!==M&&M.rows.length>0?M:null,E=!!(y||b||R),L=v?I.split(/\r?\n/,1)[0]??"":M?.target??function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.length)return"";let a=e.toolName.toLowerCase();if(t=a,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===a||a.endsWith(".eval")||a.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(-120);if("file_path"in n)return String(n.file_path).slice(-120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let i=r.map(e=>n[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(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,y),$=!v&&/^\S+$/.test(L)&&/[\\/]/.test(L),P=w?c("toolRun.diffStats",{added:w.added,removed:w.removed}):"";return(0,r.jsxs)("div",{className:`tool-call-card ${N?"is-error":"running"===C?"is-running":"is-done"}${v?" is-shell":""}`,"aria-busy":"running"===C||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,r.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>h(!T),"aria-expanded":T,"aria-controls":T?d:void 0,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,r.jsx)(lY,{toolName:e.toolName}),(0,r.jsx)("span",{className:"tool-call-name",children:v?"bash":e.toolName}),v&&f.includes("(local)")&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"}),(0,r.jsx)("span",{className:`tool-call-target${$?" is-path":""}`,title:v?I:L,children:$?(0,r.jsx)("bdi",{dir:"ltr",children:L}):L}),w&&(0,r.jsxs)("span",{className:"tool-call-diffstats",title:P,"aria-label":P,children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",w.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",w.removed]})]}),(0,r.jsx)(lG,{state:C,duration:n,exitCode:S,startedAt:i??u}),(0,r.jsx)("svg",{className:"tool-call-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:T?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),"running"===C&&m&&(0,r.jsx)("div",{className:"tool-call-progress",title:m,style:{padding:"0 10px 6px 29px",color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:m}),T&&(0,r.jsx)("div",{id:d,className:"tool-call-body",children:v?(0,r.jsx)(l0,{command:I,output:k??"",pending:!t,isError:N}):(0,r.jsxs)(r.Fragment,{children:[b&&(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(l1,{diff:b})}),t&&N&&(0,r.jsx)(l6,{text:k??"",isEmpty:j,isError:!0}),R&&!N&&(0,r.jsx)(lK,{summary:R}),!E&&(0,r.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:g}),t&&!E&&!N&&(0,r.jsx)(l6,{text:k??"",isEmpty:j,isError:!1})]})})]})}function lK({summary:e}){let{t}=(0,z.s)();return(0,r.jsxs)("div",{className:"tool-call-ask",style:{padding:"8px 10px"},children:[(0,r.jsx)("dl",{style:{margin:0,display:"grid",gap:8},children:e.rows.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("dt",{style:{color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflowWrap:"anywhere"},children:e.question}),(0,r.jsx)("dd",{style:{margin:"2px 0 0",color:"var(--text)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:""===e.answer?"—":e.answer})]},t))}),e.timedOut&&(0,r.jsx)("p",{style:{margin:"8px 0 0",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:t("toolRun.askTimedOut")})]})}function lG({state:e,duration:t,exitCode:n,startedAt:a}){let{t:i}=(0,z.s)();return"running"===e?(0,r.jsx)(lJ,{startedAt:a}):(0,r.jsxs)(r.Fragment,{children:[void 0!==t&&(0,r.jsxs)("span",{className:"tool-run-duration",children:[t,"s"]}),"failed"===e&&(0,r.jsxs)("span",{className:"tool-run-failed",children:[(0,r.jsx)(nI.E,{tone:"critical",variant:"weak",size:"medium",children:i("toolRun.failed")}),null!==n&&(0,r.jsx)("span",{className:"tool-run-exit",children:i("toolRun.exitCode",{code:n})})]})]})}function lJ({startedAt:e}){let{t}=(0,z.s)(),n=nw(500)-e;return n<400?null:(0,r.jsxs)("span",{className:"tool-run-running",children:[t("toolRun.running"),(0,r.jsxs)("span",{className:"tool-run-duration",children:[Math.floor(n/1e3),"s"]})]})}function lZ(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function lY({toolName:e}){let t,n=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||lZ(t,"edit")?"edit":lZ(t,"read")||lZ(t,"cat")?"read":lZ(t,"write")||lZ(t,"save")?"write":lZ(t,"glob")||lZ(t,"find")?"glob":lZ(t,"grep")||lZ(t,"search")?"grep":lZ(t,"bash")||lZ(t,"shell")||lZ(t,"exec")?"bash":lZ(t,"todo")?"todo":lZ(t,"eval")?"eval":lZ(t,"task")||lZ(t,"agent")?"task":lZ(t,"browser")||lZ(t,"web_search")||lZ(t,"fetch")?"browser":lZ(t,"image")||lZ(t,"inspect_image")?"image":"generic";return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:"var(--text-muted)"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)(lX,{kind:n})})})}function lX({kind:e}){switch(e){case"read":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,r.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,r.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,r.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,r.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,r.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,r.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,r.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,r.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,r.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,r.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,r.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,r.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function lQ({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),n=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,r.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,r.jsxs)("div",{className:"todo-checklist-header",children:[(0,r.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,r.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,r.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),n>0&&n<t&&(0,r.jsxs)("span",{className:"todo-checklist-progress",children:[n,"/",t]})]}),(0,r.jsx)("div",{className:"todo-checklist-body",children:e.map((t,n)=>(0,r.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,r.jsx)(ak,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function l0({command:e,output:t,pending:n,isError:a}){let{isDark:i}=nm(),{t:s}=(0,z.s)(),o=e_(t.split(/\r?\n/)),l=1===o.length&&""===o[0]?[]:o;return(0,r.jsxs)("div",{className:`shell-output-preview${a?" is-error":""}`,children:[(0,r.jsxs)("div",{className:"shell-command-line",children:[(0,r.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,r.jsx)(tW.A,{className:"shell-command-code",language:"bash",style:i?tO.xJ:tO.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsx)("div",{className:"shell-output-divider",children:(0,r.jsx)("span",{className:"shell-output-label",children:"Output"})}),(0,r.jsxs)("div",{className:"shell-output-body",children:[0===l.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:s("i18n.noOutput")}),l.map((e,t)=>{let n=e$(e).trimStart(),i=a||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${i}`.trim(),children:[ez(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},t):(0,r.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)})]})]})]})}function l1({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(l2,{text:e.text})})}function l2({text:e}){let{t}=(0,z.s)(),n=(0,a.useMemo)(()=>ay(e),[e]);if(!n)return(0,r.jsx)(l5,{text:e});let i=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[i&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(l8,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(l8,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(l4,{cell:e.left,side:"left"}),(0,r.jsx)(l4,{cell:e.right,side:"right"})]},t))})]},n))})}function l8({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function l4({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",a="added"===e.type?"+":"removed"===e.type?"-":" ",i="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:i,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:a}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function l5({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"var(--success-soft)":"removed"===n?"var(--danger-soft)":"hunk"===n?"var(--accent-soft)":"transparent",borderLeft:"added"===n?"3px solid var(--success)":"removed"===n?"3px solid var(--danger)":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"var(--success)":"removed"===n?"var(--danger)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function l6({text:e,isEmpty:t,isError:n}){let{t:a}=(0,z.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--danger-line)":"var(--success-line)"}`,background:n?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?a("i18n.noOutput"):e})})}function l3({message:e}){let{t}=(0,z.s)(),n=ct(e.content),i=(0,a.useMemo)(()=>{let e,t,r,a,i;return e=[],t=[],r=n.match(nU),a=r?.[1]??"",i=r?.index===void 0?n:n.slice(0,r.index),a.replace(nH,(n,r,a)=>{let i=a.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...i):t.push(...i),""}),{body:i.trim(),readFiles:e,modifiedFiles:t}},[n]),s=l$(e.timestamp),o=e.details&&"object"==typeof e.details&&"tokensBefore"in e.details&&"number"==typeof e.details.tokensBefore&&e.details.tokensBefore>0?e.details.tokensBefore:null;return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==o&&(0,r.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:nB(o)})}),s&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),i.body?(0,r.jsx)(ny,{className:"markdown-compaction-message",children:i.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(l7,{readFiles:i.readFiles,modifiedFiles:i.modifiedFiles})]})]})})}function l7({readFiles:e,modifiedFiles:t}){let{t:n}=(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,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:a.join(", ")})}),t.length>0&&(0,r.jsx)(l9,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(l9,{title:n("i18n.readFiles"),files:e})]})}function l9({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function ce({message:e,cwd:t,onOpenFile:n}){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=ct(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=l$(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",overflow:"hidden",background:l?"var(--bg-subtle)":"var(--bg)",opacity:l&&!c?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),c?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=cn(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,r.jsx)(ny,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(s=f.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":o("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,r.jsx)("button",{className:"message-meta-action",onClick:()=>{nf(f||v).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(h?"i18n.copied":"i18n.copy")}):null,(x||l)&&(0,r.jsx)("button",{onClick:()=>{l?d(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(l?c?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(l&&c||!l&&u)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function ct(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function cn(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[n,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===n,m=n??e.output;async function f(){if(p){o(!0),c(null);try{let e=await fetch(p),t=await e.json();t.success?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,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(lV,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:f,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),l&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",l,")"]})]})]})}n(21340);let ca="cuelo-chat-search",ci="cuelo-chat-search-active";function cs(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 co({open:e,onClose:t,containerRef:n,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)(()=>()=>{cs(ca,[]),cs(ci,[])},[]),(0,a.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){cs(ca,[]),cs(ci,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),a=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(a))continue;let i=(e.textContent??"").toLowerCase(),s=n.get(a);s||(s=[],n.set(a,s));for(let n=i.indexOf(t);-1!==n;n=i.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),s.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,a){let i=[];if(!t)return i;for(let s=0;s<e.length;s++){let o=s>=r&&s<a?n.get(s)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[s],t);for(let e=0;e<o;e++)i.push({item:s,k:e})}return i}(i,w,n,s,o);j.current=r;let a=td(r,k.current);b(e=>e.index===a&&e.total===r.length?e:{index:a,total:r.length});let l=[];for(let t of e.values())for(let e of t)l.push(e);if(cs(ca,l),a<0){cs(ci,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[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){cs(ci,[]),f&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(cs(ci,g?[g]:[]),f)if(d(),g){let e,n;e=g.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,i,s,o,l,g,n,c,d]);let C=(0,a.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=td(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,r.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsx)("input",{ref:h,type:"search",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,r.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,r.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}function cl({questions:e,containerRef:t,layoutKey:n,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 n=t.current;if(!n||!p)return;let r=0,a=null,i=()=>{r=0,a?.[0]?.isConnected||(a=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,i=0,s=a.length-1,o=a.length-1;for(;i<=s;){let e=i+s>>1,n=a[e].firstElementChild?.getBoundingClientRect();n&&n.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=()=>{r||(r=requestAnimationFrame(i))};return r=requestAnimationFrame(i),n.addEventListener("scroll",s,{passive:!0}),()=>{n.removeEventListener("scroll",s),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,a.useEffect)(()=>{let e=o.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let n=t.offsetTop-e.scrollTop;(n<0||n+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[l]);let h=e.length,m=(0,a.useCallback)((e,t)=>{let n="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===n)return;e.preventDefault();let r=Math.max(0,Math.min(h-1,n));o.current?.querySelectorAll("button")[r]?.focus()},[h]);if(!p)return null;let f=e.some(e=>e.item===l)?l:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,r.jsx)("div",{ref:o,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(cc,{question:e,position:t,count:h,active:e.item===l,focusable:e.item===f,onJump:i,onMoveFocus:m},e.item))})})}let cc=(0,a.memo)(function({question:e,position:t,count:n,active:a,focusable:i,onJump:s,onMoveFocus:o}){let l=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,r.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:i?0:-1,"aria-current":a?"true":void 0,"aria-label":`${t+1}/${n} ${l}`,title:l,onClick:()=>s(e.item),onKeyDown:e=>o(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function cd({label:e,tone:t,children:n}){return(0,r.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"run-status-label",children:e}),(0,r.jsx)("span",{className:"run-status-text",children:n})]})}let cu={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function cp({compaction:e,t}){let[n,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((n-e.startedAt)/1e3)),o=e.reason&&!0===cu[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(cd,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),o?` \xb7 ${o}`:""]})}function ch({onDismiss:e,t}){return(0,r.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,r.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,r.jsxs)("span",{className:"interrupted-run-text",children:[(0,r.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,r.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,r.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}var cm=n(39092),cf=n.n(cm);let cg=["01","02","03"];function cx(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),0x1000193);return(t>>>0)/0x100000000}function cv(e,t,n){if(e&&"streaming"!==t){let r=r$(e);if(r){let e="failed"===t?"failed":"done",a=ri(rr(rL(r),r.id,e)?.stickers??[],null,()=>cx(n));return a?{src:a,alt:n4[e]}:null}}if(!e||"streaming"===t||!n1.includes(e))return null;let r="failed"===t?"failed":"done",a=e.slice(0,e.indexOf("(")).toLowerCase(),i=ri(cg.map(e=>`/stickers/${a}/${r}/${e}.webp`),null,()=>cx(n));return i?{src:i,alt:n4[r]}:null}let cb=new Map,cy=(0,a.createContext)(cb);function cw({utterances:e,children:t}){return(0,r.jsx)(cy.Provider,{value:e,children:t})}function ck({turnIndex:e,turnEntryId:t,sessionId:n,cwd:i,onOpenFile:s}){let o=(0,a.useContext)(cy).get(e);return o&&0!==o.length?(0,r.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:o.map(e=>(0,r.jsx)(cj,{utterance:e,sessionId:n,cwd:i,onOpenFile:s},e.key))}):null}function cj({utterance:e,sessionId:t,cwd:n,onOpenFile:i}){let s=am(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??rV(e.provider),f=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==f?`작업 \xb7 ${h}`:null,x=cv(s?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...s?{minHeight:40}:null},children:[s&&(0,r.jsx)(av,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(ny,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:i,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(c||o)&&(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:o?"접기":"더보기"}),x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-e0a9ca790f024efb inline-utterance-sticker"}),(0,r.jsx)(cf(),{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 cS=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function cC(e,t,n,r){if("string"!=typeof n)return[];let a=cS.exec(n),i=a?.[1],s=a?.[2];return i&&s?[{toolCallId:e,...t?{name:t}:{},alias:i,model:s,batchSize:r}]:[]}function cN(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[]){if("toolCall"!==n.type||"task"!==n.toolName)continue;let e=n.input,r=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...cC(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let a of e.tasks)!a||"object"!=typeof a||Array.isArray(a)||t.push(...cC(n.toolCallId,"name"in a&&"string"==typeof a.name?a.name:void 0,"task"in a?a.task:void 0,r))}return t}function cT(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[])"toolCall"===n.type&&"task"===n.toolName&&t.push(n.toolCallId);return t}let cI=/^agent:\/\/([^/?#]+)\/?$/i;function cM(e,t){if(!e||"assistant"!==e.role)return[];let n=[];for(let r of e.content??[]){if("toolCall"!==r.type||"write"!==r.toolName)continue;let e=r.input,a="string"==typeof e.path?cI.exec(e.path):null,i=a?.[1],s=e.content;if(!i||"string"!=typeof s)continue;let o=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:i,message:s,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return n}function cR(e,t,n){for(let r of["string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",t?.model.trim()??""]){let e=r.indexOf("/");if(e>0&&r.slice(0,e)===n)return r.slice(e+1).trim()||void 0}}let cE=["greeting","utterance","message","text"],cL=function(e){let t=(0,a.useMemo)(()=>aO(),[]),n=function(e,t){let[n,r]=(0,a.useState)(null);return(0,a.useEffect)(()=>{if(!t)return void r(null);let n=!1,a=new AbortController;return r(null),e.getArchive(t,a.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,a.abort()}},[e,t]),n}(t,e.sessionId),r=(0,a.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let a=e.turns.flatMap(e=>e.characterSummons);for(let i of n.subagents){if(t.has(i.name))continue;let n=[...a].reverse().find(e=>e.name===i.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",a={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,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:n,id:e.name,agent:"",status:r,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,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let a=r.requests.filter(e=>e.name),i="string"==typeof t.task?cS.exec(t.task):null,s=i?.[1],o=i?.[2],l=a.find(e=>e.name===t.id)??(s&&o?r.requests.find(e=>e.alias===s&&e.model===o):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!l)return[];let c=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:r.turnIndex,summon:l,sends:c}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),i=(0,a.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),s=s7(i,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&i.length>0});return(0,a.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:a,summon:i}=e,s="completed"===(r=a.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",o="failed"===s,l=i?.model.split("/",1)[0]?.trim()||void 0,c=o&&l?l:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",a=r.indexOf("/");if(a>0)return r.slice(0,a);let i=t?.model.trim()??"",s=i.indexOf("/");return s>0?i.slice(0,s):n?.trim()||void 0}(a,i,n),d=a.id.trim()||void 0,u=`subagent:${a.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,n)=>{var r;let f;if("irc"in t){let{from:n,message:r,truncated:i}=t.irc;if(i||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let i=e.sends[t];if(i.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(i.send,a.id)&&i.send.from===n){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=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let n of e.content??[]){if("toolCall"!==n.type||"yield"!==n.toolName)continue;let e=n.input.data,r="";if("string"==typeof e)r=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...cE]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let a=r.trim();a.length>0&&(t=a)}return t}(r))||(o?t.message.errorMessage?.trim()??"":"");if(0===x.length)return;let v=t.message.model||cR(a,i,g);p.push({key:`${a.id}:${n}`,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=cR(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)),[r,s,e.sessionProvider])},c$="web6",cP=[],cA=[],cF=function(e){let t=(0,a.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let a=n.trim();if(!a)throw Error("sessionId가 필요하다");let i=`${t}?sessionId=${encodeURIComponent(a)}`,s=await e(i,{signal:r});if(!s.ok)throw Error(`HTTP ${s.status}`);let o=await s.json(),l=o&&"object"==typeof o&&"consults"in o?o.consults:null;if(!Array.isArray(l))throw Error("consults 배열이 아니다");return l.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let a="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:i,text:s,error:o}=e;return{sessionId:t,startedAt:n,finishedAt:a,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:a-n,model:"string"==typeof e.model?e.model:"",status:r,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]:[]})}}})(),[]),[n,r]=(0,a.useState)(cA),i=(0,a.useRef)(""),s=e.sessionId??"",o=s.length>0;return(0,a.useEffect)(()=>{if(!o){i.current="",r(cA);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(s,e.signal),a=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(a===i.current)return;i.current=a,r(n)}catch{}};n();let a=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(a)}},[t,o,s]),(0,a.useMemo)(()=>(function(e,t,n){if(0===e.length)return cP;let r=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if("user"!==r.role)continue;let a=r.timestamp;"number"==typeof a&&Number.isFinite(a)&&t.push({index:n,openedAt:a})}return t}(t);if(0===r.length)return cP;let a=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let i=t.error??"";0!==i.trim().length&&a.push({key:`${c$}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${c$}:${t.conversationId??"unknown"}`,text:i,status:"failed"})}return a.length>0?a:cP})(n,e.messages,s),[n,e.messages,s])},c_="lab:";function cz(e){return e.startsWith(c_)?e.slice(c_.length).split(":",1)[0]||null:null}let cW={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function cO(e){return e.multi&&e.options.length>1}function cD(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 cH(e,t){let n={};for(let[t,r]of e.hidden)cV(n,t,r);return e.fields.forEach((e,r)=>{let a=t[r];if(!e.name||!a)return;let i=function(e,t){if("text"===e.kind){var n,r,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 n=new Set(t.checked),r=t.otherOn?t.other:void 0,a=e.other?r?.trim():void 0,i=e.options.flatMap((e,t)=>n.has(t)&&!e.disabled?[e.value]:[]),cO(e)?a?[...i,a]:i:a||i[0]}}(e,a);void 0!==i&&cV(n,e.name,i)}),n}function cU(e,t){let n={};for(let r of e.fields){if(!r.name||cK(n,r.name))continue;let e=function(e,t){if("choice"===e.kind){let n=void 0===t||Array.isArray(t)&&0===t.length;if(!e.required||!n)return;return cO(e)?{code:"selectAtLeastOne"}:{code:"required"}}let n=void 0===t?"":String(t);if(""===n.trim())return e.required?{code:"required"}:void 0;if("number"===e.type||"range"===e.type){let t=Number(n);if(!Number.isFinite(t))return{code:"enterNumber"};if(void 0!==e.min&&t<e.min)return{code:"min",value:e.min};if(void 0!==e.max&&t>e.max)return{code:"max",value:e.max}}return void 0!==e.minLength&&n.length<e.minLength?{code:"minLength",value:e.minLength}:void 0!==e.maxLength&&n.length>e.maxLength?{code:"maxLength",value:e.maxLength}:"email"!==e.type||/^[^\s@]+@[^\s@]+$/.test(n)?"url"!==e.type||URL.canParse(n)?e.pattern&&(function(e){try{return RegExp(`^(?:${e})$`,"v")}catch{return}})(e.pattern)?.test(n)===!1?{code:"pattern",pattern:e.pattern.length>40?`${e.pattern.slice(0,39)}…`:e.pattern}:void 0:{code:"url"}:{code:"email"}}(r,cK(t,r.name));e&&cV(n,r.name,e)}return n}function cB(e){return e.map(e=>e.text).join("")}function cq(e,t,n){if(!e.multi)return{...t,checked:[n],otherOn:!1};let r=t.checked.includes(n)?t.checked.filter(e=>e!==n):[...t.checked,n].sort((e,t)=>e-t);return{...t,checked:r}}function cV(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function cK(e,t){return Object.hasOwn(e,t)?e[t]:void 0}let cG={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},cJ={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)"},cZ={minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"};function cY({spans:e}){return(0,r.jsx)(r.Fragment,{children:e.map((e,t)=>{let n=[];return(e.text.split("\n").forEach((e,t)=>{t>0&&n.push((0,r.jsx)("br",{},`br-${t}`)),n.push(e)}),"code"===e.style)?(0,r.jsx)("code",{style:{padding:"0 4px",borderRadius:4,background:"var(--bg-subtle)",fontFamily:"var(--font-mono)",fontSize:"0.92em"},children:n},t):"strong"===e.style?(0,r.jsx)("strong",{style:{fontWeight:600},children:n},t):"em"===e.style?(0,r.jsx)("em",{children:n},t):(0,r.jsx)("span",{children:n},t)})})}function cX({src:e,alt:t}){let{t:n}=(0,z.s)(),[i,s]=(0,a.useState)(!1);return!e||i?(0,r.jsx)("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",overflowWrap:"anywhere"},children:t||n("chat.formImageUnavailable")}):(0,r.jsx)("img",{src:e,alt:t,onError:()=>s(!0),style:{display:"block",maxWidth:"100%",maxHeight:320,height:"auto",objectFit:"contain",borderRadius:"var(--radius-control)"}})}function cQ({block:e,id:t}){let n={margin:0,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.55,overflowWrap:"anywhere"};switch(e.kind){case"text":return(0,r.jsx)("p",{id:t,style:{...n,fontWeight:e.heading?600:400},children:(0,r.jsx)(cY,{spans:e.spans})});case"list":{let t=e.ordered?"ol":"ul";return(0,r.jsx)(t,{style:{...n,paddingInlineStart:22},children:e.items.map((e,t)=>(0,r.jsx)("li",{children:(0,r.jsx)(cY,{spans:e})},t))})}case"pre":return(0,r.jsx)("pre",{tabIndex:0,style:{margin:0,padding:"8px 10px",overflowX:"auto",maxWidth:"100%",border:"1px solid var(--hairline)",borderRadius:"var(--radius-control)",background:"var(--bg-subtle)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5},children:e.text});case"table":return(0,r.jsx)("div",{tabIndex:0,style:{maxWidth:"100%",overflowX:"auto",border:"1px solid var(--hairline)",borderRadius:"var(--radius-control)"},children:(0,r.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)("tbody",{children:e.rows.map((t,n)=>(0,r.jsx)("tr",{children:t.map((t,a)=>{let i=n<e.headerRows?"th":"td";return(0,r.jsx)(i,{scope:n<e.headerRows?"col":void 0,style:{padding:"6px 10px",borderBottom:"1px solid var(--hairline)",color:n<e.headerRows?"var(--text-muted)":"var(--text)",fontWeight:n<e.headerRows?600:400,textAlign:"left",verticalAlign:"top",minWidth:72},children:(0,r.jsx)(cY,{spans:t})},a)})},n))})})});case"image":return(0,r.jsx)(cX,{src:e.src,alt:e.alt})}}function c0({field:e,id:t,index:n,error:a,children:i,hasLabel:s}){let{t:o}=(0,z.s)();return(0,r.jsxs)("div",{"data-field":n,style:{display:"grid",gap:6,minWidth:0},children:[(s||e.required)&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[s&&(0,r.jsx)("label",{id:`${t}-label`,htmlFor:"text"===e.kind||e.select?t:void 0,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:(0,r.jsx)(cY,{spans:e.label})}),e.required&&(0,r.jsx)("span",{style:{marginLeft:s?0:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:o("chat.formRequired")})]}),i,a&&(0,r.jsxs)("p",{id:`${t}-error`,style:{margin:0,display:"flex",alignItems:"flex-start",gap:6,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:500,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",style:{flex:"none",marginTop:2},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.5"}),(0,r.jsx)("path",{d:"M7 4v3.4M7 9.6v.1"})]}),(0,r.jsx)("span",{children:function(e,t){switch(e.code){case"min":case"max":case"minLength":case"maxLength":return t(`chat.formError.${e.code}`,{value:e.value});case"pattern":return t("chat.formError.pattern",{pattern:e.pattern});default:return t(`chat.formError.${e.code}`)}}(a,o)})]})]})}function c1({field:e,id:t,index:n,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,r.jsx)(c0,{field:e,id:t,index:n,error:s,hasLabel:p,children:(0,r.jsx)("select",{id:t,...h,value:String(i.checked[0]??""),onChange:t=>c(n,cq(e,i,Number(t.target.value))),style:{...cJ,height:36},children:e.options.map((e,t)=>(0,r.jsx)("option",{value:t,disabled:e.disabled,children:cB(e.label)},t))})});let m=e.multi?"checkbox":"radio",f=(e,t)=>({display:"grid",gridTemplateColumns:"16px minmax(0, 1fr)",alignItems:"start",gap:9,minHeight:40,padding:"9px 10px",border:`1px solid ${e?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:e?"var(--bg-selected)":"transparent",color:t?"var(--text-dim)":"var(--text)",cursor:t?"not-allowed":"pointer",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5,overflowWrap:"anywhere"}),g={width:16,height:16,margin:"3px 0 0",accentColor:"var(--seed-color-fg-neutral)"},x=`${t}-choice`;return(0,r.jsx)(c0,{field:e,id:t,index:n,error:s,hasLabel:p,children:(0,r.jsxs)("div",{role:e.multi?"group":"radiogroup",...h,style:{display:"grid",gap:4},children:[e.options.map((t,a)=>{let s=i.checked.includes(a);return(0,r.jsxs)("label",{style:f(s,t.disabled),children:[(0,r.jsx)("input",{type:m,name:x,checked:s,disabled:t.disabled,"aria-required":!!e.required&&!e.multi||void 0,onChange:()=>c(n,cq(e,i,a)),style:g}),(0,r.jsx)("span",{children:(0,r.jsx)(cY,{spans:t.label})})]},a)}),e.other&&(0,r.jsxs)("div",{style:{display:"grid",gap:6},children:[(0,r.jsxs)("label",{style:f(i.otherOn,!1),children:[(0,r.jsx)("input",{type:m,name:x,checked:i.otherOn,onChange:()=>{c(n,e.multi?{...i,otherOn:!i.otherOn}:{...i,checked:[],otherOn:!0}),i.otherOn&&e.multi||u.current?.focus()},style:g}),(0,r.jsx)("span",{children:d("chat.formOther")})]}),(0,r.jsx)("input",{ref:u,type:"text",value:i.other,"aria-label":d("chat.formOther"),placeholder:d("chat.formOtherPlaceholder"),onChange:t=>{var r;let a;return c(n,(a=""!==(r=t.target.value).trim(),{...i,other:r,otherOn:!!a||i.otherOn,checked:a&&!e.multi?[]:i.checked}))},style:{...cJ,height:36,width:"calc(100% - 35px)",marginInlineStart:35}})]})]})})}function c2({field:e,id:t,index:n,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(cG,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)":cJ.border;return(0,r.jsx)(c0,{field:e,id:t,index:n,error:i,hasLabel:c,children:e.multiline?(0,r.jsx)("textarea",{...u,rows:Math.max(2,e.rows),onChange:e=>l(n,{kind:"text",text:e.target.value}),style:{...cJ,padding:"8px 10px",border:p,lineHeight:1.5,resize:"vertical"}}):(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("input",{...u,type:d,min:"number"===d||"range"===d?e.min:void 0,max:"number"===d||"range"===d?e.max:void 0,step:"number"===d?"any":void 0,onChange:e=>l(n,{kind:"text",text:e.target.value}),style:{...cJ,height:"color"===d?40:36,border:p,..."range"===d?{padding:0}:{},fontVariantNumeric:"tabular-nums"}}),"range"===d&&(0,r.jsx)("output",{htmlFor:t,style:{minWidth:32,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:a.text})]})})}function c8({request:e,onRespond:t,onActivity:n,delivery:i}){let{t:s}=(0,z.s)(),o=(0,a.useId)(),l=e.form,[c,d]=(0,a.useState)(()=>l.fields.map(cD)),u=(0,a.useRef)(c),[p,h]=(0,a.useState)(!1),m=(0,a.useRef)(null),f=(0,a.useRef)(n);f.current=n;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=cW){let n,r=-1/0,a=!1,i=()=>{a&&t.clearTimeout(n),a=!1,r=t.now(),e()};return{notify(){let e=1e3-(t.now()-r);e<=0?i():a||(a=!0,n=t.setTimeout(i,e))},cancel(){a&&t.clearTimeout(n),a=!1}}}(()=>{var n,r;let a=g.current;t+=1,f.current?.(a,(n=t,r=cH(a.form,u.current),`activity:form:v2:${e}:${n}:${JSON.stringify(r)}`))})}(0,a.useEffect)(()=>()=>v.current?.cancel(),[]);let b=(0,a.useCallback)((e,t)=>{let n=u.current.slice();n[e]=t,u.current=n,d(n),g.current.timeout&&f.current&&v.current?.notify()},[]),y=cH(l,c),w=p?cU(l,y):{},k=Object.keys(w).length>0,j=()=>{if(x)return;let n=cH(l,u.current),r=cU(l,n);if(Object.keys(r).length>0){h(!0);let e=l.fields.findIndex(e=>""!==e.name&&void 0!==cK(r,e.name));m.current?.querySelector(`[data-field="${e}"] input, [data-field="${e}"] select, [data-field="${e}"] textarea`)?.focus();return}t(e,{value:JSON.stringify(n)})};return(0,r.jsxs)("div",{"data-ask-form":"",style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentFormHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askFormAutoSubmitHint",{seconds:Math.round(e.timeout/1e3)})}):null]}),(0,r.jsx)("div",{ref:m,onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&j()},style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20,minWidth:0},children:l.sections.map((e,t)=>{let n,a=cB(e.title);return(0,r.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,r.jsx)("h3",{id:`${o}-s${t}`,style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600,lineHeight:1.4},children:(0,r.jsx)(cY,{spans:e.title})}),e.blocks.map((e,i)=>{var s;let d;if("field"!==e.kind){let a=`${o}-s${t}b${i}`;return n="text"===e.kind?a:void 0,(0,r.jsx)(cQ,{block:e,id:a},i)}let u=l.fields[e.index],h=n;n=void 0;let m=(s=e.index,d=l.fields[s],{id:`${o}-f${s}`,index:s,state:c[s],error:p&&d.name?cK(w,d.name):void 0,captionId:h,fallbackName:a||d.name,onChange:b});return"choice"===u.kind?(0,r.jsx)(c1,{...m,field:u},i):(0,r.jsx)(c2,{...m,field:u},i)})]},t)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[k&&(0,r.jsx)("p",{role:"alert",style:{margin:0,marginRight:"auto",color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.formInvalid")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:cZ,children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button","aria-disabled":x||void 0,onClick:j,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:x?"var(--seed-color-bg-disabled)":"var(--seed-color-bg-neutral-inverted)",color:x?"var(--seed-color-fg-disabled)":"var(--seed-color-fg-neutral-inverted)",cursor:x?"not-allowed":"pointer",fontWeight:600},children:s(x?"chat.responseSending":"chat.submitAnswer")})]})]})}let c4={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},c5={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function c6({rows:e,removeLabel:t,onRemove:n}){let i,{st:s}=ax(),[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,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":o,onClick:()=>l(e=>!e),children:o?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:d})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:c.map(e=>{let a=lp(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,r.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,r.jsx)("span",{className:"answer-delivery-kind",children:s(c4[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:i,children:i}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:s(c5[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${i}`,onClick:()=>n(e.kind,e.text),children:(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}let c3=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),c7=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function c9({soundEnabled:e,onToggle:t}){let n=e?"완료음 끄기":"완료음 켜기";return(0,r.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:n,"aria-label":n,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?c3:c7})})})}let de=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),dt=["normal","slow"],dn={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function dr(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(i),e.removeEventListener("icegatheringstatechange",a),n()},a=()=>{"complete"===e.iceGatheringState&&r()},i=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",a),t}function da(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let di={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},ds=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),dl=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function dc({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:i}=(0,z.s)(),s=function(e,t,n){let{locale:r}=(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 n=b.current;b.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,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 dr(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:r})}),h=await u.json().catch(()=>({})),m="",f="";if(h&&"object"==typeof h&&("error"in h&&(e=h.error),"message"in h&&"string"==typeof h.message&&(t=h.message),"callId"in h&&"string"==typeof h.callId&&(m=h.callId),"sdp"in h&&"string"==typeof h.sdp&&(f=h.sdp)),!u.ok||!m||!f){k.current===i&&(g(!1),S(da(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 r;if("string"!=typeof t.state||(r=t.state,!0!==dn[r]))return;"closed"===t.state?j("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&n&&Promise.resolve().then(()=>n(o)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&de.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,n,r,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,n),o="connecting"===s.state||"live"===s.state||"working"===s.state,l="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,c=i(o?"chat.liveStop":"chat.liveStart"),d=!1===s.supported?di.unsupported:s.failure?di[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,r.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,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:i(d)}),l&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i(l)}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":o,title:p?i(p):c,"aria-label":p?i(p):c,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o?dl:ds})})]})}let dd={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 du({sessionId:e}){let{t}=(0,z.s)(),[n,i]=(0,a.useState)(null);return((0,a.useEffect)(()=>{if(!e)return void i(null);let t=!1,n=0,r=!1,a=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let a=await n.json();if(t)return;let s=Array.isArray(a.handles)?a.handles:[],o=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==o,i(o)}catch{}},s=async()=>{await a(),t||(n=window.setTimeout(()=>void s(),r?5e3:3e4))};return s(),document.addEventListener("visibilitychange",a),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",a)}},[e]),n)?(0,r.jsx)("span",{style:dd,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}let dp=new Map,dh="ompweb-drafts-for-reload-v1",dm=!1,df=new Map,dg=new Map,dx="\0stale",dv=new Map,db=0,dy=new Map,dw=new Map,dk=new Map,dj=new Map,dS=new Map,dC=(e,t,n)=>lb(e,t,n.length?{sentAttachmentIds:n}:{}),dN=null,dT=!1;function dI(){if(dm||"u"<typeof sessionStorage)return;dm=!0;let e=sessionStorage.getItem(dh);if(e){sessionStorage.removeItem(dh);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)&&(dp.set(e[0],dR(t)),"string"==typeof t.draftId&&t.draftId&&(df.set(e[0],t.draftId),dg.set(t.draftId,dx)),dW(e[0]))}}catch{}}}function dM(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(dh,JSON.stringify([...dp.entries()].map(([e,t])=>{let n=df.get(e);return[e,n?{...dR(t),draftId:n}:dR(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function dR(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function dE(e){return!e.value&&0===e.images.length&&0===e.documents.length}function dL(e){dI();let t=dp.get(e);return t?dR(t):null}function d$(e,t){dI(),dE(t)?dp.delete(e):dp.set(e,dR(t)),dW(e)}function dP(e){dp.delete(e),dW(e)}function dA(e,t,n,r,a,i=[]){let s=[...t??[],...r].filter(nO).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=lc([...a??[],...i]);return{value:e.trim()?n.trim()?`${e}
|
|
18
|
+
|
|
19
|
+
${n}`:e:n,images:s,documents:o}}function dF(e,t,n){if(e===t)return n?dR(n):dL(t);let r=dL(e),a=n&&!dE(n)?dR(n):r??(n?dR(n):null),i=dL(t),s=df.get(e);if(df.delete(e),s&&!df.has(t)&&df.set(t,s),dP(e),!a)return i;let o=i?dA(i.value,i.images,a.value,a.images,i.documents,a.documents):a;return d$(t,o),dR(o)}function d_(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function dz(e){dI();let t=df.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),df.set(e,t)),t}function dW(e){let t=d_(dp.get(e)?.documents),n=t.length?dz(e):df.get(e);for(let[e,n]of dw){for(let e of t)n.delete(e);0===n.size&&dw.delete(e)}let r=`${n??""}|${t.join(",")}`;dj.get(e)!==r&&(0!==t.length||n?dj.set(e,r):dj.delete(e),dV())}async function dO(e){let t=dz(e);dy.set(t,(dy.get(t)??0)+1),await dS.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(dy.get(t)??1)-1;if(r>0?dy.set(t,r):dy.delete(t),e){let n=dw.get(t)??new Set;n.add(e),dw.set(t,n)}dg.set(t,dx),dV()}}}function dD(e,t){let n=dk.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&dk.delete(e),[...n].sort()}async function dH(){if(!dC)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of df)t(n,d_(dp.get(e)?.documents));for(let{draftId:e,ids:n}of dv.values())t(e,n);for(let[e,n]of dw)t(e,n);for(let e of dg.keys())t(e,[]);for(let e of dk.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dy.has(e))return!1;let n=dg.get(e);return dD(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=dy.size>0,n=!1;for(let[r,a]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===a.length&&t)continue;let e=dD(r,a),i=dC(r,a,e).then(()=>{0===a.length?dg.delete(r):dg.set(r,a.join(","));let t=dk.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&dk.delete(r)}},()=>{n=!0,a.length>0&&(t=!0)});dS.set(r,i),await i,dS.get(r)===i&&dS.delete(r)}n?function(){if(dq)return;dq=!0;let e=setTimeout(()=>{dq=!1,dV()},dB);"object"==typeof e&&"unref"in e&&e.unref(),dB=Math.min(2*dB,6e4)}():dB=dU}let dU=5e3,dB=5e3,dq=!1;function dV(){if(dC){if(dN){dT=!0;return}dN=Promise.resolve().then(dH).finally(()=>{dN=null,dT&&(dT=!1,dV())})}}let dK=Math.floor(Number.MAX_SAFE_INTEGER/1048576),dG=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function dJ(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=dK}async function dZ(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!dJ(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:dJ((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:dG.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:dG.autoCleanupEnabled,orphanGraceDays:7}}async function dY(e={}){return dZ(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function dX(e){return dZ(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function dQ(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function d0(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function d1(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function d2(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function d8(e,t,n){let r=Math.max(1,Math.min(t,n)),a=Math.max(1,Math.max(t,n)),i=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===a?`:${r}`:`:${r}-${a}`;return`${i}${s} `}let d4="omp-web:model-picks";function d5(){try{let e=JSON.parse(window.localStorage.getItem(d4)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function d6(e,t,n,r,a={}){let i=a.gap??8,s=a.margin??8,o=a.prefer??"above",l=Math.min(a.minHeight??120,Math.max(0,n-2*s)),c=Math.max(0,e-i-s),d=Math.max(0,n-t-i-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=r||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(r,h?u:p))}}function d3(e,t,n){return Math.min(e*t,n)}function d7(e,t,n){let{viewportFraction:r,cap:i,gap:s,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,a.useState)({side:c??"above",maxHeight:i}),p=(0,a.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,a=t.getBoundingClientRect(),d=d6(a.top,a.bottom,n,d3(n,r,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,r]);return(0,a.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var d9=n(14755);let ue="omp-web:model-roles-expanded";async function ut(e,t,n,r,a,i,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...uf,...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 n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return 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 ur=["off","default","full"],ua={off:"none",default:"default",full:"full"},ui=d9.IN.join(" \xb7 "),us=d9.C1.filter(e=>!d9.IN.includes(e)).join(" \xb7 ");function uo(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let ul=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),uc=0,ud={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function uu(e,t){return ul.compare(e.name||e.modelId,t.name||t.modelId)||ul.compare(e.provider,t.provider)||ul.compare(e.modelId,t.modelId)}let up=["auto","off","minimal","low","medium","high","xhigh","max"],uh=["low","medium","high","xhigh"],um={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},uf=[{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"}],ug=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],ux={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},uv={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function ub(e,t,n){let r=e.name.toLowerCase(),a=uy(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:a.includes(t)?3:4}function uy(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uw(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uk(e){return{data:e.data,mimeType:e.mimeType}}function uj(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uS(e){return(e??[]).filter(nO).slice(0,10).map(uj)}let uC=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uN="\n\nTranscript of the audio ";function uT(e){return lc(e).map(e=>{let t=lg(e),n="audio"===t&&e.attachmentId&&!e.text.includes(uN)?uC.exec(e.text):null;return{...e,id:++uc,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function uI({name:e,mimeType:t,size:n,text:r,attachmentId:a}){return a?{name:e,mimeType:t,size:n,text:r,attachmentId:a}:{name:e,mimeType:t,size:n,text:r}}function uM(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class uR extends Error{constructor(e,t,n,r,a=null){super(e),this.code=t,this.completedParts=n,this.parts=r,this.offer=a}}let uE="composer:unkeyed";async function uL(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;let r="number"==typeof n.completedParts?n.completedParts:null,a="number"==typeof n.parts?n.parts:null,i="fallback_confirmation_required"===n.code&&"string"==typeof n.fallbackToken&&"string"==typeof n.notice&&null!==r&&null!==a?{token:n.fallbackToken,notice:n.notice,completedParts:r,parts:a}:null;throw new uR("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,r,a,i)}function u$(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 uA({tone:e,title:t,body:n}){let a="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${a}-line)`,borderRadius:"var(--radius-control)",background:`var(--${a}-soft)`,color:`var(--${a})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function uF({error:e}){return e?(0,r.jsx)(uA,{tone:"error",title:"Model error",body:e}):null}function u_({warnings:e}){return e&&0!==e.length?(0,r.jsx)(uA,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uz=(0,a.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,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:R=!1,thinkingCeiling:E,onThinkingLevelChange:L,availableThinkingLevels:$,thinkingLevelMap:P,fastMode:A=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,sessionId:et,onEnsureSession:en,onLiveTranscriptPersisted:er},ea){let ei,es,eo,el,ec,ed,eu,ep,eh,em,{t:ef}=(0,z.s)();af();let{st:eg}=ax(),ex=O.some(e=>e.removable),ev=B(),[eb,ey]=(0,a.useState)(()=>Q?dL(Q)?.value??"":""),[ew,ek]=(0,a.useState)(!1),[ej,eS]=(0,a.useState)(null),[eC,eN]=(0,a.useState)(""),[eT,eI]=(0,a.useState)({});(0,a.useEffect)(()=>{ew&&eI(d5())},[ew]);let[eM,eR]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(ew)try{eR("1"===window.localStorage.getItem(ue))}catch{}},[ew]);let eE=()=>{eR(e=>{let t=!e;try{window.localStorage.setItem(ue,t?"1":"0")}catch{}return t})},[eL,e$]=(0,a.useState)(!1),[eP,eA]=(0,a.useState)(null),[eF,e_]=(0,a.useState)(!1),[ez,eW]=(0,a.useState)(!1),[eO,eD]=(0,a.useState)(null),[eH,eU]=(0,a.useState)(!1),[eB,eq]=(0,a.useState)(()=>Q?uS(dL(Q)?.images):[]),[eV,eK]=(0,a.useState)(()=>Q?uT(dL(Q)?.documents):[]),[eG,eJ]=(0,a.useState)(null),eZ=(0,a.useMemo)(()=>eV.filter(e=>"ready"===e.status),[eV]),eY=eV.some(e=>"ready"!==e.status||un(e)),eX=eV.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uN))),eQ=eb.trimStart(),e0=0===eB.length&&0===eV.length&&eQ.startsWith("!"),e1=e0&&eQ.startsWith("!!"),[e2,e8]=(0,a.useState)(!1),[e4,e5]=(0,a.useState)(0),[e6,e3]=(0,a.useState)(null),[e7,e9]=(0,a.useState)(!1),[te,tt]=(0,a.useState)(0),[tn,tr]=(0,a.useState)(!1),[ta,ti]=(0,a.useState)(0),[ts,to]=(0,a.useState)(null),[tl,tc]=(0,a.useState)(!1),[td,tu]=(0,a.useState)(null),[tp,th]=(0,a.useState)(null),tm=ee&&tp?.cwd===ee?tp.values:{},tf=(0,a.useRef)(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)(null),tk=(0,a.useRef)(null),tj=(0,a.useRef)(null),tS=(0,a.useRef)(null),tC=(0,a.useRef)(null),tN=(0,a.useRef)(!1),tT=(0,a.useRef)(0),tI=(0,a.useRef)(!1),tM=(0,a.useRef)([]),tR=(0,a.useRef)([]),tE=(0,a.useRef)([]),tL=(0,a.useRef)(null),t$=(0,a.useRef)(null),tP=(0,a.useRef)(Q),tA=(0,a.useRef)(eb),tF=(0,a.useRef)(eB),t_=(0,a.useRef)(0),tz=(0,a.useRef)(eV);tA.current=eb,tF.current=eB,tz.current=eV,(0,a.useImperativeHandle)(ea,()=>({insertIfEmpty(e){let t=tf.current;(t?t.value:eb).trim()||(tA.current=e,ey(e),e3(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=tf.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:eb,tF.current.length,t_.current,tz.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"),lp(t)?.message??t),i=uS("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return nO(r)?[r]:[]})),s=uT((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),lp(n)?.documents??[]));tA.current=a,tF.current=i,tz.current=s,ey(a),e3(null),tr(!1),eq(e=>(e.forEach(uP),i)),eK(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tP.current!==e)return void dF(e,t);let n={value:tA.current,images:tF.current.map(uk),documents:tz.current.filter(e=>"ready"===e.status).map(uI)},r=dF(e,t,n)??{value:"",images:[],documents:[]},a=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tP.current=t,a)return;let i=uS(r.images),s=uM(uT(r.documents),tz.current),o=r.value;tA.current=o,tF.current=i,tz.current=s,ey(o),eq(e=>(e.forEach(uP),i)),eK(s),e3(null),tr(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let a=tP.current,i=r??a,s=i===a,o=!s&&i?dL(i):null,l=dA(e,t,s?tA.current:o?.value??"",s?tF.current.map(uk):o?.images??[],n,s?tz.current.filter(e=>"ready"===e.status).map(uI):o?.documents??[]);if(i&&d$(i,l),!s)return;let c=t?.length?[...uS(t).slice(0,Math.max(0,10-tF.current.length)),...tF.current].slice(0,10):tF.current,d=uM(uT(l.documents),tz.current);tA.current=l.value,tF.current=c,tz.current=d,ey(l.value),e3(null),tr(!1),t?.length&&eq(e=>{let n=Math.max(0,10-e.length),r=uS(t).slice(0,n),a=r.length>0?[...r,...e]:e;return tF.current=a,a}),eK(d),requestAnimationFrame(()=>{let e=tf.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=tf.current;if(!t)return void ey(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,a=t.value.slice(0,n),i=t.value.slice(r),s=a.length>0&&!a.endsWith(" ")?" ":"",o=a+s+e+i;tA.current=o,ey(o),e3(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){t0(e)}}));let tW=(0,a.useCallback)(async e=>{let t=Math.max(0,10-tF.current.length-t_.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eJ(ef("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:lh(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),a=r.slice(0,t);if(a.length<r.length&&eJ(ef("chat.attachImageLimit",{count:10})),a.length){t_.current+=a.length;try{let e=await Promise.all(a.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eq(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(uP);let r=[...t,...n];return tF.current=r,r})}finally{t_.current-=a.length}}},[ef]),tO=(0,a.useCallback)(async e=>{for(let t of e){let e=li(t);if(!e)continue;if(tz.current.length>=3){eJ(ef("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eJ(ef("chat.attachTooLarge",{name:t.name,limit:lh(8388608)}));continue}if(tz.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eJ(ef("chat.attachTotalTooLarge",{limit:lh(0x1000000)}));continue}let n={id:++uc,name:t.name,mimeType:ln[e],size:t.size,text:"",status:"extracting"},r=[...tz.current,n];tz.current=r,eK(r);try{let e=await ld(t);if(tz.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new lt("text_too_large","Total extracted text exceeds 240000 characters");let r=tz.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tz.current=r,eK(r)}catch(a){let e=tz.current.some(e=>e.id===n.id),r=tz.current.filter(e=>e.id!==n.id);if(tz.current=r,eK(r),!e)continue;a instanceof lt?"text_too_large"===a.code?eJ(ef("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===a.code?eJ(ef("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===a.code?eJ(ef("chat.attachNoPdfText",{name:t.name})):"password_protected"===a.code?eJ(ef("chat.attachPasswordProtected",{name:t.name})):eJ(ef("chat.attachExtractFailed",{name:t.name})):eJ(ef("chat.attachExtractFailed",{name:t.name}))}}},[ef]),tD=(0,a.useCallback)((e,t)=>{if(!tz.current.some(t=>t.id===e))return!1;let n=t?tz.current.map(n=>n.id===e?t:n):tz.current.filter(t=>t.id!==e);return tz.current=n,eK(n),!0},[]),tH=(0,a.useCallback)((e,t)=>{if(!tz.current.some(t=>t.attachmentId===e))return!1;let n=tz.current.map(n=>n.attachmentId===e?t(n):n);return tz.current=n,eK(n),!0},[]),tU=(0,a.useCallback)((e,t,n)=>{if(!e||e===tP.current)return;let r=dL(e);r?.documents.some(e=>e.attachmentId===t)&&d$(e,{...r,documents:uT(r.documents).map(e=>e.attachmentId===t?n(e):e).map(uI)})},[]),tB=(0,a.useRef)(new Map),tq=(0,a.useRef)(new Map),tV=(0,a.useRef)(new Set),tK=(0,a.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),a=lx({...e.storedInfo,transcript:t},r);return a.length>r?null:{...e,text:a,size:new TextEncoder().encode(a).byteLength,transcription:void 0}},[]),tG=(0,a.useCallback)(e=>e instanceof uR&&"media_tool_unavailable"===e.code?ef("chat.transcribeToolMissing"):e instanceof uR&&"fallback_confirmation_expired"===e.code?ef("chat.transcribeFallbackExpired"):e instanceof uR&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?ef("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[ef]),tJ=(0,a.useCallback)(async(e,t)=>{let n=tP.current,r=tz.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let a=r.transcription?.state==="confirm"?r.transcription.plan:null;tq.current.get(e)?.abort();let i=new AbortController;tq.current.set(e,i),tH(e,e=>({...e,transcription:{state:"running",plan:a}}));try{let r=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 r.transcript)throw new uR("Invalid transcription result",null,null,null);let a=r.transcript;tH(e,e=>tK(e,a,tz.current)??{...e,transcription:{state:"failed",error:ef("chat.transcribeTooLong")}})||tU(n,e,e=>tK(e,a,[])??e)}catch(r){if(i.signal.aborted)return void tH(e,e=>({...e,transcription:{state:"skipped"}}));if(r instanceof uR&&"confirmation_required"===r.code)return void tZ.current?.(e);let t=r instanceof uR?r.offer:null;if(t){let n={state:"fallback",reason:r instanceof Error?r.message:"",...t};tH(e,e=>({...e,transcription:n}))||u$(e,t.token);return}let n=tG(r);tH(e,e=>({...e,transcription:{state:"failed",error:n}}))}finally{tq.current.get(e)===i&&tq.current.delete(e)}},[ef,tG,tH,tU,tK]),tZ=(0,a.useRef)(null),tY=(0,a.useCallback)(async e=>{let t;tq.current.get(e)?.abort();let n=new AbortController;tq.current.set(e,n),tH(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 uR("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:n.signal})))}catch(t){if(n.signal.aborted)tH(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tG(t);tH(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{tq.current.get(e)===n&&tq.current.delete(e)}t.requiresConfirmation?tH(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tJ(e,{})},[tJ,tG,tH]);tZ.current=tY;let tX=(0,a.useCallback)(e=>{let t=tq.current.get(e);if(t)return void t.abort();let n=tz.current.find(t=>t.attachmentId===e)?.transcription;n?.state==="fallback"&&u$(e,n.token),tH(e,e=>({...e,transcription:{state:"skipped"}}))},[tH]),tQ=(0,a.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tz.current.length>=3){eJ(ef("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,a={id:++uc,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},i=[...tz.current,a];tz.current=i,eK(i);let s=(e,t)=>{let n=tz.current.filter(e=>e.id!==a.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?ll("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?ll("utf-16be",t.subarray(2)):t.includes(0)?null:ll("utf-8",t)??ll("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tD(a.id,{...a,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await dY().catch(()=>dG)).uploadLimitMb),r.size>n){tD(a.id,null)&&eJ(ef("chat.attachStoredTooLarge",{name:r.name,limit:lh(n)}));continue}let o={...a,stored:t,status:"uploading",size:0};if(!tD(a.id,o))continue;let l=tP.current??uE,c=await dO(l),d=null,u=new AbortController;tB.current.set(a.id,u);try{if(tV.current.has(a.id))continue;let e=await lv(r,{sessionId:et,draftId:c.draftId,signal:u.signal}),n=tz.current.filter(e=>e.id!==a.id).reduce((e,t)=>e+t.text.length,0),i=lx({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(i).byteLength;if(!s(i.length,p)){tD(a.id,null)&&eJ(ef("chat.attachTotalTooLarge",{limit:lh(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(tD(a.id,h))d=e.id;else if(!tV.current.has(a.id)&&l!==tP.current){let t=dL(l)??{value:"",images:[],documents:[]};d$(l,{...t,documents:[...t.documents,uI(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tD(a.id,null)&&eJ(ef("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tB.current.delete(a.id),c.end(d)}d&&"audio"===t&&tz.current.some(e=>e.attachmentId===d)&&tY(d)}},[tD,tY,et,ef]),t0=(0,a.useCallback)(async e=>{eJ(null);let{images:t,documents:n,audio:r,files:a}=function(e){let t=[],n=[],r=[],a=[];for(let i of e)i.type.startsWith("image/")?t.push(i):null!==li(i)?n.push(i):lo(i)?r.push(i):a.push(i);return{images:t,documents:n,audio:r,files:a}}(e),i=n.filter(e=>e.size>8388608);await Promise.all([tW(t),tO(n.filter(e=>e.size<=8388608)),tQ(r,"audio"),tQ([...a,...i],"file")])},[tO,tQ,tW]),t1=(0,a.useCallback)(e=>{eq(t=>{let n=[...t],[r]=n.splice(e,1);return r&&uP(r),tF.current=n,n})},[]),t2=(0,a.useCallback)(e=>{let t=tz.current.find(t=>t.id===e);if(tV.current.add(e),tB.current.get(e)?.abort(),t?.attachmentId){tq.current.get(t.attachmentId)?.abort(),t.transcription?.state==="fallback"&&u$(t.attachmentId,t.transcription.token);var n=t.attachmentId;for(let[e,t]of dw)t.delete(n)&&(0===t.size&&dw.delete(e),dV())}let r=tz.current.filter(t=>t.id!==e);tz.current=r,eK(r)},[]),t8=(0,a.useCallback)(()=>{tF.current=[],eq(e=>(e.forEach(uP),[]))},[]),t4=(0,a.useCallback)(()=>{tz.current=[],eK([])},[]),t5=(0,a.useCallback)(()=>{tA.current="",ey(""),e3(null),tr(!1),Q&&dP(Q),tP.current&&tP.current!==Q&&dP(tP.current),t8(),t4(),eJ(null),tf.current&&(tf.current.style.height="auto")},[t4,t8,Q]);(0,a.useEffect)(()=>{Q&&tP.current===Q&&d$(Q,{value:eb,images:eB.map(uk),documents:eZ.map(uI)})},[eB,Q,eZ,eb]),(0,a.useEffect)(()=>{let e=tP.current;if(e===Q)return;e&&d$(e,{value:tA.current,images:tF.current.map(uk),documents:tz.current.filter(e=>"ready"===e.status).map(uI)});let t=Q?dL(Q):null;tP.current=Q;let n=t?.value??"",r=uS(t?.images),a=uT(t?.documents);tA.current=n,tF.current=r,tz.current=a,ey(n),e3(null),tr(!1),eq(e=>(e.forEach(uP),r)),eK(a)},[Q]),(0,a.useEffect)(()=>{let e=tf.current;e&&(e.style.height="auto",eb&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[eb]),(0,a.useEffect)(()=>()=>{tF.current.forEach(uP)},[]);let t6=(0,a.useCallback)((e,t)=>{let n=function(e,t){let n=d_(t);if(0===n.length)return()=>{};let r=++db;return dv.set(r,{draftId:dz(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=dv.get(r);if(t){if(dv.delete(r),"accepted"===e){let e=dk.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);dk.set(t.draftId,e)}dV()}}}(tP.current??uE,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t3=(0,a.useCallback)(async()=>{let t=eb.trim(),n=eQ.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eB.length&&!eZ.length||o||eY)return;Y?.();let a=eB.length?eB:void 0,i=eZ.length?eZ:void 0;if(r.startsWith("/")){await ut(r,q,G,t=>t6(i,()=>e(t,a,i)),eJ,!!(a||i),K)&&t5();return}t5(),t6(i,()=>e(r,a,i))},[eb,eQ,eB,eZ,eY,o,G,q,K,e,t5,Y,t6]),t7=eQ.startsWith("/")&&!/\s/.test(eQ.slice(1))?eQ.slice(1).toLowerCase():null,t9=(()=>{if(null===t7)return[];let e=[...o?[]:uf,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=uy(e,ef).toLowerCase();return t.includes(t7)||n.includes(t7)}).sort((e,t)=>{let n=ub(e,t7,ef)-ub(t,t7,ef);return 0!==n?n:uv[e.source]-uv[t.source]||ul.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:ne,groups:nt}=(ei=0,{commands:(es=ug.map(e=>{let t=t9.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!uw(e,tm)),...t.filter(e=>uw(e,tm))]:t;return{source:e,items:n.map(e=>({command:e,index:ei++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:es}),nn=1===t9.length?ef(t7?"chat.match":"chat.command"):ef(t7?"chat.matches":"chat.commands",{count:t9.length}),nr=!!eb.trim(),na=!eY&&(nr||eB.length>0||eZ.length>0),ni=(0,a.useCallback)((e,t)=>{if(!ee)return void e3(null);let n=t??e.length;e3(dQ(e.slice(0,n)))},[ee]),ns=e6?.query??null,no=a.useMemo(()=>null!==ns&&ts&&ts.cwd===ee?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let a=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:d1(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),a=-1===e?n:n.slice(e+1);a===t?r=100:a.startsWith(t)?r=80:a.includes(t)?r=50:n.includes(t)?r=30:d1(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&a.push({entry:t,score:e})}return a.sort((e,t)=>t.score-e.score||d0(e.entry.path)-d0(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),a.slice(0,n).map(e=>e.entry)}(ts.entries,ns):[],[ns,ts,ee]),nl=!!(ns&&ts?.truncated&&ts.cwd===ee);(0,a.useEffect)(()=>{if(!nl||!ee||!ns)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(ns)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tu({cwd:ee,query:ns,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nl,ns,ee]);let nc=nl&&null!==td&&td.cwd===ee&&td.query===ns,nd=nc?td.matches:no,nu=null===e6?null:`${e6.start}:${+!!e6.quoted}:${e6.query}`;(0,a.useEffect)(()=>{if(null===nu){e9(!1),tt(0);return}e9(!0),tt(0)},[nu]);let np=null!==e6,nh=d7(tS,tn,{viewportFraction:.44,cap:360}),nm=d7(tS,e2,{viewportFraction:.56,cap:460}),nf=d7(tS,e7,{viewportFraction:.48,cap:400});(0,a.useEffect)(()=>{if(!np||!ee)return;let e=tL.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||t$.current===ee||(t$.current=ee,tc(!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=>{to({cwd:ee,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>d0(e.path)-d0(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tL.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tL.current=null}).finally(()=>{t$.current=null,tc(!1)}))},[np,ee]);let ng=(0,a.useCallback)(e=>{if(!e6)return;let t=tf.current,n=t?.selectionStart??eb.length,r=eb.slice(0,e6.start),a=eb.slice(n);e6.quoted&&a.startsWith('"')&&(a=a.slice(1));let i=function(e,t,n=!1){let r=t?`${e}/`:e,a=n||r.includes(" ");if(t){let e=a?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:a?e.length-1:e.length}}let i=a?`@"${r}" `:`@${r} `;return{text:i,cursorOffset:i.length}}(e.path,e.isDir,e6.quoted),s=r+i.text+a,o=r.length+i.cursorOffset;ey(s),e3(dQ(s.slice(0,o))),requestAnimationFrame(()=>{let e=tf.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e6,eb]);(0,a.useEffect)(()=>{te>=nd.length&&tt(Math.max(0,nd.length-1))},[nd.length,te]),(0,a.useEffect)(()=>{tR.current.length=nd.length},[nd.length]),(0,a.useEffect)(()=>{e7&&tR.current[te]?.scrollIntoView({block:"nearest",inline:"nearest"})},[te,e7]),(0,a.useEffect)(()=>{ta>=D.length&&ti(Math.max(0,D.length-1))},[D.length,ta]),(0,a.useEffect)(()=>{tE.current.length=D.length},[D.length]),(0,a.useEffect)(()=>{tn&&tE.current[ta]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ta,tn]);let nx=(0,a.useCallback)(e=>{tA.current=e,ey(e),tr(!1),ti(0),e3(null),requestAnimationFrame(()=>{let t=tf.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nv=(0,a.useCallback)(e=>{let t=`/${e.name} `;tA.current=t,ey(t),e8(!1),e5(0),requestAnimationFrame(()=>{let e=tf.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nb=(0,a.useCallback)(async e=>{let t=eb.trim(),r=eQ.trim(),a=r.startsWith("/")||r.startsWith("!")?r:t,s=eY||!a&&0===eB.length&&0===eZ.length?null:{message:a,images:eB.length?eB:void 0,documents:eZ.length?eZ:void 0};if(!s)return;Y?.();let o="steer"===e?"steer":"followUp";if(a.startsWith("/")){await ut(a,q,G,e=>{if(!X)throw Error("Cannot queue this command while the session is busy.");t6(s.documents,()=>X(e,o,s.images,s.documents))},eJ,!!(s.images?.length||s.documents?.length),K)&&t5();return}t5(),"steer"===e&&n?t6(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&i&&t6(s.documents,()=>i(s.message,s.images,s.documents))},[eb,eQ,eB,eZ,eY,q,K,G,X,n,i,t5,Y,t6]),ny=(0,a.useCallback)(e=>{let t=ne.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e4-1);if("right"===e)return Math.min(t,e4+1);let n=tM.current[e4];if(!n)return"down"===e?Math.min(t,e4+1):Math.max(0,e4-1);let r=n.getBoundingClientRect(),a=r.left+r.width/2,i=r.top+r.height/2,s=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===e4)continue;let t=tM.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-i;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-a);c<o&&(s=n,o=c)}return s>=0?s:"down"===e?Math.min(t,e4+1):Math.max(0,e4-1)},[ne.length,e4]),nw=(0,a.useCallback)(e=>{let r=e.nativeEvent,a=Date.now()-tT.current<100,s=tN.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||a)){a&&e.preventDefault();return}if(tn&&!s){if("ArrowDown"===e.key){e.preventDefault(),ti(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),ti(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tr(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[ta]){e.preventDefault(),nx(D[ta]);return}}if(e2&&null!==t7){if("ArrowDown"===e.key){e.preventDefault(),e5(ny("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e5(ny("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e5(ny("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e5(ny("left"));return}if("Escape"===e.key){e.preventDefault(),e8(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&ne[e4]){e.preventDefault(),nv(ne[e4]);return}}if(e7&&null!==e6&&!s){if("ArrowDown"===e.key){e.preventDefault(),tt(e=>Math.min(Math.max(0,nd.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tt(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e9(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nd[te]){e.preventDefault(),ng(nd[te]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===eb.trim().length){e.preventDefault(),e8(!1),e9(!1),ti(D.length-1),tr(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(n||i)?nb(n?"steer":"followup"):t3())},[o,n,i,t,e2,t7,ne,e4,nv,nb,t3,ny,e7,e6,nd,te,ng,tn,D,ta,nx,eb]),nk=(0,a.useCallback)(()=>{let e=tf.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nj=(0,a.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),t0(t))},[t0]);(0,a.useEffect)(()=>{if(null===t7){e8(!1),e5(0),tI.current=!1;return}e8(!0),e5(0),!tI.current&&K&&(tI.current=!0,Promise.resolve(K()).catch(()=>{tI.current=!1}))},[t7,K]),(0,a.useEffect)(()=>{if(!e2||!ee)return;let e=!1;return th({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;th({cwd:ee,values:n})}).catch(()=>{e||th({cwd:ee,values:{}})}),()=>{e=!0}},[e2,ee]),(0,a.useEffect)(()=>{e4>=ne.length&&e5(Math.max(0,ne.length-1))},[ne.length,e4]),(0,a.useEffect)(()=>{tM.current.length=ne.length},[ne.length]),(0,a.useEffect)(()=>{e2&&tM.current[e4]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e4,e2]);let nS=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(uu):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(uu),nC=g??null,nN=rm.find(e=>e.alias===nC)?.provider??null,nT=nN?nS.filter(e=>e.provider===nN):nS,nI=(eo=eC.trim().toLocaleLowerCase())?nT.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(eo)):nT,nM=nT.length>8,nR=[];for(let e of nI){let t=nR.find(t=>t.provider===e.provider);t?t.options.push(e):nR.push({provider:e.provider,options:[e]})}let nE=nN?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nL=l?nE.find(e=>e.resolved?.provider===l.provider&&e.resolved?.modelId===l.modelId):void 0,n$=eC.trim()?[]:nT.map((e,t)=>{var n,r;return{option:e,order:t,count:eT[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nP=(e,t,n)=>{let a=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ek(!1),eN(""),!a||c){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(d5(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(d4,JSON.stringify(r))}catch{}eI(r),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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:ef("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nA=l?nS.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,nF=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,n_=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:ef("chat.compacted")} ${nB(S.tokensBefore)} -> ${nB(S.estimatedTokensAfter)} tokens (${ef("chat.tokensSaved",{saved:nB(nF)})})`:null,nz=e=>{let t=P?.[e];return null!=t&&t!==e?t:null},nW="auto"===(el=T??"auto")?E?`auto ≤ ${nz(E)??E}`:"auto":P?P[el]??el:el,nD=(T??"auto")==="auto"&&I&&"auto"!==I?P?.[I]??I:null,nH=L&&nD?ef("chat.currentReasoning",{level:nD}):null,nU=e=>!$||$.includes(e),nq=[{level:"auto",ceiling:null},...uh.filter(nU).map(e=>({level:"auto",ceiling:e})),...up.filter(e=>"auto"!==e&&nU(e)).map(e=>({level:e,ceiling:null}))],nV=Object.entries(ua).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,a.useEffect)(()=>{let e=e=>{tg.current&&!tg.current.contains(e.target)&&tx.current&&!tx.current.contains(e.target)&&(ek(!1),eN("")),tv.current&&!tv.current.contains(e.target)&&tb.current&&!tb.current.contains(e.target)&&e$(!1),ty.current&&!ty.current.contains(e.target)&&e_(!1),tw.current&&!tw.current.contains(e.target)&&eW(!1),tk.current&&!tk.current.contains(e.target)&&eU(!1),!tj.current||tj.current.contains(e.target)||tf.current?.contains(e.target)||tr(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,a.useEffect)(()=>{ev||eU(!1)},[ev]);let nK=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eB.length||eV.length?" is-active":""}`,onClick:()=>tC.current?.click(),title:ef("chat.attachFile"),"aria-label":ef("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:eB.length||eV.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=eB.length||eV.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eB.length||eV.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),nG=f&&rm.length>0?(0,r.jsxs)("div",{ref:tv,style:{position:"relative",flexShrink:+!!ev,minWidth:0},children:[(0,r.jsxs)("button",{className:`${ev?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eA({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ek(!1),eN(""),e$(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),e$(!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:ef("chat.mainPreset"),"aria-label":ef("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),ev?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ef("chat.mainPreset")})]}),eL&&eP&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=d6(eP.top,eP.bottom,e,d3(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eP.top+6}:{top:eP.bottom+6},i=ev?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eP.left,width:"max-content",minWidth:eP.width};return(0,r.jsx)("div",{ref:tb,role:"menu","aria-label":ef("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(e$(!1),tv.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:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:rm.map(e=>{let t=e.alias===nC;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{e$(!1),f({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:rB(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:rP(e.alias)}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,nJ=L?(0,r.jsxs)("div",{ref:tw,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${ev?"composer-icon-button":"composer-chip"}${ez?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eD({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ek(!1),eN(""),e$(!1),eW(e=>!e)},disabled:o||b,"aria-haspopup":"menu","aria-expanded":ez,onKeyDown:e=>{"Escape"===e.key&&ez&&(e.stopPropagation(),eW(!1))},title:ef("chat.changeReasoning",{level:nW}),"aria-label":ef("chat.changeReasoning",{level:nW}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ev?0:"8px 12px",height:32,background:ez?"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=ez?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),ev?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nW})]}),ez&&eO&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=d6(eO.top,eO.bottom,e,d3(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-eO.top+6}:{top:eO.bottom+6},i=ev?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eO.left,width:"max-content",minWidth:Math.max(180,eO.width)};return(0,r.jsx)("div",{role:"menu","aria-label":ef("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eW(!1),tw.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:n},children:nq.map(({level:e,ceiling:t})=>{let n=(T??"auto")===e&&("auto"!==e||(E??null)===t),a=t??e,i="auto"===e&&null===t?null:nz(a),s=t?`auto ≤ ${i??t}`:i??e,o=t?ef("chat.thinkingAutoCapped",{level:i??t}):ef(um[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eW(!1),L(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==i&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",a,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,nZ=_?(ec=F?ef("chat.fastModeBusy"):null===A?ef("chat.fastModeUnknown"):A.active?ef("chat.fastModeActive"):A.enabled?ef("chat.fastModeInactive"):ef("chat.fastModeOff"),ed=F||o||b,eu=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:_,disabled:ed,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":F||void 0,title:ec,"aria-label":ec,style:{flexShrink:0,opacity:o?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:eu?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:eu&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,nY=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nb("steer"),disabled:!na,title:eY?ef("chat.attachExtractingWait"):ef("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:na?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:na?"var(--warning)":"var(--text-dim)",cursor:na?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),ef("chat.steer")]}),i&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nb("followup"),disabled:!na,title:eY?ef("chat.attachExtractingWait"):ef("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:na?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:na?"var(--accent-hover)":"var(--text-dim)",cursor:na?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),ef("chat.followUp")]})]}),nX=void 0!==Z?(0,r.jsx)(c9,{soundEnabled:J??!0,onToggle:Z}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tC,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t0(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(uF,{error:p}),(0,r.jsx)(u_,{warnings:h}),O.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:eg("delivery.title",{count:O.length})}),H&&ex&&(0,r.jsxs)("button",{onClick:H,title:ef("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),ef("chat.recall")]})]}),(0,r.jsx)(c6,{rows:O,removeLabel:ef("chat.queueRemove"),onRemove:U?(e,t)=>U("steer"===e?"steering":"followUp",t):void 0})]}),W&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),ef("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),n_&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),n_]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eG&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eG}),(0,r.jsx)("button",{type:"button",onClick:()=>eJ(null),"aria-label":ef("i18n.close"),title:ef("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eB.length>0||eV.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":ef("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eB.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":ef("chat.removeImage",{index:t+1}),onClick:()=>t1(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eV.map(e=>(0,r.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,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):aI(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?ef("chat.attachKindAudio"):"file"===e.stored?ef("chat.attachKindFile"):ud[e.mimeType]," \xb7 ",lh(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${ef("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${ef("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${ef("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"||e.transcription?.state==="fallback"?` \xb7 ${ef("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${ef("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${ef("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t2(e.id),"aria-label":ef("chat.removeAttachment",{name:e.name}),title:ef("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eX.length>0&&(0,r.jsx)("div",{role:"group","aria-label":ef("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eX.map(e=>{let t,n,a,i,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?ef("chat.transcribePlanSummary",{duration:null===c.durationSeconds?ef("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),a=Math.floor(t%3600/60),i=String(t%60).padStart(2,"0"),n>0?`${n}:${String(a).padStart(2,"0")}:${i}`:`${a}:${i}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?ef("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="fallback"?ef("chat.transcribeFallbackTitle",{name:e.name}):l?.state==="running"?ef("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${ef("chat.transcribeChecking")}`:l?.state==="failed"?ef("chat.transcribeFailedRow",{name:e.name,error:l.error}):ef("chat.transcribeSkipped",{name:e.name});return(0,r.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[l.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:ef("chat.transcribeUsageNotice")})]}),l?.state==="fallback"&&(0,r.jsxs)(r.Fragment,{children:[l.reason&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.reason}),l.completedParts>0&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:ef("chat.transcribeFallbackProgress",{done:l.completedParts,total:l.parts})}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:ef("chat.transcribeFallbackUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tJ(o,{confirmed:!0}),children:ef("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tX(o),children:ef("chat.transcribeSkip")})]}),l?.state==="fallback"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tJ(o,{fallbackToken:l.token,approve:!0}),children:ef("chat.transcribeFallbackStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tX(o),children:ef("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tX(o),children:ef("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tY(o),children:ef(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tS,style:{position:"relative",minWidth:0},children:[tn&&D.length>0&&(0,r.jsxs)("div",{ref:tj,style:{position:"absolute",left:0,right:0,...uo(nh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nh.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nh.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===ta;return(0,r.jsxs)("button",{ref:e=>{tE.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nx(e)},onMouseEnter:()=>ti(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),e2&&null!==t7&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uo(nm.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nm.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:V?ef("chat.loadingCommands"):ef("chat.slashCommands",{label:nn})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ef("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nm.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==t9.length?nt.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:ef(ux[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===e4,a=uw(e,tm);return(0,r.jsxs)("button",{ref:e=>{tM.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nv(e)},onMouseEnter:()=>e5(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:a?"var(--text-dim)":void 0},children:["/",e.name,a&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:ef("chat.dormant")})]}),uy(e,ef)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uy(e,ef)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ef("chat.noCommands")})})]}),e7&&null!==e6&&(ep=tl&&(!ts||ts.cwd!==ee),eh=1===nd.length?ef("chat.match"):ef("chat.matches",{count:nd.length}),em=ts?.truncated&&!nc?e6.query?ef("chat.searchingAll"):ef("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uo(nf.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nf.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ep?ef("chat.loadingFiles"):ef("chat.files",{label:eh,hint:em})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ef("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nf.maxHeight-34),overflowY:"auto",padding:4},children:ep||0!==nd.length?nd.map((e,t)=>{let n=t===te,a=e.path.split("/").pop()??e.path,i=e.path.slice(0,e.path.length-a.length);return(0,r.jsxs)("button",{ref:e=>{tR.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ng(e)},onMouseEnter:()=>tt(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(aC,{size:14}):aI(a,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[i&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:i}),a,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:nl&&!nc?ef("chat.searching"):ef("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${e0?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${e0?"var(--tool-bg)":o&&(n||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,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tf,value:eb,onChange:e=>{tA.current=e.target.value,ey(e.target.value),tr(!1),ni(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;ni(t.value,t.selectionStart)},onKeyDown:nw,onCompositionStart:()=>{tN.current=!0},onCompositionEnd:e=>{tN.current=!1,tT.current=Date.now();let t=e.currentTarget;ni(t.value,t.selectionStart)},onInput:nk,onPaste:nj,placeholder:o&&(n||i)?ef("chat.steerPlaceholder"):o?ef("chat.agentPlaceholder"):ef("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?ev?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nY}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t3,disabled:!na,"aria-busy":eY||void 0,"aria-label":ev?ef("chat.send"):void 0,title:eY?ef("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ev?44:void 0,padding:ev?0:"7px 14px",background:na?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:na?"var(--accent-hover)":"var(--text-dim)",cursor:na?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),ev?null:ef("chat.send")]})]})]}),e0&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e1?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ef("chat.shell")," \xb7 ",e1?ef("chat.outputLocal"):ef("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ev?"1 1 0%":"0 0 auto",minWidth:ev?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!ev||!o)&&nK,!ev&&nG,!(ev&&o)&&(nS.length>0||nA||p)&&m&&(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flex:ev?"1 1 0%":void 0,width:ev?0:void 0,minWidth:44*!!ev},children:[(0,r.jsxs)("button",{className:`composer-chip${ew?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eS({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ek(e=>(e&&eN(""),!e))},disabled:o||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:ev?"flex-start":void 0,padding:ev?"8px 10px":"8px 12px",height:32,width:ev?"100%":void 0,maxWidth:ev?"100%":220,overflow:"hidden",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)"},title:b?"Switching model":nS.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nA??(nS.length>0?"Select model":"No models")})]}),ew&&ej&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=d6(ej.top,ej.bottom,e,d3(e,.6,460),{gap:6,prefer:"above"}),a="above"===t?{bottom:e-ej.top+6}:{top:ej.bottom+6},i=ev?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ej.left,width:"max-content",minWidth:ej.width};return(0,r.jsxs)("div",{ref:tx,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:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:eC,onChange:e=>eN(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eN(""),ek(!1))},placeholder:ef("chat.filterModels"),"aria-label":ef("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!ev,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[n$.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:ef("chat.frequentModels")}),n$.map(({option:e,count:t})=>nP(e,"frequent",t))]}),nE.length>0&&!eC.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:n$.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eM,"aria-controls":"model-role-rows",onClick:eE,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eM?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:ef("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nE.length}),nL&&(0,r.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:nL.tag??nL.role.toUpperCase()}),nL.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eM,children:nE.map(e=>{let t=nL?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ek(!1),eN(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:ef("chat.allModels")})]}),0===nR.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eC.trim()?ef("chat.noMatchingModels"):"No available models"}):nR.map((e,t)=>(0,r.jsxs)("div",{children:[nR.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nP(e,"all"))]},e.provider))]})]})})()]}),ev&&o&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nY}),!ev&&nJ,!ev&&nZ,!ev&&nH&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nH}),!ev&&null!==M&&(0,r.jsx)("span",{title:ef(R?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:ef(R?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,r.jsx)(du,{sessionId:et})]}),(0,r.jsxs)("div",{ref:tk,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:ev?4:2},children:[ev?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eH?" is-active":""}`,title:ef("chat.moreControls"),"aria-label":ef("chat.moreControls"),"aria-expanded":eH,onClick:()=>{ek(!1),eN(""),eU(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eH?void 0:ef("chat.moreControls"),"aria-label":ef("chat.moreControls"),"aria-expanded":eH,onClick:()=>{ek(!1),eN(""),eU(e=>!e)},children:ef("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":ef("chat.moreControls"),style:{display:eH?"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:ev?"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:[ev&&(0,r.jsxs)(r.Fragment,{children:[o&&nK,nG,nJ,nZ]}),!o&&N&&(0,r.jsxs)("div",{ref:ty,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eF?" is-active":""}`,onClick:()=>!o&&e_(e=>!e),disabled:o,title:ef("chat.changeToolPreset")+`: ${nV}`,"aria-label":ef("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eF?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eF?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nV})]}),eF&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:ur.map(e=>{let t=ua[e],n=(C??"default")===t,a="off"===e?ef("chat.noTools"):"default"===e?ef("chat.builtInTools",{tools:ui}):ef("chat.allBuiltInTools",{tools:`${ui} + ${us}`});return(0,r.jsxs)("button",{onClick:()=>{e_(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:a})]},e)})})]}),!o&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?ef("chat.stopCompaction"):ef("chat.compactContext"),"aria-label":k?ef("chat.stopCompaction"):ef("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ef("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ef("chat.compact")})]})})}),ev&&nX,eH&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:ef("chat.collapseControls"),"aria-label":ef("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{e_(!1),eW(!1),eU(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:ef("chat.stopAgent"),"aria-label":ev?ef("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ev?44:void 0,padding:ev?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),ev?null:ef("chat.stop")]}),(0,r.jsx)(dc,{sessionId:et,onEnsureSession:en,onTranscriptPersisted:er}),!ev&&nX]})]})]})]})});function uW({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),n=e$(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ez(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function uO({phases:e,flow:t,busy:n}){let{t:i}=(0,z.s)(),{st:s}=ax(),[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}=tP(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,s);if(0===b&&null===j)return null;let S=b>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:j}),b>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!j&&f&&(0,r.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:S?i("todo.allDone",{count:v}):g?.content??""}),(0,r.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,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,r.jsx)(ow,{flow:t,live:n,st:s,id:h}),o&&b>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(ak,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:i(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function uD(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uH(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 uU(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}class uB extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function uq(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new uB(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let uV="ompweb-update-client-id",uK="ompweb-update-resume-intent-v2",uG="ompweb-update-return-v1",uJ="cuelo-restart-return-v1",uZ="ompweb-update-failure-return-v1",uY="ompweb:update-wake";function uX(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function uQ(){let e=sessionStorage.getItem(uV);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(uV,t),t}function u0(){sessionStorage.removeItem(uK)}function u1(){let e=sessionStorage.getItem(uG);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 u2(e){let t=u1();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(uG,JSON.stringify(n))}catch{}return n}async function u8(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:uQ(),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 u4(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let n=await t.json().catch(()=>null);!function(e){let t=u1();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(uG,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u0();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(uY,{detail:{sessionId:e.sessionId}}))}async function u5(e){let t=function(e){let t=sessionStorage.getItem(uZ);if(!t)return null;sessionStorage.removeItem(uZ);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(u0(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(uY,{detail:{sessionId:e.sessionId}})),"failed"):(await u4(e),"resumed")}function u6(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function u3(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 u7(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function u9(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function pe(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function pt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],a=t[n];if(!r||!a||r.name!==a.name||r.tasks.length!==a.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=a.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker||(t.dependsOn?.length??0)!==(n.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==n.dependsOn?.[t]))return!1}}return!0}function pn(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function pr(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!ta(r??void 0))return{message:e[n],entryId:r}}return null}let pa=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class pi 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 ps(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function po(e){return new Promise(t=>setTimeout(t,e))}function pl(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function pc(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:pl(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:pl(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=pl(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function pd(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 pu(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(pd).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function pp(e){return"user"===e.role?`user:${pu(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 ph(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 pm(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function pf(e){nT(e),e.clear()}function pg(e,t,n){for(let r of n??[]){let n=nN(t,r);n&&e.add(n)}}function px(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let pv=!1,pb={width:0,height:0},py=new Set,pw=null;function pk(){let e=window.visualViewport,t=px();pb.width!==window.innerWidth?pb={width:window.innerWidth,height:window.innerHeight}:t||(pb.height=Math.max(pb.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:a}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||a-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:pb.height});if(n!==pv)for(let e of(pv=n,py))e()}function pj(e){if(py.add(e),!pw){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,pk()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),pk(),pw=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{py.delete(e),0===py.size&&pw&&(pw(),pw=null)}}function pS(){return(0,a.useSyncExternalStore)(pj,()=>pv,()=>!1)}let pC={count:50,end:null};function pN(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),a=Math.min(Math.max(t.count,0),r),i=r-a;return{startIndex:i,endIndex:r,hasMore:i>0,hasLater:r<n}}function pT(e,t,n){let{startIndex:r,endIndex:a}=pN(e,n);if(t>=r&&t<a)return n;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 pI({sticker:e,text:t,tag:n,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,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:n4[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(cf(),{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 pM(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=(lp(t)?.message??t).trim();return n.length>0?n:null}function pR(e){return`omp-cues:${e}`}function pE(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(pR(e),JSON.stringify(n.slice(-200)))}catch{}}let pL=[];function p$(e){return`omp-web:interrupted-dismissed:${e}`}let pP=(0,a.memo)(function({messages:e,entryIds:t,toolResultsMap:n,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:n,modelNames:i,cwd:s,sessionId:f})},[T,x,e,t,n,i,s,f]);let R=(0,a.useMemo)(()=>(function(e){let t=new Map;for(let n=0;n<e.length;n++){let r=tn(e,n);r>=0&&t.set(r,function(e){let t="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");if(!t.startsWith("[interpreter] "))return t;let n=t.indexOf("\n\n");return n<0?t:t.slice(n+2)}(e[n]))}return t})(e),[e]),E=(0,a.useMemo)(()=>{let t=new Map;for(let[r,a]of function(e,t,n,r){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=n[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,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let a=r.input??{};if("manage_skill"===r.toolName){let e=tl(a.action);if(!0===to[e]){let t={kind:"skill",action:e,name:tl(a.name)};n(JSON.stringify(t),t)}continue}let i=tl(a.memory),s=a.skill,o=s?{action:tl(s.action),name:tl(s.name)}:void 0;n(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??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=i.get(s);n?n.push(t):i.set(s,[t])})}}return i}(g,x,e,n)){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(r,{role:"custom",customType:te,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,N]),L=(0,a.useMemo)(()=>{let r=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(r=t.idx);return function(e,t,n,r,a,i,s=[]){let o=function(e,t,n){let r=new Map,a=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&sH(t,e.idx)===e.idx).map(e=>e.idx),i=null===n?null:sH(t,n),s=new Map;for(let[n,o]of(e.forEach((e,n)=>{"answer"===e.kind&&s.set(sH(t,e.anchorIdx),n)}),s)){if(n===i)continue;let e=a.find(e=>e>n);r.set(o,{from:n+1,to:e??t.length})}return r}(e,t,n),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,n]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(sB(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&i){let a=n.to-1;for(;a>=n.from&&ta(s[a]);)a-=1;if(s[a]!==i.throughEntryId)continue;let o=sO(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=sU(t,r,n.from,n.to);c.set(e,{...i.summary,...p?{remaining:sz(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...i.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,a,i=[]){let s=sO(e,n,r),o=sU(e,t,n,r);return{...sW(s,t,a),remaining:o?sz(o):null,span:sq(e,n,r),flow:sF(s,t,!1,i,a,sD(e,n,r))}}(t,r,n.from,n.to,a,d),latest:e===l})}return c}(g,e,r,n,s,y,t)},[g,e,n,s,l,y,t]),$=w>0,P=k<g.length,A=(a,g={})=>{let x=g.messageOverride??e[a],v=a-1;for(;v>=0&&ta(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 n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&a===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(lP,{message:x,toolResults:n,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?R.get(a):void 0},`${y}-view-${a}`)},F=(t,n)=>{let a=g[t],i="message"===a.kind&&e[a.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":i?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[$&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((i,l)=>{let c=w+l,d=b?.position===c?(0,r.jsx)(oz,{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(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=i.idx&&r<m}).map(e=>(0,r.jsx)(pI,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),y=h!==u,k=E.get(c),j=k?(0,r.jsx)(lP,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=y?(0,r.jsx)(ck,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:o}):null;if("message"===i.kind)return(0,r.jsxs)(a.Fragment,{children:[d,F(c,A(i.idx)),j,S,x]},`message-${i.idx}`);let C=tT(i.precedingBlocks,n,s);return(0,r.jsxs)(a.Fragment,{children:[d,F(c,A(i.idx,{keyPrefix:`answer-${i.runIndex}`,messageOverride:function(e,t){let n=eV(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[i.idx],i.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:L.get(c)})),j,S,x]},`answer-${i.idx}-${i.runIndex}`)}),b?.position===g.length&&k===g.length&&(0,r.jsx)(oz,{calls:b.calls}),P&&(0,r.jsx)("div",{ref:S,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadLater",{count:g.length-k})})]})});function pA({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:R,onAttentionChange:E,soundEnabled:L=!0,onSoundToggle:$,playCueSound:P=async()=>({sticker:null,text:null}),preloadCueSound:A,unlockAudio:F,jumpRequest:_=null,onJumpHandled:W}){var O,D;let H,U,V,{t:K}=(0,z.s)(),G=pS(),J=B(),Z=(0,a.useRef)(P);Z.current=P;let Y=(0,a.useRef)(null),X=(0,a.useRef)(A);X.current=A;let[Q,et]=(0,a.useState)([]),en=(0,a.useRef)(Q);en.current=Q;let er=(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,n,r)=>{if(!e.sticker&&!e.text)return;er.current=Math.max(er.current+1,Date.now());let a={id:er.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},i="entry"===r.kind?{...a,anchorEntryId:r.entryId}:{...a,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};et(e=>{let t=[...e,i];return null!==i.anchorEntryId&&pE(n.sessionId,t),t})},[]),eh=(0,a.useCallback)((e,t,n,r)=>{let a=()=>eu(n)&&("working"!==t||ec.current!==n.turn);a()&&Z.current(e,t,a).then(e=>{null!==t&&null!==r&&a()&&ep(e,t,n,r)}).catch(()=>{})},[eu,ep]),em=(0,a.useCallback)(async(e,t,n,r)=>{let a=(await ah(e,t,n,r))?.alias??null;return a&&X.current?.(a),a},[]),ef=(0,a.useCallback)((e,t,n,r,a)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let a=rs(e[n]),i=0;for(let t=r;t<=n;t++)rs(e[t])===a&&(i+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:a,occurrence:i}}}(ea.current,ei.current);em(t.sessionId,n,r,a).then(n=>{eh(n,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!==n7(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 n=n7(e.outcome),r="neutral"===n?null:n;t?ef(r,t,e.provider,e.credentialId,e.model):Z.current(null,r).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:eR,modelError:eE,modelScopeWarnings:eL,modelThinkingLevels:eP,modelThinkingLevelMaps:eA,modelRoles:eF,toolPreset:e_,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eO,fastMode:eD,fastModeBusy:eH,handleFastModeToggle:eU,retryInfo:eB,contextUsage:eq,forkingEntryId:eK,isCompacting:eY,compaction:eX,compactError:e1,compactResult:e2,displayModel:e4,modelSwitching:e5,sessionStats:te,runStateKnown:to,compactedWork:tl,slashCommands:td,slashCommandsLoading:tu,deliveryRows:tp,subagents:th,todoPhases:tm,notices:tf,extensionDialog:tg,extensionResponse:tx,extensionCustomUi:tv,extensionStatuses:tb,extensionWidgets:ty,respondToExtensionUi:tw,sendExtensionCustomInput:tk,isAutoModelSelection:tj,agentPhase:tS,isNew:tC,autoFollowPaused:tN,resumeAutoFollow:tT,pauseAutoFollow:tI,goalStatus:tM,sessionIdRef:tR,messagesEndRef:tE,scrollContainerRef:t$,handleSend:tP,handleAbort:tA,handleFork:tF,handleNavigate:tz,handleModelChange:tW,handleRoleModelChange:tO,handleMainPresetChange:tD,newSessionAccount:tH,handleCompact:tU,handleSteer:tB,handleFollowUp:tq,handlePromptWithStreamingBehavior:tV,handleAbortCompaction:tK,handleRecallQueue:tG,handleRemoveQueuedMessage:tJ,handleBuiltinSlashCommand:tZ,handleToolPresetChange:tY,handleThinkingLevelChange:tX,loadSlashCommands:tQ,ensureNewSession:t0,refreshLiveTranscript:t1}=function(e){let{session:t,newSessionCwd:r,initialData:i,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,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),[R,E]=(0,a.useReducer)(u3,{isStreaming:!1,streamingMessage:null}),[L,$]=(0,a.useState)(!1),[P,A]=(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),[en,er]=(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,eR]=(0,a.useState)(null),[eE,eL]=(0,a.useState)(!1),[eP,eA]=(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)(pc,{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),[e7,te]=(0,a.useState)([]),[tt,tn]=(0,a.useState)([]),[ts,to]=(0,a.useState)({steering:[],followUp:[]}),[tl,tc]=(0,a.useState)([]),[td,tu]=(0,a.useReducer)(ii,[]),tp=(0,a.useRef)(0);(0,a.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,a.useEffect)(()=>{L||tu({type:"idle"})},[L]),(0,a.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,a.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${ir(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],a=(e,t)=>{t.forEach((t,a)=>{let i=`${e}\u0000${it(t)}`,s=n.get(i)??0;s>0?n.set(i,s-1):r.push({key:`queue-${e}-${a}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(a("steer",t?.steering??[]),a("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(td,ts),[td,ts]),[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)(()=>()=>pf(tM.current),[]);let tR=(0,a.useRef)(!1),tE=(0,a.useRef)(!1),tL=(0,a.useRef)(-1),t$=(0,a.useRef)("unknown"),tP=(0,a.useRef)(null),tA=(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),ne=(0,a.useRef)(null),nt=(0,a.useRef)(!1);nt.current=e.transitioning??!1;let nn=(0,a.useRef)(Date.now()),nr=(0,a.useRef)(0),na=(0,a.useRef)(0),ni=(0,a.useRef)(null),ns=(0,a.useRef)(!1),no=(0,a.useRef)(Promise.resolve()),nl=e.setToolPreset??ei,nc=eT??g?.context.model??eM??null,nd=m?X??en:nc,nu=(0,a.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,a=0,i=0,s=0;for(let t of S){if("user"===t.role&&(r+=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,n+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:a,toolCalls:s,toolResults:i,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),np=(0,a.useRef)(0),nh=(0,a.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(np.current+=1,tf(n=>n?.sid===e&&pt(n.phases,t)?n:{sid:e,phases:t}))},[]),nm=(0,a.useCallback)((e,t,n)=>{tj.current===e&&np.current===n&&Array.isArray(t)&&tf(n=>n?.sid===e&&pt(n.phases,t)?n:{sid:e,phases:t})},[]),nf=(0,a.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),ng=(0,a.useCallback)(e=>{tN.current=e,T(e)},[]),nx=(0,a.useCallback)(async(e,t=!1,n=!1,r)=>{let a=!1;try{t&&b(!0);let i=r??null;if(!i){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nf([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);i=await r.json()}if(tj.current!==e)return null;x(i),j(i.leafId),tS.current=i.leafId??null;let s=ti(i.context.messages,i.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);nf(s.messages),ng(s.entryIds),M(i.context.compactedWork??null),ek(i.contextUsage??null),eI(e=>ns.current?e:null),w(null);let o=!n&&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),!n){if(o)try{let t=t7.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t7.current===t&&(r.state?.thinkingLevel!==void 0?(eo(r.state.configuredThinkingLevel??r.state.thinkingLevel),ec(r.state.thinkingLevel)):r.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=np.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let a=r.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&&tn(a.extensionWidgets??[]),void 0!==a.queuedMessages&&to(u7(a.queuedMessages)),void 0!==a.subagents&&tc(e=>u6(e,a.subagents??[])),nm(e,a.todoPhases,t)):r.running||to({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!a&&b(!1)}},[nm,ng,nf]),nv=(0,a.useCallback)(e=>{let t=no.current.then(async()=>{tj.current===e&&await nx(e)});return no.current=t.catch(()=>{}),t},[nx]),nb=(0,a.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let a=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,i=await fetch(a);if(!i.ok)throw Error(`HTTP ${i.status}`);let s=await i.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let o=ti(s.context.messages,s.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);nf(o.messages),ng(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[ng,nf]),ny=(0,a.useCallback)(async e=>{try{let t=await uq(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));nl(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[nl]),nw=(0,a.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;m&&r&&n&&!t8.current&&(t8.current=!0,l?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,l]),nj=(0,a.useCallback)(async()=>{if(t1.current)return t1.current;let e=tj.current;if(e&&ne.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t4.current,n=t6.current,a=t5.current;e&&eR(e);let i={cwd:r,type:"ensure_session",toolNames:(0,d9.xG)(ea),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==a?{oauthPosition:a}:{}},s=JSON.stringify(i),o=t2.current,l=o?.body===s?o.createRequestId:ps();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&&(ne.current=t),d.model&&t4.current===e&&(eR(d.model),e||er(d.model)),d.thinkingLevel&&t6.current===n&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;ne.current===t;){let e=t9.current;await uq(t,{type:"set_thinking_ceiling",ceiling:e}),t9.current===e&&ne.current===t&&(ne.current=null)}return t})();t1.current=t;try{return await t}finally{t1.current=null}},[m,r,ea]),nC=(0,a.useCallback)(async()=>{let e=tj.current??await nj();if(!e)return eG([]),[];eZ(!0);try{let t=await uq(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[nj]),nI=(0,a.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),nM=(0,a.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nR=(0,a.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),nE=(0,a.useCallback)(e=>{nR();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tW.current?.(n):"agent_start"===n.type&&tO.current?.(e)}catch{}}},[nR]),nL=(0,a.useCallback)(e=>{nM();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,a=e=>{r||(r=!0,clearTimeout(i),tv.current?.source===t&&(tv.current.pending=!1),n({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)&&nL(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nM]),n$=(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 n=await nL(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new pi(n.status)},[nL]),nP=(0,a.useCallback)(async(e,t)=>{let n=e5.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,a=e=>{e5.current=e,e4(e)};if(!r)return void a({id:e.id,status:"failed",error:"no session"});a({id:e.id,status:"sending"});try{await uq(r,{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)},[]),nA=(0,a.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await uq(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nF=(0,a.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??ps(),message:t,type:e.type??"info"}})},[]),n_=(0,a.useCallback)(e=>{let t={role:"custom",customType:e9,content:e$(e).trim(),display:!0,timestamp:Date.now()},n=tT.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let a=tN.current.slice(0,tC.current.length),i=null;for(let e=a.length-1;e>=0;e--)if(!ta(a[e])){i=a[e];break}n.seq+=1,n.outputs.push({entryId:`${tr}${n.seq}`,baseEntryId:i,message:t});let s=ti(tC.current,tN.current,n.outputs);nf(s.messages),ng(s.entryIds)},[nf,ng]),nz=(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(uH(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":nF({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":te(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":tn(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e3(e=>t.closed?e?.id===t.id?null:e:t)}},[nF,o,e.chatInputRef]),nW=(0,a.useCallback)(()=>{let e=tI.current;return tI.current=!1,$(!1),eV(null),pf(tM.current),ey(null),E({type:"end"}),e},[]),nO=(0,a.useCallback)(()=>{t$.current="unknown",tP.current=null;let e=pr(tC.current,tN.current);tA.current=e?{entryId:e.entryId,key:pp(e.message)}:null,tF.current+=1},[]),nD=(0,a.useCallback)(()=>{let e=t$.current,t=tP.current;if("unknown"===e){let n=pr(tC.current,tN.current),r=n?.message,a=tA.current;null!==n&&(null===a||(null!==n.entryId&&null!==a.entryId?n.entryId!==a.entryId:pp(n.message)!==a.key))&&r?.role==="assistant"&&r.stopReason&&(e=pn(r),t??={provider:r.provider,...r.model?{model:r.model}:{},...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nH=(0,a.useCallback)(e=>{let t=nD();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tF.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tF.current===n;s?.(e?nD():t)})},[s,nD]),nU=(0,a.useCallback)((e,t)=>tL.current!==e&&(tL.current=e,nH(t),!0),[nH]),nB=(0,a.useCallback)(e=>{nI(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=np.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=>u6(e,s?.subagents??[])),nm(e,s?.todoPhases,r),i.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tR.current=!!s?.isStreaming,tE.current=!!s?.isPromptRunning,tI.current=!0,$(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&s?.isCompacting){eA(!0),eD(pe(s)),ty.current=setTimeout(()=>void n(),600);return}if(i.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,ty.current=null,nM()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void n(),600)}};ty.current=setTimeout(()=>void n(),3e4)},[nm,nI,nM]),nq=(0,a.useCallback)(async(e=tj.current,t=nr.current)=>{if(nr.current===t)try{e&&await nx(e)}finally{if(nr.current!==t)return;let n=tE.current,r=tR.current;tE.current=!1,tR.current=!1,ni.current=null;let a=nW();n?nU(t):r&&a&&nH(),e&&nB(e)}},[nx,nH,nU,nB,nW]),nV=(0,a.useCallback)(async(e,t)=>{await po(800);let n=Date.now();for(;tI.current&&Date.now()-n<2e4;){if(void 0!==t&&nr.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),a=r.state;if(!r.running||!a||!a.isStreaming&&!a.isPromptRunning)return void await nq(e,t)}}catch{}await po(600)}},[nq]),nK=(0,a.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;t_.current&&tz.current===t&&tj.current===e;){await po(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nx(e),tz.current!==t||tj.current!==e)return;t_.current=!1,A(!1),_(null);return}catch{}}},[nx]),nG=(0,a.useCallback)(async e=>{if(!tI.current)return;let t=nr.current;try{let n=np.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let a=await r.json();if(nr.current!==t)return;let i=a.state;if(eA(i?.isCompacting??!1),eD(pe(i)),to(u7(i?.queuedMessages)),i?.contextUsage!==void 0&&ek(i.contextUsage??null),tc(e=>u6(e,i?.subagents??[])),nm(e,i?.todoPhases,n),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&&tn(i.extensionWidgets??[])),await nq(e,t)}catch{}},[nm,nq]),nJ=(0,a.useCallback)(async e=>{let t=await nx(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tI.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tR.current=!!n.isStreaming,tE.current=!!n.isPromptRunning,tI.current=!0,$(!0),eV(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),pg(tM.current,e,n.pendingToolCalls),nL(e),!n.isStreaming&&n.isPromptRunning&&nV(e),!0)},[nL,nx,nV]),nZ=(0,a.useCallback)(async(e,t=nr.current)=>{let n=na.current+1;na.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let a=await r.json();if(n!==na.current||tj.current!==e||nr.current!==t)return;a.state?.contextUsage!==void 0&&ek(a.state.contextUsage??null)}catch{}},[]);(0,a.useEffect)(()=>{if(!eP){eH.current=null,eD(null);return}eD(e=>e??{startedAt:Date.now(),reason:eH.current})},[eP]),(0,a.useEffect)(()=>{if(!L&&!eP)return;let e=()=>{let e=tj.current;e&&nZ(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[L,eP,nZ]),(0,a.useEffect)(()=>{if(!L)return;let e=()=>{let e=tj.current;e&&nG(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[L,nG]),(0,a.useEffect)(()=>{if(L)return;let e=()=>{let e=tj.current;e&&!tI.current&&nJ(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tI.current&&nJ(t).then(e=>{e||tj.current!==t||tI.current||nx(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(uY,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(uY,n)}},[L,nJ,nx]),tO.current=e=>{if(tj.current!==e||tI.current||tg.current||tD.current)return;let t=nJ(e).then(async t=>{t||tj.current!==e||tI.current||await nx(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,a.useEffect)(()=>{tI.current=L},[L]),tW.current=(0,a.useCallback)(e=>{var t;switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,a){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let i=e.context.messages,s=new Map;for(let e of i){let t=pp(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(r.length,a.length);for(let e of r.slice(0,o)){let t=pp(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=pp(e),n=s.get(t)??0;return 0===n||(s.set(t,n-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 n=ti(t.messages,t.entryIds,tT.current.sessionId===tj.current?tT.current.outputs:[]);nf(n.messages),ng(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tI.current;nI(),e&&nO(),tR.current=!0,tI.current=!0,$(!0),eV({kind:"waiting_model"}),E({type:"start"});break}case"agent_end":if(!tI.current)break;if(eV(null),pf(tM.current),ey(null),E({type:"end"}),tj.current){nx(tj.current);let e=np.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&&tn(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>u6(e,t.state?.subagents??[])),tj.current&&nm(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),to(u7(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tR.current;if(tR.current=!1,!e||tE.current)break;let t=tj.current,n=nW();eA(!1);let r=t?nx(t):void 0;t&&nB(t),n&&nH(r);break}case"prompt_done":{let e=nr.current,t=tE.current;tE.current=!1,ni.current=null;let n=tL.current!==e;if(!t&&!n)break;let r=tj.current;nU(e,r?nx(r):void 0),!tR.current&&(nW(),r&&nB(r))}break;case"prompt_error":t$.current="failed",nF({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t$.current="failed",nF({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&&E({type:"update",message:s8(t)}),eV(null);break}case"message_end":{if(!tI.current)break;let t=e.message;if(t?.role==="assistant"&&(tP.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},t$.current=pn(t)),t&&"user"===t.role){let e=s8(t),n=pu(e),r=ni.current;ni.current=null,nf(t=>{let a=t[t.length-1];return r&&a?.role==="user"&&pu(a)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tu({type:"user-message",kind:io(e),text:is(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nf(e=>[...e,s8(t)]);let n=tj.current;n&&nZ(n),E({type:"reset"}),eV(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t3.current=t,t7.current+=1,eo(e.configured??n),ec(n));break}case"todo_changed":nh(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,a=nN(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:n,args:r}),{kind:"running_tools",tools:a}});break}case"tool_execution_update":{let n=nN(tj.current,"string"==typeof e.toolCallId?e.toolCallId:null);n&&tM.current.has(n)&&"string"==typeof e.text&&(t=e.text,nk.get(n)!==t&&(nk.set(n,t),nS()));break}case"tool_execution_end":{let t=e.toolCallId,n=nN(tj.current,t);n&&tM.current.delete(n)&&nT([n]),eV(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";tc(n=>{let r=n.find(e=>e.id===t.id);return u6(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};tc(e=>u6(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};tc(e=>u6(e,[r]));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)}eA(!0),e_(null),eW(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)e_(e.errorMessage),eW(null);else if(!e.aborted){eW(ph(e.result,e.reason??"auto"));let t=tj.current;t&&(nx(t),nZ(t))}break;case"extension_ui_request":nz(e)}},[nF,nh,nm,nI,nz,nx,nH,nU,nZ,nO,nB,nW,ng,nf]);let nY=(0,a.useCallback)(async(n,a,i)=>{let s=n.trim();if(!s&&!a?.length&&!i?.length)return"returned";if(tI.current||t_.current||ns.current)return"unknown";let o=lu(n,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"}nO();let c=nr.current+1;nI(),tE.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()};nf(e=>[...e,u]),ni.current=pu(u),nr.current=c,tI.current=!0,$(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),E({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&&r){let e=tj.current??await t1.current,t=await nj();t&&(h=t,X&&(eR(X),e&&await uq(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await n$(t),f=!0,await uq(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),nw(1,n),g="accepted")}else t&&(h=t.id,await n$(t.id),f=!0,await uq(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&nV(h,c),g}catch(o){console.error("Failed to send message:",o);let r=o instanceof uB&&"update_draining"===o.code&&!1===o.accepted;if(!(!f||o instanceof uB&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return nV(h,c),"unknown";tE.current=!1,tI.current=!1,nM();let s=ni.current;return s&&nf(e=>{let t=e[e.length-1];return t?.role==="user"&&pu(t)===s?e.slice(0,-1):e}),nF({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,pm(a),i,t?.id??h??void 0),ni.current=null,$(!1),eV(null),E({type:"end"}),"returned"}},[m,r,X,t,nj,n$,nw,nV,nF,nI,nM,e.chatInputRef,nO,nf]);tG.current=(0,a.useCallback)(async(n,r)=>{if(tI.current||t_.current)return;let a=`${r?"!!":"!"}${n}`;t_.current=!0,tX.current(!0),_({command:n,excludeFromContext:r}),A(!0);try{let e=tj.current??t?.id??await nj();if(!e)throw Error("Unable to create a session for the shell command");await uq(e,{type:"bash",command:n,excludeFromContext:r}),await nx(e),nw(1,a)}catch(t){console.error("Failed to execute shell command:",t),nF({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(a)}finally{t_.current=!1,_(null),A(!1)}},[nF,nj,nx,e.chatInputRef,nw,t]);let nX=(0,a.useCallback)(async()=>{let e=tj.current;if(e){if(t_.current){try{await uq(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uq(e,{type:"abort"}),t$.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nQ=(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:n,newSessionId:r}=await uq(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eN(null)}},[c]),n0=(0,a.useCallback)(async e=>{if(t_.current)return;let t=tj.current;t&&(uq(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nb(t,e))},[nb]),n1=(0,a.useCallback)(async e=>{if(t_.current)return;j(e);let t=tj.current;t&&(await nb(t,e),e&&uq(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nb]),n2=(0,a.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t4.current?.provider===e;t4.current=n,r||(t5.current=null,et(null)),Q(n),eR(n);let a=tj.current??await t1.current;if(!a)return;try{await uq(a,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ns.current){ns.current=!0,eI({provider:e,modelId:t}),eL(!0);try{await uq(n,{type:"set_model",provider:e,modelId:t}),ns.current=!1,await nx(n)}catch(e){console.error("Failed to set model:",e),ns.current=!1,eI(eT),nF({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nx(n)}finally{ns.current=!1,eL(!1)}}},[nF,eT,m,nx,Q]),n8=(0,a.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},a=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(ns.current)return!1;ns.current=!0,eL(!0);let e=t4.current,i=t5.current,s=t6.current;try{t4.current=t,t5.current=n??null,t6.current="auto";let e=tj.current??await t1.current;return e&&await uq(e,r),Q(t),et(n??null),eR(t),eo("auto"),ec(void 0),e&&await nx(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t4.current=e,t5.current=i,t6.current=s,nF({type:"error",message:a(n)});let t=tj.current;return t&&await nx(t),!1}finally{ns.current=!1,eL(!1)}}let i=tj.current;if(!i||ns.current)return!1;ns.current=!0,eI(t),eL(!0);try{return await uq(i,r),await nx(i),!0}catch(e){return console.error("Failed to apply Main preset:",e),eI(eT),nF({type:"error",message:a(e)}),await nx(i),!1}finally{ns.current=!1,eL(!1)}},[nF,eT,el,m,nx,Q,es]),n4=(0,a.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t6.current=t??null,eo(t??"auto"),ec(void 0),t4.current=e,t5.current=null,et(null),Q(e),eR(e)}let r=tj.current??(m?await t1.current:null);if(r)try{await uq(r,{type:"set_role_model",role:e}),m||eI({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,Q]),n5=(0,a.useCallback)(async()=>{let e=tj.current;if(e&&!eP){eH.current="manual",eA(!0),e_(null),eW(null);try{let t=await uq(e,{type:"compact"});eW(ph(t,"manual")),await nx(e,!0)}catch(e){e_(e instanceof Error?e.message:String(e)),eW(null)}finally{eA(!1)}}},[eP,nx]),n6=(0,a.useCallback)(async e=>{let n=r??t?.cwd??"",a=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/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];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t6.current&&eo(t??"auto")}},[m,r,t?.cwd]),n3=(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[,n,r=""]=t,a=r.trim(),i=await nj(),s=e=>(e.handled&&(e.error?nF({type:"error",message:e.error}):"openSessionStats"!==e.action&&nF({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!i||eP)return s({handled:!0,error:"No active session to compact"});eH.current="manual",eA(!0),e_(null),eW(null);let e=await uq(i,{type:"compact",...a?{customInstructions:a}:{}});return eW(ph(e,"manual")),await nx(i,!0)&&nw(),s({handled:!0,message:"Compacted context"})}case"reload":if(!i)return s({handled:!0,error:"No active session to reload"});return await uq(i,{type:"reload"}),await Promise.all([nx(i,!1,!0),ny(i),nC(),n6()]),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 uq(i,{type:"set_session_name",name:a}),await nx(i)&&nw(),s({handled:!0,message:`Session renamed to ${a}`});case"session":{if(!i)return s({handled:!0,error:"No active session"});let e=await uq(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 uq(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 nQ();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 uq(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(n_(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nF({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,$(!0),eV({kind:"running_command"});try{await n$(i);let e=await uq(i,{type:"handoff",...a?{customInstructions:a}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nx(i,!0)&&nw(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tI.current=!1,$(!1),eV(null),tj.current===i&&nB(i)}default:{if(!i)return s({handled:!0,error:"No active session"});let t=await uq(i,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&n_(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[nF,n_,n$,nj,nQ,eP,n6,nx,nC,ny,nw,h,nB]),n7=(0,a.useCallback)(async(t,n,r)=>{let a=tj.current;if(!a)return nF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pm(n),r),"returned";let i=lu(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:i,images:s?.length??0});try{return await uq(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),nF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pm(n),r,a),"returned"}},[nF,e.chatInputRef]),n9=(0,a.useCallback)(async(t,n,r,a)=>{let i=tj.current;if(!i)return nF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pm(r),a),"returned";let s=lu(t,a??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:n,text:s,images:o?.length??0});try{return await uq(i,{type:"prompt",message:s,streamingBehavior:n,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(n){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",n),nF({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,pm(r),a,i),"returned"}},[nF,e.chatInputRef]),re=(0,a.useCallback)(async(t,n,r)=>{let a=tj.current;if(!a)return nF({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,pm(n),r),"returned";let i=lu(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:i,images:s?.length??0});try{return await uq(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),nF({type:"error",message:i instanceof Error?i.message:String(i)}),e.chatInputRef?.current?.restoreSubmission?.(t,pm(n),r,a),"returned"}},[nF,e.chatInputRef]),rt=(0,a.useCallback)(async()=>{let e=tj.current;if(e)try{await uq(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rn=(0,a.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await uq(t,{type:"clear_queue"});tu({type:"withdraw"}),to({steering:[],followUp:[]});let a={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(a.text,a.images.length?a.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nF({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nF]),rr=(0,a.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await uq(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nF({type:"error",message:"Failed to remove queued message"})}},[nF]),ra=(0,a.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ed;eo(e),eu(n),m&&(!tj.current||ne.current===tj.current)&&(t6.current=e,t9.current=n),ec(void 0);let a=tj.current??await t1.current;if(a)try{ne.current===a?await nj():r&&await uq(a,{type:"set_thinking_ceiling",ceiling:n}),await uq(a,{type:"set_thinking_level",level:e}),await nx(a)}catch(e){console.error("Failed to set thinking level:",e),nF({type:"error",message:"Failed to set thinking level"}),await nx(a)}},[m,nx,nF,ed,nj]);ev.current=nd?`${nd.provider}/${nd.modelId}`:"";let ri=e=>e?`${e}|${ev.current}`:null,rs=t?.id??tj.current,ro=ri(rs),rl=ep&&ep.key===ro?ep.value:null;(0,a.useEffect)(()=>{let e=++eg.current;ro&&rs&&!L&&!eE&&fetch(`/api/agent/${encodeURIComponent(rs)}`).then(e=>e.json()).then(t=>{eg.current===e&&ri(tj.current)===ro&&eh({key:ro,value:(t.running?u9(t.state):void 0)??null})}).catch(()=>{})},[ro,L,eE]);let rc=(0,a.useCallback)(async()=>{let e=tj.current??await nj(),t=ri(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&ri(tj.current)===t,a=e=>{r()&&eh({key:t,value:e})};ef(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=u9(await uq(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let i=await uq(e,{type:"set_fast_mode",enabled:!n});a({enabled:i?.enabled===!0,active:i?.active===!0})}catch(t){if(!r())return;nF({type:"error",message:t instanceof Error?t.message:String(t)});try{a(u9(await uq(e,{type:"get_state"}))??null)}catch{a(null)}}finally{ef(!1)}},[nj,ep,nF]),rd=(0,a.useCallback)(async e=>{let t=(0,d9.xG)(e);nl(e);let n=tj.current??await t1.current;if(n)try{await uq(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[nl]),ru=(0,a.useCallback)(e=>{tU.current=e,tq(t=>!e===t?t:!e)},[]);tX.current=e=>{tZ.current=null,ru(e)};let rp=(0,a.useCallback)((e="smooth")=>{tY.current=Date.now()+700,tQ.current?.scrollIntoView({behavior:e})},[]),rh=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,ru(!0),rp("smooth")},[rp,ru]),rm=(0,a.useCallback)(()=>{tJ.current=0,tZ.current=null,ru(!1)},[ru]),rf=(0,a.useCallback)(()=>{if(!tZ.current)return;tZ.current=null;let e=t0.current;e&&ru(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[ru]),rg=(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 rf();rm();let e=t0.current;return void(tZ.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}rf(),e instanceof KeyboardEvent&&(!pa.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[rf,rm]),rx=(0,a.useCallback)(()=>{let e=t0.current;if(!e)return;let t=tZ.current;if(null!==t){let n=t.top;t.moved||=e.scrollTop!==n,t.top=e.scrollTop;return}if(!tI.current&&!t_.current)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight,r=Date.now()<=tJ.current;if(!(!r&&Date.now()<tY.current)){if(n<=72)return void ru(!0);r&&ru(!1)}},[ru]);return(0,a.useEffect)(()=>(tj.current=t?.id??null,tT.current.sessionId!==tj.current&&(tT.current={sessionId:tj.current,outputs:[],seq:0}),t&&nx(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;nE(t.id),e?.running&&(ny(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tR.current=!!e.state.isStreaming,tE.current=!!e.state.isPromptRunning,tI.current=!0,$(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),pg(tM.current,t.id,e.state.pendingToolCalls),nL(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nV(t.id)),e.state?.isBashRunning&&(t_.current=!0,A(!0),nK(t.id)),(e.state?.subagents?.length??0)>0&&nL(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eA(n.isCompacting),eD(pe(n)),void 0!==n.contextUsage&&ek(n.contextUsage??null),void 0!==n.systemPrompt&&eS(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t3.current=t.id,eo(n.configuredThinkingLevel??n.thinkingLevel),ec(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&te(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&tn(n.extensionWidgets??[]),void 0!==n.queuedMessages&&to(u7(n.queuedMessages)),void 0!==n.subagents&&tc(e=>u6(e,n.subagents??[])),void 0!==n.goal&&tK(n.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,nI(),nM(),nR()}),[t?.id]),(0,a.useEffect)(()=>{p?.(ej)},[ej,p]),(0,a.useEffect)(()=>{u&&u(g?.tree??[],k,n1)},[g?.tree,k,n1,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))?rf():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",rg),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",rg)}},[rf,rg]),(0,a.useEffect)(()=>{let e=t0.current;if(!e)return;let t=()=>{tZ.current?.moved&&rf()};return e.addEventListener("pointerdown",rg,{passive:!0}),e.addEventListener("wheel",rg,{passive:!0}),e.addEventListener("touchstart",rg,{passive:!0}),e.addEventListener("scroll",rx,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",rg),e.removeEventListener("wheel",rg),e.removeEventListener("touchstart",rg),e.removeEventListener("scroll",rx),e.removeEventListener("scrollend",t)}},[S.length,v,rf,rx,rg]),(0,a.useEffect)(()=>{if(nt.current||!L&&!P||!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)},[L,P,S.length,R.streamingMessage,eq,F,e.transitioning]),(0,a.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,rp("instant");return}if(!nt.current&&tU.current){let e=Date.now()-nn.current<1500;rp(tI.current||t_.current||e?"instant":"smooth")}}},[S.length,L,P,rp,e.transitioning]),(0,a.useEffect)(()=>{let e=new AbortController;return n6(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n6,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:R,agentRunning:L,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:eP,compaction:eO,compactError:eF,compactResult:ez,currentModel:nc,displayModel:nd,modelSwitching:eE,sessionStats:nu,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:e7,extensionWidgets:tt,respondToExtensionUi:nP,sendExtensionCustomInput:nA,isAutoModelSelection:m&&null===X,agentPhase:eq,isNew:m,autoFollowPaused:tB,resumeAutoFollow:rh,pauseAutoFollow:rm,goalStatus:tV,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tQ,scrollContainerRef:t0,handleSend:nY,handleAbort:nX,handleFork:nQ,handleNavigate:n0,handleModelChange:n2,handleRoleModelChange:n4,handleMainPresetChange:n8,newSessionAccount:ee,handleCompact:n5,handleSteer:n7,handleFollowUp:re,handlePromptWithStreamingBehavior:n9,handleAbortCompaction:rt,handleRecallQueue:rn,handleRemoveQueuedMessage:rr,handleBuiltinSlashCommand:n3,handleToolPresetChange:rd,handleThinkingLevelChange:ra,fastMode:rl,fastModeBusy:em,handleFastModeToggle:rc,loadTools:ny,loadSlashCommands:nC,ensureNewSession:nj,refreshLiveTranscript:nv,setActiveLeafId:j,setData:x,setMessages:C,dispatch:E,setAgentRunning:$,setForkingEntryId:eN,bashRunning:P,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}),t2=(0,a.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let a=e[r],i=e7(a);if(!i||"custom"!==a.role)continue;t??=[...e];let s=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===i.sourceHash){r.timestamp===i.sourceTimestamp&&s.push(t);continue}let a=n.get(t);void 0===a&&(a=function(e){let t=e3(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,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[r]={...a,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(e6)?{kind:"translated",text:n.slice(e6.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(a,e3(o.content??[]))}}return t??e})(ej),[ej]),t8=am(e?.id,e4?.provider,void 0,e4?.modelId),t4=t8?.alias;(0,a.useEffect)(()=>{t4&&X.current?.(t4)},[t4]);let t5=(0,a.useMemo)(()=>{if(!e4)return null;let e=tC?tH:rm.find(e=>e.alias===t8?.alias)?.oauthPosition;return rm.find(t=>t.provider===e4.provider&&(void 0===t.oauthPosition?null===t8||t8.seed===t.seed:t.oauthPosition===e))?.alias??null},[e4,tC,tH,t8]),t6=eN||eT,t3=e?.id;ea.current=t2,ei.current=eS,es.current=tR;let t7=(0,a.useRef)(!0);t7.current=!tN;let t9=(0,a.useRef)(!1);(0,a.useEffect)(()=>{eN&&!t9.current&&(eo.current+=1),t9.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(pR(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[]}}(t3),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t3)])},[t3]),(0,a.useEffect)(()=>{let e=tR.current;e&&en.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let n=!1,r=[];for(let a of t){if(null!==a.anchorEntryId||!a.intent||a.sessionId!==e){r.push(a);continue}let i=function(e,t,n){let r=Math.min(t.length,n.length),a=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};a=t+1}let i=0;for(let s=a;s<r;s++)if(rs(t[s])===e.identity&&(i+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(a.intent,t2,eS);if(null===i){r.push(a);continue}n=!0,"drop"!==i.kind&&("working"===a.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===i.entryId)||r.push({id:a.id,anchorEntryId:i.entryId,sticker:a.sticker,text:a.text,tag:a.tag,sessionId:a.sessionId}))}return n?(pE(e,r),r):t})},[t2,eS,tR]);let ne=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=tR.current,t=ne.current;if(ne.current=e?{sessionId:e,entryIds:eS}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],a=Math.min(n.length,t.length);for(let i=e.length;i<a;i++){let e=n[i];"assistant"===e.role&&"web6"===e.provider&&e.model===rl&&r.push(t[i])}return r}(t.entryIds,eS,t2),r=ed();if(0===n.length||!r)return;let a=ap(e,"web6",void 0)?.alias??null;for(let e of n)en.current.some(t=>t.anchorEntryId===e)||eh(a,"done",r,{kind:"entry",entryId:e})},[eS,t2,tR,ed,eh]);let nt=eN&&tS?.kind==="running_tools"&&tS.tools.length>0&&tS.tools.every(e=>"wait"===e.name),nn=ew||s,{hideThinkingBlock:nr}=(O=t??e?.cwd??null,H=nQ(),(0,a.useEffect)(()=>{nX(O).catch(()=>{})},[O]),H),na=(0,a.useMemo)(()=>({hideThinking:nr}),[nr]);(0,a.useEffect)(()=>{var e;if(!tg||Y.current===tg.id)return;Y.current=tg.id;let t=ed();if(!t)return;ec.current=t.turn;let n=eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,r=ro(ea.current,n,e4?.provider,e4?.modelId);ef("select"===(e=tg.method)||"ask"===e||"form"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tg,eC.streamingMessage,e4?.provider,e4?.modelId,ed,ef]),(0,a.useEffect)(()=>(v=t6?tA:null,()=>void(v=null)),[t6,tA]),(0,a.useEffect)(()=>{M?.(t6)},[M,t6]),(0,a.useEffect)(()=>()=>M?.(!1),[M]),(0,a.useEffect)(()=>{R?.(nt)},[nt,R]),(0,a.useEffect)(()=>()=>R?.(!1),[R]),(0,a.useEffect)(()=>{E?.(null!==tg)},[E,tg]),(0,a.useEffect)(()=>()=>E?.(!1),[E]);let{main:ni,process:ns}=(0,a.useMemo)(()=>(function(e,t,n={}){let r=[],a=[],i=-1,s=null,o=(e,t,n)=>{if(0===t.length)return;let i=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},a.push(s)),s),o=r.length-1;for(let e of t)i.entries.push({...e,afterMainIndex:o});i.messageCount+=t.length,i.toolCallCount+=n},l=e8(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:i,idx:e,runIndex:n,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){r.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,r.push(a);continue}if(tt(t)){r.push(void 0!==a.anchorIdx||i<0?a:{...a,anchorIdx:i});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===e7(t)&&0>tn(e,a.idx)&&o(i,[{idx:a.idx}],0);continue}let s=eJ(t,n),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}],eZ(e.blocks)),l.collect(a.idx,e.blocks)}!c&&eG(t,n)&&d(a.idx,[])}return u(),{main:r,process:a}})(t2,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(ts(e[t])){n=t;break}let r=[];for(let a=0;a<e.length;){if(!ts(e[a])){r.push({kind:"message",idx:a}),a+=1;continue}let i=a,s=i+1;for(;s<e.length&&!ts(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&i===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,i+1,s)){for(let e=i;e<s;e++)r.push({kind:"message",idx:e});a=s;continue}for(let n of(r.push({kind:"message",idx:i}),function(e,t,n,r){let a=[],i=[],s=0,o=[],l=0,c=0,d=e8(e.slice(t+1,n)),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,n)=>{u(),a.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(n),precedingBlocks:o}),o=[]};for(let l=t+1;l<n;l++){let n=e[l];if("assistant"!==n.role){if(null!==e7(n)||tn(e,l)>=0)continue;if(tt(n)){u(),a.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&i.push({idx:l});continue}let c=eJ(n,r),h=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){p(l,e.blocks);continue}for(let t of(i.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eZ(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&eG(n,r)&&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})))r.push(n);a=s}return r}(t2,{sessionBusy:t6,isStreaming:eC.isStreaming,hideThinking:na.hideThinking}),na),[t2,t6,eC.isStreaming,na]),no=(0,a.useMemo)(()=>(function(e,t,n=[]){let r=new Map,a=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===a.length)return r;let i=-1,s=-1;t.forEach((e,t)=>{let n=a8(e);if(n.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=r.get(l.position);e?e.calls.push(...n):r.set(l.position,{calls:[...n],placement:o?"after":"before"})}}"user"===e.role&&(i=t),ts(e)&&(s=t)});let{continuing:o}=a4(e,t,n);if(o){let e=r.get(o.position);e?e.calls.unshift(...o.calls):r.set(o.position,{calls:o.calls,placement:"before"})}return r})(ni,t2,tl?.messages),[ni,t2,tl]),nl=(0,a.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=a4(e,t,n);if(0===r.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:r}})(ni,t2,tl?.messages),[ni,t2,tl]),[nc,nd]=(0,a.useState)(pC),{startIndex:nu,endIndex:np,hasLater:nh}=pN(ni.length,nc),nm=null!==nc.end&&nh,nf=(0,a.useRef)(ni.length);nf.current=ni.length;let ng=(0,a.useRef)(null),nx=(0,a.useRef)(null),nv=(0,a.useRef)(null);(0,a.useEffect)(()=>{null!==nc.end&&nc.end>=ni.length&&nd(e=>({count:e.count,end:null}))},[nc.end,ni.length]),(0,a.useEffect)(()=>{let e=ng.current,t=t$.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nv.current=t.scrollHeight-t.scrollTop,nd(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nc,ni.length,t$]),(0,a.useEffect)(()=>{if(null==nv.current)return;let e=t$.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nv.current),nv.current=null}},[nc.count,t$]),(0,a.useEffect)(()=>{let e=nx.current,t=t$.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nd(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:a}=pN(e,t),i=a+n;return i>=e?{count:e-r,end:null}:{count:i-r,end:i}})(nf.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nc,ni.length,t$]);let[nb,ny]=(0,a.useState)(null),[nw,nj]=(0,a.useState)(0),nC=(0,a.useRef)(null),nI=(0,a.useCallback)(e=>{tI(),nC.current=e,ny(null),nd(t=>pT(nf.current,e,t)),nj(e=>e+1)},[tI]);(0,a.useLayoutEffect)(()=>{let e=nC.current,t=t$.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;nC.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,ny(e)},[nw,nc,ni,t$]),(0,a.useEffect)(()=>{if(null===nb)return;let e=setTimeout(()=>ny(null),1800);return()=>clearTimeout(e)},[nb]);let nM=(0,a.useCallback)(()=>{(0,q.flushSync)(()=>nd(pC));let e=t$.current;e&&(e.scrollTop=e.scrollHeight)},[t$]),nR=(0,a.useCallback)(()=>{nm&&nM(),tT()},[nm,nM,tT]),nE=(0,a.useRef)(null),[nL,n$]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(!_||nE.current===_.id||_.sessionId!==e?.id||ew||0===t2.length)return;nE.current=_.id,W?.(_.id);let t=eS.indexOf(_.entryId);if(t<0)return void n$(!0);let n=0;for(let e=0;e<ni.length;e++){let r=ni[e].idx;if(r>t||(n=e,r===t))break}nI(n)},[_,e?.id,ew,t2.length,eS,ni,nI,W]),(0,a.useEffect)(()=>{if(!nL)return;let e=setTimeout(()=>n$(!1),6e3);return()=>clearTimeout(e)},[nL]);let[nP,nA]=(0,a.useState)(!1),[nF,n_]=(0,a.useState)(0),nz=(0,a.useMemo)(()=>nP?ni.map(e=>(function(e,t){if("answer"===e.kind)return tc(e.blocks);let n=t[e.idx];return n&&"content"in n?tc(n.content):""})(e,t2).toLowerCase()):pL,[nP,ni,t2]),nW=(0,a.useCallback)(e=>{tI(),nd(t=>pT(nf.current,e,t))},[tI]),nO=(0,a.useCallback)(()=>nA(!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=t$.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nA(!0),n_(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t$]);let nD=(0,a.useMemo)(()=>{let e=[];return ni.forEach((t,n)=>{if("message"!==t.kind)return;let r=pM(t2[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[ni,t2]),nH=`${nu}:${np}`,nU=eS.length>0?eS[eS.length-1]:null,[nB,nq]=(0,a.useState)(null),nV=(0,a.useRef)(!1);(0,a.useEffect)(()=>{nV.current||!to||ew||!e?.id||(nV.current=!0,t6||!nU||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(t2)||function(e){try{return window.localStorage.getItem(p$(e))}catch{return null}}(e.id)!==nU&&nq(nU))},[to,ew,e?.id,t6,nU,t2]);let nK=(0,a.useCallback)(()=>{e?.id&&nB&&function(e,t){try{window.localStorage.setItem(p$(e),t)}catch{}}(e.id,nB),nq(null)},[e?.id,nB]),nG=null!==nB&&nB===nU&&!t6&&!nm,nJ=te?[te.sessionId,te.sessionFile??"",te.sessionName??"",te.userMessages,te.assistantMessages,te.toolCalls,te.toolResults,te.totalMessages,te.tokens.input,te.tokens.output,te.tokens.cacheRead,te.tokens.cacheWrite,te.tokens.total,te.cost??0,te.totalActiveMs??0].join("|"):null,nZ=(0,a.useRef)(te);nZ.current=te,(0,a.useEffect)(()=>{f?.(nZ.current)},[nJ,f]),(0,a.useEffect)(()=>()=>{f?.(null)},[f]);let nY=eq?`${eq.percent??"null"}|${eq.contextWindow}|${eq.tokens??"null"}`:null,n0=(0,a.useRef)(eq);n0.current=eq,(0,a.useEffect)(()=>{x?.(n0.current)},[nY,x]),(0,a.useEffect)(()=>()=>{x?.(null)},[x]),(0,a.useEffect)(()=>{b?.(th)},[b,th]),(0,a.useEffect)(()=>()=>{b?.([])},[b]);let{regular:n1,lab:n2}=(0,a.useMemo)(()=>(function(e){let t=[],n=[];for(let a of e){var r;((r=a.key).startsWith(c_)&&null!==cz(r)?n:t).push(a)}return{regular:t,lab:n}})(ty),[ty]),n8=e?.id??null;(0,a.useEffect)(()=>{y?.(n8,n2)},[y,n8,n2]),(0,a.useEffect)(()=>()=>{y?.(null,[])},[y]);let{isDragOver:n4,handleDragEnter:n5,handleDragOver:n6,handleDragLeave:n3,handleDrop:n9}=function(e){let[t,n]=(0,a.useState)(!1),r=(0,a.useRef)(0),i=(0,a.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!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)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,a.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,a.useCallback)(e=>{t6||p?.current?.addAttachments(e)},[t6,p])),re=(0,a.useMemo)(()=>{var e;return e=tl?.messages,e&&e.length>0?[...e,...t2]:t2},[tl,t2]),rt=(0,a.useMemo)(()=>{let e=new Map;for(let t of re)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[re]),rn=(0,a.useMemo)(()=>{let e,t,n,r,a,i,s,o,l,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,a=new Map,i=new Map,s=new Map,o=(e,r,a)=>{let i=n.get(e);i&&r&&t.set(i,{status:r,order:a})},l=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,i=aG(e.status);if(!r||l.has(r)||"completed"!==i&&"failed"!==i&&"aborted"!==i)return;l.add(r);let s=aK(e);null!==s&&a.set(r,s)},d=(e,t,r)=>{let a=t?n.get(t):void 0,i=aK(e);a&&"number"==typeof r&&null!==i&&"running"===aG(e.status)&&s.set(a,Math.max(s.get(a)??-1/0,r-i))},re.forEach((t,a)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rt.get(e.toolCallId);if(t)for(let a of aZ(e,t)??[])n.set(a.agentId,a.key),"number"==typeof t.timestamp&&r.set(a.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(aJ(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=aV(t.assignmentId),a=r?.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:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:aV(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:a,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of aq(t.details?.jobs)){if("task"!==r.type)continue;let i=aV(r.id);if(i&&o(i,aG(r.status),a),c(r,i),d(r,i,t.timestamp),i&&"running"===aG(r.status)){let t=n.get(i);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=i.get(t);e||i.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of aJ(t.content).matchAll(aY)){let t=Object.fromEntries([...e[1].matchAll(aX)].map(e=>[e[1],e[2]]));t.id&&o(t.id,aG(t.status),a)}for(let e of aq(t.details?.jobs))"task"===e.type&&c(e,aV(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:a,parallelWith:i,runStartedAt:s}},[re,rt]),rr=(0,a.useMemo)(()=>({ledger:rn,subagents:th,toolResults:rt,onOpenPanel:w,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:j,selectedMaker:S}),[rn,th,rt,w,e?.id,e?.cwd,t,j,S]),ra=(0,a.useMemo)(()=>{let e=new Set,t=[];for(let n=t2.length-1;n>=0;n-=1){let r=pM(t2[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[t2]),ri=(0,a.useMemo)(()=>tL(t2,rt,tm,tl?.todoPhases??null),[t2,rt,tm,tl]),rc=(0,a.useMemo)(()=>cT(eC.streamingMessage).join("|"),[eC.streamingMessage]),rd=(0,a.useMemo)(()=>JSON.stringify(cN(eC.streamingMessage)),[eC.streamingMessage]),ru=(0,a.useMemo)(()=>JSON.stringify(cM(eC.streamingMessage)),[eC.streamingMessage]),rp=(0,a.useMemo)(()=>(function(e,t,n=[],r=[],a=[]){let i=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let a=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:a})}return t}(e),s=[],o=new Map,l=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){l=n;continue}let a=cT(r),c=cM(r,i);if(0===a.length&&0===c.length||l<0)continue;let d=cN(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...a],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.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,...n.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...a.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(t2,eS,rc.length>0?rc.split("|"):[],JSON.parse(rd),JSON.parse(ru)),[t2,eS,rc,rd,ru]),rh=e?.id??tR.current??void 0,rf=(U=cL(D=(0,a.useMemo)(()=>({sessionId:rh,sessionProvider:e4?.provider,turns:rp,messages:t2,subagents:th}),[rh,e4?.provider,rp,t2,th])),V=cF(D),(0,a.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...U,...V])),[U,V])),rg=tC&&0===t2.length&&!eC.isStreaming&&!t6,rx=(0,a.useMemo)(()=>t2.filter(e=>"assistant"===e.role).length,[t2]),rv=function(e,t){let n=(0,a.useRef)(new Map),r=(0,a.useMemo)(()=>{if(!e)return n.current=new Map,0;let t=new Map,r=0;return(e.content??[]).forEach((e,a)=>{let i=eQ(e);if(null===i)return;let s=e0(n.current.get(a),i);t.set(a,{text:i,tokens:s}),r+=s}),n.current=t,r},[e]),i=(0,a.useRef)(r);i.current=r;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 n=setInterval(t,1e3);return()=>clearInterval(n)},[s,o,t]),s?l??0:null}(eC.streamingMessage?.role==="assistant"?eC.streamingMessage:null,rx),rb=(0,a.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("assistant"!==n.role)continue;let{usage:r,timestamp:a,completedAt:i}=n,s=r?.output??0;if(!(s<=0)&&a&&i&&!(i<=a))return s/((i-a)/1e3)}return null})(t2),[t2]),ry=e?.cwd??t??void 0,rw=e4?eP[`${e4.provider}:${e4.modelId}`]??null:null,rk=e4?eA[`${e4.provider}:${e4.modelId}`]??null:null,rj=(0,a.useRef)(null),rS=(0,a.useRef)(null),rC=(0,a.useCallback)(()=>{let e=rj.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,a.useEffect)(()=>(I?.(rC),()=>I?.(null)),[rC,I]),(0,a.useLayoutEffect)(()=>{let e=rS.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=t$.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let a=t$.current;if(!a)return;let i=n-a.clientHeight;n=a.clientHeight,i<=0||a.scrollHeight-a.scrollTop-a.clientHeight-i<=1&&(a.scrollTop+=i)};r();let a=new ResizeObserver(r);return a.observe(e),()=>a.disconnect()},[ew,t$]);let rN=(0,a.useCallback)((...e)=>(null!==nc.end&&nM(),tP(...e)),[tP,nc.end,nM]),rT=(0,r.jsx)("div",{ref:rj,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(uz,{ref:p,sessionId:e?.id??tR.current??void 0,onEnsureSession:tC&&t?t0:void 0,onLiveTranscriptPersisted:t1,onSend:rN,onAbort:tA,onSteer:eN?tB:void 0,onFollowUp:eN?tq:void 0,onPromptWithStreamingBehavior:eN?tV:void 0,isStreaming:t6,model:e4,isAutoModelSelection:tj,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:eL,onModelChange:tW,onMainPresetChange:e||tC?tD:void 0,mainPresetActiveAlias:t5,modelRoles:eF,onRoleModelChange:tO,modelSwitching:e5,onCompact:e||tC?tU:void 0,onAbortCompaction:tK,isCompacting:eY,compactError:e1,compactResult:e2,toolPreset:e_,onToolPresetChange:e||tC?tY:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,outputTokensPerSecond:rv??rb,outputSpeedLive:null!==rv,thinkingCeiling:eO,onThinkingLevelChange:e||tC?tX:void 0,fastMode:eD,fastModeBusy:eH,onFastModeToggle:e||tC?eU:void 0,availableThinkingLevels:rw,thinkingLevelMap:rk,retryInfo:eB,deliveryRows:tp,inputHistory:ra,onRecallQueue:tG,onRemoveQueuedMessage:tJ,slashCommands:td,slashCommandsLoading:tu,onLoadSlashCommands:tQ,onBuiltinCommand:tZ,soundEnabled:L,onSoundToggle:$,onAudioUnlock:F,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rI=eC.streamingMessage,rM=(0,a.useMemo)(()=>rI?eJ(rI,{isStreaming:!0}):[],[rI]),rR=(0,a.useMemo)(()=>rM.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rM]),rE=(0,a.useMemo)(()=>rM.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rM]),rL=rI?.role==="assistant"?rI:null,r$=(0,a.useMemo)(()=>{let e=-1;for(let t=t2.length-1;t>=0;t-=1)if("user"===t2[t].role){e=t;break}let t=e<0?-1:sH(t2,e);return{start:t,blocks:sO(t2,t+1,t2.length),priorCiHeads:sB(t2,rt,t+1),jobNotices:sD(t2,t+1,t2.length)}},[t2,rt]),rP=(0,a.useMemo)(()=>sF(rL?[...r$.blocks,...rL.content??[]]:r$.blocks,rt,t6,r$.priorCiHeads,ry,r$.jobNotices),[r$,rL,rt,t6,ry]),rA=(0,a.useMemo)(()=>t6?{...sW(r$.blocks,rt,ry),span:sq(t2,r$.start+1,t2.length)}:null,[t6,r$,rt,ry,t2]),rF=(0,a.useMemo)(()=>rA?{...rA,flow:rP,latest:!0}:null,[rA,rP]),r_=eN&&(tS?.kind==="running_tools"||(rL?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rz=ro(t2,rL,e4?.provider,e4?.modelId),rW=rz.provider,rO=rz.model,rD=rz.credentialId;(0,a.useEffect)(()=>{if(!r_)return;let e=ed();e&&el.current!==e.turn&&ec.current!==e.turn&&(el.current=e.turn,ef("working",e,rW,rD,rO))},[r_,rW,rO,rD,ed,ef]);let[rH,rU]=(0,a.useState)(null),rB=(0,a.useCallback)(e=>{rU(e)},[]),rq=(0,a.useMemo)(()=>eI?{role:"bashExecution",command:eI.command,output:"",excludeFromContext:eI.excludeFromContext}:null,[eI]),rV=(0,a.useMemo)(()=>{let e=[eN&&!rI&&tS?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tS,K):null,eT&&!eI?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eN,rI,tS,eT,eI,K]);(0,a.useEffect)(()=>{if(!rH)return void C?.(null);let e=[],t=[],n=0;if(rI&&rE.length>0){let r=rH.messages.length+e.length;for(let a of(e.push(rI),rE))t.push({idx:r,blocks:a}),n+=eZ(a)}if(rq&&(t.push({idx:rH.messages.length+e.length}),e.push(rq)),0===t.length)return void C?.(rV?{...rH,status:rV}:rH);let r=-1;for(let e=rH.messages.length-1;e>=0;e--)if(ts(rH.messages[e])){r=e;break}let a=rH.groups.slice(),i=a.length>0?a[a.length-1]:void 0;i&&i.anchorIdx===r?a[a.length-1]={...i,entries:[...i.entries,...t],messageCount:i.messageCount+t.length,toolCallCount:i.toolCallCount+n}:a.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),C?.({...rH,groups:a,messages:[...rH.messages,...e],status:rV})},[rH,rE,rI,rq,rV,C]),(0,a.useEffect)(()=>()=>C?.(null),[C]);let rK=n1.filter(e=>"belowEditor"!==e.placement),rG=n1.filter(e=>"belowEditor"===e.placement);return ek?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ek}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":nn,"data-empty-start":rg&&!T?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n5,onDragOver:n6,onDragLeave:n3,onDrop:n9,children:[nn?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,n4&&!t6&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),tv&&(0,r.jsx)(pD,{request:tv,onInput:tk}),rg&&!T?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[860px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(ee,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.201"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.18.7"]})]})]})]}),ry&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":K("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:K("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:t_(ry)||ry}),(0,r.jsx)("code",{title:ry,children:ry}),(0,r.jsx)("p",{children:K("chat.emptyProjectHint")})]}),k&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:k,children:K("chat.openSessionList")})]}),(0,r.jsx)(pz,{notices:tf,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[T&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:T}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!T,style:{display:T?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(co,{open:nP,onClose:nO,containerRef:t$,index:nz,renderedStart:nu,renderedEnd:np,contentKey:t2,onReveal:nW,onProgrammaticScroll:tI,focusRequest:nF,t:K}),nL&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,r.jsx)(pz,{notices:tf,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:t$,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(p_,{widgets:rK}),(0,r.jsxs)(s9.Provider,{value:rr,children:[(0,r.jsx)(cw,{utterances:rf,children:(0,r.jsx)(pP,{messages:t2,entryIds:eS,toolResultsMap:rt,modelNames:eM,messageCwd:ry,onOpenFile:N,sessionBusy:t6,isNew:tC,isStreaming:eC.isStreaming,handleFork:tF,forkingEntryId:eK,handleNavigate:tz,handleEditContent:ey,sessionId:e?.id??tR.current??void 0,main:ni,dispatchSlots:no,compactedDispatch:nl,openRequest:tl?.openRequest??null,process:ns,startIndex:nu,endIndex:np,sentinelRef:ng,laterSentinelRef:nx,flashItem:nb,t:K,cues:Q,cueFollowRef:t7,onProcessLogChange:rB})}),!nm&&eC.isStreaming&&eC.streamingMessage&&rR.length>0&&(0,r.jsx)(lP,{message:eV(eC.streamingMessage,rR),sessionId:e?.id??tR.current??void 0,isStreaming:!0,modelNames:eM,cwd:ry,onOpenFile:N}),!nm&&rF&&(0,r.jsx)(o6,{summary:rF,live:!0,onOpenFile:N})]}),nG&&(0,r.jsx)(ch,{onDismiss:nK,t:K}),(0,r.jsx)("div",{ref:tE})]})})}),(0,r.jsx)(cl,{questions:nD,containerRef:t$,layoutKey:nH,onJump:nI,label:K("chat.questionRail")}),(t6&&tN||nm)&&(0,r.jsxs)("button",{type:"button",onClick:nR,"aria-label":K("chat.jumpToBottom"),title:K("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:J?44:void 0,borderRadius:"var(--seed-radius-full)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rS,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tg&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,r.jsx)(pO,{request:tg,onRespond:tw,onActivity:(e,t)=>void tk(e,t??"activity"),delivery:tx})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(cp,{compaction:eX,t:K}),(0,r.jsx)(pF,{goal:tM,t:K}),(0,r.jsx)(p_,{widgets:rG}),(ri||rP.steps.length>0)&&!(G&&J)&&(0,r.jsx)(uO,{phases:ri,flow:rP,busy:t6})]})}),rT,(0,r.jsx)(uW,{statuses:tb})]})]})}function pF({goal:e,t}){if(!e)return null;let n=!e.enabled,a=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nB(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nB(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:a})]})}function p_({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function pz({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,a)=>{let i="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(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:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:i,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function pW({focusKey:e,label:t,labelledBy:n,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 n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:i},children:[o?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function pO({request:e,onRespond:t,onActivity:n,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||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,a.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("form"===e.method)return(0,r.jsx)(pW,{focusKey:e.id,label:s("chat.agentQuestion"),delivery:i,children:(0,r.jsx)(c8,{request:e,onRespond:t,onActivity:n,delivery:i},e.id)});if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),a=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(pW,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let i=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let a=i.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":a,onClick:()=>{m(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let a=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:a}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${a?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:a?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${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,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:a?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),a&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let n=e.target.value;d(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&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,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||i?.status==="sending",onClick:a,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&i?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&i?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&i?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:i?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(pW,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:i,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(ny,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(pW,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:i,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&f()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function pD({request:e,onInput:t}){let{t:n}=(0,z.s)(),i=(0,a.useRef)(null),s=(0,a.useRef)(!1),o=e_(e.lines);return(0,a.useEffect)(()=>{i.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||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,r.jsx)("textarea",{ref:i,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eO[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":" ":eW[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var i;return(0,r.jsxs)(a.Fragment,{children:[(i=`line-${t}`,ez(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${i}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}var pH=n(40960),pU=n.n(pH);function pB({sessionId:e,refreshKey:t,compact:n}){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,n=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(r=>{if(t||n!==m.current)return;let a=r.running?r.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 n=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok)throw Error("shared_settings"===r.code?i("computerTakeover.shared"):r.error??n.statusText);h.current===t&&(m.current+=1,l({sessionId:t,state:{enabled:!0===r.enabled,available:!0!==r.enabled}}))}catch(e){h.current===t&&p(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,r.jsxs)(s.r,{className:`workspace-header-action workspace-takeover${x?` ${pU().active}`:""}`,variant:x?"neutralWeak":"ghost",size:"small",type:"button",disabled:c,"aria-pressed":x,"aria-label":v,title:b,onClick:()=>void f(!x),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!n)&&(0,r.jsx)("span",{children:v})]})}function pq({onPick:e,t}){let[n,i]=(0,a.useState)(""),[s,o]=(0,a.useState)({kind:"idle"}),l=(0,a.useRef)(null),c=n.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,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,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 n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,a)=>{let i=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!i,onClick:()=>i&&e(i,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(a+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:i?i.name?.trim()||i.firstMessage?.trim()||i.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var pV=n(50640),pK=n(73620);let pG=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pJ(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let pZ=["tags","categories","keywords","tag","category"];function pY({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let a="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,i=pZ.find(t=>Array.isArray(e[t])),s=i?e[i].map(pJ).filter(Boolean):[],o=n.filter(([e])=>e!==i&&("title"!==e||!a));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[a&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:a}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=pJ(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var pX=n(8745);let pQ=(0,a.createContext)(null),p0=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),p1=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),p2=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10 3-5 5 5 5"})}),p8=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),p4=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function p5({back:e,title:t,titleTooltip:n,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,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:p2})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:a,tabIndex:a?-1:void 0,children:t}),i,l&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:l})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(pX.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,r.jsxs)(pX.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(pX.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(pX.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,r.jsx)(o.In,{size:"16px",svg:p4})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":f("panel.more"),children:(0,r.jsx)(c.k.ScrollArea,{children:(0,r.jsx)(c.k.Group,{children:h.map(e=>(0,r.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(p6,{}),m&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:m.onClick,"aria-label":m.label,title:m.label,children:(0,r.jsx)(o.In,{size:"16px",svg:p8})})]})}function p6({className:e="panel-header-button"}){let{t}=(0,z.s)(),n=(0,a.useContext)(pQ);if(!n)return null;let i=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":i,title:i,onClick:n.onToggle,children:(0,r.jsx)(o.In,{size:"16px",svg:n.expanded?p1:p0})})}let p3="cuelo-html-pick",p7="cuelo-html-pick-exit";function p9(e,t){return"string"==typeof e&&e.length<=t}function he(e){return"number"==typeof e&&Number.isFinite(e)}function ht({content:e,title:t,picking:n,onExitPick:i,onRequestEdit:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null),d=(0,a.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
|
|
20
|
+
var NONCE=${JSON.stringify(n)},TYPE=${JSON.stringify(p3)},EXIT=${JSON.stringify(p7)};
|
|
21
|
+
var host=window.parent;
|
|
22
|
+
if(document.currentScript)document.currentScript.remove();
|
|
23
|
+
var box=document.createElement("div");
|
|
24
|
+
box.setAttribute("aria-hidden","true");
|
|
25
|
+
box.style.cssText="position:fixed;pointer-events:none;z-index:2147483647;border:2px solid #e5484d;outline:1px solid #fff;border-radius:2px;display:none;box-sizing:border-box";
|
|
26
|
+
document.documentElement.appendChild(box);
|
|
27
|
+
function pickable(t){return t&&t.nodeType===1&&t!==box&&t!==document.documentElement&&t!==document.body;}
|
|
28
|
+
function esc(v){return window.CSS&&CSS.escape?CSS.escape(v):String(v).replace(/[^a-zA-Z0-9_-]/g,"\\\\$&");}
|
|
29
|
+
function uniqueId(el){return el.id&&esc(el.id).length<=200&&document.querySelectorAll("#"+esc(el.id)).length===1;}
|
|
30
|
+
function cssPath(el){
|
|
31
|
+
if(uniqueId(el))return "#"+esc(el.id);
|
|
32
|
+
var parts=[],node=el;
|
|
33
|
+
while(node&&node.nodeType===1&&node!==document.body&&node!==document.documentElement){
|
|
34
|
+
if(node!==el&&uniqueId(node)){parts.unshift("#"+esc(node.id));break;}
|
|
35
|
+
var tag=node.tagName.toLowerCase(),part=tag,parent=node.parentElement;
|
|
36
|
+
if(parent){var same=0,index=0;for(var c=parent.firstElementChild;c;c=c.nextElementSibling){if(c.tagName===node.tagName){same++;if(c===node)index=same;}}if(same>1)part+=":nth-of-type("+index+")";}
|
|
37
|
+
parts.unshift(part);node=parent;
|
|
38
|
+
if(node===document.body){parts.unshift("body");break;}
|
|
39
|
+
}
|
|
40
|
+
// 부모 검사가 받는 길이 안에 들도록, 너무 길면 앞쪽 조상부터 떼어 낸다(끝 요소에 가까운 경로는 남는다).
|
|
41
|
+
while(parts.length>1&&parts.join(" > ").length>1000)parts.shift();
|
|
42
|
+
var sel=parts.join(" > ");
|
|
43
|
+
return sel.length>1000?sel.slice(-1000):sel;
|
|
44
|
+
}
|
|
45
|
+
function startTag(el){var s=el.cloneNode(false).outerHTML,end="</"+el.tagName.toLowerCase()+">";if(s.slice(-end.length).toLowerCase()===end)s=s.slice(0,-end.length);return s.slice(0,300);}
|
|
46
|
+
function show(el){var r=el.getBoundingClientRect();box.style.display="block";box.style.left=r.left+"px";box.style.top=r.top+"px";box.style.width=r.width+"px";box.style.height=r.height+"px";}
|
|
47
|
+
function block(e){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();}
|
|
48
|
+
window.addEventListener("pointermove",function(e){if(pickable(e.target))show(e.target);else box.style.display="none";},true);
|
|
49
|
+
window.addEventListener("pointerleave",function(){box.style.display="none";},true);
|
|
50
|
+
["pointerdown","mousedown","mouseup","pointerup","auxclick","dblclick"].forEach(function(n){window.addEventListener(n,function(e){if(pickable(e.target))block(e);},true);});
|
|
51
|
+
window.addEventListener("submit",block,true);
|
|
52
|
+
window.addEventListener("click",function(e){
|
|
53
|
+
block(e);
|
|
54
|
+
// 누르기 기본 동작을 막아 이 문서가 초점을 받지 못하므로, Escape가 이 문서로 오도록 직접 초점을 가져온다.
|
|
55
|
+
try{window.focus();}catch(err){}
|
|
56
|
+
var el=e.target;if(!pickable(el))return;
|
|
57
|
+
show(el);
|
|
58
|
+
var r=el.getBoundingClientRect();
|
|
59
|
+
var text=(el.textContent||"").replace(/\\s+/g," ").trim().slice(0,160);
|
|
60
|
+
host.postMessage({type:TYPE,nonce:NONCE,selector:cssPath(el),tag:el.tagName.toLowerCase(),id:String(el.id||"").slice(0,256),
|
|
61
|
+
classes:Array.prototype.slice.call(el.classList,0,32).map(function(c){return c.slice(0,128);}),text:text,startTag:startTag(el),
|
|
62
|
+
rect:{x:r.left,y:r.top,w:r.width,h:r.height},viewport:{w:window.innerWidth,h:window.innerHeight}},"*");
|
|
63
|
+
},true);
|
|
64
|
+
window.addEventListener("keydown",function(e){if(e.key==="Escape"){block(e);host.postMessage({type:EXIT,nonce:NONCE},"*");}},true);
|
|
65
|
+
})();`)}</script>`,a=-1;for(let t of e.matchAll(/<\/body>/gi))a=t.index;return a<0?e+r:e.slice(0,a)+r+e.slice(a)}(e,t)}},[n,e]),u=d.nonce,[p,h]=(0,a.useState)(null),[m,f]=(0,a.useState)(""),g=n&&m===u?p:null;return(0,a.useEffect)(()=>{if(!n)return;let e=e=>{let t=function(e,t,n,r){var a;if(!n||e!==n||!r||!t||"object"!=typeof t||t.nonce!==r)return null;if(t.type===p7)return{kind:"exit"};if(t.type!==p3)return null;let{selector:i,tag:s,id:o,classes:l,text:c,startTag:d}=t;if(!p9(i,1e3)||0===i.length||!p9(s,64)||!/^[a-z][a-z0-9-]*$/.test(s)||!p9(o,256)||!p9(c,160)||!p9(d,300)||!Array.isArray(l)||l.length>32||!l.every(e=>p9(e,128)))return null;let u=(a=t.rect)&&"object"==typeof a&&he(a.x)&&he(a.y)&&he(a.w)&&he(a.h)&&!(a.w<0)&&!(a.h<0)?{x:a.x,y:a.y,w:a.w,h:a.h}:null,p=t.viewport;return u&&p&&"object"==typeof p&&he(p.w)&&he(p.h)&&!(p.w<=0)&&!(p.h<=0)?{kind:"pick",element:{selector:i,tag:s,id:o,classes:[...l],text:c,startTag:d,rect:u,viewport:{w:p.w,h:p.h}}}:null}(e.source,e.data,c.current?.contentWindow,u);if(t){if("exit"===t.kind)return void i();h(t.element),f(u)}};return window.addEventListener("message",e),()=>window.removeEventListener("message",e)},[u,i,n]),(0,r.jsxs)("div",{className:"html-pick-shell",children:[n&&(0,r.jsxs)("div",{className:"html-pick-bar","aria-label":l("files.pickedElement"),role:"group",children:[g?(0,r.jsxs)("p",{className:"html-pick-summary",title:`${g.selector}${g.text?`
|
|
66
|
+
${g.text}`:""}`,children:[(0,r.jsxs)("span",{className:"html-pick-tag",children:["<",g.tag,">"]}),g.text&&(0,r.jsxs)("span",{className:"html-pick-text",children:[' \xb7 "',g.text,'"']}),(0,r.jsx)("span",{className:"html-pick-selector",children:g.selector})]}):(0,r.jsx)("p",{className:"html-pick-summary html-pick-hint",children:l("files.pickElementHint")}),(0,r.jsxs)("div",{className:"html-pick-actions",children:[(0,r.jsx)(s.r,{variant:"neutralSolid",size:"small",disabled:!g,onClick:()=>g&&o(g),children:l("files.requestElementEdit")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"small",disabled:!g,onClick:()=>h(null),children:l("files.clearPick")})]})]}),(0,r.jsx)("iframe",{ref:c,className:"html-pick-frame",srcDoc:d.srcDoc,sandbox:"allow-scripts",title:t},u||"plain")]})}let hn={source:"Source",preview:"Preview",diff:"Diff"},hr={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},ha={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function hi(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function hs(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function ho(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=hs(n.startContainer),a=hs(n.endContainer);if(!r||!a||!e.contains(r)||!e.contains(a))return null;let i=Number(r.dataset.lineNumber),s=Number(a.dataset.lineNumber);if(!Number.isInteger(i)||!Number.isInteger(s))return null;if(i<s){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(i=Number((r=e).dataset.lineNumber))}}let t=a.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=a.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((a=e).dataset.lineNumber))}}}return i>s?null:{startLine:i,endLine:s}}function hl({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:a}){return e.map((e,i)=>{let s=e.children??[],o=s[0]?.properties?.className,l=Array.isArray(o)&&o.includes("react-syntax-highlighter-line-number"),c=l?s[0]:null,d=l?s.slice(1):s;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":i+1,style:{display:"flex",minWidth:"100%"},children:[c&&(0,pV.Ay)({node:c,stylesheet:t,useInlineStyles:n,key:`source-line-number-${i}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:a?"anywhere":"normal",whiteSpace:a?"pre-wrap":"pre"},children:d.map((e,r)=>(0,pV.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${i}-${r}`}))})]},`source-line-${i}`)})}let hc=(0,a.memo)(function({content:e,language:t,isDark:n,wrapLines:a}){return(0,r.jsx)(tW.A,{className:a?"file-source-view is-wrapped":"file-source-view",language:"text"===t?"plaintext":t,style:n?tO.xJ:tO.vs,showLineNumbers:!0,lineNumberStyle:{...ha},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...hr,width:a?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:a?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(hl,{...e,wrapLines:a}),wrapLongLines:a,children:e})});function hd(e,t,n,r={}){let a=tF(e),i=new URLSearchParams({type:t});for(let[e,t]of(n&&i.set("sessionId",n),Object.entries(r)))void 0!==t&&i.set(e,String(t));return`/api/files/${a}?${i.toString()}`}let hu=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),hp=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]}),hh=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M4 4h6M4 4v6M20 4h-6M20 4v6M4 20h6M4 20v-6"}),(0,r.jsx)("path",{d:"m13 13 7 3-3 1-1 3z"})]});function hm({filePath:e,cwd:t,sourceSessionId:n,meta:a,watching:i,viewSwitch:s,actions:o=[],downloadable:l=!0}){let{t:c}=(0,z.s)(),d=t_(e),u=tz(e,t),p=u.endsWith(d)?u.slice(0,u.length-d.length).replace(/[\\/]+$/,""):"",h=c(i?"panel.liveSync":"i18n.notWatching");return(0,r.jsx)(p5,{title:d,titleTooltip:`${u}
|
|
67
|
+
${a}`,titleAdornment:null===i?void 0:(0,r.jsx)("span",{className:"panel-header-live",role:"img","aria-label":h,"data-live":i?"true":"false",title:h}),subtitle:p||void 0,subtitleKind:"path",viewSwitch:s,actions:l?[...o,{id:"download",label:c("i18n.downloadFile"),icon:hu,href:hd(e,"download",n),download:d}]:o})}function hf(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function hg({patch:e}){let t,{t:n}=(0,z.s)(),a=(t=ay(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!a.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let i=new Set(a.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of i)for(let t=Math.max(0,e-3);t<=Math.min(a.length-1,e+3);t++)s.add(t);let o=[],l=0;for(;l<a.length;)if(s.has(l)){let e=[];for(;l<a.length&&s.has(l);)e.push(a[l]),l++;o.push({hidden:!1,lines:e})}else{let e=0;for(;l<a.length&&!s.has(l);)e++,l++;o.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...hr},children:o.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",a="added"===e.type?"+":"removed"===e.type?"-":" ",i="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:ha,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:i,userSelect:"none",flexShrink:0,fontWeight:600},children:a}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function hx({filePath:e,cwd:t,sourceSessionId:n}){let[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),f=(0,a.useRef)(null),g=t_(e).toLowerCase().split(".").pop()??"";(0,a.useEffect)(()=>{l(0),d(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(hd(e,"watch",n));return f.current=t,t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}l(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{t.close(),f.current=null}},[e,n]);let x=hd(e,"read",n,o?{v:o}:void 0),v=null!=c?hf(c):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hm,{filePath:e,cwd:t,sourceSessionId:n,watching:i,meta:[g||"image",u?`${u.w} \xd7 ${u.h}`:null,v].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:h?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:h}):(0,r.jsx)("img",{src:x,alt:e,onLoad:e=>{let t=e.currentTarget;p({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>m("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function hv({filePath:e,cwd:t,sourceSessionId:n}){let[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(0),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),f=(0,a.useRef)(null),g=t_(e).toLowerCase().split(".").pop()??"";(0,a.useEffect)(()=>{l(0),d(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(hd(e,"watch",n));return f.current=t,t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&d(t.size)}catch{}p(null),m(null),l(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{t.close(),f.current=null}},[e,n]);let x=hd(e,"read",n,o?{v:o}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hm,{filePath:e,cwd:t,sourceSessionId:n,watching:i,meta:[g||"audio",null!=u?function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}(u):null,null!=c?hf(c):null].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[h&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:h}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:x,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>m("Failed to load audio"),style:{width:"100%"}},x)]})})]})}function hb({filePath:e,cwd:t,sourceSessionId:n}){let{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(!1),[l,c]=(0,a.useState)(0),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)(null),m=(0,a.useRef)(null),f=eU(e),g="pdf"===f,x=g?hd(e,"read",n,l?{v:l}:void 0):hd(e,"preview",n,l?{v:l}:void 0);return(0,a.useEffect)(()=>{c(0),u(null),h(null),o(!1),m.current&&(m.current.close(),m.current=null),fetch(hd(e,"meta",n)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(hd(e,"watch",n));return m.current=t,t.addEventListener("connected",()=>o(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!g&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),c(e=>e+1)}),t.addEventListener("error",()=>o(!1)),t.onerror=()=>o(!1),()=>{t.close(),m.current=null}},[e,g,n]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hm,{filePath:e,cwd:t,sourceSessionId:n,watching:s,meta:["docx"===f?"docx preview":"pdf",null!=d?hf(d):null].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:i("i18n.previewFile",{file:t_(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function hy({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:a,onMentionLines:i,onAtMention:s,onInsertText:o,gitRefreshKey:l,initialDisplayMode:c,viewStateStore:d,viewStateKey:u}){return eB(e)?(0,r.jsx)(hx,{filePath:e,cwd:t,sourceSessionId:n}):null!==(eH[eU(e)]??null)?(0,r.jsx)(hv,{filePath:e,cwd:t,sourceSessionId:n}):eq(e)?(0,r.jsx)(hb,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(hw,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:a,onMentionLines:i,onAtMention:s,onInsertText:o,gitRefreshKey:l,initialDisplayMode:c,viewStateStore:d,viewStateKey:u})}function hw({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:o,onInsertText:l,gitRefreshKey:c,initialDisplayMode:d,viewStateStore:u,viewStateKey:p}){let h,m,{isDark:f}=nm(),{t:g}=(0,z.s)(),x=p?u?.get(p):void 0,v=(0,a.useCallback)(e=>{u&&p&&u.set(p,{...u.get(p),...e})},[p,u]),b=x?.mode,[y,w]=(0,a.useState)(null),[k,j]=(0,a.useState)(null),[S,C]=(0,a.useState)(!1),[N,T]=(0,a.useState)(!0),[I,M]=(0,a.useState)(null),[R,E]=(0,a.useState)("source"),[L,$]=(0,a.useState)(!1),[P,A]=(0,a.useState)(!1),F=(0,a.useCallback)(()=>A(!1),[]),[_,W]=(0,a.useState)(!1),O=(0,a.useRef)(null),D=(0,a.useRef)(0),H=(0,a.useRef)(null),[U,B]=(0,a.useState)(null),q=(0,a.useCallback)(e=>fetch(hd(e,"read",n)).then(e=>e.json()).then(e=>e.error?(M(e.error),null):(M(null),w(e),e)).catch(e=>(M(String(e)),null)),[n]),V=(0,a.useCallback)(async e=>{let n=++D.current;if(C(!0),!t){j(null),C(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),a=await fetch(`/api/git/diff?${r.toString()}`),i=await a.json();if(n!==D.current)return;j(a.ok&&i.supported&&"string"==typeof i.patch?i:null)}catch{n===D.current&&j(null)}finally{n===D.current&&C(!1)}},[t]);(0,a.useEffect)(()=>{T(!0),M(null),w(null),j(null),E("source"),$(!1),W(!1),O.current&&(O.current.close(),O.current=null),q(e).finally(()=>T(!1));let t=new EventSource(hd(e,"watch",n));return O.current=t,t.addEventListener("connected",()=>{W(!0)}),t.addEventListener("change",()=>{q(e),V(e)}),t.addEventListener("error",()=>{W(!1)}),t.onerror=()=>{W(!1)},()=>{t.close(),O.current=null}},[e,q,V,n]),(0,a.useEffect)(()=>{V(e)},[V,e,c]),(0,a.useEffect)(()=>{let e=y?.language==="markdown"||y?.language==="html";if(b){"preview"===b&&e&&E("preview");return}e&&"diff"!==d&&E("preview")},[y?.language,d,b]);let K=k?.supported===!0&&"string"==typeof k.patch,G=K&&"deleted"===k.status;(0,a.useEffect)(()=>{K||"diff"!==R||E("source")},[R,K]),(0,a.useEffect)(()=>{G&&O.current&&(O.current.close(),O.current=null,W(!1))},[G]);let J=(0,a.useRef)(!1);(0,a.useEffect)(()=>{J.current=!1},[e]),(0,a.useEffect)(()=>{(b?"diff"===b:"diff"===d)&&K&&!J.current&&(J.current=!0,E("diff"))},[d,K,b]);let Z=(0,a.useRef)(!1);(0,a.useEffect)(()=>{Z.current=!1},[p]);let Y=x?.scrollTop;(0,a.useEffect)(()=>{if(Z.current||!y)return;if(!Y){Z.current=!0;return}if(b&&R!==b)return;let e=requestAnimationFrame(()=>{let e=H.current;e&&(e.scrollTop=Y,Z.current=!0)});return()=>cancelAnimationFrame(e)},[y,R,b,Y]);let X=(0,a.useMemo)(()=>y?.language==="markdown"?tZ(y.content):"",[y]),Q=(0,a.useMemo)(()=>y?.language==="markdown"?function(e){let t=function(e){let t=pG.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,pK.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(y.content):null,[y]);(0,a.useEffect)(()=>{let e=()=>{let e=H.current,t=s&&"source"===R&&e?ho(e,window.getSelection()):null;B(e=>e?.startLine===t?.startLine&&e?.endLine===t?.endLine?e:t)};if(e(),s&&"source"===R)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[y?.content,R,s]);let ee=(0,a.useCallback)(n=>{s&&n&&s(tz(e,t),n.startLine,n.endLine)},[t,e,s]);if((0,a.useEffect)(()=>{if(!s||"source"!==R)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=H.current,r=n?ho(n,window.getSelection()):null;r&&(e.preventDefault(),ee(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[R,ee,s]),N||"diff"===d&&S&&!y)return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hm,{filePath:e,cwd:t,sourceSessionId:n,meta:g("i18n.loading"),watching:null,downloadable:!1}),(0,r.jsx)("div",{role:"status",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:g("i18n.loading")})]});if(I&&!G)return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hm,{filePath:e,cwd:t,sourceSessionId:n,meta:I,watching:null,downloadable:!1}),(0,r.jsx)("div",{role:"alert",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--danger)",fontSize:13},children:I})]});if(!y&&!G)return null;let et=y?.language??"text",en=y?.content??"",er="html"===et,ea="markdown"===et,ei=(m=(h=tA(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===m?"/":2===m&&/^[a-zA-Z]:\//.test(h)?h.slice(0,3):h.slice(0,m),es=en.split("\n"),eo=G?"diff":R,el=G?["diff"]:["source",...er||ea?["preview"]:[],...K?["diff"]:[]],ec=G?g("files.deleted"):`${et} \xb7 ${es.length} lines \xb7 ${hf(y.size)}`,ed=er&&"preview"===eo&&!!l,eu=ed&&P;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(hm,{filePath:e,cwd:t,sourceSessionId:n,meta:ec,watching:G?null:_,downloadable:!G,viewSwitch:{label:g("i18n.fileViewMode"),value:eo,options:el.map(e=>({value:e,label:hn[e],title:"diff"===e?g("i18n.compareHead"):void 0})),onChange:e=>{E(e),A(!1),v({mode:e})}},actions:[...o||s?[{id:"mention",label:g("files.mention"),icon:(0,r.jsx)(hi,{}),onPointerDown:e=>e.preventDefault(),onClick:()=>{U&&s?ee(U):o?.(tz(e,t),!1)},title:U&&s?`${g("i18n.mentionSelectedLines")} (L${U.startLine}${U.startLine!==U.endLine?`-L${U.endLine}`:""})`:g("files.insertPath")}]:[],..."source"===eo?[{id:"wrap",label:L?g("i18n.disableWrap"):g("i18n.enableWrap"),icon:hp,pressed:L,onClick:()=>$(e=>!e)}]:[],...ed?[{id:"pick-element",label:g("files.pickElement"),icon:hh,pressed:P,onClick:()=>A(e=>!e)}]:[]]}),(0,r.jsx)("div",{ref:H,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},onScroll:e=>v({scrollTop:e.currentTarget.scrollTop}),children:"diff"===eo&&K?(0,r.jsx)(hg,{patch:k.patch}):er&&"preview"===eo?(0,r.jsx)(ht,{content:en,title:g("i18n.htmlPreview"),picking:eu,onExitPick:F,onRequestEdit:n=>{var r,a;let i;if(!l)return;let s=tz(e,t),o=function(e,t){if(!t)return null;let n=e.indexOf(t);if(n<0||e.indexOf(t,n+1)>=0)return null;let r=1;for(let t=e.indexOf("\n");t>=0&&t<n;t=e.indexOf("\n",t+1))r+=1;return r}(en,n.startTag);l((r=null===o?d2(s,!1):d8(s,o,o),a={element:e=>g("files.pickLocatorElement",{selector:e}),text:e=>g("files.pickLocatorText",{text:e}),position:e=>g("files.pickLocatorPosition",e)},i=[r.trimEnd(),a.element(n.selector)],n.text&&i.push(a.text(n.text)),i.push(a.position({x:Math.round(n.rect.x),y:Math.round(n.rect.y),w:Math.round(n.rect.w),h:Math.round(n.rect.h),vw:Math.round(n.viewport.w),vh:Math.round(n.viewport.h)})),`${i.join("\n")}
|
|
68
|
+
`))}}):ea&&"preview"===eo?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[Q?.data&&(0,r.jsx)(pY,{data:Q.data}),(0,r.jsx)(tD.oz,{remarkPlugins:t1,rehypePlugins:t8,components:{code({className:e,children:t,...n}){let a=e?.replace("language-","").toLowerCase()??"",i=String(t);return e?.includes("language-")||i.includes("\n")?"mermaid"===a?(0,r.jsx)(nx,{code:i.replace(/\n$/,"")}):(0,r.jsx)(nb,{code:i.replace(/\n$/,""),lang:a}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...a}){delete a.node;let s=i?tm(e,ei,t??ei):null;return s&&i?(0,r.jsx)("a",{href:e,...a,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),i(s))},children:n}):(0,r.jsx)("a",{href:e,...a,children:n})},img({src:e,alt:a,...i}){delete i.node;let s="string"==typeof e?tm(e,ei,t??ei):null,o=s?hd(s,"read",n):e;return(0,r.jsx)("img",{src:o,alt:a??"",loading:"lazy",...i})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:X})]}):(0,r.jsx)(hc,{content:en,language:et,isDark:f,wrapLines:L})})]})}function hk({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:i}){let{t:s,locale:o}=(0,z.s)(),[l,c]=(0,a.useState)(null);return(0,r.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===o?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let a=e.id===t;return(0,r.jsxs)("div",{className:`file-tab${a?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),i(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"tab","aria-selected":a,onClick:()=>n(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:a?1:.7,display:"flex",alignItems:"center"},children:aI(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:a?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),i(e.id)},onMouseEnter:()=>c(e.id),onMouseLeave:()=>c(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:l===e.id?"var(--bg-hover)":"transparent",border:"none",color:l===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("i18n.close"),"aria-label":`${s("i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let hj=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],hS=new Set(hj);function hC(e){return void 0!==e&&hS.has(e)}function hN(e){if(!e)return[...hj];let t=new Set(e);return hj.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function hT(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return hC(n)?n:"inherit"}function hI(e,t){let n=e.lastIndexOf(":"),r=hC(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var hM=n(98795),hR=n.n(hM);function hE(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function hL({value:e,options:t,onChange:n,disabled:i=!1,placeholder:s="Select…",searchPlaceholder:o="Search options…",noResultsLabel:l="No matching options",ariaLabel:c,className:d,style:u}){let p=(0,a.useRef)(null),h=(0,a.useRef)(null),m=(0,a.useRef)(null),f=(0,a.useRef)([]),[g,x]=(0,a.useState)(!1),[v,b]=(0,a.useState)(""),[y,w]=(0,a.useState)(0),k=(0,a.useId)(),j=t.find(t=>t.value===e),S=(0,a.useMemo)(()=>{let e=hE(v.trim());return e?t.filter(t=>hE(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,a.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,a.useEffect)(()=>{g?requestAnimationFrame(()=>m.current?.focus()):b("")},[g]),(0,a.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,a.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,a.useEffect)(()=>{g&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=d7(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),T=e=>{e.disabled||(n(e.value),x(!1))},I=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${hR().root}${d?` ${d}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:hR().trigger,disabled:i,"aria-label":c,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,r.jsx)("span",{className:j?hR().value:hR().placeholder,children:j?.label??(e||s)}),(0,r.jsx)("svg",{className:hR().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:hR().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,r.jsxs)("div",{className:hR().searchWrap,children:[(0,r.jsxs)("svg",{className:hR().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:hR().search,value:v,placeholder:o,"aria-label":o,role:"combobox","aria-expanded":"true","aria-controls":k,"aria-activedescendant":S[y]?`${k}-${y}`:void 0,autoComplete:"off",spellCheck:!1,onChange:e=>{b(e.target.value),w(0)},onKeyDown:e=>{if("ArrowDown"===e.key)e.preventDefault(),I(1);else if("ArrowUp"===e.key)e.preventDefault(),I(-1);else if("Enter"===e.key){e.preventDefault();let t=S[y];t&&T(t)}else"Tab"===e.key&&x(!1)}})]}),(0,r.jsx)("div",{id:k,className:hR().options,role:"listbox","aria-label":c,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:hR().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>T(t),children:[(0,r.jsxs)("span",{className:hR().optionCopy,children:[(0,r.jsx)("span",{className:hR().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:hR().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:hR().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:hR().empty,children:l})})]})]})}let h$=["global","project"],hP=["implSol","implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet","crossReviewOpenAI","crossReviewAnthropic","crossReviewAdvisory","skim","draft","ocr","interpreter"];function hA(e){return`${e.provider}/${e.id}`}function hF({cwd:e,onRolesChanged:t}){let{t:n}=(0,z.s)(),[i,s]=(0,a.useState)([]),[o,l]=(0,a.useState)([]),[c,d]=(0,a.useState)({}),[u,p]=(0,a.useState)("global"),[h,m]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),b=(0,a.useCallback)(async t=>{if(!e){s([]),l([]),d({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,a]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(i.error)throw Error(i.error);if(!a.ok)throw Error(`HTTP ${a.status}`);let o=await a.json();s(i.roles??[]),l(o.modelList??[]),d(o.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[e]);(0,a.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,a.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let a=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),i=await a.json();if(!a.ok||i.error)throw Error(i.error??`HTTP ${a.status}`);s(i.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,a.useMemo)(()=>i.filter(e=>!e.hidden),[i]),k=w.some(e=>hP.includes(e.role)&&!e.selector);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")}),!h&&k&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:n("roles.harnessNote")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",overflow:"hidden"},children:h$.map(e=>(0,r.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:hI(e.selector??"","inherit"),a=hT(e.selector),i=hN(c[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=hP.includes(e.role);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),s&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:n(`roles.harness.${e.role}`)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:s&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(hL,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let n=o.find(e=>hA(e)===t),r=n?c[`${n.provider}:${n.id}`]:void 0,a=hT(e.selector),i=hN(r).includes(a)?a:"inherit";y(e.role,hI(t,i))},options:[{value:"",label:n("roles.unset")},...o.map(e=>({value:hA(e),label:`${e.name} — ${e.provider}`,searchText:hA(e)})),...t&&!o.some(e=>hA(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:i.map(i=>{let s=a===i;return(0,r.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===i?n("roles.thinkingInherit"):i,onClick:()=>{s||y(e.role,hI(t,i))},style:{padding:"3px 7px",border:`1px solid ${s?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:s?"var(--bg-selected)":"transparent",color:s?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:s?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:i},i)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function h_(e){window.open(e,"_blank","noopener,noreferrer")}var hz=n(67381),hW=n(64433),hO=n(70350),hD=n(88195),hH=n(9312),hU=n(87275),hB=n(22008),hq=n(95476),hV=n(35029),hK=n(14489),hG=n(78728),hJ=n(19872),hZ=n(7751),hY=n(92526),hX=n(48238),hQ=n(57794),h0=n(41098),h1=n(84604),h2=n(15315),h8=n(74278),h4=n(55457),h5=n(71437),h6=n(29167),h3=n(97283),h7=n(34166),h9=n(33889),me=n(85486),mt=n(74068),mn=n(83546),mr=n(83709);let ma={anthropic:{Icon:hz.A,hasColor:!1},openai:{Icon:hW.A,hasColor:!1},"openai-codex":{Icon:hW.A,hasColor:!1},google:{Icon:hO.A,hasColor:!0},"google-vertex":{Icon:hO.A,hasColor:!0},"ant-ling":{Icon:h9.A,hasColor:!0},deepseek:{Icon:hD.A,hasColor:!0},groq:{Icon:hH.A,hasColor:!1},mistral:{Icon:hU.A,hasColor:!0},moonshotai:{Icon:hB.A,hasColor:!1},"moonshotai-cn":{Icon:hB.A,hasColor:!1},moonshot:{Icon:hB.A,hasColor:!1},minimax:{Icon:hq.A,hasColor:!0},"minimax-cn":{Icon:hq.A,hasColor:!0},fireworks:{Icon:hV.A,hasColor:!0},huggingface:{Icon:hK.A,hasColor:!0},cerebras:{Icon:hG.A,hasColor:!0},openrouter:{Icon:hJ.A,hasColor:!1},xai:{Icon:hZ.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:hY.A,hasColor:!0},"cloudflare-workers-ai":{Icon:hY.A,hasColor:!0},"vercel-ai-gateway":{Icon:hX.A,hasColor:!1},"github-copilot":{Icon:hQ.A,hasColor:!1},"amazon-bedrock":{Icon:h0.A,hasColor:!0},"azure-openai-responses":{Icon:h1.A,hasColor:!0},"kimi-coding":{Icon:h2.A,hasColor:!0},nvidia:{Icon:me.A,hasColor:!0},opencode:{Icon:mt.A,hasColor:!1},"opencode-go":{Icon:mt.A,hasColor:!1},qwen:{Icon:h8.A,hasColor:!0},xiaomi:{Icon:mn.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:mn.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:mn.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:mn.A,hasColor:!1},zai:{Icon:mr.A,hasColor:!1},"zai-coding-cn":{Icon:mr.A,hasColor:!1},zhipu:{Icon:h4.A,hasColor:!0},cohere:{Icon:h5.A,hasColor:!0},perplexity:{Icon:h6.A,hasColor:!0},together:{Icon:h3.A,hasColor:!0},grok:{Icon:h7.A,hasColor:!1}},mi=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function ms({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let mo={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function ml({value:e,onChange:t,placeholder:n,mono:a}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...mo,fontFamily:a?"var(--font-mono)":"inherit"}})}function mc({value:e,onChange:t,placeholder:n,mono:i,onKeyDown:s,autoComplete:o="off",spellCheck:l=!1,style:c}){let[d,u]=(0,a.useState)(!1),{t:p}=(0,z.s)();return(0,a.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,r.jsx)("input",{type:d?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:n,style:{...mo,paddingRight:34,fontFamily:i?"var(--font-mono)":"inherit"},autoComplete:o,spellCheck:l}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(d?"i18n.hideDetails":"i18n.showDetails"),title:p(d?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:d?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function md({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:mo})}function mu({value:e,onChange:t,options:n,required:a}){let{t:i}=(0,z.s)();return(0,r.jsx)(hL,{value:e,onChange:t,options:[...a?[]:[{value:"",label:`— ${i("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function mp({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function mh({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function mm({name:e,provider:t,onChange:n,onRename:i,onDelete:s,onAddModels:o}){let{t:l}=(0,z.s)(),[c,d]=(0,a.useState)(e),[u,p]=(0,a.useState)({phase:"idle"}),[h,m]=(0,a.useState)(""),[f,g]=(0,a.useState)([]),x=(0,a.useRef)(0),v=(0,a.useRef)(null);(0,a.useEffect)(()=>d(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,a.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,a.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,a.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),a=await r.json();if(n!==x.current)return;if(!r.ok||a.error||!a.models)return void p({phase:"error",message:a.error??`HTTP ${r.status}`});p({phase:"success",models:a.models,endpoint:a.endpoint??t.baseUrl})}catch(e){if(n!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),T=f.filter(e=>!w.has(e)).length,I=N.length>0&&N.every(e=>f.includes(e)),M=!I&&N.some(e=>f.includes(e));return(0,a.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mh,{children:l("i18n.provider")}),(0,r.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11},children:l("i18n.delete")})]}),(0,r.jsxs)(ms,{label:l("i18n.providerName"),children:[(0,r.jsx)(ml,{value:c,onChange:d,placeholder:"provider-name",mono:!0}),c!==e&&c.trim()&&(0,r.jsx)("button",{onClick:()=>i(c.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"var(--radius-control)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:l("i18n.rename")})]}),(0,r.jsx)(ms,{label:"Base URL",children:(0,r.jsx)(ml,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(ms,{label:"API Key",children:[(0,r.jsx)(mc,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(ms,{label:"API",children:(0,r.jsx)(mu,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:mi,required:!0})}),(0,r.jsxs)(ms,{label:"Headers",children:[(0,r.jsx)(mb,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?l("models.discoveryFetching"):l("models.discoveryFetch")}),"error"===u.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-surface)",color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:l("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":l("models.discoveryFilter"),style:{...mo,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:I,disabled:0===N.length,onChange:()=>{let e=new Set(N);g(t=>I?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...N])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),l("models.discoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:l("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),a=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:a||n,disabled:n,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:l("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?l("models.discoveryShowing",{shown:C.length,total:S.length}):l("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(o(t),g([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:"var(--radius-control)",background:T?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:T?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?l("models.discoveryAddSelectedCount",{count:T}):l("models.discoveryAddSelected")})]})]})]})]})}let mf=["off","minimal","low","medium","high","xhigh","max"],mg={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function mx({value:e,onChange:t}){let n=e??{},a=(e,r)=>{let a={...n};"omit"===r?delete a[e]:a[e]=r,t(Object.keys(a).length?a:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:mf.map(e=>{let t=n[e],i=e in n?null===t?"null":"string":"omit",s="string"==typeof t?t:"",o=mg[e],l={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},c={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:"var(--radius-control)",background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:o,flexShrink:0,opacity:"null"===i?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===i?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===i?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>a(e,"omit"),style:{...l,..."omit"===i?c:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>a(e,null),style:{...l,borderLeft:"1px solid var(--border)",..."null"===i?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:`1px solid ${"string"===i?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>a(e,s||e),style:{...l,..."string"===i?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:s,onChange:t=>a(e,t.target.value),onFocus:()=>{"string"!==i&&a(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===i?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===i?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let mv={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function mb({headers:e,onChange:t}){let[n,i]=(0,a.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),s=(0,a.useRef)(n.length),o=e=>{i(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},l=(e,t)=>{o(n.map(n=>n.id===e?{...n,...t}:n))},c={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>l(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...mo,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>l(e.id,{value:t.target.value}),placeholder:"value",style:{...mo,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void o(n.filter(e=>e.id!==t))},style:c,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>i(e=>[...e,{id:s.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function my({providerName:e,provider:t,model:n,onChange:i,onDelete:s}){let[o,l]=(0,a.useState)({phase:"idle"}),{t:c}=(0,z.s)(),[d,u]=(0,a.useState)({phase:"idle"}),p=(0,a.useRef)(0),h=(0,a.useRef)(null),m=(e,t)=>i({...n,[e]:t}),f=(()=>{if("idle"===o.phase)return null;if("testing"===o.phase)return c("i18n.testingModel");let e=[void 0!==o.latencyMs?`${o.latencyMs}ms`:null,void 0!==o.status?`HTTP ${o.status}`:null].filter(Boolean);return"success"===o.phase?[c("i18n.connected"),...e,o.responseText||null].filter(Boolean).join(" \xb7 "):[c("i18n.failed"),...e,o.message].filter(Boolean).join(" \xb7 ")})();(0,a.useEffect)(()=>{l({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,a.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,a.useCallback)(async()=>{if(n.id.trim()&&"testing"!==o.phase){l({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),a=await r.json();if(!r.ok||!a.ok)return void l({phase:"error",message:a.error??`HTTP ${r.status}`,latencyMs:a.latencyMs,status:a.status});l({phase:"success",latencyMs:a.latencyMs,status:a.status,responseText:a.responseText})}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,o.phase]),x=(0,a.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===d.phase)return;let a=++p.current;u({phase:"loading"});try{let s=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let o=await fetch(`/api/models-config/catalog?${s}`),l=await o.json();if(a!==p.current)return;if(!o.ok||l.error||!l.recommendation)return void u({phase:"error",message:l.error??`HTTP ${o.status}`});let c=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let a={...e.cost??{}},i=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===a[e]&&void 0!==t.cost[e]&&(a[e]=t.cost[e],i=!0,r+=1);i&&(n.cost=a)}return{model:n,appliedCount:r}}(n,l.recommendation.preset);c.appliedCount>0&&(h.current=n,i(c.model)),u({phase:"success",recommendation:l.recommendation,appliedCount:c.appliedCount})}catch(e){if(a!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[d.phase,n,i,t.baseUrl,e]),v=(()=>{if("success"!==d.phase)return null;let{recommendation:t,appliedCount:n}=d,r=n>0?c("models.catalogFilled",{count:n}):c("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?c("models.catalogNoExactMatch"):c("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let a="provider"===t.price.method?c("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?c("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):c("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${a}`})(),b="error"===d.phase?d.message:v,y="error"===d.phase?"#ef4444":"success"===d.phase&&"unreliable"===d.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mh,{children:c("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===o.phase?"#fecaca":"success"===o.phase?"#bbf7d0":"var(--border)"}`,borderRadius:"var(--radius-control)",background:"error"===o.phase?"#fee2e2":"success"===o.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,r.jsxs)("button",{onClick:g,disabled:!n.id.trim()||"testing"===o.phase,title:c("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===o.phase?"#16a34a":"none",border:`1px solid ${"success"===o.phase?"#16a34a":"var(--border)"}`,borderRadius:"var(--radius-control)",color:"success"===o.phase?"#fff":n.id.trim()&&"testing"!==o.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==o.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===o.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===o.phase?c("i18n.checking"):"success"===o.phase?c("common.ok"):c("i18n.test")]}),(0,r.jsx)("button",{onClick:s,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:c("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(ms,{label:"ID *",children:(0,r.jsx)(ml,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(ms,{label:"Name",children:(0,r.jsx)(ml,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===d.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==d.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==d.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===d.phase?c("models.catalogFilling"):c("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:c("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,i(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:c("models.catalogUndo")})]})]}),(0,r.jsx)(ms,{label:"API override",children:(0,r.jsx)(mu,{value:n.api??"",onChange:e=>m("api",e||void 0),options:mi})}),(0,r.jsxs)(ms,{label:"Headers",children:[(0,r.jsx)(mb,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(mp,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(mp,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(mp,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>i(function(e,t){if(t)return{...e,compat:{...e.compat??{},...mv}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(mp,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>i({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(mh,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,r.jsx)(mx,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(ms,{label:"Context window (tokens)",children:(0,r.jsx)(md,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(ms,{label:"Max output tokens",children:(0,r.jsx)(md,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(mh,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(ms,{label:e,children:(0,r.jsx)(md,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void i({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let mw={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function mk({provider:e,onRefresh:t,relogin:n}){let i=n?.onLoginSucceeded,[s,o]=(0,a.useState)({phase:"idle"}),{t:l}=(0,z.s)(),[c,d]=(0,a.useState)(""),u=(0,a.useRef)(null),p=(0,a.useRef)(!1),h=(0,a.useRef)(null),m=(0,a.useRef)(null),f=void 0!==n;(0,a.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,a.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,a.useEffect)(()=>{o({phase:"idle"}),d(""),u.current?.close(),u.current=null},[e.id]),(0,a.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,a.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,d(""),o({phase:"success"}),t(),i?.())},[t,i]),x=(0,a.useCallback)(t=>{u.current?.close(),p.current=!1,o({phase:"connecting"}),d("");let n=void 0!==t,r=n?`?login=${encodeURIComponent(t)}`:"",a=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}${r}`);u.current=a,a.onmessage=e=>{let t=JSON.parse(e.data);if("auth"===t.type)o({phase:"auth",url:t.url,instructions:t.instructions??null,token:t.token,device:n,progress:null}),h_(t.url);else if("device_code"===t.type)o({phase:"device_code",userCode:t.userCode,verificationUri:t.verificationUri,intervalSeconds:t.intervalSeconds??null,expiresInSeconds:t.expiresInSeconds??null}),h_(t.verificationUri);else if("prompt_request"===t.type)o({phase:"prompt",message:t.message,placeholder:t.placeholder??null,token:t.token});else if("select_request"===t.type)o({phase:"select",message:t.message,options:t.options??[],token:t.token});else if("progress"===t.type){let e=t.message;o(t=>"auth"===t.phase&&t.device?{...t,progress:e}:{phase:"progress",message:e})}else"success"===t.type?g():"error"===t.type?(a.close(),o({phase:"error",message:t.message})):"cancelled"===t.type&&(a.close(),o({phase:"idle"}))},a.onerror=()=>{a.close(),o(e=>"success"===e.phase||"auth"===e.phase||"prompt"===e.phase||"select"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,g]),v=(0,a.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),o({phase:"idle"}),t()},[e.id,t]),b=(0,a.useCallback)(async(t,n,r)=>{o({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})}),a=await r.json().catch(()=>({}));if(!r.ok)return void o({phase:"error",message:a.error??`Server error ${r.status}`});if(d(""),"success"===a.state)return void g();u.current?.readyState===EventSource.CLOSED&&o({phase:"error",message:"Connection lost. Start the login again."})}catch(e){o({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id,g]),y=(0,a.useCallback)(async(e,t)=>{t.trim()&&await b(e,t.trim(),"Verifying…")},[b]),w=(0,a.useCallback)(async(e,t)=>{await b(e,t,"Continuing…")},[b]),k="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mh,{children:l("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:l(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),n&&(0,r.jsxs)("div",{role:"note","aria-label":l("relogin.title"),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)"},children:[(0,r.jsx)(av,{seed:n.target.seed,size:32,provider:n.target.provider}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:l("relogin.title")}),(0,r.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[n.target.alias,n.target.masked&&(0,r.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:n.target.masked})]}),n.target.reason&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:n.target.reason})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n?l("relogin.guide",{action:l(e.loggedIn?"i18n.relogin":"i18n.login")}):e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),"auth"===s.phase&&s.device&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:l("i18n.deviceLoginGuide")}),s.instructions&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0,overflowWrap:"anywhere"},children:s.instructions}),(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{fontSize:12,color:"var(--accent)",wordBreak:"break-all"},children:s.url}),s.progress&&(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:s.progress})]}),("auth"===s.phase&&!s.device||"prompt"===s.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===s.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":s.message}),"auth"===s.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:h,value:c,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&y(s.token,c)},placeholder:"auth"===s.phase?"Paste the redirect URL or code":s.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>y(s.token,c),disabled:!c.trim(),style:{padding:"6px 12px",background:c.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:"var(--radius-control)",color:c.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:c.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:l("i18n.submit")})]})]}),"device_code"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(n?(0,r.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("relogin.done")}),n.outcome&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===n.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===n.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:l(mw[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:l("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,r.jsx)("button",{onClick:()=>{u.current?.close(),o({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:l("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:m,onClick:()=>x(),style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"var(--radius-control)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:12,fontWeight:600},children:l(e.loggedIn?"i18n.relogin":"i18n.login")}),e.deviceLoginId&&(0,r.jsx)("button",{onClick:()=>x(e.deviceLoginId),style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",cursor:"pointer",fontSize:12},children:l("i18n.deviceLogin")}),e.loggedIn&&!n&&(0,r.jsx)("button",{onClick:v,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:"pointer",fontSize:12},children:l("i18n.disconnect")})]})})]})}function mj({provider:e,onRefresh:t}){let[n,i]=(0,a.useState)(""),[s,o]=(0,a.useState)(!1),[l,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)(!1),{t:m}=(0,z.s)();(0,a.useEffect)(()=>{i(""),u(null),h(!1)},[e.id]);let f=(0,a.useCallback)(async()=>{if(n.trim()){o(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),a=await r.json();!r.ok||a.error?u(a.error??`HTTP ${r.status}`):(i(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{o(!1)}}},[n,e.id,t]),g=(0,a.useCallback)(async()=>{c(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{c(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(mh,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,r.jsx)(ms,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(mc,{value:n,onChange:i,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:s||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:"var(--radius-control)",color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:s||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":s?"i18n.saving":"i18n.save")]})]})}),d&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:d}),e.configured&&(0,r.jsx)("button",{onClick:g,disabled:l,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:"var(--radius-control)",color:"#ef4444",cursor:l?"not-allowed":"pointer",fontSize:12},children:m(l?"i18n.removing":"i18n.disconnect")})]})}function mS({id:e,size:t}){let n=ma[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:700,lineHeight:1},children:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}let mC={display:"flex",alignItems:"center",width:"100%",borderRadius:"var(--radius-control)",border:"none",cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},mN={padding:"6px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.04em"};function mT({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:i,onAddCustom:s,onClose:o}){let[l,c]=(0,a.useState)(""),{t:d}=(0,z.s)(),u=(0,a.useRef)(null);(0,a.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=l.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+m.length+ +!!f,x={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&o()},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:u,value:l,onChange:e=>c(e.target.value),onKeyDown:e=>{"Escape"===e.key&&o()},placeholder:d("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:d("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{s(),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(mS,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{i(e.id),o()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(mS,{id:e.id,size:28})]},e.id))]})})]})})}function mI({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:i,relogin:s}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,a.useState)({providers:{}}),[u,p]=(0,a.useState)(!0),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[j,S]=(0,a.useState)([]),[C,N]=(0,a.useState)([]),[T,I]=(0,a.useState)(!1),M=(0,a.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),R=(0,a.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>N(e.providers)).catch(()=>{})},[]),E=(0,a.useCallback)(()=>{M(),R()},[M,R]);(0,a.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok||!t||t.error)throw Error(t?.error??`HTTP ${e.status}`);d(t.providers?t:{...t,providers:{}})}).catch(e=>v(e instanceof Error?e.message:String(e))).finally(()=>p(!1)),E()},[E]);let L=(0,a.useCallback)(()=>{let e="new-provider",t=1;for(;c.providers?.[e];)e=`new-provider-${t++}`;d(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),k({type:"provider",name:e})},[c.providers]),$=(0,a.useCallback)((e,t)=>{d(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),P=(0,a.useCallback)((e,t)=>{d(n=>{let r=Object.entries(n.providers??{}),a=r.findIndex(([t])=>t===e);return -1===a?n:(r[a]=[t,r[a][1]],{...n,providers:Object.fromEntries(r)})}),k(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),A=(0,a.useCallback)(e=>{d(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),d(e=>{let t=Object.keys(e.providers??{});return k(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),F=(0,a.useCallback)(e=>{d(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),d(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return k({type:"model",providerName:e,index:n}),t})},[]),_=(0,a.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},a=[...r.models??[]],i=new Set(a.map(e=>e.id));for(let e of t)i.has(e.id)||(i.add(e.id),a.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:a}}}})},[]),W=(0,a.useCallback)((e,t,n)=>{d(r=>{let a=r.providers?.[e]??{},i=[...a.models??[]];return i[t]=n,{...r,providers:{...r.providers??{},[e]:{...a,models:i}}}})},[]),O=(0,a.useCallback)((e,t)=>{d(n=>{let r=n.providers?.[e]??{},a=[...r.models??[]];return a.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:a.length?a:void 0}}}}),k({type:"provider",name:e})},[]),D=(0,a.useCallback)(async()=>{m(!0),g(null),y(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),t=await e.json();!e.ok||t.error?g(t.error??`HTTP ${e.status}`):(y(!0),i?.(),setTimeout(()=>y(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[c,i]),H=Object.entries(c.providers??{}),U=j.filter(e=>e.loggedIn),q=C.filter(e=>e.configured),V=u||null!==x,K=(()=>{if(!w)return null;if("roles"===w.type)return(0,r.jsx)(hF,{cwd:e??null,onRolesChanged:i});if("oauth"===w.type){let e=j.find(e=>e.id===w.providerId);return e?(0,r.jsx)(mk,{provider:e,onRefresh:E,relogin:s?.target.provider===e.id?s:void 0},e.id):null}if("apikey"===w.type){let e=C.find(e=>e.id===w.providerId);return e?(0,r.jsx)(mj,{provider:e,onRefresh:E},e.id):null}if("provider"===w.type){let e=c.providers?.[w.name];return e?(0,r.jsx)(mm,{name:w.name,provider:e,onChange:e=>$(w.name,e),onRename:e=>P(w.name,e),onDelete:()=>A(w.name),onAddModels:e=>_(w.name,e)},w.name):null}let t=c.providers?.[w.providerName],n=t?.models?.[w.index];return n?(0,r.jsx)(my,{providerName:w.providerName,provider:t,model:n,onChange:e=>W(w.providerName,w.index,e),onDelete:()=>O(w.providerName,w.index)},`${w.providerName}-${w.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},...n?{}:{role:"dialog","aria-modal":!0,"aria-label":l("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,r.jsxs)("div",{style:{width:n?"100%":o?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":o?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.jsx)("button",{onClick:t,"aria-label":l("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:o?"100%":210,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.jsxs)("div",{role:"group","aria-labelledby":"models-nav-roles",children:[(0,r.jsx)("div",{id:"models-nav-roles",style:mN,children:l("models.navGroupRoles")}),(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":w?.type==="roles"?"true":void 0,onClick:()=>k({type:"roles"}),style:{...mC,gap:7,padding:"5px 8px",background:w?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{w?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{w?.type!=="roles"&&(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:l("roles.title")})]})]}),(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),(U.length>0||q.length>0)&&(0,r.jsx)("div",{id:"models-nav-accounts",style:mN,children:l("models.navGroupAccounts")}),U.map(e=>{let t=w?.type==="oauth"&&w.providerId===e.id;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"oauth",providerId:e.id}),style:{...mC,gap:7,padding:"5px 8px",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(mS,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),q.map(e=>{let t=w?.type==="apikey"&&w.providerId===e.id;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":t?"true":void 0,onClick:()=>k({type:"apikey",providerId:e.id}),style:{...mC,gap:7,padding:"5px 8px",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(mS,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(U.length>0||q.length>0)&&H.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),!u&&H.length>0&&(0,r.jsx)("div",{style:mN,children:l("models.navGroupCustom")}),u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("i18n.loading")}):H.map(([e,t])=>{let n=w?.type==="provider"&&w.name===e,a=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":n?"true":void 0,onClick:()=>k({type:"provider",name:e}),style:{...mC,gap:6,padding:"7px 8px",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),a.map((t,n)=>{let a=w?.type==="model"&&w.providerName===e&&w.index===n;return(0,r.jsxs)("button",{type:"button",className:"models-nav-row","aria-current":a?"true":void 0,onClick:()=>k({type:"model",providerName:e,index:n}),style:{...mC,gap:6,padding:"5px 8px 5px 26px",background:a?"var(--bg-selected)":"none"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||l("i18n.newModel")}),t.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:"var(--radius-control)",flexShrink:0},children:"T"})]},n)}),(0,r.jsx)("div",{onClick:t=>{t.stopPropagation(),F(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:"var(--radius-control)",cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("span",{style:{fontSize:11},children:["+ ",l("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.jsxs)("button",{onClick:()=>I(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:["+ ",l("i18n.addProvider")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:K??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(x??f)&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:x??f}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:l("i18n.cancel")}),(0,r.jsxs)("button",{onClick:D,disabled:h||b||V,style:{position:"relative",padding:"6px 16px",minWidth:92,background:b?"#16a34a":h||V?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:"var(--radius-control)",color:b?"#fff":h||V?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:V?"not-allowed":h||b?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:b?"saved-pop 0.45s ease":void 0},children:[b&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:b?l("i18n.saved"):h?l("i18n.saving"):l("i18n.save")})]})]})]})}),T&&(0,r.jsx)(mT,{oauthProviders:j,apiKeyProviders:C,onSelectOAuth:e=>k({type:"oauth",providerId:e}),onSelectApiKey:e=>k({type:"apikey",providerId:e}),onAddCustom:L,onClose:()=>I(!1)})]})}function mM(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function mR(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function mE(e){let t=mR(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function mL(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function m$(e){return e?e.slice(0,8):"unknown"}function mP({enabled:e,loading:t,onToggle:n}){let{t:a}=(0,z.s)();return(0,r.jsx)("button",{onClick:n,disabled:t,title:a(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:"var(--seed-radius-full)",border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mA({skill:e,cwd:t,onToggle:n,toggling:a,saveError:i,updateStatus:s,checkingUpdate:o,updating:l,updateError:c,onCheckUpdate:d,onUpdate:u}){let{t:p}=(0,z.s)(),h=mR(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:h}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return mM(e)}(e.filePath)}),(0,r.jsx)(mP,{enabled:m,loading:a,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),i&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:i})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:m$(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)("button",{onClick:d,disabled:o||l,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"none",color:"var(--text-muted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11},children:p("i18n.check")}),s?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:m$(s.latestVersion)}),(o||s&&"update-available"!==s.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:o?"var(--accent)":s?.state==="up-to-date"?"#16a34a":s?.state==="error"?"#ef4444":"var(--text-dim)"},children:o?p("i18n.checking"):s?.state==="up-to-date"?p("i18n.upToDate"):s?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):s?.message||p("i18n.checkFailed")}),s?.state==="update-available"&&(0,r.jsx)("button",{onClick:u,disabled:l||o,style:{padding:"4px 10px",border:"none",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11,fontWeight:600},children:p(l?"i18n.updating":"i18n.update")})]}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:c})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function mF({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:i}){let{t:s}=(0,z.s)(),[o,l]=(0,a.useState)(""),[c,d]=(0,a.useState)([]),[u,p]=(0,a.useState)(!1),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(new Set),[w,k]=(0,a.useState)("global"),j=(0,a.useRef)(null);(0,a.useEffect)(()=>{j.current?.focus()},[]);let S=(0,a.useCallback)(async e=>{if(e.trim()){p(!0),m(null),d([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);d(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,a.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),i()}catch(e){v(String(e))}finally{g(null)}},[i,w,e]),N="global"===w?"~/.claude/skills/":`${mM(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:s("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(o)},placeholder:s("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text)",outline:"none"}}),(0,r.jsx)("button",{onClick:()=>S(o),disabled:u||!o.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:"var(--radius-control)",border:"none",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:u||!o.trim()?"not-allowed":"pointer",opacity:u||!o.trim()?.5:1,flexShrink:0},children:u?s("i18n.searching"):s("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),c.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:c.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),a=f===e.package,i=e.package.indexOf("@"),o=i>-1?e.package.slice(0,i):e.package,l=i>-1?e.package.slice(i+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??o}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!a&&C(e.package),disabled:n||a||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",cursor:n||a||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":a?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${s("i18n.installed")}`:a?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function m_({cwd:e,onClose:t,embedded:n=!1}){let i=B(),{t:s}=(0,z.s)(),[o,l]=(0,a.useState)([]),[c,d]=(0,a.useState)(!0),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(new Set),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)({}),[j,S]=(0,a.useState)(new Set),[C,N]=(0,a.useState)(!1),[T,I]=(0,a.useState)(null),[M,R]=(0,a.useState)(null),[E,L]=(0,a.useState)(!0),[$,P]=(0,a.useState)({}),A=(0,a.useCallback)(async()=>{d(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(l(r),L(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&P(t=>({...t,[mE(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{d(!1)}},[e,h]);(0,a.useEffect)(()=>{k({}),R(null),A()},[e]);let F=(0,a.useCallback)(async t=>{let n=(t?[t]:o.filter(e=>!!e.install)).map(mL).filter(e=>!!e);if(0!==n.length){R(null),S(e=>new Set([...e,...n])),t||N(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){R(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||N(!1)}}},[e,o]),_=(0,a.useCallback)(async t=>{if(!t.install)return;let n=mL(t);I(n),R(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),a=await r.json();if(!r.ok||a.error||!a.success)throw Error(a.error??`HTTP ${r.status}`);await A();let i=a.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:i,latestVersion:i}}))}catch(e){R(e instanceof Error?e.message:String(e))}finally{I(null)}},[e,A]),W=(0,a.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);l(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&P(t=>({...t,[mE(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),O=o.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":i?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":i?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mM(e)})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!E&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:i?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:i?"100%":210,maxHeight:i?"40vh":void 0,borderRight:i?"none":"1px solid var(--border)",borderBottom:i?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===o.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===mR(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===mR(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===mR(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===mR(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===mR(e)}]){let r=o.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,a=!b&&h===e.filePath,i=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:a?"var(--bg-selected)":"none"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{a||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:i?"var(--border)":"var(--accent)",boxShadow:i?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:a?600:400,color:i?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=mL(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:s("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let a=n.filter(e=>!e.disableModelInvocation),i=n.filter(e=>e.disableModelInvocation),o=$[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),a.map(t),i.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>P(t=>({...t,[e]:!o})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:o?"▾":"▸"}),s("i18n.dormant")," (",i.length,")"]}),o&&i.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(mF,{cwd:e,projectResourcesLoaded:E,installedPackages:{global:new Set(o.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(o.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{A()}}):c?null:O?(0,r.jsx)(mA,{skill:O,cwd:e,onToggle:W,toggling:f.has(O.filePath),saveError:x,updateStatus:mL(O)?w[mL(O)]:void 0,checkingUpdate:!!mL(O)&&j.has(mL(O)),updating:T===mL(O),updateError:M,onCheckUpdate:()=>void F(O),onUpdate:()=>void _(O)},O.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[o.some(e=>!!e.install)&&(0,r.jsx)("button",{onClick:()=>void F(),disabled:C||null!==T,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:C||null!==T?"not-allowed":"pointer",opacity:C||null!==T?.5:1,fontSize:12},children:C?s("i18n.checking"):s("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?s("i18n.update"):s("i18n.updates")]})]}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("i18n.close")})]})]})})}let mz="global";function mW(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function mO(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function mD(e){return`${e.scope}\0${e.source}`}function mH(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function mU(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function mB(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function mq({pkg:e}){let{t}=(0,z.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function mV({scope:e}){return(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function mK(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function mG({enabled:e,loading:t,onToggle:n,label:a}){return(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,title:a,"aria-label":a,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:"var(--seed-radius-full)",border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function mJ({installDir:e,source:t,busy:n,actionError:i,onSourceChange:s,onInstall:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null);return(0,a.useEffect)(()=>{c.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:l("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mW(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:c,value:t,onChange:e=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=mO(t);n!==t&&(e.preventDefault(),s(n))},onBlur:e=>s(mO(e.currentTarget.value)),placeholder:"@scope/package or github:user/repo",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!n&&o()}})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,r.jsx)("button",{type:"button",onClick:o,disabled:n||!t.trim(),style:{...mK(n||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:l(n?"i18n.installing":"i18n.install")})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function mZ({pkg:e,cwd:t,busyKey:n,actionError:a,actionMessage:i,sessionId:s,onAction:o,onReloadSession:l}){let{t:c}=(0,z.s)(),d=mD(e),u=n?.endsWith(d)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(mG,{enabled:h,loading:u||p,onToggle:()=>o(e.disabled?"enable":"disable",e),label:c(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(mV,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:c("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:"var(--radius-control)",background:"rgba(245,158,11,0.12)",color:"#d97706"},children:c("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>o("update",e),disabled:u||p,style:mK(u||p),children:c(n===`update:${d}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:l,disabled:!s||p||u,style:mK(!s||p||u),title:c(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:c(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>o("remove",e),disabled:u||p,style:mK(u||p,!0),children:c(n===`remove:${d}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.status")}),(0,r.jsx)("div",{style:{color:mB(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:mU(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??c("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:mH(e,c)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?mW(e.installedPath):c("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:c("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:mW(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:c("i18n.resolvedResources")}),(0,r.jsx)(mq,{pkg:e})]}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:i}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function mY({cwd:e,sessionId:t,onClose:n,onReloaded:i,embedded:s=!1}){let o=B(),{t:l}=(0,z.s)(),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!0),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(!1),[b,y]=(0,a.useState)(""),[w,k]=(0,a.useState)(null),[j,S]=(0,a.useState)(null),[C,N]=(0,a.useState)(null),T=(0,a.useMemo)(()=>c?.packages??[],[c?.packages]),I=T.find(e=>mD(e)===f)??null,M=c?.projectResourcesLoaded??!0,R=(0,a.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:T.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[T]),E=(0,a.useCallback)(async()=>{p(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);d(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>mD(t)===e)?e:n.packages[0]?mD(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,a.useEffect)(()=>{E()},[E]);let L=(0,a.useCallback)(async(t,n)=>{let r=mD(n);k(`${t}:${r}`),S(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),a=await r.json();if(!r.ok||a.error)throw Error(a.error??`HTTP ${r.status}`);if(d(a),"remove"===t)g(a.packages[0]?mD(a.packages[0]):null),0===a.packages.length&&v(!0),N(l("i18n.packageRemoved"));else{let e={install:l("i18n.packageInstalled"),update:l("i18n.packageUpdated"),disable:l("i18n.packageDisabledRestartRequired"),enable:l("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,l]),$=(0,a.useCallback)(async()=>{let t=mO(b).trim();if(!t)return;y(t);let n=`${mz}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let a,i,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:mz,cwd:e})}),o=await s.json();if(!s.ok||o.error)throw Error(o.error??`HTTP ${s.status}`);d(o);let c=(r=o.packages,i=(a=t.trim()).startsWith("npm:")?a.slice(4):a,r.find(e=>e.scope===mz&&e.source===a)??r.find(e=>e.scope===mz&&e.source===`npm:${i}`)??r.find(e=>e.scope===mz&&e.source.endsWith(a)));g(c?mD(c):n),v(!1),y(""),N(l("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,l]),P=(0,a.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await uq(t,{type:"reload"}),i?.(),await E(),N(l("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,i,t,l]),A=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:s?"100%":o?"calc(100vw - 16px)":860,maxWidth:s?"none":"calc(100vw - 16px)",height:s?"100%":o?"calc(100dvh - 16px)":"76vh",maxHeight:s?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:s?"none":"1px solid var(--border)",borderRadius:8*!s,display:"flex",flexDirection:"column",boxShadow:s?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mW(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:l("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:o?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:o?"100%":245,maxHeight:o?"40vh":void 0,borderRight:o?"none":"1px solid var(--border)",borderBottom:o?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===T.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):R.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=mD(e),n=!x&&f===t;return(0,r.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:"var(--radius-control)",cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:mB(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mH(e,l)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:mU(e,l)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("button",{type:"button",onClick:()=>{v(!0),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:"var(--radius-control)",border:"none",width:"100%",cursor:"pointer",background:x?"var(--bg-selected)":"none",color:x?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{x||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{x||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),l("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(mJ,{installDir:c?.installDir,source:b,busy:A,actionError:j,onSourceChange:y,onInstall:$}):u?null:I?(0,r.jsx)(mZ,{pkg:I,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:P},mD(I)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:c?.diagnostics.length?(0,r.jsxs)("span",{title:c.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:c.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[c.diagnostics.length," diagnostic",1===c.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:c?`${c.totals.extensions} ext \xb7 ${c.totals.skills} skills \xb7 ${c.totals.prompts} prompts \xb7 ${c.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:mK(u||null!==w),children:l("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:mK(!1),children:l("i18n.close")})]})]})})}var mX=n(13004),mQ=n.n(mX);function m0(){let[e,t]=(0,a.useState)(null),[n,i]=(0,a.useState)(null),[s,o]=(0,a.useState)(null),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1),[p,h]=(0,a.useState)(""),[m,f]=(0,a.useState)(""),g=(0,a.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),i(null)}catch(e){i(e instanceof Error?e.message:String(e))}},[]);(0,a.useEffect)(()=>{g()},[g]);let x=(0,a.useCallback)(async(e,n={})=>{u(!0),o(null),c(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),a=await r.json();if(!r.ok||a.error)throw Error(a.error??`HTTP ${r.status}`);return t(a),a}catch(e){return o(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,a.useCallback)(async()=>{if(p!==m)return void o("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),f(""),c(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[m,p,x]),b=(0,a.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&c(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,a.useCallback)(async()=>{await x("clear")&&c("The stored password was removed and password access is off.")},[x]);if(!e)return(0,r.jsx)("div",{className:mQ().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!d&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:mQ().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,r.jsxs)("div",{className:mQ().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),l&&(0,r.jsx)("div",{className:mQ().reloadNotice,children:(0,r.jsx)("span",{children:l})})]}),(0,r.jsxs)("div",{className:mQ().settingsBody,children:[(0,r.jsxs)("section",{className:mQ().group,children:[(0,r.jsx)("h3",{className:mQ().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:mQ().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!e.configured&&!w&&(0,r.jsx)("div",{className:mQ().settingDescription,children:"Set a password below before turning this on."}),s&&(0,r.jsx)("div",{className:mQ().error,children:s})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("button",{type:"button",className:mQ().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:d||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,r.jsxs)("section",{className:mQ().group,children:[(0,r.jsx)("h3",{className:mQ().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:mQ().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("input",{className:mQ().textInput,type:"password",autoComplete:"new-password",value:p,disabled:d||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:mQ().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("input",{className:mQ().textInput,type:"password",autoComplete:"new-password",value:m,disabled:d||w,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,r.jsxs)("div",{className:mQ().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:mQ().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:mQ().dangerButton,disabled:d,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:mQ().primaryButton,disabled:!k,onClick:()=>void v(),children:d?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:mQ().group,children:[(0,r.jsx)("h3",{className:mQ().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:mQ().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("a",{className:mQ().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:mQ().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,r.jsx)("div",{className:mQ().settingControl})]})]})]})]})}let m1="/api/live/voices";function m2(){let{t:e}=(0,z.s)(),[t,n]=(0,a.useState)(null),[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(null),c=(0,a.useCallback)(async()=>{try{let e=await fetch(m1,{cache:"no-store"}),t=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(t.voices)||"string"!=typeof t.defaultVoice)throw Error(`HTTP ${e.status}`);let r=dt.includes(t.pace)?t.pace:"normal";n({voices:t.voices,defaultVoice:t.defaultVoice,pace:r})}catch(e){l(e instanceof Error?e.message:String(e))}},[]);(0,a.useEffect)(()=>{c()},[c]);let d=async e=>{s(!0),l(null);try{let t=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"live.voice",value:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let a="string"==typeof r.value?r.value:e;n(e=>e?{...e,defaultVoice:a}:e)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(!1)}},u=async e=>{s(!0),l(null);try{let t=await fetch(m1,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({pace:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);n(t=>t?{...t,pace:r.pace??e}:t)}catch(e){l(e instanceof Error?e.message:String(e))}finally{s(!1)}};return t?(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:mQ().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsx)("div",{className:mQ().settingsBody,children:(0,r.jsxs)("section",{className:mQ().group,children:[(0,r.jsx)("h3",{className:mQ().groupTitle,children:e("chat.liveVoiceSpeakerGroup")}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:e("chat.liveVoiceCodexLabel")}),(0,r.jsx)("div",{className:mQ().settingDescription,children:e("chat.liveVoiceCodexHelp")}),o&&(0,r.jsx)("div",{className:mQ().error,role:"alert",style:{overflowWrap:"anywhere"},children:o})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)(hL,{value:t.defaultVoice,disabled:i,ariaLabel:e("chat.liveVoiceCodexLabel"),options:t.voices,onChange:e=>{e!==t.defaultVoice&&d(e)}})})]}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:e("chat.livePaceLabel")}),(0,r.jsx)("div",{className:mQ().settingDescription,children:e("chat.livePaceHelp")})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)(hL,{value:t.pace,disabled:i,ariaLabel:e("chat.livePaceLabel"),options:[{value:"normal",label:e("chat.livePaceNormal")},{value:"slow",label:e("chat.livePaceSlow")}],onChange:e=>{e!==t.pace&&dt.includes(e)&&u(e)}})})]})]})})]}):(0,r.jsx)("div",{className:mQ().empty,children:o?`${e("chat.liveVoiceLoadFailed")}: ${o}`:"…"})}function m8(){let{t:e}=(0,z.s)(),t=(0,a.useId)(),n=(0,a.useId)(),[i,s]=(0,a.useState)(null),[o,l]=(0,a.useState)(""),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1),[h,m]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=new AbortController;return dY({signal:e.signal}).then(e=>{s(e),l(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||d(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let f=(0,a.useCallback)(async e=>{p(!0),d(null),m(!1);try{let t=await dX(e);s(t),l(String(t.uploadLimitMb)),m(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return i?(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:mQ().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:mQ().settingsBody,children:(0,r.jsxs)("section",{className:mQ().group,children:[(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:mQ().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:mQ().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("input",{id:t,className:mQ().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:o,disabled:u,onChange:e=>l(e.target.value),onBlur:()=>{let t=o.trim();if(t===String(i.uploadLimitMb))return;let n=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n<1){m(!1),d(e("chat.attachmentUploadLimitInvalid"));return}f({uploadLimitMb:n})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:mQ().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:mQ().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:i.orphanGraceDays})})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("button",{type:"button",className:mQ().switch,"data-on":i.autoCleanupEnabled,"aria-pressed":i.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!i.autoCleanupEnabled})})})]}),c&&(0,r.jsx)("div",{className:mQ().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),h&&!c&&(0,r.jsx)("div",{className:mQ().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:mQ().empty,children:c?`${e("chat.attachmentSettingsLoadFailed")}: ${c}`:"…"})}function m4(){let{t:e}=(0,z.s)(),t=(0,a.useId)(),n=af(),[i,s]=(0,a.useState)(!1),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(!1);(0,a.useEffect)(()=>{rR().then(()=>s(!0))},[]);let h=(0,a.useCallback)(async e=>{l(!0),d(null),p(!1);try{let t=await fetch("/api/character-mode",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:e})}),n=await t.json().catch(()=>null);if(!t.ok)throw Error("object"==typeof n&&null!==n&&"error"in n?String(n.error):`HTTP ${t.status}`);rT(n),p(!0)}catch(e){d(e instanceof Error?e.message:String(e))}finally{l(!1)}},[]);if(!i)return(0,r.jsx)("div",{className:mQ().empty,children:"…"});let m=[{mode:"default",label:e("characterMode.default")},{mode:"office",label:e("characterMode.office")}];return(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:e("characterMode.title")}),(0,r.jsx)("p",{className:mQ().contentDescription,children:e("characterMode.description")})]}),(0,r.jsx)("div",{className:mQ().settingsBody,children:(0,r.jsxs)("section",{className:mQ().group,children:[(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:t,className:mQ().settingLabel,children:e("characterMode.label")}),(0,r.jsx)("div",{className:mQ().settingDescription,children:e("characterMode.help")})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("div",{className:mQ().multiSelect,role:"radiogroup","aria-labelledby":t,children:m.map(e=>(0,r.jsx)("span",{className:mQ().choice,"data-selected":n.mode===e.mode,children:(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":n.mode===e.mode,className:mQ().choiceToggle,disabled:o,onClick:()=>{n.mode!==e.mode&&h(e.mode)},children:e.label})},e.mode))})})]}),"office"===n.mode&&!n.rosterAvailable&&(0,r.jsx)("div",{className:mQ().settingDescription,role:"status",children:e("characterMode.noRoster")}),c&&(0,r.jsx)("div",{className:mQ().error,role:"alert",style:{overflowWrap:"anywhere"},children:c}),u&&!c&&(0,r.jsx)("div",{className:mQ().saveState,role:"status",children:e("characterMode.saved")})]})})]})}function m5({cwd:e}){let{t}=(0,z.s)(),[n,i]=(0,a.useState)(null),[s,o]=(0,a.useState)(null),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)({}),[m,f]=(0,a.useState)(null),[g,x]=(0,a.useState)(null),v=(0,a.useRef)(new Map);(0,a.useEffect)(()=>{g&&d!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[d,n,g]);let b=(0,a.useRef)(0),y=(0,a.useRef)(null),w=(0,a.useRef)(null),k=(0,a.useRef)(!1),j=(0,a.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let a=e?`?include=${encodeURIComponent(e)}`:"",s=await fetch(`/api/project-trust${a}`,{cache:"no-store",signal:r.signal}),l=await s.json();if(n!==b.current||r.signal.aborted)return;if(!s.ok||!l.projects)throw Error(l.error??`HTTP ${s.status}`);let c=l.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=l.projects,i(l.projects),o(null),c&&f({cwd:c.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;o(e instanceof Error?e.message:String(e))}finally{y.current===r&&(y.current=null)}},[e,t]);(0,a.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=n?.some(e=>null!==e.pending)??!1;(0,a.useEffect)(()=>{let e;if(!S||null!==d||null!==l)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},n=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",n),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[d,l,n,S,j]);let C=(0,a.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),c(null),x(e),f(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),a=await r.json();if(!r.ok)throw Error(a.error??`HTTP ${r.status}`);let s=w.current?.map(t=>t.cwd===e?{...a,cwd:e}:t)??null;w.current=s,i(s),"cancel"===n?f({cwd:e,text:t("trust.doneCancelled")}):a.error||null!==a.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(n=>({...n,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!n)return(0,r.jsxs)("div",{className:mQ().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,r.jsx)("button",{type:"button",className:mQ().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==d;return(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:mQ().contentDescription,children:t("trust.settingsDescription")}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,r.jsx)("button",{type:"button",className:mQ().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,r.jsx)("div",{className:mQ().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,r.jsx)("div",{className:mQ().settingsBody,children:(0,r.jsxs)("section",{className:mQ().group,children:[0===n.length&&(0,r.jsx)("div",{className:mQ().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let a=d===e.cwd,i=l?.cwd===e.cwd?l:null,s=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),o=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:mQ().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:mQ().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,r.jsx)("span",{children:(n=e.cwd).split(/[\\/]/).filter(Boolean).pop()??n}),(0,r.jsx)("span",{className:mQ().settingDescription,style:{fontWeight:600},children:s})]}),(0,r.jsx)("code",{className:mQ().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:mQ().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,r.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,r.jsx)("div",{className:mQ().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:mQ().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),i&&(0,r.jsx)("div",{className:mQ().settingDescription,style:{color:"var(--text)"},children:"revoke"===i.action?t("trust.confirmRevoke"):i.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:mQ().saveState,children:m.text})]}),o&&(0,r.jsx)("div",{className:mQ().error,role:"alert",children:o})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:mQ().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:i?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:mQ().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{c(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===i.action?mQ().dangerButton:mQ().primaryButton,disabled:N,onClick:()=>void C(e.cwd,i.action),children:"revoke"===i.action?t("trust.revoke"):t("trust.confirm")})]}):a?(0,r.jsx)("button",{type:"button",className:mQ().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:mQ().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,r.jsx)("button",{type:"button",className:mQ().primaryButton,disabled:N,onClick:()=>c({cwd:e.cwd,action:"grant",again:"revoke"===e.pending}),children:"revoke"===e.pending?t("trust.trustAgain"):t("trust.trustProject")}),e.trusted&&(0,r.jsx)("button",{type:"button",className:mQ().dangerButton,disabled:N,onClick:()=>c({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let m6="cuelo-look",m3="cuelo-look-wallpaper",m7="data-cuelo-look",m9="data-cuelo-wallpaper";function fe(e){try{return localStorage.getItem(e)}catch{return null}}function ft(e,t){try{return null===t?localStorage.removeItem(e):localStorage.setItem(e,t),!0}catch{return!1}}function fn(e,t){let n=document.documentElement;e?n.setAttribute(m7,"graphite"):n.removeAttribute(m7),e&&t?n.setAttribute(m9,t):n.removeAttribute(m9)}let fr=new Set,fa=null,fi=null;function fs(){return fa??"graphite"===fe(m6)}function fo(e){let t;fa=ft(m6,e?"graphite":null)?null:e,fn(e,fi??("default"===(t=fe(m3))||"office"===t?t:null)),fr.forEach(e=>e())}function fl(e){let t="office"===e?"office":"default";fi=ft(m3,t)?null:t,fn(fs(),t)}function fc(e){return fr.add(e),()=>{fr.delete(e)}}let fd=JSON.parse('{"tabs":{"appearance":"외관","model":"모델 동작","interaction":"상호작용","context":"컨텍스트","memory":"메모리","files":"파일","shell":"셸","tools":"도구","tasks":"작업","providers":"제공자"},"groups":{"Theme":"테마","Status Line":"상태 표시줄","Display":"표시","Images":"이미지","Thinking":"사고","Sampling":"샘플링","Prompt":"프롬프트","Retry & Fallback":"재시도 및 폴백","Advisor":"어드바이저","Prewalk":"Prewalk","Vision":"비전","Input":"입력","Approvals":"승인","Notifications":"알림","Speech":"음성","Collab":"협업","Magic Keywords":"매직 키워드","Startup & Updates":"시작 및 업데이트","Power (macOS)":"전원 (macOS)","Agent":"에이전트","Git":"Git","General":"일반","Compaction":"압축","Rules (TTSR)":"규칙 (TTSR)","Experimental":"실험적 기능","Auto-Learn":"자동 학습","Mnemopi":"Mnemopi","Hindsight":"Hindsight","Editing":"편집","Reading":"읽기","Read Summaries":"읽기 요약","LSP":"LSP","Bash":"Bash","Eval & Runtimes":"평가 및 런타임","Available Tools":"사용 가능한 도구","Todos":"할 일","Grep & Browser":"Grep 및 브라우저","Computer":"컴퓨터","GitHub":"GitHub","Output Limits":"출력 제한","Execution":"실행","Discovery & MCP":"탐색 및 MCP","Developer":"개발자","Modes":"모드","Subagents":"서브에이전트","Isolation":"격리","Commands & Skills":"명령 및 스킬","Services":"서비스","Fireworks":"Fireworks","Tiny Model":"Tiny Model","Protocol":"프로토콜","Timeouts":"타임아웃","Privacy":"개인정보"},"shell":{"Loading omp settings…":"omp 설정을 불러오는 중…","Settings unavailable":"설정을 사용할 수 없음","Matching canonical /settings entries across every category.":"모든 카테고리에서 표준 /settings 항목을 일치시킨다.","Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.":"표준 omp /settings 값이다. 변경 사항은 공유 에이전트 설정에 즉시 저장된다.","Saved. Reload the active session to apply runtime settings.":"저장됨. 런타임 설정을 적용하려면 활성 세션을 다시 불러온다.","Reloading…":"다시 불러오는 중…","Reload session":"세션 다시 불러오기","No settings match this search.":"이 검색과 일치하는 설정이 없다.","Search /settings":"/settings 검색","Configuration":"구성","OMP settings":"OMP 설정","Close settings":"설정 닫기","Global configuration":"전역 구성","Settings":"설정","Search":"검색","Models & accounts":"모델\xb7계정","Access":"접속 암호","Themes":"테마","Skills":"스킬","Plugins":"플러그인","MCP":"MCP","Loading themes…":"테마를 불러오는 중…","Themes unavailable":"테마를 사용할 수 없음","Active on web":"웹에서 활성","Preview ":"미리보기 ","The web interface uses the same dark and light theme mappings as omp. Changes are persisted to ":"웹 인터페이스는 omp와 동일한 다크 및 라이트 테마 매핑을 사용한다. 변경 사항은 다음에 저장된다: "," and applied here immediately.":" 그리고 여기에 즉시 적용된다."," mapping":" 매핑","requires a project":"프로젝트가 필요하다"},"fields":{"theme.dark":{"label":"다크 테마","description":"터미널 배경이 어두울 때 사용하는 테마이다"},"theme.light":{"label":"라이트 테마","description":"터미널 배경이 밝을 때 사용하는 테마이다"},"symbolPreset":{"label":"심볼 프리셋","description":"아이콘과 기호에 사용하는 글리프 세트이다 (Unicode, Nerd Font, ASCII)"},"colorBlindMode":{"label":"색맹 모드","description":"diff 추가 표시에 초록색 대신 파란색을 사용한다"},"statusLine.preset":{"label":"상태 표시줄 프리셋","description":"미리 구성된 상태 표시줄 설정이다"},"statusLine.separator":{"label":"상태 표시줄 구분자","description":"세그먼트 사이 구분자의 스타일이다"},"statusLine.sessionAccent":{"label":"세션 강조색","description":"에디터 테두리와 상태 표시줄 여백에 세션 이름 색상을 사용한다"},"statusLine.transparent":{"label":"투명 상태 표시줄","description":"상태 표시줄에 테마의 `statusLineBg` 대신 터미널 기본 배경을 사용한다. Powerline 끝 캡은 주변 터미널로 이어지려면 대비되는 채움색이 필요하므로 제거된다."},"statusLine.compactThinkingLevel":{"label":"간결한 thinking 레벨","description":"thinking 레벨을 별도의 ` \xb7 <level>` 접미사 대신 모델 이름에 아이콘 하나로 표시한다."},"statusLine.showHookStatus":{"label":"hook 상태 표시","description":"상태 표시줄 아래에 hook 상태 메시지를 표시한다"},"terminal.showImages":{"label":"인라인 이미지 표시","description":"터미널에 이미지를 인라인으로 렌더링한다"},"images.autoResize":{"label":"이미지 자동 크기 조정","description":"모델 호환성을 높이기 위해 큰 이미지를 최대 2000x2000으로 축소한다"},"images.blockImages":{"label":"이미지 차단","description":"이미지가 LLM 제공자에게 전송되지 않도록 한다"},"terminal.showProgress":{"label":"네이티브 터미널 진행 표시","description":"에이전트나 컨텍스트 유지 작업이 실행되는 동안 OSC 9;4 부정형 진행 표시를 내보낸다"},"tui.textSizing":{"label":"큰 제목 (Kitty)","description":"Kitty의 OSC 66 text-sizing 프로토콜을 사용해 Markdown H1 제목을 2배 크기로 렌더링한다. Kitty 터미널에서만 적용되며 그 외에서는 무시된다. 기본값은 꺼짐이다."},"tui.renderMermaid":{"label":"Mermaid 다이어그램 렌더링","description":"Mermaid 코드 블록을 ASCII 다이어그램으로 렌더링한다"},"tui.codexResetFireworks":{"label":"Codex 리셋 불꽃놀이","description":"예정에 없던 Codex 주간 사용량 리셋과 새로 적립된 저장 리셋을 화면 상단 1/3의 불꽃놀이 오버레이로 축하하며, Escape를 누를 때까지 유지된다"},"tui.titleState":{"label":"터미널 제목 실행 상태","description":"터미널 제목의 구분자에 에이전트 실행 상태를 표시한다 — 작업 중에는 애니메이션 스피너(Windows에서는 고정된 \':\'), 사용자 차례일 때는 \'>\', 에이전트가 사용자를 기다릴 때는 \'!\'이다"},"tui.hyperlinks":{"label":"터미널 하이퍼링크","description":"터미널 자체의 클릭 열기를 위해 경로와 URL을 OSC 8 하이퍼링크로 감싼다 (auto: 지원 여부 감지, off: 사용 안 함, always: 무조건 사용)"},"tui.tight":{"label":"조밀한 레이아웃","description":"터미널 출력 좌우의 1문자 가로 여백을 제거한다"},"tui.scrollbackRebuild":{"label":"스크롤백 다시 쓰기","description":"블록의 최종 형태가 실시간 미리보기를 대체할 때 터미널 스크롤백을 지우고 다시 출력한다. 꺼짐(기본값)일 때는 오래된 미리보기 사본이 기록에 남고 최종 내용이 그 아래에 추가된다."},"display.shimmer":{"label":"셔머","description":"작업/로딩 메시지의 애니메이션 스타일이다"},"display.smoothStreaming":{"label":"부드러운 스트리밍","description":"청크가 도착하는 동안 어시스턴트 텍스트와 스트리밍되는 도구 입력을 부드럽게 표시한다"},"display.hideToolActivity":{"label":"도구 활동 숨김","description":"모델이 시작한 도구 호출과 결과를 대화 기록에서 숨긴다"},"display.showTokenUsage":{"label":"토큰 사용량 표시","description":"어시스턴트 메시지에 턴별 토큰 사용량을 표시한다"},"display.cacheMissMarker":{"label":"캐시 미스 표시","description":"요청이 프롬프트 캐시를 놓친(miss) 어시스턴트 턴 위에 구분선을 표시한다"},"display.collapseCompacted":{"label":"압축 히스토리 접기","description":"라이브 트랜스크립트에서 compaction 이전 히스토리를 요약 구분선 뒤로 접는다. 비활성화하면 각 compaction 지점에 구분선을 둔 채 전체 트랜스크립트를 인라인으로 유지한다"},"showHardwareCursor":{"label":"하드웨어 커서 표시","description":"IME 지원을 위해 터미널 커서를 표시한다"},"tui.imeSafeCursor":{"label":"IME 안전 프롬프트 레이아웃","description":"macOS IME preedit가 프롬프트 하단 테두리를 밀어내지 못하도록 테두리를 별도 행으로 옮긴다"},"task.showResolvedModelBadge":{"label":"확정 모델 배지 표시","description":"task 위젯 상태줄에 각 subagent가 실제로 사용한 모델 ID를 표시한다"},"advisor.enabled":{"label":"Advisor 활성화","description":"\'advisor\' 역할에 배정된 두 번째 모델을 함께 두어 각 턴을 수동적으로 검토하고 메모를 주입한다."},"prewalk.enabled":{"label":"Prewalk 활성화","description":"활성 모델로 시작한 뒤, plan nudge의 todo 목록이 생성된 이후 첫 edit/write 시점에 빠르고 저렴한 모델(기본값은 \'smol\' 역할)로 전환한다 — 강한 모델이 계획하고 todo를 확정하며 구현을 시작한 후 인계한다. 세션별로 --prewalk / --no-prewalk로 재정의할 수 있다."},"advisor.syncBacklog":{"label":"Advisor 동기화 백로그","description":"advisor가 이 턴 수만큼 뒤처지면 메인 에이전트를 최대 30초 동안 멈춘다. Off로 두면 따라잡기 지연을 비활성화한다."},"advisor.immuneTurns":{"label":"Advisor 면역 턴","description":"advisor의 concern 또는 blocker가 한 번 인터럽트한 뒤에는, 이 primary 턴 수 동안 이후 concern/blocker를 인터럽트 없이 전달한다."},"modelRoleStorage":{"label":"모델 역할 저장소","description":"모델 선택기의 역할 배정이 저장되는 위치이다"},"images.describeForTextModels":{"label":"텍스트 모델용 이미지 설명","description":"vision을 지원하지 않는 모델에 이미지가 첨부되면, 이미지를 버리지 않고 local:// 아래에 저장한 뒤 vision 지원 모델이 만든 설명을 주입한다"},"defaultThinkingLevel":{"label":"Thinking 레벨","description":"thinking을 지원하는 모델의 추론 깊이이다"},"hideThinkingBlock":{"label":"Thinking 블록 숨김","description":"어시스턴트 응답에서 thinking 블록을 숨긴다"},"proseOnlyThinking":{"label":"산문 전용 Thinking","description":"thinking 요약에서 코드 블록을 제외하고 생략 부호로 대체한다"},"omitThinking":{"label":"Thinking 요약 생략","description":"응답에서 thinking 요약을 완전히 생략하도록 업스트림 provider에 지시한다(지원되는 경우)"},"externalThinking":{"label":"외부 Thinking","description":"사용자에게 표시되지 않는 비공개 스크래치패드이다. 지원되는 GPT, Claude, Gemini의 reasoning을 비활성화한다"},"model.loopGuard.enabled":{"label":"Loop Guard","description":"모델 reasoning과 산문에 대한 자동 스트림 루프 감지를 활성화한다"},"model.loopGuard.checkAssistantContent":{"label":"Loop Guard 산문 검사","description":"thinking 로그 외에 어시스턴트 산문 메시지에도 loop guard를 적용한다"},"model.loopGuard.toolCallReminder":{"label":"Loop Guard 도구 호출 알림","description":"Gemini reasoning 스트림이 도구를 호출하지 않고 계획 헤더를 연속으로 다수 출력하면 중단하고 도구 호출을 요구하는 알림을 주입한다(Loop Guard 필요)"},"model.toolCallLoopGuard.enabled":{"label":"도구 호출 Loop Guard","description":"여러 턴에 걸친 동일한 연속 도구 호출을 감지하고 교정용 steer를 주입한다"},"inlineToolDescriptors":{"label":"인라인 도구 디스크립터","description":"시스템 프롬프트에 전체 도구 디스크립터를 렌더링하고 provider 도구 스키마에서 최상위/중첩 description을 제거해 디스크립터 텍스트를 한 번만 전송한다. Auto는 Gemini 모델에서 이를 활성화하고 그 외에는 비활성화한다"},"includeModelInPrompt":{"label":"프롬프트에 모델 포함","description":"에이전트가 자신이 어떤 모델인지 알 수 있도록 시스템 프롬프트에 활성 모델 식별자를 노출한다"},"includeWorkspaceTree":{"label":"워크스페이스 트리 포함","description":"시스템 프롬프트에 워크스페이스 디렉터리 트리를 렌더링한다. 경고: 파일이 수정되면 세션 간 프롬프트 캐싱이 깨질 수 있다."},"personality":{"label":"성격","description":"시스템 프롬프트의 personality 블록에 렌더링되는 의사소통 스타일이다"},"temperature":{"label":"Temperature","description":"샘플링 temperature이다(0 = 결정적, 1 = 창의적, -1 = provider 기본값)"},"topP":{"label":"Top P","description":"Nucleus 샘플링 컷오프이다(0-1, -1 = provider 기본값)"},"topK":{"label":"Top K","description":"상위 K개 토큰에서 샘플링한다(-1 = provider 기본값)"},"minP":{"label":"Min P","description":"최소 확률 임계값 (0-1, -1 = provider 기본값)"},"presencePenalty":{"label":"Presence Penalty","description":"이미 등장한 토큰을 도입하는 데 대한 페널티 (-1 = provider 기본값)"},"repetitionPenalty":{"label":"Repetition Penalty","description":"반복된 토큰에 대한 페널티 (-1 = provider 기본값)"},"textVerbosity":{"label":"텍스트 상세도","description":"OpenAI Responses 및 Codex 응답의 상세도 (low, medium, high)"},"tier.openai":{"label":"서비스 티어 — OpenAI","description":"OpenAI / OpenAI-Codex 요청 및 OpenRouter를 경유하는 OpenAI 계열 모델의 처리 티어 (none = 생략). `service_tier`로 전송한다."},"tier.anthropic":{"label":"서비스 티어 — Anthropic","description":"Claude 요청의 처리 티어. `priority`는 지원되는 직접 Anthropic 모델에서 fast 모드(`speed: \\"fast\\"`)를 활성화하며, Bedrock/Vertex Claude 및 OpenRouter 경유에서는 무시된다."},"tier.google":{"label":"서비스 티어 — Google","description":"Gemini(Google AI Studio + Vertex) 요청 및 OpenRouter를 경유하는 Google 계열 모델의 처리 티어 (none = 생략). 최상위 `serviceTier` 필드로 전송한다."},"tier.subagent":{"label":"서비스 티어 — 서브에이전트","description":"생성된 task/eval 서브에이전트의 서비스 티어. Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다(/fast를 추적한다). 값을 지정하면 서브에이전트 모델이 속한 계열에 그 값을 적용한다."},"tier.advisor":{"label":"서비스 티어 — Advisor","description":"advisor 모델의 서비스 티어. None = 표준 처리, Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다. 값을 지정하면 advisor 모델의 계열에 그 값을 적용한다."},"retry.maxRetries":{"label":"재시도 횟수","description":"API 오류 시 최대 재시도 횟수"},"retry.modelFallback":{"label":"재시도 모델 폴백","description":"재시도 복구 시 설정된 폴백 모델로 전환하도록 허용한다"},"retry.usageAwareFallback":{"label":"사용량 인식 폴백","description":"신뢰할 수 있는 coding-plan 할당량 보고를 활용해, 하드 사용량 한도에 도달하기 전에 동일 provider 계정을 먼저 사용하고 그다음 설정된 폴백 모델을 사용한다. 일반 설정 API 키는 제외한다."},"retry.usageReservePct":{"label":"예비 마진","description":"남은 비율이 이 값 미만이면 coding-plan 모델이 한도에 근접한 것으로 간주한다. 사용량을 알 수 없거나 매핑되지 않은 경우 주 모델을 유지한다."},"retry.usageReservePolicy":{"label":"예비 정책","description":"동일 provider의 모든 coding-plan 계정이 예비 마진 안에 들어왔을 때의 동작이다."},"retry.fallbackChains":{"label":"재시도 폴백 체인","description":"모델 역할, 모델 선택자(\\"provider/model-id\\"), 또는 provider 와일드카드(\\"provider/*\\")를 순서가 있는 폴백 선택자에 매핑하는 JSON 객체이다. 예: {\\"default\\":[\\"openai/gpt-4o-mini\\"],\\"google-antigravity/*\\":[\\"google/*\\",\\"google-vertex/*\\"]}. 모델 지향 키는 역할과 무관하게 해당 모델/provider가 활성일 때마다 적용되며, \\"provider/*\\" 항목은 실패한 모델의 id를 유지한 채 provider만 교체한다. id 접두사 와일드카드(\\"openrouter/google/*\\")는 실패한 모델의 순수 id에 접두사를 다시 붙이고(google-antigravity/gemini-x -> openrouter/google/gemini-x), 키로 사용될 때는 해당 접두사 아래의 그 provider id에만 매칭된다."},"retry.fallbackRevertPolicy":{"label":"폴백 복귀 정책","description":"폴백 이후 주 모델로 되돌아가는 시점이다"},"providers.anthropic.serverSideFallback":{"label":"Anthropic 서버 사이드 폴백 (Fable 5)","description":"Claude Fable 5 / Mythos 5 요청이 Anthropic의 안전 분류기에 의해 차단되면 서버 사이드에서 Claude Opus 4.8로 재시도한다(Anthropic `server-side-fallback-2026-06-01` 베타). 옵트인 방식이며, 끄면 모든 요청에 대해 폴백 이전 동작이 유지된다."},"providers.autoThinkingModel":{"label":"Auto Thinking 모델","description":"`auto` thinking 레벨의 난이도 분류기이다. 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 사용할 수 있다"},"providers.autoThinkingMaxEffort":{"label":"Auto Thinking 상한","description":"`auto` 분류기가 도달할 수 있는 최고 effort이다. `xhigh`는 분류기를 최상위보다 한 단계 아래로 유지해 명시적인 `ultrathink`만 `max`에 도달하게 하며, `max`는 분류기가 예외적이라고 판단한 턴이 이를 노출하는 모델에서 최상위 티어로 과금되도록 허용한다."},"autoResume":{"label":"자동 재개","description":"현재 디렉터리의 가장 최근 세션을 자동으로 재개한다"},"power.sleepPrevention":{"label":"절전 방지","description":"활성 세션 동안 macOS 절전을 방지한다. 각 레벨은 누적되며, 하위 레벨의 플래그를 모두 포함한다."},"git.enabled":{"label":"Git 통합 활성화","description":"TUI에 git 브랜치, 상태, PR 정보를 표시하고 저장소 메타데이터를 감시한다."},"steeringMode":{"label":"Steering 모드","description":"에이전트가 작업하는 동안 대기 중인 메시지를 처리하는 방식이다"},"followUpMode":{"label":"후속 메시지 모드","description":"턴이 완료된 후 후속 메시지를 처리하는 방식이다"},"interruptMode":{"label":"인터럽트 모드","description":"steering 메시지가 도구 실행을 중단하는 시점이다"},"loop.mode":{"label":"Loop 모드","description":"/loop 반복 사이에 프롬프트를 다시 제출하기 전에 일어나는 동작이다"},"doubleEscapeAction":{"label":"이중 Escape 동작","description":"편집기가 비어 있는 상태에서 Escape를 두 번 누를 때의 동작이다"},"treeFilterMode":{"label":"세션 트리 필터","description":"세션 트리를 열 때의 기본 필터 모드이다"},"autocompleteMaxVisible":{"label":"자동완성 항목 수","description":"자동완성 드롭다운에 표시되는 최대 항목 수이다 (3-20)"},"emojiAutocomplete":{"label":"이모지 자동완성","description":"`:name:` 숏코드로 이모지를 제안하고 `:D` 또는 `:-)` 같은 텍스트 이모티콘을 확장한다"},"paste.largeMenuThreshold":{"label":"대용량 붙여넣기 메뉴","description":"붙여넣기가 이 줄 수에 도달하면 코드 블록으로 감싸기, XML 태그로 감싸기, 파일로 저장하기 메뉴를 제공한다. 0은 메뉴를 비활성화한다(대용량 붙여넣기는 여전히 [Paste] 마커로 축약된다)."},"startup.quiet":{"label":"조용한 시작","description":"환영 화면과 시작 상태 메시지를 건너뛴다"},"startup.showSplash":{"label":"시작 스플래시 표시","description":"설정을 다시 실행하지 않고 일반 대화형 시작 시 전체 애니메이션 설정 스플래시를 표시한다. 조용한 시작은 여전히 이를 억제한다."},"startup.setupWizard":{"label":"설정 위저드","description":"새로 추가된 온보딩 단계를 설정 버전마다 한 번 표시한다"},"startup.checkUpdate":{"label":"업데이트 확인","description":"시작 시 omp 업데이트를 확인한다"},"marketplace.autoUpdate":{"label":"마켓플레이스 자동 업데이트","description":"시작 시 플러그인 업데이트를 확인한다"},"startup.changelogMode":{"label":"시작 변경 내역","description":"업데이트 노트를 요약으로 시작할지, 전체 상세로 시작할지, 숨긴 상태로 둘지 선택한다"},"magicKeywords.enabled":{"label":"매직 키워드","description":"단독으로 쓰인 ultrathink, orchestrate, workflowz 키워드에 대한 숨겨진 공지를 활성화한다"},"magicKeywords.ultrathink":{"label":"Ultrathink 키워드","description":"단독으로 쓰인 ultrathink가 최대 자동 사고를 요청하고 숨겨진 공지를 덧붙이도록 한다"},"magicKeywords.orchestrate":{"label":"Orchestrate 키워드","description":"단독으로 쓰인 orchestrate가 숨겨진 멀티 에이전트 오케스트레이션 공지를 덧붙이도록 한다"},"magicKeywords.workflow":{"label":"Workflow 키워드","description":"단독으로 쓰인 workflowz가 숨겨진 eval 워크플로 공지를 덧붙이도록 한다"},"completion.notify":{"label":"완료 알림","description":"에이전트가 턴을 마쳤을 때 알린다"},"error.notify":{"label":"오류 알림","description":"에이전트가 오류로 중단되었을 때 알린다"},"ask.timeout":{"label":"Ask 타임아웃","description":"이 초가 지나면 권장 ask 옵션을 자동 선택한다 (0은 비활성화)"},"ask.notify":{"label":"Ask 알림","description":"ask 도구가 입력을 기다릴 때 알린다"},"recap.enabled":{"label":"유휴 요약","description":"터미널이 유휴 상태가 된 후 현재 상황에 대한 간단한 LLM 요약을 생성한다"},"recap.idleSeconds":{"label":"유휴 요약 지연","description":"요약을 표시하기 전 유휴 상태로 대기하는 초이다"},"collab.relayUrl":{"label":"Relay URL","description":"/collab에서 사용하는 relay이다 (wss://host[:port])"},"collab.webUrl":{"label":"웹 UI URL","description":"/collab 링크에 사용되는 브라우저 UI이다. 비어 있으면 collab.relayUrl에서 파생되며, 명시적인 http://는 localhost에서만 사용된다"},"collab.displayName":{"label":"표시 이름","description":"다른 collab 참가자에게 표시되는 이름이다 (기본값: OS 사용자 이름)"},"share.serverUrl":{"label":"Share 서버","description":"/share에서 사용하는 공유 뷰어/업로드 기준 주소이다 (암호화된 blob 업로드 + 뷰어, 링크는 <base>/<id>#<key> 형식이다)"},"share.store":{"label":"Share 저장소","description":"/share가 암호화된 세션 blob을 업로드하는 위치이다"},"share.redactSecrets":{"label":"공유 시 비밀정보 삭제","description":"업로드 전에 /share 스냅샷에 대해 secret obfuscator를 실행한다(secrets.* 설정을 사용한다)"},"stt.enabled":{"label":"음성 인식","description":"마이크를 통한 speech-to-text 입력을 활성화한다"},"stt.modelName":{"label":"음성 모델","description":"로컬 온디바이스 음성 모델이다. Parakeet TDT v3(sherpa-onnx)가 SoTA 기본값이며, Whisper base/small/large-v3-turbo 등급(transformers.js)은 크기를 다국어 지원과 맞바꾼다. 첫 사용 시 다운로드된다."},"stt.submitTrigger":{"label":"음성 입력 전송 트리거","description":"음성 받아쓰기가 자동으로 전송되는 시점을 선택한다: Never, Release(2단어 이상), 완전한 문장으로 Release, 또는 When I Say Submit."},"tools.approval":{"label":"도구 승인 정책","description":"도구별 승인 정책이다. \'allow\'는 자동 승인, \'prompt\'는 확인 요구, \'deny\'는 차단으로 설정한다. 재정의는 모든 승인 모드에서 적용된다."},"tools.approvalMode":{"label":"도구 승인","description":"도구 호출의 기본 승인 동작이다. \'Always ask\'는 읽기 전용 도구만 자동 승인한다. \'Write\'는 읽기 및 workspace-write 도구를 자동 승인한다. \'Yolo\'는 모든 등급을 자동 승인하지만, 사용자 정책에 따라 확인이나 차단이 발생할 수 있다."},"features.unexpectedStopDetection":{"label":"예상치 못한 중단","description":"어시스턴트가 예상치 못하게 멈추면 자동으로 복구한다. \'기계적\'(기본값)은 표시할 답변 없이 끝난 경우를 재시도하고 도구 호출이 있었던 중단은 제외한다. \'스마트\'는 기계적 감지에 더해 작은 모델로 텍스트만 남긴 중단도 판별하며, \'사용 안 함\'은 감지를 끈다."},"contextPromotion.enabled":{"label":"컨텍스트 자동 승격","description":"컨텍스트 초과 시 compaction 대신 더 큰 컨텍스트 모델로 승격한다"},"compaction.enabled":{"label":"자동 Compact","description":"컨텍스트가 너무 커지면 자동으로 compact한다"},"compaction.midTurnEnabled":{"label":"턴 중간 Compaction","description":"다음 provider 요청 전에 안전한 턴 중간 tool-loop 경계에서 임계값을 확인한다"},"compaction.strategy":{"label":"Compaction 전략","description":"제자리 context-full 유지, auto-handoff, surgical shake(무거운 콘텐츠 제거), snapcompact(히스토리를 밀집 이미지로 보관) 중에서 선택하거나 자동 유지를 비활성화(off)한다"},"compaction.thresholdPercent":{"label":"Compaction 임계값","description":"컨텍스트 유지의 퍼센트 임계값이다. Default로 설정하면 기존 reserve 기반 동작을 사용한다"},"compaction.thresholdTokens":{"label":"Compaction 토큰 한도","description":"컨텍스트 유지의 고정 토큰 한도이다. 설정하면 퍼센트 값을 재정의한다"},"compaction.handoffSaveToDisk":{"label":"Handoff 문서 저장","description":"auto-handoff 흐름에서 생성된 handoff 문서를 markdown 파일로 저장한다"},"compaction.remoteEnabled":{"label":"원격 Compaction","description":"가능한 경우 로컬 요약 대신 원격 compaction 엔드포인트를 사용한다"},"compaction.remoteStreamingV2Enabled":{"label":"원격 Compaction V2","description":"호환되는 원격 compaction 모델에 대해 Responses 스트리밍 compaction을 사용한다"},"compaction.idleEnabled":{"label":"유휴 Compaction","description":"토큰 수가 임계값을 넘으면 유휴 상태에서 컨텍스트를 compact한다"},"compaction.idleThresholdTokens":{"label":"유휴 Compaction 임계값","description":"유휴 compaction이 트리거되는 토큰 수 기준이다"},"compaction.idleTimeoutSeconds":{"label":"유휴 Compaction 지연","description":"compact하기 전 유휴 상태로 대기하는 초이다"},"compaction.supersedeReads":{"label":"오래된 읽기 대체","description":"같은 파일을 다시 읽으면 이전 읽기 결과를 정리한다(캐시 인식, 매 턴 실행)"},"compaction.dropUseless":{"label":"무의미한 결과 제거","description":"컨텍스트상 무용하다고 표시된 도구 결과(일치 없음, 시간 초과된 대기)를 소비된 후 정리한다(캐시 인식)"},"snapcompact.systemPrompt":{"label":"Snapcompact 시스템 프롬프트","description":"실험적 기능이다: 선택한 시스템 프롬프트 텍스트를 밀집 PNG 이미지로 렌더링해 첫 사용자 메시지에 첨부한다(비전 모델 전용). 토큰을 절약하지만 이미지화된 텍스트의 prompt caching을 잃는다."},"snapcompact.toolResults":{"label":"Snapcompact 도구 결과","description":"실험적 기능이다: 큰 과거 도구 결과를 텍스트 대신 밀집 PNG 이미지로 렌더링한다(비전 모델 전용). 누적된 읽기/검색 출력의 토큰을 절약한다."},"tools.format":{"label":"도구 호출 모드","description":"도구가 모델에 노출되는 방식을 제어한다. Auto는 provider-native 도구 호출을 사용하지만, 선택된 모델이 이를 지원하지 않는다고 표시된 경우 GLM owned dialect로 대체한다. Native는 provider-native 도구를 강제하고, 나머지 값은 지정된 owned dialect를 강제한다. 세션 시작 시 적용된다."},"snapcompact.shape":{"label":"Snapcompact 형태","description":"snapcompact가 텍스트를 출력하는 프레임 형태이다(compaction 보관 및 인라인 이미지화). Auto는 현재 모델에 맞게 조정된 형태를 선택한다."},"branchSummary.enabled":{"label":"브랜치 요약","description":"브랜치를 떠날 때 요약을 요청한다"},"ttsr.enabled":{"label":"TTSR","description":"출력이 규칙 패턴과 일치하면 스트리밍 도중에 에이전트를 중단한다(Time-Traveling Stream Rules)"},"ttsr.contextMode":{"label":"TTSR 컨텍스트 모드","description":"TTSR이 발동할 때 부분 출력을 어떻게 처리할지 정한다"},"ttsr.interruptMode":{"label":"TTSR 인터럽트 모드","description":"스트리밍 도중에 중단할지, 완료 후 경고를 주입할지 정한다"},"ttsr.repeatMode":{"label":"TTSR 반복 모드","description":"규칙이 반복되는 방식을 정한다: 세션당 한 번 또는 메시지 간격 이후"},"ttsr.repeatGap":{"label":"TTSR 반복 간격","description":"규칙이 다시 발동할 수 있기까지의 메시지 수이다"},"ttsr.builtinRules":{"label":"기본 제공 규칙","description":"에이전트에 기본 포함된 규칙을 로드한다(ttsr.disabledRules로 개별 해제 가능)"},"memory.backend":{"label":"메모리 백엔드","description":"끄기, 로컬 요약 파이프라인, Mnemopi SQLite, 또는 Hindsight 원격 메모리 중에서 선택한다"},"autolearn.enabled":{"label":"자동 학습 (실험적)","description":"에이전트가 멈춘 뒤 교훈을 메모리에 기록하고 격리된 관리형 skill을 생성/보강하도록 유도한다"},"autolearn.autoContinue":{"label":"중지 시 캡처 자동 실행","description":"켜면 중지 시 비공개 캡처 턴을 한 번 자동 실행한다(추가 토큰을 사용한다). 끄면 상시 자동 학습 안내만 남는다."},"mnemopi.dbPath":{"label":"Mnemopi DB 경로","description":"선택적 SQLite DB 경로이다. 기본값은 에이전트 memories 디렉터리이다."},"mnemopi.bank":{"label":"Mnemopi 뱅크","description":"선택적 공유 뱅크 기본 이름이다. per-project 모드는 이를 기반으로 프로젝트 로컬 뱅크를 파생한다."},"mnemopi.scoping":{"label":"Mnemopi 스코핑","description":"global = 공유 뱅크 하나, per-project = cwd별 격리 뱅크, per-project-tagged = 프로젝트 로컬 쓰기에 global recall 가시성을 더한 방식이다"},"mnemopi.embeddingVariant":{"label":"임베딩 variant","description":"로컬 임베딩 모델 계열이다. en = 더 강력한 영어 모델, multilingual = 교차 언어 모델이다. 이를 변경하면 다음 시작 시 기존 메모리 임베딩을 다시 생성한다."},"mnemopi.autoRecall":{"label":"Mnemopi 자동 recall","description":"각 세션의 첫 턴에 로컬 메모리를 recall한다"},"mnemopi.autoRetain":{"label":"Mnemopi 자동 retain","description":"완료된 대화 턴을 로컬 Mnemopi 메모리에 retain한다"},"mnemopi.polyphonicRecall":{"label":"Mnemopi 폴리포닉 recall","description":"reciprocal rank fusion으로 융합한 4-voice recall(vector, graph, fact, temporal)을 활성화한다"},"mnemopi.enhancedRecall":{"label":"Mnemopi 향상된 recall","description":"반복되거나 유사한 recall 쿼리를 위한 계층형 쿼리 결과 캐시를 활성화한다"},"mnemopi.proactiveLinking":{"label":"Mnemopi 선제적 링킹","description":"새 메모리를 저장하는 즉시 episodic 그래프에 수집해 관련 엔터티 및 메모리와 연결한다"},"mnemopi.noEmbeddings":{"label":"Mnemopi 임베딩 비활성화","description":"vector 임베딩 대신 결정적인 FTS 전용 recall을 강제한다"},"mnemopi.embeddingModel":{"label":"Mnemopi 임베딩 모델","description":"고급: variant를 재정의하는 명시적 임베딩 모델 id이다. 비워 두면 mnemopi.embeddingVariant를 사용한다."},"mnemopi.embeddingApiUrl":{"label":"Mnemopi 임베딩 API URL","description":"Mnemopi에 전달하는 선택적 OpenAI 호환 임베딩 엔드포인트이다"},"mnemopi.embeddingApiKey":{"label":"Mnemopi 임베딩 API 키","description":"Mnemopi에 전달하는 선택적 임베딩 API 키이다"},"mnemopi.llmMode":{"label":"Mnemopi LLM 모드","description":"LLM 미사용, 온라인 tiny 모델(/models의 TINY 역할, 없으면 @smol), 또는 원격 OpenAI 호환 엔드포인트를 사용한다"},"mnemopi.llmBaseUrl":{"label":"Mnemopi LLM Base URL","description":"Mnemopi 원격 모드를 위한 선택적 OpenAI 호환 LLM 엔드포인트이다"},"mnemopi.llmApiKey":{"label":"Mnemopi LLM API 키","description":"Mnemopi 원격 모드를 위한 선택적 LLM API 키이다"},"mnemopi.llmModel":{"label":"Mnemopi LLM 모델","description":"Mnemopi 원격 모드를 위한 선택적 LLM 모델 이름이다"},"hindsight.apiUrl":{"label":"Hindsight API URL","description":"Hindsight 서버 URL(Cloud 또는 self-hosted)이다"},"hindsight.apiToken":{"label":"Hindsight API 토큰","description":"인증이 필요한 Hindsight 서버용 Bearer 토큰이다"},"hindsight.bankId":{"label":"Hindsight Bank ID","description":"메모리 뱅크 식별자다(기본값: 프로젝트 이름)"},"hindsight.scoping":{"label":"Hindsight 범위","description":"global = 하나의 공유 뱅크, per-project = cwd별로 격리된 뱅크, per-project-tagged = 프로젝트 태그가 붙은 공유 뱅크로 recall 시 global 메모리와 프로젝트 메모리가 병합된다"},"hindsight.autoRecall":{"label":"Hindsight 자동 recall","description":"각 세션의 첫 턴에 메모리를 recall한다"},"hindsight.autoRetain":{"label":"Hindsight 자동 retain","description":"N턴마다 그리고 세션 경계에서 대화 기록을 retain한다"},"hindsight.retainMode":{"label":"Hindsight retain 모드","description":"full-session = 세션당 문서 하나를 upsert하고, last-turn = 청크 단위로 저장한다"},"hindsight.mentalModelsEnabled":{"label":"Hindsight 멘탈 모델","description":"부팅 시 정리된 reflect 요약(멘탈 모델)을 developer instructions로 읽어들인다. 뱅크에 있는 기존 모델을 로드하며 쓰기는 하지 않는다. 내장 seed 세트를 자동 생성하려면 hindsight.mentalModelAutoSeed와 함께 사용한다."},"hindsight.mentalModelAutoSeed":{"label":"Hindsight 멘탈 모델 자동 seed","description":"세션 시작 시 뱅크에 아직 없는 내장 멘탈 모델(project-conventions, project-decisions, user-preferences)을 생성한다."},"providers.memoryModel":{"label":"메모리 모델","description":"사실 추출 및 통합에 사용하는 Mnemopi LLM이다: 기본값은 online(/models의 TINY 역할, 없으면 smol/remote)이며, 로컬 on-device 모델도 사용할 수 있다"},"edit.mode":{"label":"편집 모드","description":"edit 도구 변형을 선택한다(replace, patch, hashline, apply_patch)"},"edit.fuzzyMatch":{"label":"퍼지 매치","description":"공백 차이에 대해 신뢰도가 높은 퍼지 매치를 허용한다"},"edit.fuzzyThreshold":{"label":"퍼지 매치 임계값","description":"퍼지 매치를 허용하는 유사도 임계값(0-1)이다"},"edit.streamingAbort":{"label":"프리뷰 실패 시 중단","description":"패치 프리뷰가 실패하면 스트리밍 edit 도구 호출을 중단한다"},"edit.blockAutoGenerated":{"label":"자동 생성 파일 차단","description":"자동 생성된 것으로 보이는 파일(protoc, sqlc, swagger 등)의 편집을 막는다"},"edit.enforceSeenLines":{"label":"확인된 줄 가드 적용","description":"이전 read/search가 전체를 표시하지 않은 줄을 기준으로 하는 편집을 거부한다"},"readLineNumbers":{"label":"줄 번호","description":"기본적으로 read 도구 출력에 줄 번호를 앞에 붙인다"},"read.defaultLimit":{"label":"기본 read 제한","description":"에이전트가 limit 없이 read를 호출할 때 반환하는 기본 줄 수다"},"read.renderMarkdown":{"label":"Markdown 프리뷰","description":"Markdown read 결과를 원본 소스가 아니라 서식이 적용된 터미널 Markdown 프리뷰로 렌더링한다"},"read.summarize.enabled":{"label":"read 요약","description":"명시적 selector 없이 read가 호출되면 구조적 코드 요약을 반환한다"},"read.summarize.prose":{"label":"산문 요약","description":"Markdown 및 일반 텍스트 read에 대해 구조적 요약을 반환한다"},"read.toolResultPreview":{"label":"인라인 read 프리뷰","description":"read 도구 결과를 요약 행이 아니라 대화 기록에 인라인으로 렌더링한다"},"lsp.enabled":{"label":"LSP","description":"코드 인텔리전스(정의, 참조, 진단, 이름 변경)를 위한 lsp 도구를 활성화한다"},"lsp.lazy":{"label":"LSP 지연 시작","description":"세션 시작 시점이 아니라 처음 사용할 때(lsp 도구 호출 또는 해당 파일 타입 편집) language server를 시작한다"},"lsp.shared":{"label":"공유 language server","description":"daemon broker를 통해 프로젝트당 하나의 language server를 omp 인스턴스 간에 공유한다(사용할 수 없으면 개별 서버로 대체된다)"},"lsp.formatOnWrite":{"label":"쓰기 시 포맷","description":"파일을 쓴 후 LSP로 코드 파일을 자동 포맷한다"},"lsp.diagnosticsOnWrite":{"label":"쓰기 시 진단","description":"코드 파일을 쓴 후 LSP 진단을 반환한다"},"lsp.diagnosticsOnEdit":{"label":"편집 시 진단","description":"코드 파일을 편집한 후 LSP 진단을 반환한다"},"lsp.diagnosticsDeduplicate":{"label":"진단 중복 제거","description":"파일에 대해 이미 표시된 편집 후 LSP 진단을 억제하고, 새롭거나 변경된 것만 표시한다"},"bash.enabled":{"label":"Bash","description":"셸 명령 실행을 위한 bash 도구를 활성화한다"},"bash.autoBackground.enabled":{"label":"Bash 자동 백그라운드","description":"오래 실행되는 bash 명령을 자동으로 백그라운드로 보내고 결과를 나중에 전달한다"},"bashInterceptor.enabled":{"label":"Bash 인터셉터","description":"전용 도구가 있는 셸 명령을 차단한다"},"bash.direnv":{"label":"direnv 자동 로드","description":"저장소의 direnv/devenv `.envrc`를 bash 세션에 자동으로 로드해 수동 `direnv exec` 없이 devenv 도구와 환경 변수를 사용할 수 있게 한다. direnv의 허용 목록을 따르며, `direnv allow`하지 않은 `.envrc`는 절대 실행되지 않는다"},"shellMinimizer.enabled":{"label":"셸 출력 축소","description":"장황한 셸 출력(git, npm, cargo 등)을 에이전트에 반환하기 전에 압축한다"},"shellMinimizer.sourceOutlineLevel":{"label":"셸 축소 소스 아웃라인","description":"소스 파일의 cat/read에 대한 소스 아웃라인 모드: default 또는 aggressive"},"eval.py":{"label":"Python Eval 백엔드","description":"eval 도구가 Python 셀을 IPython 커널로 보내도록 허용한다"},"eval.js":{"label":"JavaScript Eval 백엔드","description":"eval 도구가 JavaScript 셀을 인프로세스 런타임으로 보내도록 허용한다"},"eval.rb":{"label":"Ruby Eval 백엔드","description":"eval 도구가 Ruby 셀을 상시 유지되는 Ruby 커널로 보내도록 허용한다"},"eval.jl":{"label":"Julia Eval 백엔드","description":"eval 도구가 Julia 셀을 상시 유지되는 Julia 커널로 보내도록 허용한다"},"python.kernelMode":{"label":"Python 커널 모드","description":"eval 호출 간에 IPython 커널을 유지할지 매번 새로 시작할지 정한다"},"python.interpreter":{"label":"Python 인터프리터","description":"정확한 Python 실행 파일의 선택적 경로이다. 설정하면 자동 Python 런타임 탐색을 건너뛴다."},"ruby.interpreter":{"label":"Ruby 인터프리터","description":"정확한 Ruby 실행 파일의 선택적 경로이다. 설정하면 자동 Ruby 런타임 탐색을 건너뛴다."},"julia.interpreter":{"label":"Julia 인터프리터","description":"정확한 Julia 실행 파일의 선택적 경로이다. 설정하면 자동 Julia 런타임 탐색을 건너뛴다."},"tools.artifactSpillThreshold":{"label":"아티팩트 분리 임계값(KB)","description":"이 크기를 넘는 도구 출력은 아티팩트로 저장되고, 끝부분은 인라인으로 유지된다"},"tools.artifactTailBytes":{"label":"아티팩트 끝부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 양이다"},"tools.artifactHeadBytes":{"label":"아티팩트 앞부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 끝부분과 함께 인라인으로 유지되는 앞부분 내용의 양이다(중간 생략). 0이면 비활성화되어 끝부분만 유지한다."},"tools.outputMaxColumns":{"label":"출력 열 제한","description":"스트리밍 도구 출력(bash, python, js eval)과 `read`에 대한 줄당 바이트 제한이다. 이보다 긴 줄은 말줄임표로 잘리고, 다음 줄바꿈까지 남은 바이트는 버려진다. 0이면 비활성화된다."},"tools.artifactTailLines":{"label":"아티팩트 끝부분 줄 수","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 최대 줄 수이다"},"todo.enabled":{"label":"할 일 목록","description":"작업 추적을 위한 todo 도구를 활성화한다"},"todo.reminders":{"label":"할 일 알림","description":"중지하기 전에 할 일을 완료하도록 에이전트에 상기시킨다"},"todo.remindersMax":{"label":"할 일 알림 제한","description":"포기하기 전까지의 최대 할 일 알림 횟수이다"},"todo.eager":{"label":"할 일 자동 생성","description":"첫 메시지 이후 자동 할 일 목록 생성을 얼마나 강하게 유도할지 정한다"},"glob.enabled":{"label":"Glob","description":"glob 기반 파일 조회를 위한 glob 도구를 활성화한다"},"grep.enabled":{"label":"Grep","description":"정규식 내용 검색을 위한 grep 도구를 활성화한다"},"grep.contextBefore":{"label":"Grep 앞 컨텍스트","description":"각 grep 일치 항목 앞에 표시할 컨텍스트 줄 수이다"},"grep.contextAfter":{"label":"Grep 뒤 컨텍스트","description":"각 grep 일치 항목 뒤에 표시할 컨텍스트 줄 수이다"},"astGrep.enabled":{"label":"AST Grep","description":"구조적 AST 검색을 위한 ast_grep 도구를 활성화한다"},"astEdit.enabled":{"label":"AST Edit","description":"구조적 AST 재작성을 위한 ast_edit 도구를 활성화한다"},"debug.enabled":{"label":"디버그","description":"DAP 기반 디버깅을 위한 debug 도구를 활성화한다"},"launch.enabled":{"label":"Launch","description":"공유되는 장기 실행 프로젝트 프로세스를 감독하는 launch 도구를 활성화한다"},"speechgen.enabled":{"label":"음성 생성","description":"온디바이스(Kokoro) 또는 xAI Grok Voice 음성 파일 합성을 위한 tts 도구를 활성화한다"},"generate_image.enabled":{"label":"이미지 생성","description":"generate_image 도구(텍스트-이미지 생성 및 편집)를 활성화한다. tools.xdev가 켜져 있으면 xd:// 장치로 노출된다."},"inspect_image.mode":{"label":"이미지 분석","description":"이미지 이해를 비전 지원 모델에 위임하는 inspect_image 도구를 제어한다. \'auto\'는 활성 모델이 네이티브 이미지 입력을 지원하지 않을 때만 노출하고, \'on\'은 항상 노출하며, \'off\'는 노출하지 않는다."},"computer.enabled":{"label":"컴퓨터","description":"스크립트 가능한 호스트 데스크톱 제어 도구(스크린샷, 입력, 접근성)를 활성화한다"},"computer.display":{"label":"컴퓨터 디스플레이","description":"모든 디스플레이를 합성하거나 네이티브 display id를 선택한다"},"inspect_image.timeoutMs":{"label":"이미지 분석 타임아웃","description":"inspect_image 비전 모델 호출의 요청당 타임아웃이며 단위는 milliseconds이다. 응답이 멈춘 제공자는 수동 중단까지 차단되지 않고 타임아웃 오류로 빠르게 실패한다. 0으로 설정하면 타임아웃을 비활성화한다."},"checkpoint.enabled":{"label":"체크포인트/되돌리기","description":"컨텍스트 체크포인팅을 위한 checkpoint 및 rewind 도구를 활성화한다"},"fetch.enabled":{"label":"URL 읽기","description":"read 도구가 URL을 가져와 처리하도록 허용한다"},"vault.enabled":{"label":"Obsidian Vault","description":"Obsidian CLI를 통해 Obsidian vault 내용을 읽고 편집하는 vault:// 내부 URL을 활성화한다. 비활성화하면 vault:// 해석이 거부되고 시스템 프롬프트에서 vault:// 항목이 생략된다."},"github.enabled":{"label":"GitHub CLI","description":"github 도구(리포지터리, 이슈, pull request, diff, 검색, checkout, push, Actions watch 워크플로에 대한 op 기반 디스패치)를 활성화한다"},"github.cache.enabled":{"label":"GitHub 뷰 캐시","description":"렌더링된 이슈/PR 뷰 출력을 ~/.omp/cache/github-cache.db에 캐시해 반복 읽기 비용을 없앤다"},"web_search.enabled":{"label":"웹 검색","description":"실시간 웹 결과를 위한 web_search 도구를 활성화한다"},"security.enabled":{"label":"보안","description":"OMP 네이티브 보안 스캔 계획과 실행, 그리고 읽기 전용 security:// 리소스 네임스페이스를 활성화한다"},"ask.enabled":{"label":"Ask","description":"대화형 사용자 질문을 위한 ask 도구를 활성화한다"},"browser.enabled":{"label":"브라우저","description":"스크립트 기반 Chromium 자동화(puppeteer)를 위한 browser 도구를 활성화한다"},"browser.cdpUrl":{"label":"브라우저 CDP URL","description":"브라우저를 실행하는 대신 연결할 기본 HTTP CDP 디스커버리 엔드포인트이다(예: http://127.0.0.1:9222). 도구 호출에 명시된 app.cdp_url 또는 app.path가 우선한다."},"browser.relay":{"label":"브라우저 릴레이","description":"omp browser relay를 통해 사용자의 Chrome 탭을 제어한다. 확장 프로그램을 한 번 설치하면(`omp browser-relay install`) browser 도구가 필요할 때 릴레이 서버가 자동으로 시작된다. Browser CDP URL보다 우선하며, PI_BROWSER_RELAY=0 또는 PI_BROWSER_RELAY=1로 재정의한다."},"browser.relayUrl":{"label":"브라우저 릴레이 URL","description":"omp browser relay 엔드포인트이다(기본값 http://127.0.0.1:9224)."},"browser.headless":{"label":"헤드리스 브라우저","description":"브라우저를 headless 모드로 실행한다(비활성화하면 브라우저 UI를 표시한다)"},"browser.cmux":{"label":"cmux 브라우저","description":"cmux 소켓을 사용할 수 있을 때 브라우저 자동화에 cmux WKWebView 서피스를 사용한다. PI_BROWSER_CMUX=0 또는 PI_BROWSER_CMUX=1로 재정의한다."},"browser.screenshotDir":{"label":"스크린샷 디렉터리","description":"스크린샷을 저장할 디렉터리이다. 설정하지 않으면 스크린샷은 임시 파일로 저장된다. ~를 지원한다. 예: ~/Downloads, ~/Desktop, /sdcard/Download (Android)"},"tools.intentTracing":{"label":"인텐트 트레이싱","description":"각 도구 호출을 실행하기 전에 그 의도를 설명하도록 에이전트에 요청한다"},"tools.abortOnFabricatedResult":{"label":"조작된 도구 결과 시 중단","description":"in-band 도구 호출에서 모델이 턴 중간에 도구 결과를 환각하기 시작하면 즉시 중단한다. 비활성화하면 모델이 생성을 끝내도록 두고 조작된 이어쓰기를 폐기한다."},"tools.maxTimeout":{"label":"최대 도구 타임아웃","description":"에이전트가 임의의 도구에 설정할 수 있는 최대 타임아웃(초, 0 = 무제한)"},"async.enabled":{"label":"비동기 실행","description":"비동기 bash 명령과 백그라운드 작업 실행을 활성화한다"},"tools.xdev":{"label":"xd:// 도구","description":"드물게 쓰이는(탐색 가능한) 도구의 스키마를 매 요청마다 보내는 대신 read/write로 구동되는 xd:// 디바이스 URL 아래에 마운트한다. write 도구가 허용되지 않은 세션은 마운트를 건너뛰고 모든 도구를 최상위로 노출한다. 비활성화하면 활성화된 모든 도구를 최상위로 노출한다."},"tools.xdevDocs":{"label":"xd:// 프롬프트 문서","description":"시스템 프롬프트에 인라인으로 포함할 마운트된 디바이스 문서와 스키마를 선택한다. Built-ins는 핵심 도구를 인라인으로 유지하고 MCP 및 확장 도구는 on-demand로 남긴다."},"mcp.selection":{"label":"MCP 연결 선택","description":"all은 시작 시 기존 설정대로 연결한다. per-request는 JEV가 요청에 필요한 서버를 선택해 연결하며, 설치\xb7인증\xb7권한은 자동 승인하지 않는다. 변경 후 새 세션에서 적용된다."},"mcp.enableProjectConfig":{"label":"MCP 프로젝트 설정","description":"프로젝트 루트에서 .mcp.json/mcp.json을 로드한다"},"mcp.renderMarkdownResults":{"label":"MCP Markdown 결과","description":"JSON이 아닌 MCP 텍스트 결과를 트랜스크립트에서 Markdown으로 렌더링한다"},"mcp.notifications":{"label":"MCP 업데이트 주입","description":"MCP 리소스 업데이트를 에이전트 대화에 주입한다"},"tasks.todoClearDelay":{"label":"Todo 자동 정리 지연","description":"완료되거나 중단된 todo가 todo 위젯에서 제거되기까지의 지연 시간이다"},"dev.autoqa":{"label":"Auto QA","description":"자동 도구 이슈 보고(xd://report_issue)이다. 기본적으로 켜져 있으며, 첫 보고 시 동의를 요청하고 거부하면 명시적으로 다시 활성화할 때까지 보고를 비활성화한다"},"dev.autoqaPush.endpoint":{"label":"Auto QA 푸시 엔드포인트","description":"Auto QA JSON 보고를 수신하는 전체 URL이다(기본값 https://qa.omp.sh/v1/grievances)"},"plan.enabled":{"label":"Plan 모드","description":"실행 전 읽기 전용 탐색과 계획 수립을 위한 plan 모드를 활성화한다"},"plan.defaultOnStartup":{"label":"Plan 모드로 시작","description":"모든 새 세션 시작 시 자동으로 plan 모드로 진입한다"},"goal.enabled":{"label":"Goal 모드","description":"세션별 goal 모드와 숨겨진 goal 도구를 활성화한다"},"goal.statusInFooter":{"label":"푸터의 Goal 상태","description":"상태 표시줄에서 goal 표시기와 함께 토큰 예산을 표시한다"},"title.refreshOnReplan":{"label":"재계획 시 제목 갱신","description":"사용자가 제목을 설정한 경우가 아니면 todo init 재계획 이후 생성된 세션 제목을 갱신한다"},"task.isolation.mode":{"label":"격리 모드","description":"서브에이전트의 격리 백엔드이다. \\"auto\\"는 네이티브 PAL이 사용 가능한 최적 백엔드를 선택하게 한다(CoW를 지원하는 파일시스템, 그다음 overlayfs/ProjFS, 그다음 git worktree / 재귀 복사 폴백)."},"task.isolation.apply":{"label":"격리 변경 적용","description":"성공한 격리 작업의 변경을 부모 체크아웃에 자동으로 적용한다. 비활성화하면 patch 또는 branch 아티팩트를 유지한다"},"task.isolation.merge":{"label":"격리 병합 전략","description":"격리 작업의 변경을 통합하는 방식이다(patch apply 또는 branch merge)"},"task.isolation.commits":{"label":"격리 커밋 스타일","description":"중첩 저장소 변경의 커밋 메시지 스타일이다(generic 또는 AI 생성)"},"worktree.base":{"label":"Worktree 기본 디렉터리","description":"에이전트가 관리하는 worktree의 기본 디렉터리로, 작업 격리 사본, `github` PR 체크아웃, `omp worktree` 정리가 모두 여기에 위치한다. 설정하지 않으면 ~/.omp/wt를 사용한다. 절대 경로 또는 ~ 기준 경로여야 하며, 상대 경로는 무시된다. OMP_WORKTREE_DIR 환경 변수가 이 값을 재정의한다."},"task.eager":{"label":"작업 위임 선호도","description":"서브에이전트에 작업을 위임하도록 얼마나 강하게 유도할지를 정한다"},"task.batch":{"label":"작업 호출 배치","description":"task 도구를 배치 형태로 전환한다: 한 번의 호출이 { context, tasks[] }를 전달하며, 항목당 서브에이전트 하나가 실행되고, 항목별 agent(기본값은 세션 spawn-policy 에이전트)와 항목별 격리를 지정할 수 있으며, 공유 context는 모든 assignment 앞에 필수로 붙는다. async.enabled=true인 경우 각 spawn은 일반적인 idle/parked 수명 주기를 갖는 독립 백그라운드 에이전트로 실행되고, 그렇지 않으면 호출은 병합된 결과를 기다리며 블로킹된다. 비활성화하면 평면적인 단일 spawn 스키마로 되돌아간다."},"task.enableEffort":{"label":"작업별 effort","description":"task spawn에서 선택적 effort 파라미터를 노출해, 호출자가 각 서브에이전트의 thinking 레벨을 재정의할 수 있게 한다"},"task.maxConcurrency":{"label":"최대 동시 작업 수","description":"동시에 실행되는 서브에이전트의 최대 개수이다"},"task.enableLsp":{"label":"서브에이전트 LSP","description":"task 도구로 생성된 서브에이전트가 lsp 도구를 사용할 수 있게 한다. 서브에이전트 비용을 낮게 유지하기 위해 기본적으로 꺼져 있으며, LSP를 활용한 위임이 추가 토큰만큼 가치가 있을 때 활성화한다."},"task.maxRecursionDepth":{"label":"최대 작업 재귀 깊이","description":"서브에이전트가 자신의 서브에이전트를 생성할 수 있는 최대 깊이이다"},"task.maxRuntimeMs":{"label":"서브에이전트 최대 실행 시간","description":"서브에이전트당 절대 실행 시간 제한(ms)이다. 0이면 비활성화된다. 추론 계층 워치독을 빠져나가는 프로바이더 측 스트림 정지에 대한 심층 방어 수단이며, \'timed out\' 사유로 일반적인 서브에이전트 중단을 발생시킨다."},"task.softRequestBudget":{"label":"서브에이전트 소프트 요청 예산","description":"서브에이전트당 소프트 요청 예산(실행당 assistant 요청 수)이다. 이를 초과하면 마무리를 유도하는 steering 알림이 주입되며(task.softRequestBudgetNotice 참고), 예산의 1.5배에 도달하면 실행이 강제 중단되고 에이전트는 부분 결과를 내놓아야 한다. 0이면 이 보호 장치가 비활성화된다. 번들된 scout/sonic 에이전트는 더 낮은 내장 예산이 상한이므로, 그 상한보다 낮은 값은 이들에게도 적용된다."},"task.softRequestBudgetNotice":{"label":"소프트 요청 예산 알림","description":"서브에이전트가 소프트 요청 예산을 초과할 때 steering 알림을 한 번 주입해, 1.5배 강제 중단 전에 마무리하도록 요청한다."},"task.maxEffort":{"label":"spawn당 최대 effort","description":"task 도구의 spawn별 effort 힌트에 허용되는 최대 추론 effort이다. 값을 낮추면 호출자가 서브에이전트를 이 상한 이상으로 올릴 수 없으며, 기본값은 모델의 전체 범위를 유지한다."},"task.prewalk":{"label":"일반 작업 prewalk","description":"번들된 일반 `task` 서브에이전트에 prewalk를 적용한다: 해석된 모델로 시작해 계획을 세우고 구현을 시작한 뒤, 첫 편집/쓰기 시점에 \'smol\' 역할로 넘긴다. 에이전트별 재정의(/agents 허브에서 설정하는 task.agentPrewalk)와 사용자 에이전트의 `prewalk` frontmatter는 이 토글과 무관하게 적용된다."},"skills.enableSkillCommands":{"label":"스킬 명령","description":"스킬을 /skill:name 명령으로 등록한다"},"commands.enableClaudeUser":{"label":"Claude 사용자 명령","description":"~/.claude/commands/에서 명령을 로드한다"},"commands.enableClaudeProject":{"label":"Claude 프로젝트 명령","description":".claude/commands/에서 명령을 로드한다"},"commands.enableOpencodeUser":{"label":"OpenCode 사용자 명령","description":"~/.config/opencode/commands/에서 명령을 로드한다"},"commands.enableOpencodeProject":{"label":"OpenCode 프로젝트 명령","description":".opencode/commands/에서 명령을 로드한다"},"providers.maxInFlightRequests":{"label":"최대 동시 요청 수","description":"프로바이더 id별(예: \\"openai\\" 또는 \\"anthropic\\") 최대 동시 LLM 요청 수로, 같은 config root를 쓰는 로컬 OMP 프로세스 간에 공유된다. 명시되지 않은 프로바이더는 제한이 없다."},"secrets.enabled":{"label":"시크릿 숨김","description":"AI 프로바이더로 전송하기 전에 설정된 시크릿을 난독화하고 자격 증명 형태의 토큰을 마스킹한다"},"providers.webSearchOrder":{"label":"웹 검색 프로바이더 순서","description":"web_search 도구에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 그 뒤에 기본 순서를 유지한다"},"providers.webSearchExclude":{"label":"제외할 웹 검색 프로바이더","description":"web_search가 폴백으로도 절대 사용하지 않을 프로바이더이다"},"providers.webSearchTimeoutSeconds":{"label":"웹 검색 타임아웃","description":"web_search가 다음 폴백으로 넘어가기 전 각 프로바이더 검색 전송에 적용되는 절대 타임아웃이며 단위는 초이다(최대 300)"},"providers.webSearchGeminiModel":{"label":"Gemini web_search 모델","description":"Gemini Google Search grounding에 사용할 모델 ID이다. 기본값은 gemini-2.5-flash이다."},"providers.antigravityEndpoint":{"label":"Antigravity 엔드포인트 모드","description":"google-antigravity 프로바이더의 엔드포인트 라우팅 전략이다(chat, search, image, discovery)"},"providers.imageOrder":{"label":"이미지 프로바이더 순서","description":"이미지 생성에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 활성 세션 프로바이더와 내장 순서를 따른다"},"providers.fireworksTier":{"label":"Fireworks 티어","description":"Fireworks 요청의 서빙 경로이다. Priority는 `service_tier: \\"priority\\"`를 전송해 트래픽이 몰릴 때 더 높은 신뢰성을 더 높은 가격에 제공하고, Standard는 이를 생략한다. Fast(`-fast`) 모델은 이 설정을 무시하며, Fast는 별도의 서빙 경로이다."},"live.voice":{"label":"Live 음성","description":"Codex 기반 realtime 음성 세션에서 사용하는 음성이다"},"providers.tts":{"label":"TTS 제공자","description":"tts 도구의 백엔드이다: 로컬 온디바이스 신경망 TTS(Kokoro-82M) 또는 xAI Grok Voice 중 하나이다"},"tts.localModel":{"label":"로컬 TTS 모델","description":"로컬 TTS 백엔드가 사용하는 온디바이스 신경망 TTS 모델(Kokoro-82M)이다"},"tts.localVoice":{"label":"로컬 TTS 음성","description":"로컬 TTS 백엔드가 사용하는 Kokoro 음성이다(미국/영국, 여성/남성)"},"speech.enabled":{"label":"음성 출력","description":"어시스턴트의 출력을 스트리밍되는 대로 스피커로 소리내어 읽는다"},"speech.mode":{"label":"음성 출력 모드","description":"읽을 대상이다: all = 어시스턴트 메시지 + 사고 과정, assistant = 메시지만, yield = 턴 종료 시 마지막 메시지만이다"},"speech.enhanced":{"label":"향상된 음성 재작성","description":"합성 전에 tiny/smol 모델로 어시스턴트 출력을 자연스러운 구어체 산문으로 재작성한다(코드는 설명으로 바꾸고 링크와 markdown은 제거한다). 실패하면 기계적 정리로 대체된다"},"speech.voice":{"label":"음성 출력 목소리","description":"어시스턴트의 출력을 소리내어 읽을 때 사용하는 Kokoro 음성이다"},"providers.tinyModel":{"label":"Tiny 모델","description":"세션 제목 생성 모델이다: 기본값은 온라인(/models의 TINY 역할, 없으면 @smol)이며, 로컬 온디바이스 모델도 가능하다"},"providers.tinyModelDevice":{"label":"Tiny 모델 디바이스","description":"로컬 tiny 모델(제목 + 메모리)에 사용하는 ONNX 실행 제공자이다. 기본값은 CPU 전용 추론을 사용한다. PI_TINY_DEVICE 환경 변수가 이 값을 덮어쓴다."},"providers.tinyModelDtype":{"label":"Tiny 모델 정밀도","description":"로컬 tiny 모델의 ONNX 양자화/정밀도이다. 기본값은 각 모델에 포함된 dtype(q4)을 사용하며, 정밀도가 낮으면 더 빠르고 높으면 원본에 더 충실하다. PI_TINY_DTYPE 환경 변수가 이 값을 덮어쓴다."},"providers.unexpectedStopModel":{"label":"예기치 않은 중단 모델","description":"예기치 않은 중단 감지용 분류기이다: 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 가능하다."},"providers.kimiApiFormat":{"label":"Kimi API 형식","description":"Kimi Code 제공자의 API 형식이다(auto는 라이브 모델 메타데이터를 따른다)"},"providers.openaiWebsockets":{"label":"OpenAI WebSockets","description":"OpenAI Codex 모델의 websocket 정책이다(auto는 모델 기본값을 사용하고, on은 강제하며, off는 비활성화한다)"},"providers.streamFirstEventTimeoutSeconds":{"label":"스트림 첫 이벤트 타임아웃","description":"모델 스트림의 첫 이벤트를 기다리는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.streamIdleTimeoutSeconds":{"label":"스트림 유휴 타임아웃","description":"모델 스트림이 이벤트 사이에 무응답 상태로 있을 수 있는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.openrouterVariant":{"label":"OpenRouter 라우팅","description":"OpenRouter 모델 ID에 덧붙이는 기본 라우팅 variant 접미사이다(선택기에서 이미 variant를 지정한 경우 무시된다)"},"providers.fetch":{"label":"Fetch 제공자","description":"fetch/read URL 도구의 리더 백엔드 우선순위이다"},"codexResets.autoRedeem":{"label":"Codex 리셋 자동 사용","description":"저장된 Codex rate-limit 리셋을 자동으로 사용한다: 턴이 멈추고 다른 계정이 대체할 수 없을 때 5h 또는 weekly 창을 소진해 차단된 계정을 복구하고, 곧 만료될 크레딧을 회수한다. unset은 첫 사용 전에 확인하고, yes는 확인 없이 사용하며, no는 두 검사 모두 비활성화한다."},"provider.appendOnlyContext":{"label":"추가 전용 컨텍스트","description":"시스템 프롬프트 + 도구 명세를 캐시하고 추가 전용 메시지 로그를 유지해 provider prefix 캐시(DeepSeek, Xiaomi/SGLang, Anthropic) 적중률을 최대화한다. auto는 prefix 캐시가 알려진 제공자에 대해 활성화한다."},"exa.enabled":{"label":"Exa","description":"Exa 웹 검색 제공자를 활성화한다"},"searxng.endpoint":{"label":"SearXNG 엔드포인트","description":"웹 검색에 사용하는 자체 호스팅 SearXNG 인스턴스의 기본 URL이다"}}}'),fu=[{id:"models",label:"Models & accounts",icon:"model"},{id:"themes",label:"Themes",icon:"theme"},{id:"skills",label:"Skills",icon:"skill",requiresCwd:!0},{id:"plugins",label:"Plugins",icon:"plugin",requiresCwd:!0},{id:"mcp",label:"MCP",icon:"mcp"},{id:"access",label:"Access",icon:"access"},{id:"trust",label:"Project trust",labelKey:"trust.settingsNav",icon:"trust"},{id:"live-voice",label:"Call voice",labelKey:"chat.liveVoiceSettingsNav",icon:"liveVoice"},{id:"attachments",label:"Attachments",labelKey:"chat.attachmentSettingsNav",icon:"attachments"},{id:"characters",label:"Characters",labelKey:"characterMode.nav",icon:"characters"}],fp={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),characters:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}),attachments:(0,r.jsx)("path",{d:"m21 12-8.6 8.6a5 5 0 0 1-7-7l8.5-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9"}),appearance:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function fh({kind:e}){return(0,r.jsx)("svg",{className:mQ().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:fp[e]??fp.tools})}function fm({field:e,busy:t,onSave:n}){let[i,s]=(0,a.useState)("secret"===e.type?"":String(e.value??""));(0,a.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let o="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:mQ().textInput,type:"secret"===e.type?"password":"text",value:i,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{i!==o&&("secret"!==e.type||i.length>0)&&n(i)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function ff({field:e,busy:t,onSave:n}){let i=JSON.stringify(e.value??{},null,2),[s,o]=(0,a.useState)(i),[l,c]=(0,a.useState)(null);return(0,a.useEffect)(()=>{o(i),c(null)},[i]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:mQ().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>o(e.target.value),onBlur:()=>{if(s!==i)try{n(JSON.parse(s)),c(null)}catch(e){c(e instanceof Error?e.message:String(e))}}}),l&&(0,r.jsx)("div",{className:mQ().error,children:l})]})}function fg({field:e,busy:t,onSave:n}){let a=Array.isArray(e.value)?e.value:[],i=(e,t)=>{let r=e+t;if(r<0||r>=a.length)return;let i=[...a];[i[e],i[r]]=[i[r],i[e]],n(i)};return(0,r.jsx)("div",{className:mQ().multiSelect,children:e.options?.map(s=>{let o=a.indexOf(s.value);return(0,r.jsxs)("span",{className:mQ().choice,"data-selected":o>=0,title:s.description,children:[(0,r.jsx)("button",{type:"button",className:mQ().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,n(a.includes(e)?a.filter(t=>t!==e):[...a,e])},children:s.label}),e.ordered&&o>=0&&(0,r.jsxs)("span",{className:mQ().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===o,onClick:()=>i(o,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||o===a.length-1,onClick:()=>i(o,1),children:"→"})]})]},s.value)})})}function fx({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:mQ().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(hL,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(fg,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(ff,{field:e,busy:t,onSave:n}):(0,r.jsx)(fm,{field:e,busy:t,onSave:n})}function fv({field:e,busy:t,error:n,onSave:a}){return(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:mQ().settingLabel,children:e.label}),(0,r.jsx)("div",{className:mQ().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:mQ().error,children:n})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)(fx,{field:e,busy:t,onSave:a})})]})}function fb({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:mQ().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:mQ().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:mQ().themePreviewPanel,children:[(0,r.jsx)("div",{className:mQ().themePreviewLine}),(0,r.jsx)("div",{className:mQ().themePreviewLine})]})]})}let fy='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',fw=new Set(["hideThinkingBlock"]);function fk({cwd:e,sessionId:t,initialSection:n="models",onClose:i,onModelsChanged:s,onReloaded:o}){let[l,c]=(0,a.useState)(n),[d,u]=(0,a.useState)(null),[p,h]=(0,a.useState)(!0),[m,f]=(0,a.useState)(null),[g,x]=(0,a.useState)(""),[v,b]=(0,a.useState)(new Set),[y,w]=(0,a.useState)({}),[k,j]=(0,a.useState)(!1),[S,C]=(0,a.useState)(!1),{theme:N,setPreference:T}=nm(),I={enabled:(0,a.useSyncExternalStore)(fc,fs,()=>!1),setEnabled:fo},{locale:M,t:R}=(0,z.s)(),E=(0,a.useRef)(null),L=e=>"ko"===M?fd.shell[e]??e:e,$=(0,a.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,a.useEffect)(()=>{$()},[$]),(0,a.useEffect)(()=>{let e=E.current;if(!e)return;(Array.from(e.querySelectorAll(fy)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(fy)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let a=n[0],i=n[n.length-1];t.shiftKey&&(r===a||!e.contains(r))?(t.preventDefault(),i.focus()):t.shiftKey||r!==i&&e.contains(r)||(t.preventDefault(),a.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let P=(0,a.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),a=await r.json();if(!r.ok||a.error)throw Error(a.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:a.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await nh(e),await $()):fw.has(t.path)?await nX(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,$]),A=(0,a.useMemo)(()=>new Map(d?.fields.map(e=>[e.path,e.value])??[]),[d?.fields]),F=(0,a.useMemo)(()=>d?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,A))??[],[d?.fields,A]),_=l.startsWith("settings:")?l.slice(9):null,W=(0,a.useMemo)(()=>{let e=g.trim().toLowerCase();return e?F.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):_?F.filter(e=>e.tab===_&&("appearance"!==_||"Theme"!==e.group)):[]},[_,g,F]),O=(0,a.useCallback)(()=>{s?.(),i()},[i,s]),D=(0,a.useCallback)(async()=>{if(t){C(!0);try{await uq(t,{type:"reload"}),j(!1),o?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[o,t]),H=d?.tabs.find(e=>e.id===_),U=g.trim()?`${L("Search")} \xb7 ${W.length}`:H?.label??L("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:mQ().group,children:[(0,r.jsx)("h3",{className:mQ().groupTitle,children:t}),n.map(e=>(0,r.jsx)(fv,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void P(e,t)},e.path))]},t):null}),q=()=>p?(0,r.jsx)("div",{className:mQ().empty,children:L("Loading omp settings…")}):m||!d?(0,r.jsx)("div",{className:mQ().empty,children:m??L("Settings unavailable")}):(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:U}),(0,r.jsx)("p",{className:mQ().contentDescription,children:L(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,r.jsxs)("div",{className:mQ().reloadNotice,children:[(0,r.jsx)("span",{children:L("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:L(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:mQ().settingsBody,children:W.length?B(W,H?.groups??[]):(0,r.jsx)("div",{className:mQ().empty,children:L("No settings match this search.")})})]});return(0,r.jsx)("div",{className:mQ().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&O()},children:(0,r.jsxs)("div",{ref:E,tabIndex:-1,className:mQ().window,role:"dialog","aria-modal":"true","aria-label":L("Settings"),children:[(0,r.jsxs)("aside",{className:mQ().sidebar,children:[(0,r.jsxs)("div",{className:mQ().brand,children:[(0,r.jsx)("div",{className:mQ().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:mQ().title,children:L("Settings")}),(0,r.jsx)("code",{className:mQ().context,title:e??L("Global configuration"),children:e??L("Global configuration")})]}),(0,r.jsxs)("div",{className:mQ().searchWrap,children:[(0,r.jsxs)("svg",{className:mQ().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:mQ().search,value:g,"aria-label":L("Search /settings"),placeholder:L("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:mQ().nav,children:[(0,r.jsx)("div",{className:mQ().navLabel,children:L("Configuration")}),fu.map(t=>{let n=t.labelKey?R(t.labelKey):L(t.label);return(0,r.jsxs)("button",{type:"button",className:mQ().navButton,"data-active":!g&&l===t.id,"aria-current":g||l!==t.id?void 0:"page",disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${L("requires a project")}`:n,onClick:()=>{x(""),c(t.id)},children:[(0,r.jsx)(fh,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:mQ().navLabel,children:L("OMP settings")}),d?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:mQ().navButton,"data-active":!g&&_===e.id,"aria-current":g||_!==e.id?void 0:"page",onClick:()=>{x(""),c(`settings:${e.id}`)},children:[(0,r.jsx)(fh,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:mQ().closeRail,children:(0,r.jsxs)("button",{type:"button",className:mQ().closeButton,onClick:O,children:[(0,r.jsx)("span",{children:L("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:mQ().content,children:g.trim()?q():"models"===l?(0,r.jsx)(mI,{cwd:e,embedded:!0,onClose:O,onModelsChanged:s}):"themes"===l?d?(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:L("Themes")}),(0,r.jsxs)("p",{className:mQ().contentDescription,children:[L("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),L(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:mQ().settingsBody,children:[(0,r.jsx)("div",{className:mQ().themeGrid,children:["dark","light"].map(e=>{let t=d.fields.find(t=>t.path===`theme.${e}`),n=d.theme.palettes[e];return(0,r.jsxs)("div",{className:mQ().themeCard,children:[(0,r.jsx)(fb,{mode:e,palette:n}),(0,r.jsxs)("div",{className:mQ().themeCardBody,children:[(0,r.jsxs)("div",{className:mQ().themeCardHeader,children:[(0,r.jsxs)("span",{className:mQ().themeSlot,children:[e,L(" mapping")]}),N===e&&(0,r.jsx)("span",{className:mQ().themeActive,children:L("Active on web")})]}),(0,r.jsx)(hL,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void P(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:mQ().closeButton,style:{marginTop:8},onClick:()=>T(e),children:[L("Preview "),e]})]})]},e)})}),(0,r.jsx)("section",{className:mQ().group,children:(0,r.jsxs)("div",{className:mQ().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:"settings-graphite-label",className:mQ().settingLabel,children:R("theme.graphite")}),(0,r.jsx)("div",{className:mQ().settingDescription,children:R("theme.graphiteHint")})]}),(0,r.jsx)("div",{className:mQ().settingControl,children:(0,r.jsx)("button",{type:"button",role:"switch",className:mQ().switch,"data-on":I.enabled,"aria-checked":I.enabled,"aria-labelledby":"settings-graphite-label",onClick:()=>I.setEnabled(!I.enabled)})})]})}),B(d.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,r.jsx)("div",{className:mQ().empty,children:p?L("Loading themes…"):m??L("Themes unavailable")}):"skills"===l&&e?(0,r.jsx)(m_,{cwd:e,embedded:!0,onClose:O}):"plugins"===l&&e?(0,r.jsx)(mY,{cwd:e,sessionId:t,embedded:!0,onClose:O,onReloaded:o}):"mcp"===l?(0,r.jsx)(fj,{cwd:e,sessionId:t,onReloaded:o}):"access"===l?(0,r.jsx)(m0,{}):"trust"===l?(0,r.jsx)(m5,{cwd:e}):"live-voice"===l?(0,r.jsx)(m2,{}):"attachments"===l?(0,r.jsx)(m8,{}):"characters"===l?(0,r.jsx)(m4,{}):q()})]})})}function fj({cwd:e,sessionId:t,onReloaded:n}){let[i,s]=(0,a.useState)(null),[o,l]=(0,a.useState)("user"),[c,d]=(0,a.useState)(0),[u,p]=(0,a.useState)(""),[h,m]=(0,a.useState)(""),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(!1),[b,y]=(0,a.useState)(null),w=(0,a.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);s(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,a.useEffect)(()=>{w()},[w]);let k=i?"user"===o?i.user:i.project:null,j=k?.servers[c]??null;(0,a.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(t=>{if(!t)return t;let n={..."user"===o?t.user:t.project,servers:e};return"user"===o?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===c?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,servers:n})}),i=await a.json();if(!a.ok||i.error)throw Error(i.error??`HTTP ${a.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${o}:${r.name}`),g(null);try{let a=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${a}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:o,name:r.name,enabled:!r.enabled})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await w(),t&&(await uq(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:mQ().scrollContent,children:[(0,r.jsxs)("header",{className:mQ().contentHeader,children:[(0,r.jsx)("h2",{className:mQ().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:mQ().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,r.jsx)("div",{className:mQ().settingsBody,children:i?(0,r.jsxs)("div",{className:mQ().mcpLayout,children:[(0,r.jsxs)("aside",{className:mQ().mcpList,children:[(0,r.jsxs)("div",{className:mQ().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:mQ().scopeButton,"data-active":"user"===o,onClick:()=>{l("user"),d(0)},children:["User \xb7 ",i.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:mQ().scopeButton,"data-active":"project"===o,disabled:!i.project,onClick:()=>{l("project"),d(0)},children:["Project \xb7 ",i.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:mQ().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:mQ().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${o}:${e.name}`;return(0,r.jsxs)("div",{className:mQ().serverRow,"data-active":c===t,children:[(0,r.jsxs)("button",{type:"button",className:mQ().serverSelect,title:e.source?.path,onClick:()=>d(t),children:[(0,r.jsx)("span",{className:mQ().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:mQ().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:mQ().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:mQ().serverToggle,"data-on":e.enabled,disabled:b===n,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:mQ().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:mQ().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),d(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:mQ().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:mQ().editorHeader,children:[(0,r.jsx)("input",{className:mQ().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:mQ().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==c)),d(Math.max(0,c-1)))},children:"Delete"})]}),!1===j.editable&&(0,r.jsxs)("div",{className:mQ().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:mQ().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:mQ().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:mQ().error,children:f}),(0,r.jsx)("div",{className:mQ().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:mQ().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:mQ().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:mQ().empty,children:f??"Loading MCP configuration…"})})]})}let fS="cuelo-notification-prompt-dismissed";function fC({variant:e,locale:t,permission:n,dismissed:a,request:i,dismiss:s}){let o="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||a?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":o?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:o?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:i,children:o?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":o?"알림 권한 안내 닫기":"Dismiss notification prompt",children:o?"닫기":"Dismiss"})]}):(0,r.jsx)(c.k.Item,{disabled:"denied"===n,onClick:"default"===n?i:void 0,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:"default"===n?o?"알림 켜기":"Enable notifications":o?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(c.k.ItemDescription,{children:o?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function fN({cwd:e,busy:t,scheduled:n,error:i,onCancel:s,onConfirm:o,onCancelSchedule:l}){let{t:c}=(0,z.s)(),d=(0,a.useRef)(null);(0,a.useEffect)(()=>{d.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:"var(--radius-control)",cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||s()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:c(n?"trust.scheduledTitle":"trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:c(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),i&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:i})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c("trust.cancelSchedule")}),(0,r.jsx)("button",{ref:d,type:"button",onClick:s,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:c(n?"trust.close":"trust.cancel")}),!n&&(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:c(t?"trust.trusting":"trust.trustProject")})]})]})})}var fT=n(55681);let fI={kind:"loading"};function fM(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":s4(e.status)?"var(--accent)":"var(--success)"}function fR(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let fE={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function fL(e){return e.lastUpdate||e.progress?.durationMs||0}let f$=(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})}),fP=[];function fA({state:e,summary:t,reason:n,onOpenFile:a}){let{st:i}=ax(),{t:s}=(0,z.s)(),o="ready-archive"===e.kind||"empty"===e.kind&&"archive"===e.source;if(!t&&!o)return null;let l=t?.files??[],c=t?.checks??[];return(0,r.jsxs)("div",{className:"maker-detail-outcome",children:[n&&(0,r.jsxs)("p",{className:"maker-detail-reason",children:[(0,r.jsx)("span",{children:i("detail.reason")})," ",n]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:i("summary.heading.files")}),o?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):l.length>0?(0,r.jsx)(aM,{files:l,onOpenFile:a}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noFiles")})]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:i("summary.heading.checks")}),o?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):c.length>0?(0,r.jsx)("ul",{className:"answer-summary-list",children:c.map(e=>(0,r.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,r.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,r.jsxs)("span",{className:"answer-check-result",children:[s(fF[e.state]),null!==e.exitCode?` \xb7 ${i("summary.check.exit",{code:e.exitCode})}`:null]})]},e.toolCallId))}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noChecks")})]})]})}let fF={passed:"makerDetail.checkPassed",unverified:"makerDetail.checkUnverified",failed:"makerDetail.checkFailed",unobserved:"makerDetail.checkUnobserved"};function f_({sessionId:e,sessionCwd:t,record:n,selection:i,client:s,visible:o,onBack:l,onOpenFile:c}){let{st:d}=ax(),{t:u}=(0,z.s)(),p=n?.key,h=n?.live?.id,m=n?.live?.status,f=n?.archive?.name,g=(0,a.useMemo)(()=>p?[{key:p,liveId:h,status:m,archiveName:f}]:[],[p,h,m,f]),x=(0,a.useRef)(null),v=(0,a.useRef)(null),b=s7(g,{sessionId:e,client:s,enabled:o&&g.length>0}),y=(p?b.get(p)?.state:void 0)??fI;(0,a.useEffect)(()=>{o&&v.current?.focus({preventScroll:!0})},[i.key,o]),(0,a.useEffect)(()=>{if(!o||"ready-live"!==y.kind&&"ready-archive"!==y.kind)return;let e=requestAnimationFrame(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[y,o]);let w="ready-live"===y.kind?y.entries:fP,k=(0,a.useMemo)(()=>{let e=new Map;for(let t of w)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[w]),j=(0,a.useMemo)(()=>"ready-live"===y.kind?oP(y.entries,t):null,[y,t]),S=n?.live?.id||n?.archive?.name||"Subagent",C=n?aL(n).title:S,N=i.status;return(0,r.jsxs)("div",{role:"region","aria-label":u("makerDetail.region",{title:S}),style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsx)(p5,{back:{label:u("subagents.back"),onClick:l},title:C,titleTooltip:n?`${C}
|
|
69
|
+
${S} \xb7 ${fR(n)}`:void 0,titleRef:v,subtitle:n?`${S} \xb7 ${fR(n)}`:void 0,state:N?(0,r.jsx)(o$,{maker:N,st:d}):n?.live&&(0,r.jsx)("span",{style:{color:fM(n.live),fontFamily:"var(--font-mono)",fontSize:11},children:n.live.status})}),!n&&(0,r.jsx)("div",{role:"status",className:"maker-detail-empty",style:{padding:24,textAlign:"center"},children:u("makerDetail.unavailable")}),n&&(0,r.jsx)(fA,{state:y,summary:j,reason:N?.verdict?.reason??null,onOpenFile:c}),n&&(0,r.jsxs)("div",{ref:x,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===y.kind&&(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===y.kind&&y.entries.flatMap((e,n)=>{if(!("message"in e))return[];let a=y.entries[n-1];return[(0,r.jsx)(lP,{message:e.message,toolResults:k,cwd:t,showTimestamp:!0,prevTimestamp:a&&"message"in a?a.message.timestamp:void 0},e.id)]}),"ready-archive"===y.kind&&(0,r.jsxs)(r.Fragment,{children:[y.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:y.note}),y.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),y.entries.map((e,t)=>(0,r.jsxs)("div",{style:{margin:"0 0 7px",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:11,lineHeight:1.55},children:[(0,r.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===y.kind&&(0,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[y.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:y.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===y.kind&&(0,r.jsx)("div",{role:"status",style:{padding:10,border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:y.message}),"error"===y.kind&&(0,r.jsx)("div",{role:"alert",style:{padding:10,border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5},children:y.message})]})]})}function fz({record:e,view:t,onSelect:n}){let i,s,o,{st:l}=ax(),c=(0,a.useId)(),d=e.live,u=e.archive,p=aL(e),h=!!(d&&s4(d.status)),m=h?p.stage:null,f=h&&t?t:null,g=f?.phase?l("phase.current",{phase:l(`phase.${f.phase}`)}):"",x=f?.todo?oM(l,f.todo):"",v=d?.id||u?.name||"Subagent",b=fR(e),y=(i=e.live,(o=(s=(i?.agent||i?.progress?.agent||"").trim()).toLowerCase().split(/[-_.:/\s]+/).filter(Boolean).join(" "))?{kind:"known",agent:s,source:i?.agentSource??"bundled",label:o}:{kind:"unknown"}),w=a$(e),k=w.modelShort??"모델 미확인",j=w.effort??"추론 미확인",S="known"===y.kind?y.label:"역할 미확인";return(0,r.jsx)("div",{role:"listitem",children:(0,r.jsxs)("button",{type:"button",onClick:n,"data-identity":e.identity,"data-subagent-key":e.key,title:`${v}
|
|
70
|
+
${w.model??"모델 미확인"} \xb7 ${j}
|
|
71
|
+
${p.title}${m?`
|
|
72
|
+
현재 단계: ${m}`:""}${g?`
|
|
73
|
+
${g}`:""}${x?`
|
|
74
|
+
${x}`:""}`,"aria-label":`${S} ${v}, 업무 ${p.title}${m?`, 현재 단계 ${m}`:""}${g?`, ${g}`:""}${x?`, ${x}`:""}, ${d?d.status:u?.status??"미확인"}, 모델 ${w.model??"미확인"}, 추론 ${j}`,"aria-describedby":f&&d?c:void 0,style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"4px 8px",width:"100%",marginBottom:8,padding:12,border:"1px solid var(--seed-color-stroke-neutral-weak)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-default)",color:"var(--seed-color-fg-neutral)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===y.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":y.agent,title:`${y.agent} \xb7 ${fE[y.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),y.label]}):(0,r.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,r.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:p.title})]}),d?(0,r.jsx)("span",{style:{color:fM(d),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:d.status}):u?(0,r.jsx)("span",{style:{color:"failed"===u.status?"var(--danger)":"aborted"===u.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:u.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),m&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${m}`,style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)"},children:[(0,r.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",m]}),f?.phase&&(0,r.jsxs)("span",{className:"subagent-phase-line",style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[(0,r.jsx)(oC,{phase:f.phase}),x&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle)"},title:x,children:` \xb7 ${x}`})]}),f&&d&&(0,r.jsx)("span",{className:"subagent-eta-line",style:{gridColumn:"1 / -1",minWidth:0,color:"var(--seed-color-fg-neutral)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)(oR,{snapshot:d,view:f,id:c})}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":w.model?w.effort?"both":"model":w.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[k,w.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",j]})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 8px",minWidth:0,color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)"},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v}),(0,r.jsx)("span",{children:b})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 10px",color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)",fontVariantNumeric:"tabular-nums"},children:[d?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",d.progress.toolCount]}),(0,r.jsxs)("span",{children:[d.progress.tokens.toLocaleString()," Token"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}초`;let n=Math.floor(t/60);return n<60?`${n}분${t%60?` ${t%60}초`:""}`:`${Math.floor(n/60)}시간 ${n%60}분`}(d.progress.durationMs)})]}),u&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===u.messages?"메시지 수 미확인":`메시지 ${u.messages}`}),(0,r.jsxs)("span",{children:[(u.bytes/1024).toFixed(+(u.bytes<10240))," KB"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Date.now()-e);return t<1e4?"방금 전":t<6e4?`${Math.floor(t/1e3)}초 전`:t<36e5?`${Math.floor(t/6e4)}분 전`:t<864e5?`${Math.floor(t/36e5)}시간 전`:`${Math.floor(t/864e5)}일 전`}(u.modified)})]})]})]})})}function fW({title:e,sessionId:t,sessionPath:n,sessionCwd:i,liveSubagents:s,client:o,visible:l=!0,onClose:c,onReturnFocus:d,selection:u,onSelectionChange:p,onReturnToOrigin:h,onOpenFile:m}){let{t:f}=(0,z.s)(),g=(0,a.useMemo)(()=>o??aO(),[o]),[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)({kind:"loading"}),[w,k]=(0,a.useState)({kind:"loading"}),[j,S]=(0,a.useState)(!1),[C,N]=(0,a.useState)(null),T=p?u??null:C,I=p??N,[M,R]=(0,a.useState)(0),E=(0,a.useRef)(null),L=(0,a.useRef)(null);(0,a.useEffect)(()=>{v([]),y({kind:"loading"}),k({kind:"loading"}),S(!1),N(null)},[t]),(0,a.useEffect)(()=>{if(!l||!t)return;let e=!1,n=!1,r=null,a=async()=>{if(e||n||"visible"!==document.visibilityState)return;n=!0,r=new AbortController;let[a,i]=await Promise.allSettled([g.getLiveSnapshots(t,r.signal),g.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===a.status)v(a.value.subagents),y(a.value.subagents.length>0?{kind:"ready",data:a.value.subagents}:{kind:"empty",data:[]});else{let e=s3(a.reason);y("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===i.status)S(!0===i.value.listTruncated),k(i.value.subagents.length>0?{kind:"ready",data:i.value.subagents}:{kind:"empty",data:[]});else{let e=s3(i.reason);k("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};a();let i=setInterval(()=>void a(),3e3),s=()=>{"visible"===document.visibilityState&&a()};return document.addEventListener("visibilitychange",s),()=>{e=!0,r?.abort(),clearInterval(i),document.removeEventListener("visibilitychange",s)}},[M,g,t,l]);let $=(0,a.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let a of[...e,...t]){let e=n.get(a.id);if(!e){r.push(a.id),n.set(a.id,a);continue}let[t,i]=fL(a)>=fL(e)?[a,e]:[e,a];n.set(a.id,{...t,assignment:t.assignment??i.assignment,description:t.description??i.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(s,x),[s,x]),P="ready"===w.kind||"empty"===w.kind?w.data:[],A=(0,a.useMemo)(()=>(function(e,t){let n=new Map(t.map(e=>[e.name,e])),r=new Set,a=e.map(e=>{let t=(function(e){let t=[];if(e.sessionFile){let n=e.sessionFile.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"");n&&t.push({name:n,match:"session-file"})}return t.some(t=>t.name===e.id)||t.push({name:e.id,match:"name"}),t})(e).find(e=>n.has(e.name)&&!r.has(e.name)),a=t?n.get(t.name):void 0;return a&&r.add(a.name),{key:`live:${e.id}`,identity:a?"live-archive":"live",live:e,...a&&t?{archive:a,archiveMatch:t.match}:{}}});for(let e of t)r.has(e.name)||a.push({key:`archive:${e.name}`,identity:"archive",archive:e});return a})($,P),[P,$]),F=T?A.find(e=>e.key===T.key)??null:null,_=F&&T?.toolCallId&&F.live?.parentToolCallId!==T.toolCallId?null:F,W=ok({sessionId:t,snapshots:$,client:g,enabled:l&&!T,cwd:i??void 0});if((0,a.useEffect)(()=>{let e=L.current;if(T||!e)return;L.current=null;let t=[...E.current?.querySelectorAll("[data-subagent-key]")??[]].find(t=>t.dataset.subagentKey===e);t?.focus({preventScroll:!1})}),T&&t)return(0,r.jsx)(f_,{sessionId:t,sessionCwd:i,record:_,selection:T,client:g,visible:l,onOpenFile:m,onBack:()=>{I(null),T.origin&&h?h(T.origin):L.current=T.key}});let O=0===A.length&&"loading"===b.kind&&"loading"===w.kind,D=0===A.length&&("empty"===b.kind||0===s.length)&&"empty"===w.kind;return(0,r.jsxs)("section",{ref:E,"aria-label":"Subagent 기록","data-state":O?"loading":D?"empty":"ready",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsx)(p5,{title:e,titleTooltip:n??void 0,subtitle:O||!t?void 0:f("panel.subagentsCount",{count:A.length}),actions:[{id:"refresh",label:f("panel.refresh"),icon:f$,onClick:()=>R(e=>e+1)}],close:c?{label:f("panel.close"),onClick:()=>{c?.(),d?.()}}:void 0}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?O?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):D?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,r.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:A.map(e=>(0,r.jsx)(fz,{record:e,view:e.live?W.get(e.live.id):void 0,onSelect:()=>I({key:e.key})},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!O&&"loading"===b.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!O&&"loading"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===b.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:b.message}),"error"===b.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:b.message}),"unreachable"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:w.message}),"error"===w.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:9.5},children:w.message}),j&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let fO=new Set(["efficiency","sidechat","resource"]),fD=["process","efficiency","subagents","files","resource","sidechat","plugins","memory"];function fH({activeView:e,onViewChange:t,viewLabels:n,sessionId:a,sessionPath:i,sessionName:l,sessionCwd:c,liveSubagents:d,subagentClient:u,processSlot:p,fileSlot:h,sideChatSlot:m,resourceSlot:f,efficiencySlot:g,pluginsSlot:x,memorySlot:v,visible:b=!0,onClose:y,onReturnFocus:w,expand:k=null,selectedMaker:j,onSelectMaker:S,onReturnToDispatch:C,onOpenFile:N,fileOpen:T=!1}){return(0,r.jsx)(pQ.Provider,{value:k,children:(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":"보조 패널","data-auxiliary-view":e,"data-expanded":k?.expanded?"true":void 0,children:(0,r.jsxs)(fT.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:e,onValueChange:e=>t(e),children:[(0,r.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,r.jsxs)(fT.J.List,{"aria-label":"보조 패널 보기",children:[fD.map(e=>{let t="subagents"===e?d.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(fT.J.Trigger,{value:e,"aria-label":t>0?`${n[e]} (실행 중 ${t})`:void 0,children:[(0,r.jsx)("span",{className:"auxiliary-deck-tab-label",children:n[e]}),t>0&&(0,r.jsx)(nI.E,{size:"medium",variant:"weak",tone:"informative","aria-hidden":"true",children:t})]},e)}),(0,r.jsx)(fT.J.Indicator,{})]}),(fO.has(e)||"files"===e&&!T)&&(0,r.jsx)(p6,{className:"auxiliary-deck-expand"}),y&&(0,r.jsx)(s.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{y?.(),w?.()},"aria-label":"보조 패널 닫기",children:(0,r.jsx)(o.In,{size:"16px",svg:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})})]}),(0,r.jsx)(fT.J.Content,{value:"process",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(fT.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(fT.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(fW,{title:n.subagents,sessionId:a,sessionPath:i,sessionCwd:c,liveSubagents:d,client:u,visible:b&&"subagents"===e,selection:j,onSelectionChange:S,onReturnToOrigin:C,onOpenFile:N})}),(0,r.jsx)(fT.J.Content,{value:"files",className:"auxiliary-deck-panel",children:h}),(0,r.jsx)(fT.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:m}),(0,r.jsx)(fT.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:f}),(0,r.jsx)(fT.J.Content,{value:"plugins",className:"auxiliary-deck-panel",children:x}),(0,r.jsx)(fT.J.Content,{value:"memory",className:"auxiliary-deck-panel",children:v})]})})})}function fU({title:e,data:t,onOpenFile:n}){let{t:i}=(0,z.s)(),o=t?.groups??[],[l,c]=(0,a.useState)(()=>new Set);return(0,r.jsxs)("section",{className:"process-log","aria-label":e,children:[(0,r.jsx)(p5,{title:`${o.length} ${i(1===o.length?"process.turn":"process.turns")}`}),(0,r.jsxs)("div",{className:"process-log-body",children:[t?.status?(0,r.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,r.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),t.status]}):null,0===o.length?(0,r.jsx)("p",{className:"process-log-empty",children:i("process.empty")}):o.map((e,a)=>{let o=l.has(e.anchorIdx),d=function(e){if(!e||"user"!==e.role)return null;let t=("string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join(" ")).replace(/\s+/g," ").trim();return 0===t.length?null:t.length>72?`${t.slice(0,72)}…`:t}(t?.messages[e.anchorIdx]),u=[`${e.messageCount} ${i(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${i(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(s.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!o,onClick:()=>c(t=>{let n=new Set(t);return n.has(e.anchorIdx)?n.delete(e.anchorIdx):n.add(e.anchorIdx),n}),title:o?i("chat.expandProcess"):i("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:d??i("chat.processDetails")}),(0,r.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!o&&(0,r.jsx)("div",{className:"process-log-entries",children:e.entries.map((a,i)=>{let s=t?.messages[a.idx];return s?(0,r.jsx)(lP,{message:a.blocks?eV(s,a.blocks,{omitUsage:!0}):s,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[a.idx],sessionId:t?.sessionId,showTimestamp:!1},`process-${e.anchorIdx}-${i}`):null})})]},`turn-${e.anchorIdx}-${a}`)})]})]})}let fB=6,fq="omp-btw-log:",fV="omp-btw-log-index";function fK(e){return e.trim().toLowerCase()}function fG(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function fJ(e){if(!Array.isArray(e))return[];let t=[],n=0;for(let r of e){if(!r||"object"!=typeof r||"string"!=typeof r.q||"string"!=typeof r.a)continue;let e={q:r.q,a:r.a,at:"number"==typeof r.at&&Number.isFinite(r.at)?r.at:0};t.push(e),n+=e.q.length+e.a.length}for(;t.length>40||n>12e4;){let e=t.shift();if(!e)break;n-=e.q.length+e.a.length}return t}function fZ(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function fY(e,t={}){let n=t.now??Date.now,r=new Map,a=new Set,i=!1,s=[],o=t=>{if(e)try{e.removeItem(t)}catch{}},l=e=>{r.delete(e),a.delete(e),o(fq+e)},c=()=>{let e=new Set,t=[];for(let n of(s.sort((e,t)=>t.updatedAt-e.updatedAt),s))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):l(n.id));s=t},d=()=>{if(!i){if(i=!0,e)try{let t=e.getItem(fV),n=t?JSON.parse(t):[];Array.isArray(n)&&(s=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:fK(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{s=[]}c()}},u=e=>{d();for(let t=s.length-1;t>=0;t-=1){if(s[t].id===e)continue;let[n]=s.splice(t,1);return l(n.id),!0}return!1},p=t=>{if(e){try{e.setItem(fV,JSON.stringify(s));return}catch(e){if(!fZ(e)||!u(t))return}try{e.setItem(fV,JSON.stringify(s))}catch{}}},h=t=>{let n=fK(t);if(!n)return[];if(a.has(n))return fG(r.get(n)??[]);if(e)try{let t=e.getItem(fq+n);if(t){let e=JSON.parse(t),a=fJ(e?.entries);return r.set(n,a),fG(a)}}catch{}return fG(r.get(n)??[])},m=e=>{let t=fK(e);t&&(d(),s=s.filter(e=>e.id!==t),l(t),p(null))};return{read:h,append:(t,i)=>((t,i)=>{let o=fK(t);if(!o)return[];let l=fJ(i),h=n();if(r.set(o,fG(l)),d(),(s=s.filter(e=>e.id!==o)).unshift({id:o,updatedAt:h}),c(),p(o),!e)return fG(l);let m=JSON.stringify({updatedAt:h,entries:l});try{return e.setItem(fq+o,m),a.delete(o),fG(l)}catch(e){if(!fZ(e)||!u(o))return a.add(o),fG(l)}p(o);try{e.setItem(fq+o,m),a.delete(o)}catch{a.add(o)}return fG(l)})(t,[...h(t),i]),history:(e,t=fB)=>h(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:m,cleanup:(t,r)=>{if(!t.complete)return;d();let a=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=fK(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);a.set(t,Number.isFinite(n)?n:0)}let i=r?fK(r):null,l=n();for(let e of[...s])if(e.id!==i){if(!a.has(e.id)){m(e.id);continue}l-Math.max(a.get(e.id)??0,e.updatedAt)>6048e5&&m(e.id)}if(!e||"function"!=typeof e.key||"number"!=typeof e.length)return;let c=[];try{for(let t=0;t<e.length;t+=1){let n=e.key(t);if(!n?.startsWith(fq))continue;let r=fK(n.slice(fq.length));a.has(r)||r===i||c.push(n)}}catch{return}for(let e of c)o(e)}}}function fX(){let e=new Map,t=new Map,n=new Map,r=e=>{n.get(e)?.forEach(e=>{e()})};return{read(t){let n=e.get(t);return n?{...n.snapshot}:null},begin(t,n){if(e.has(t))return null;let a=new AbortController;return e.set(t,{snapshot:{sessionId:t,question:n,text:"",model:null},controller:a}),r(t),{controller:a}},ingest(t,n){let a=e.get(t);a&&("d"===n.t?a.snapshot.text+=n.v:"done"===n.t?a.snapshot.text=n.v||a.snapshot.text:"m"===n.t&&(a.snapshot.model=n.v),r(t))},abort(t){let n=e.get(t);return!!n&&(n.controller.abort(),!0)},finish(n,a){e.has(n)&&(e.delete(n),t.set(n,a),r(n))},takeOutcome(e){let n=t.get(e)??null;return n&&t.delete(e),n},subscribe(e,t){let r=n.get(e);return r||(r=new Set,n.set(e,r)),r.add(t),()=>{r.delete(t),0===r.size&&n.delete(e)}}}}class fQ extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function f0(e){let t;try{t=JSON.parse(e)}catch{throw new fQ("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new fQ("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new fQ("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class f1{push(e){this.buffer+="string"==typeof e?e:this.decoder.decode(e,{stream:!0});let t=this.buffer.split("\n");return this.buffer=t.pop()??"",t.flatMap(e=>e.trim()?[f0(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[f0(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function f2(e){let t=await e.text().catch(()=>"");if(!t)return`HTTP ${e.status}`;try{let e=JSON.parse(t);if("string"==typeof e.error&&e.error)return e.error}catch{}return t}function f8(e=!1){return{minHeight:30,padding:"4px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",fontWeight:650}}function f4({children:e}){return(0,r.jsx)("div",{className:"side-chat-question",style:{alignSelf:"flex-end",maxWidth:"92%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55},children:e})}function f5({children:e,streaming:t=!1}){return(0,r.jsxs)("div",{className:`side-chat-answer${t?" is-streaming":""}`,style:{alignSelf:"flex-start",maxWidth:"100%",padding:"8px 10px",border:"1px solid var(--border)",color:"var(--text)",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.58},children:[e?(0,r.jsx)(ny,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function f6({identity:e,status:t,utteranceKey:n,children:a}){let i=am(e?.sessionId,e?.provider,e?.credentialId,e?.model),s=cv(i?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[i&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(av,{seed:i.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:i.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[a,s&&(0,r.jsx)("img",{src:s.src,alt:s.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function f3({title:e,sessionId:t,sessionPath:n,sessionName:i,historyStore:s,flights:o,sessionCensus:l,client:c,visible:d=!0,onClose:u,onReturnFocus:p}){let h,m,f=(0,a.useMemo)(()=>c??function(e=(e,t)=>fetch(e,t),t="/api/sidecars/sidechat/ask"){return{async ask(n){let r;try{r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:n.sessionPath,question:n.question,history:n.history.slice(-fB)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new fQ("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new fQ("http",await f2(r),r.status);if(!r.body)throw new fQ("stream","사이드채팅 스트림을 열 수 없습니다.");let a=r.body.getReader(),i=new f1,s="",o=null,l=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)s+=t.v;else if("done"===t.t)s=t.v||s;else if("m"===t.t)o=t.v;else throw new fQ("server",t.v)};try{for(;;){let e=await a.read();if(e.done)break;l(i.push(e.value))}l(i.finish())}catch(e){if(n.signal?.aborted||e instanceof fQ)throw e;throw new fQ("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{a.releaseLock()}if(!s)throw new fQ("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:s,model:o}}}}(),[c]),g=t?.toLowerCase()??null,[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)({}),w=g??"",k=b[w]??"",j=(e,t)=>{y(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,a.useState)(0),[N,T]=(0,a.useState)({}),[I,M]=(0,a.useState)({}),[R,E]=(0,a.useState)({}),[L,$]=(0,a.useState)(null),[P,A]=(0,a.useState)(null),[F,_]=(0,a.useState)({}),[z,W]=(0,a.useState)({}),[O,D]=(0,a.useState)({}),H=(0,a.useRef)((h=new Set,m=new Set,{claim:e=>!(!e||h.has(e)||m.has(e))&&(h.add(e),!0),markSent(e){h.delete(e),m.add(e)},release(e){h.delete(e)}})),U=(0,a.useRef)(!0),B=(0,a.useRef)(g),q=(0,a.useRef)(d),V=(0,a.useRef)(null),K=(0,a.useRef)(!1),G=(0,a.useRef)(0),J=(0,a.useRef)(null);B.current=g,q.current=d,(0,a.useEffect)(()=>(U.current=!0,()=>{U.current=!1}),[]),(0,a.useEffect)(()=>{v(g?s.read(g):[])},[s,g]);let Z=(0,a.useRef)(null);(0,a.useEffect)(()=>{$(null),Z.current=null},[g]),(0,a.useEffect)(()=>{if(!d||!g||Z.current===g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0,a="model"in t?t.model:void 0;return{provider:t.provider,..."string"==typeof a&&a?{model:a}:{},..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&(Z.current=g,$(t?{...t,sessionId:g}:null))}).catch(()=>{e&&(Z.current=g,$(null))}),()=>{e=!1}},[g,d]),(0,a.useEffect)(()=>{if(!g)return;let e=()=>{if(!U.current||B.current!==g)return;let e=o.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)T(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),y(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;E(e=>({...e,[g]:t}))}v(s.read(g))}else null===o.read(g)&&v(s.read(g));C(e=>e+1)},t=o.subscribe(g,e);return e(),t},[o,s,g]),(0,a.useEffect)(()=>{l&&s.cleanup(l,g)},[s,g,l]),(0,a.useEffect)(()=>{d&&V.current?.focus()},[d,g]),(0,a.useEffect)(()=>{if(!d)return;let e=requestAnimationFrame(()=>{let e=J.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,d]);let Y=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=o.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await f.ask({sessionPath:n,question:e,history:s.history(g),signal:r,onEvent:e=>o.ingest(g,e)});s.append(g,{q:e,a:t.text,at:Date.now()}),o.finish(g,{kind:"done",model:t.model})}catch(n){let t=o.read(g)?.text??"";if(r.aborted){let n=!1;t&&(s.append(g,{q:e,a:t,at:Date.now()}),n=!0),o.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof fQ?n.kind:"unknown",a=n instanceof Error?n.message:String(n);o.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:a})}}finally{U.current&&q.current&&V.current?.focus()}},X=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(H.current.claim(r)){W(e=>({...e,[r]:"sending"})),D(e=>{let t={...e};return delete t[r],t});try{var a,i;let t,s=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),o=null;try{o=await s.json()}catch{}if(!s.ok){if(o&&"object"==typeof o&&"error"in o&&"string"==typeof o.error)throw Error(o.error);throw Error(`HTTP ${s.status}`)}let l=function(e){if(!e||"object"!=typeof e||!("running"in e)||"boolean"!=typeof e.running)return null;if(!e.running)return!1;if(!("state"in e)||!e.state||"object"!=typeof e.state)return null;let t=e.state;return"isStreaming"in t&&"boolean"==typeof t.isStreaming&&"isPromptRunning"in t&&"boolean"==typeof t.isPromptRunning&&"isBashRunning"in t&&"boolean"==typeof t.isBashRunning&&"isCompacting"in t&&"boolean"==typeof t.isCompacting&&"isHandoffRunning"in t&&"boolean"==typeof t.isHandoffRunning?t.isStreaming||t.isPromptRunning||t.isBashRunning||t.isCompacting||t.isHandoffRunning:null}(o);if(null===l)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let c=(a=e.q,i=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",a,"","[사이드채팅 답변]",i,...t?["","[추가 지시]",t]:[]].join("\n"));await uq(g,{type:l?"steer":"prompt",message:c}),H.current.markSent(r),W(e=>({...e,[r]:"sent"}))}catch(e){H.current.release(r),W(e=>{let t={...e};return delete t[r],t}),D(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},Q=()=>{if(g&&null!==o.read(g))return void o.abort(g);let e=k.trim();e&&(j(w,""),Y(e))},ee=N[g??""]??[],et=I[g??""],en=g?o.read(g):null,er=x.length>0||ee.length>0||null!==en,ea=en?.model??R[g??""],ei=!g||!n,es=null!==en,eo=!es&&!ei&&k.trim().length>0,el=!g||es,ec=L?.sessionId===g?L:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==en,"data-state":g&&n?en?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[i||g?.slice(0,8)||"세션 없음",ea?` \xb7 ${ea}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===o.read(g)&&(s.clear(g),v([]),T(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:el,style:f8(el),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),p?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...f8(),width:32,padding:0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{ref:J,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,a=`${g}:${n}`,i=z[a],s=P===a;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(f4,{children:e.q}),(0,r.jsx)(f6,{identity:ec,status:"settled",utteranceKey:n,children:(0,r.jsx)(f5,{children:e.a})}),"sent"===i?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!s&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>A(a),style:{...f8(),alignSelf:"flex-start"},children:"메인에 보내기"}),s&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value:F[a]??"",onChange:e=>_(t=>({...t,[a]:e.target.value})),style:{width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",padding:"7px 8px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void X(e,n,F[a]??""),disabled:"sending"===i,style:f8("sending"===i),children:"sending"===i?"보내는 중…":"메인으로 전송"}),"sending"!==i&&(0,r.jsx)("button",{type:"button",onClick:()=>A(null),style:f8(),children:"취소"})]})]}),O[a]&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:O[a]})]})]},n)}),ee.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(f4,{children:e.question}),(0,r.jsxs)(f6,{identity:ec,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(f5,{children:e.partialAnswer}),(0,r.jsx)("div",{role:"alert","data-error-kind":e.kind,style:{padding:"7px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:e.message})]})]},`${e.question}:${t}`)),en&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(f4,{children:en.question}),(0,r.jsx)(f6,{identity:ec,status:"streaming",utteranceKey:`stream:${en.question}`,children:(0,r.jsx)(f5,{streaming:!0,children:en.text})})]}),!er&&(0,r.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,r.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,r.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,r.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),et&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:et})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),Q()},style:{display:"flex",flexDirection:"column",gap:6,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,r.jsx)("textarea",{ref:V,id:"side-chat-question",rows:4,value:k,onChange:e=>j(w,e.target.value),onCompositionStart:()=>{K.current=!0},onCompositionEnd:()=>{K.current=!1,G.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-G.current<100;if(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}es||(e.preventDefault(),Q())},disabled:es||ei,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ei?"세션 파일이 준비되면 질문할 수 있습니다.":es?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!es&&!eo,style:f8(!es&&!eo),children:es?"중단":"전송"})]})]})]})}let f7="min-h-9 border border-border bg-bg px-3 text-xs font-medium text-text transition-colors hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-50",f9="pointer-coarse:min-h-11 pointer-coarse:min-w-11 max-sm:min-h-11 max-sm:min-w-11";function ge(...e){return e.filter(Boolean).join(" ")}function gt(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),a=Math.floor(n%1440/60),i=n%60;return r>0?`${r}d ${a}h 후 리셋`:a>0?`${a}h ${i}m 후 리셋`:`${i}m 후 리셋`}function gn(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let a=Math.floor(r/1440),i=Math.floor(r%1440/60),s=r%60;return a>0?`${a}d ${i}h 후 만료`:i>0?`${i}h ${s}m 후 만료`:`${s}m 후 만료`}function gr(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function ga(e,t){return!1!==t?gr(e):"number"==typeof e&&Number.isFinite(e)&&0!==e?`≥${gr(e)}`:"가격 미상"}function gi(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function gs(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function go(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function gl(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function gc(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function gd({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:t})]})}function gu({state:e,loading:t,subject:n}){return t&&"idle"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[n," 불러오는 중…"]}):"error"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsxs)("div",{className:"font-medium",children:[n,"을 불러오지 못했습니다."]}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:e.error.message}),(0,r.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===e.status?(0,r.jsxs)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:["마지막 데이터를 표시합니다. 새로고침 실패: ",e.error.message]}):null}function gp(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${t.getMonth()+1}/${t.getDate()} ${n}:${r}`}function gh({limit:e,now:t,detailed:n}){let a="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,i=Math.max(0,Math.min(100,100*a)),s=Math.round(100*a),o=function(e,t){let n=e.window,r=e.amount?.usedFraction;if(!n?.resetsAt||"number"!=typeof r)return null;let a=Math.max(0,n.resetsAt-t),i=100*r,s=Math.max(0,100-i);if(!n.durationMs){let e=a/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?s/e:s}}let o=Math.min(n.durationMs,Math.max(0,n.durationMs-a)),l=n.durationMs>432e5,c=l?864e5:36e5,d=n.durationMs/c,u=a/c,p=o/n.durationMs*100;return{burnOnly:!1,unit:l?"하루":"시간",partial:u<1,burn:u>=1?s/u:s,pacePct:p,deltaPct:i-p,nominal:100/d}}(e,t),l=e.daySlot,c=l?.usedPct==null||null==l.baselinePct?null:Math.max(0,Math.min(l.baselinePct,100)),d=null==c?null:Math.max(c,Math.min(100*a,100)),u=o?.pacePct==null?null:Math.min(o.pacePct,99.6),p=s>=90,h=o?.deltaPct!=null&&o.deltaPct>=.5?o.deltaPct:null,m=l?"unknown"===l.quality||null==l.usedPct?"구간 사용 — 기록 부족":"approx"===l.quality?`구간 사용 ≈${l.usedPct.toFixed(0)}% \xb7 추정`:"estimate"===l.quality?`구간 사용 ≥${l.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${l.usedPct.toFixed(1)}%`:null;return(0,r.jsxs)("div",{className:"usage-limit py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:e.label||e.id}),a>=1?(0,r.jsx)("span",{className:"usage-chip","data-tone":"danger",children:a>1?"한도 초과":"한도 도달"}):null,null!=h?(0,r.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${h.toFixed(1)}%`}):null,(0,r.jsxs)("span",{className:ge("shrink-0 font-mono text-sm font-semibold tabular-nums",p?"text-danger":"text-text"),children:[s,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":s,children:[(0,r.jsx)("div",{className:ge("absolute inset-y-0 left-0",p?"bg-danger":"bg-metric"),style:{width:`${i}%`}}),null!=c&&null!=d&&d>c?(0,r.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${c}%`,width:`${d-c}%`,boxShadow:"inset 1px 0 var(--bg-panel)"}}):null,null!=u?(0,r.jsx)("div",{className:"absolute inset-y-0 w-0.5 bg-text",style:{left:`${u}%`,boxShadow:"0 0 0 1px color-mix(in srgb, var(--bg-panel) 80%, transparent)"},"aria-hidden":"true"}):null,a>1?(0,r.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),m||e.window?.resetsAt?(0,r.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,r.jsx)("span",{className:"min-w-0 truncate",children:m??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:gt(e.window.resetsAt,t)}):null]}):null,n?(0,r.jsxs)("dl",{className:"m-0 mt-1.5 border-s-2 border-border ps-2.5",children:[o?.pacePct!=null?(0,r.jsx)(gd,{label:"페이스",value:`${o.pacePct.toFixed(1)}%`}):null,o?(0,r.jsx)(gd,{label:o.partial?"남은 한도":`앞으로 ${o.unit}`,value:`${o.burn.toFixed(1)}%`}):null,o?.nominal!=null?(0,r.jsx)(gd,{label:"균등 배분 기준",value:`${o.nominal.toFixed(1)}%/${"하루"===o.unit?"일":"시간"} \xb7 계산값`}):null,l?(0,r.jsx)(gd,{label:"구간",value:`${gp(l.slotStart)} ~ ${gp(l.slotEnd)} \xb7 ${l.slotIndex+1}/${l.slotCount}`}):null,l?(0,r.jsx)(gd,{label:"기록 품질",value:function(e){let t;if("unknown"===e.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";if("estimate"===e.quality){let t=null==e.firstSeenAt?"?":gp(e.firstSeenAt);return`추정 \xb7 구간 시작 표본이 없어 ${t}부터 센 최소량${e.paceOver?" \xb7 주간 진도 초과":""}`}let n=null==e.gapMs||0===e.gapMs?null:(t=Math.round(e.gapMs/6e4))<60?`${t}분`:`${Math.floor(t/60)}시간 ${t%60}분`;return"exact"===e.quality?n?`실측 \xb7 경계 ${n} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${n??"?"} 전 표본`}(l)}):null]}):null]})}let gm={"anthropic:5h":"5시간","anthropic:7d":"주간","anthropic:7d:opus":"주간","anthropic:7d:sonnet":"주간"};function gf({confirmId:e,pending:t,primaryRef:n,summary:a,onConfirm:i,onCancel:s}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),s())},children:[(0,r.jsxs)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:["저장된 리셋 ",a]}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:ge(f7,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:i,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:f7,disabled:t,onClick:s,children:"취소"})]})]})}function gg({report:e,brokerOk:t,now:n,active:i,identity:s,recommendation:o,pendingAction:l,feedback:c,onToggle:d,onReset:u}){let p=e.metadata??{},h=s??rK([e])[0],m=e.credentialId,f=Number.isSafeInteger(m)&&m>0,g=e.accountRole,x="usage-only"===g?"사용량":"control-only"===g?"계정 제어":p.planType,v=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,b=i?"active":e.disabled?"off":v?"auto-blocked":"idle",y="toggle"===l?"전환 중…":"reset"===l?"리셋 사용 중…":f?i?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":v?`자동 차단 \xb7 ${gt(e.autoBlockedUntilMs,n)}`:"control-only"===g?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===g?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",w=(0,a.useId)(),k=(0,a.useId)(),[j,S]=(0,a.useState)(!1),[C,N]=(0,a.useState)(!1),[T,I]=(0,a.useState)(null),M=(0,a.useRef)(null),R=(0,a.useRef)(null),E=(0,a.useRef)(!1),L=(0,a.useRef)(!1),$="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,P=function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e),A=P?.id??null,F=gn(P?.expiresAt??null,n),_=$?.availableCount,z=$&&"unavailable"!==$.state?"empty"===$.state||0===_?"없음":`${_??$.credits.length}개${F?` \xb7 ${F}`:""}`:"확인 불가",W=function(e){if("anthropic"!==e.provider)return null;let t=e.savedReset,n=t?.credits.find(e=>e.id===t.nextCreditId)??t?.credits[0],r=[...new Set((n?.clears??[]).map(e=>gm[e]).filter(e=>void 0!==e))];return r.length?`${r.join("\xb7")} 한도만`:null}(e),O=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let n="number"==typeof e.naturalResetAt?gt(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=gn(e.expiresAt??null,t),r="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${n&&"만료됨"!==n?n:"곧 만료"}됩니다.${r}`}(o,n),D=("openai-codex"===e.provider||"anthropic"===e.provider)&&t&&!0!==e.disabled&&$?.state==="available"&&0!==_&&null!=A;(0,a.useLayoutEffect)(()=>{if(T)return void R.current?.focus();if(E.current){var e;E.current=!1,e=M.current,e?.focus()}},[T]),(0,a.useEffect)(()=>{"reset"!==l&&(e.disabled||!t||$?.state!=="available")&&(E.current=!1,I(null))},[t,l,e.disabled,$?.state]);let H=async()=>{if(T&&!L.current){L.current=!0;try{await u(e,T.creditId)}finally{L.current=!1,E.current=!0,I(null)}}},U=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),B=l?"pending":i?"active":e.disabled?"off":v?"blocked":"idle";return(0,r.jsxs)("section",{className:"resource-account border-b border-border-strong px-4 py-3 last:border-b-0","data-account-state":b,"aria-current":i?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(av,{seed:h.seed,size:48,provider:e.provider}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("h3",{className:"m-0 flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm font-semibold text-text",children:[(0,r.jsx)("span",{children:h.alias}),(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${rV(e.provider)}${x?` \xb7 ${x}`:""}`})]}),(0,r.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,r.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":B,role:l?"status":void 0,children:y}),null!=U&&U-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${gt(U,n).replace(/ 후 리셋$/,"")}`}):null]})]}),f?(0,r.jsxs)("span",{className:"resource-account-toggle",children:[(0,r.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,r.jsx)("button",{type:"button",role:"switch",className:ge(f7,"resource-account-switch min-w-[3.25rem]"),disabled:null!=l||!t,"aria-label":`${h.alias} 계정 사용 설정`,"aria-checked":!e.disabled,"aria-busy":null!=l||void 0,title:t?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{E.current=!1,I(null),d(e)},children:e.disabled?"OFF":"ON"})]}):null]}),e.disabled?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):v?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(e.limits??[]).some(rd)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,c?(0,r.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===c.tone?"alert":"status",children:c.message}):null,(0,r.jsxs)("div",{id:k,className:"resource-account-limits divide-y divide-border",children:[j?(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,r.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:C?h.raw:h.masked||"—"}),h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":C,onClick:()=>N(!C),children:C?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(gh,{limit:e,now:n,detailed:j},e.id))]}),(e.limits??[]).length>0||h.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":j,"aria-controls":k,onClick:()=>{let e=!j;S(e),e||N(!1)},children:j?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?T?(0,r.jsx)(gf,{confirmId:w,pending:"reset"===l,primaryRef:R,summary:T.summary,onConfirm:()=>{H()},onCancel:()=>{E.current=!0,I(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3 border-t border-border pt-2.5","data-reset-state":t?$&&"unavailable"!==$.state?"empty"===$.state||0===_?"empty":"reset"===l?"pending":"ready":"unavailable":"offline",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,r.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,r.jsx)("span",{className:ge("font-mono text-xs tabular-nums text-text",o?.reason==="expiring-credit"&&"text-warning"),children:z})]}),W?(0,r.jsx)("span",{className:"text-xs text-text-muted",children:W}):null,D?(0,r.jsx)("button",{ref:M,type:"button",className:ge(f7,"ml-auto flex-none"),disabled:null!=l,onClick:()=>{A&&I({creditId:A,summary:z})},children:"리셋 사용"}):t&&e.disabled&&$?.state==="available"?(0,r.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),O?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:O}):null]}):null]})}function gx({state:e,loading:t,accountState:n,pendingActions:a,feedbackByCredential:i,onToggle:s,onReset:o}){let l=nw(1e4);af();let c=e.data,d=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,u=rK(c?.reports??[]),p=null==d?-1:c?.reports.findIndex(e=>e.credentialId===d)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(gu,{state:e,loading:t,subject:"사용량"}),c?.brokerOk===!1?(0,r.jsx)("div",{className:"border-b border-border bg-bg px-4 py-2 text-xs text-text-muted",role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,r.jsxs)("div",{className:"flex min-h-7 items-center gap-4 border-b border-border bg-bg-raised px-4 text-[11px] font-semibold tracking-[0.08em] text-text-muted uppercase","aria-label":"사용량 그래프 범례",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),c&&0===c.reports.length?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,c?.reports.map((e,t)=>{let d=e.credentialId;return(0,r.jsx)(gg,{report:e,brokerOk:!0===c.brokerOk,now:l,active:t===p,identity:u[t],recommendation:null==d?void 0:n?.resetRecommendations.find(e=>e.credentialId===d),pendingAction:null==d?null:a.get(d)??null,feedback:null==d?void 0:i.get(d),onToggle:s,onReset:o},`${e.provider}:${d??e.metadata?.accountId??e.metadata?.email??t}`)})]})}let gv={invalid_total:!0,invalid_start_date:!0,start_date_in_future:!0,session_scan_failed:!0,session_scan_partial:!0,internal:!0,settings_unreadable:!0,invalid_balance:!0,invalid_observed_at:!0,observed_at_in_future:!0,routes_unreadable:!0},gb={session:!0,memory:!0,"korean-reply-translation":!0};function gy(e,t,n=""){return t?Object.hasOwn(gv,t)?e(`credits.error.${t}`):n||t:n}function gw({face:e,title:t,model:n,cost:a,costMinimum:i=!1,detail:s,t:o}){return(0,r.jsxs)("li",{className:"flex min-w-0 items-start gap-2 py-1.5",children:[e?(0,r.jsx)(av,{seed:e.seed,size:28,provider:"hive"}):(0,r.jsx)("span",{className:"w-7 shrink-0","aria-hidden":"true"}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline gap-1.5",children:[t?(0,r.jsx)("span",{className:"shrink-0 text-[13px] font-medium text-text",children:t}):null,(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-text-dim",children:n}),(0,r.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-text",children:null===a?o("credits.priceUnknown"):`${i?"≥":""}${gr(a)}`})]}),(0,r.jsx)("div",{className:"mt-0.5 whitespace-pre-line font-mono text-[11px] tabular-nums text-text-muted",children:s})]})]})}function gk({walletName:e,setting:t,onSave:n,onClose:i,t:s}){let o=(0,a.useId)(),[l,c]=(0,a.useState)(t?String(t.totalUsd):""),[d,u]=(0,a.useState)(t?.startDate??""),[p,h]=(0,a.useState)(!1),[m,f]=(0,a.useState)(null),g="min-h-8 w-full min-w-0 border border-border bg-bg px-2 font-mono text-xs text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent",x=async e=>{h(!0),f(null);try{await n(e),i()}catch(e){f(s("credits.saveFailed",{reason:gy(s,e instanceof rG?e.code:void 0,e instanceof Error?e.message:String(e))}))}finally{h(!1)}};return(0,r.jsxs)("form",{className:"mt-2 grid gap-2 border border-border bg-bg-raised p-2.5","aria-label":s("credits.formLabel",{wallet:e}),onSubmit:e=>{var t;let n;e.preventDefault();let r=(n=Number((t={totalUsd:l,startDate:d}).totalUsd.replace(/[$,\s]/g,"")),t.totalUsd.trim()&&Number.isFinite(n)?{totalUsd:n,startDate:t.startDate.trim()}:null);r?x(r):f(s("credits.invalid.total"))},children:[(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,r.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${o}-total`,children:[s("credits.totalUsd"),(0,r.jsx)("input",{id:`${o}-total`,className:g,inputMode:"decimal",value:l,onChange:e=>c(e.target.value),placeholder:"300",required:!0})]}),(0,r.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${o}-start`,children:[s("credits.startDate"),(0,r.jsx)("input",{id:`${o}-start`,className:g,type:"date",value:d,onChange:e=>u(e.target.value),required:!0})]})]}),m?(0,r.jsx)("div",{className:"text-xs text-danger",role:"alert",children:m}):null,(0,r.jsxs)("div",{className:"flex flex-wrap justify-end gap-1.5",children:[t?(0,r.jsx)("button",{type:"button",className:ge(f7,"me-auto"),disabled:p,onClick:()=>{x(null)},children:s("credits.clear")}):null,(0,r.jsx)("button",{type:"button",className:f7,disabled:p,onClick:i,children:s("credits.cancel")}),(0,r.jsx)("button",{type:"submit",className:f7,disabled:p,children:p?s("credits.saving"):s("credits.save")})]})]})}function gj({wallet:e,setting:t,balance:n,now:i,onSave:o,onSaveBalance:l,t:c}){let d=(0,a.useId)(),[u,p]=(0,a.useState)(!1),h=c("credits.wallet.hive"),m=function(e){if(null===e.totalUsd||e.totalUsd<=0)return{spentFraction:null,tone:"normal"};let t=e.spentUsd/e.totalUsd;return{spentFraction:Math.max(0,Math.min(1,t)),tone:t>=1?"danger":t>=.9?"warning":"normal"}}(e),f="start-date"===e.sinceSource?c("credits.since",{date:e.since}):c("credits.sinceDefault"),g=e.spentComplete||e.upperBoundRows?gr(e.spentUsd):`≥${gr(e.spentUsd)}`,x=null===e.remainingUsd?null:`${e.remainingUpperBound?"≤":""}${gr(Math.max(0,e.remainingUsd))}`,v=null===m.spentFraction||null===e.remainingUsd?null:Math.round(100*m.spentFraction);return(0,r.jsxs)("section",{className:"border-b border-border-strong px-4 py-3 last:border-b-0","aria-labelledby":d,"data-credit-wallet":e.wallet,children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("h3",{id:d,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:h}),u?null:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>p(!0),children:t?c("credits.edit"):c("credits.enter")}),(0,r.jsx)(gN,{wallet:"hive",walletName:h,t:c})]}),n?(0,r.jsx)(gR,{balance:n,walletName:h,now:i,onSave:l,t:c}):null,(0,r.jsx)("div",{className:ge("text-xs text-text-muted",n?"mt-2":"mt-0.5"),children:`${c(`credits.scope.${e.wallet}`)} \xb7 ${f}`}),"error"===e.status?(0,r.jsx)("div",{className:"mt-1.5 text-xs text-text",role:"alert",children:c("credits.walletError",{reason:gy(c,e.error)})}):null,null!==v?(0,r.jsxs)("div",{className:"py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[13px] text-text-muted",children:c("credits.remaining")}),(0,r.jsx)("span",{className:ge("font-mono text-sm font-semibold tabular-nums","danger"===m.tone?"text-danger":"text-text"),children:x})]}),(0,r.jsx)("div",{className:"relative mt-1 h-3.5 overflow-hidden border border-border-strong bg-metric-track",role:"progressbar","aria-label":c("credits.meterLabel",{wallet:h}),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":v,children:(0,r.jsx)("div",{className:ge("absolute inset-y-0 left-0","danger"===m.tone?"bg-danger":"bg-metric"),style:{width:`${v}%`}})}),(0,r.jsx)("div",{className:"mt-1 text-right text-[11px] text-text-muted tabular-nums",children:c("credits.usedPct",{pct:v})})]}):null,(0,r.jsxs)("dl",{className:"m-0 mt-1",children:[null!==e.totalUsd?(0,r.jsx)(gd,{label:c("credits.total"),value:gr(e.totalUsd)}):null,(0,r.jsx)(gd,{label:c("credits.spent"),value:g})]}),t||u?null:(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text-muted",children:c("credits.enterPrompt")}),u?(0,r.jsx)(gk,{walletName:h,setting:t,onSave:o,onClose:()=>p(!1),t:c}):null,e.rows.length>0?(0,r.jsx)("ul",{className:"m-0 mt-1.5 list-none border-t border-border p-0",children:e.rows.map(e=>{let t=rD("hive",e.model)??rH("hive"),n=e.purposes.map(e=>{let t=Object.hasOwn(gb,e.purpose)?c(`credits.purpose.${e.purpose}`):e.purpose;return`${t} ${null===e.costUsd?c("credits.priceUnknown"):gr(e.costUsd)}`}),a=[c("credits.requests",{count:gi(e.requests)}),c("credits.tokens",{input:gs(e.inputTokens),output:gs(e.outputTokens)}),e.cacheReadTokens>0?c("credits.cacheTokens",{cache:gs(e.cacheReadTokens)}):null].filter(Boolean).join(" \xb7 ");return(0,r.jsx)(gw,{face:t,title:t?.alias??e.model,model:e.model,cost:e.costUsd,detail:n.length>0?`${a}
|
|
75
|
+
${n.join(" \xb7 ")}`:a,t:c},e.model)})}):null]})}let gS={input:"inputTokens",output:"outputTokens",cacheRead:"cacheReadTokens",cacheWrite:"cacheWriteTokens"},gC={hive:"https://portal.deploy.com/",exa:"https://dashboard.exa.ai/billing",typesafe:"https://console.typesafe.ai/billing",anthropic:"https://platform.claude.com/settings/billing"};function gN({wallet:e,walletName:t,t:n}){return(0,r.jsxs)("a",{href:gC[e],target:"_blank",rel:"noopener noreferrer",className:ge("inline-flex shrink-0 items-center text-xs text-accent underline-offset-2 hover:underline",f9),"aria-label":n("credits.billingLinkLabel",{wallet:t}),"data-billing-link":e,children:[n("credits.billingLink")," ↗"]})}function gT({wallet:e,balance:t,now:n,onSaveBalance:i,t:s}){let o,l=(0,a.useId)(),c="error"===e.status&&"session_scan_partial"!==e.error,d=null!==e.coverageSince,u=null===e.spentUsd?s("credits.priceUnknown"):`${e.spentComplete?"":"≥"}${gr(e.spentUsd)}`;return(0,r.jsxs)("section",{className:"border-b border-border-strong px-4 py-3 last:border-b-0","aria-labelledby":l,"data-credit-wallet":"anthropic",children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("h3",{id:l,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:s("credits.wallet.anthropic")}),(0,r.jsx)(gN,{wallet:"anthropic",walletName:s("credits.wallet.anthropic"),t:s})]}),t?(0,r.jsx)(gR,{balance:t,walletName:s("credits.wallet.anthropic"),now:n,onSave:i,t:s}):null,(0,r.jsx)("div",{className:ge("text-xs text-text-muted",t?"mt-2":"mt-0.5"),children:`${s("credits.scope.anthropic")} \xb7 ${s("credits.sinceDefault")}`}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs text-text-muted",children:s("credits.anthropic.note")}),"error"===e.status?(0,r.jsx)("div",{className:"mt-1.5 text-xs text-text",role:"alert",children:s("credits.walletError",{reason:gy(s,e.error)})}):null,c?null:(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text","data-anthropic-coverage":d?"recorded":"none",children:d?s("credits.anthropic.coverageSince",{date:(o=new Date(e.coverageSince),`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`)}):s("credits.anthropic.noCoverage")}),c?null:(0,r.jsxs)("dl",{className:"m-0 mt-1",children:[d?(0,r.jsx)(gd,{label:s("credits.spent"),value:u}):null,(0,r.jsx)(gd,{label:s("credits.anthropic.oauthExcluded"),value:s("credits.requests",{count:gi(e.oauthRequests)})}),e.unattributedRequests>0?(0,r.jsx)(gd,{label:s("credits.anthropic.unattributedExcluded"),value:s("credits.requests",{count:gi(e.unattributedRequests)})}):null]}),d&&!c&&0===e.rows.length?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text-muted",children:s("credits.anthropic.none")}):null,e.rows.length>0?(0,r.jsx)("ul",{className:"m-0 mt-1.5 list-none border-t border-border p-0",children:e.rows.map(e=>{let t=t=>{let n=e.costs[t];return`${s(`credits.category.${t}`)} ${gs(e[gS[t]])} ${null===n?s("credits.priceUnknown"):gr(n)}`},n=e.purposes.map(e=>{let t=Object.hasOwn(gb,e.purpose)?s(`credits.purpose.${e.purpose}`):e.purpose,n=null===e.costUsd?s("credits.priceUnknown"):`${e.unpricedRequests>0?"≥":""}${gr(e.costUsd)}`;return`${t} ${n}`}),a=[[s("credits.requests",{count:gi(e.requests)}),t("input"),t("output")].join(" \xb7 "),[t("cacheRead"),t("cacheWrite")].join(" \xb7 "),n.length>0?n.join(" \xb7 "):null].filter(Boolean);return(0,r.jsx)(gw,{face:null,title:"",model:e.model,cost:e.costUsd,costMinimum:e.unpricedRequests>0,detail:a.join("\n"),t:s},e.model)})}):null]})}function gI(e){return n0(e).replace("T"," ")}function gM({walletName:e,recorded:t,onSave:n,onClose:i,t:s}){let o=(0,a.useId)(),[l,c]=(0,a.useState)(t?String(t.amountUsd):""),[d,u]=(0,a.useState)(()=>n0(t?.observedAt??Date.now())),[p,h]=(0,a.useState)(!1),[m,f]=(0,a.useState)({}),g="min-h-8 w-full min-w-0 border border-border bg-bg px-2 font-mono text-xs text-text focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent pointer-coarse:min-h-11 max-sm:min-h-11",x={amount:`${o}-amount`,observedAt:`${o}-observed`,hint:`${o}-hint`,amountError:`${o}-amount-error`,observedAtError:`${o}-observed-error`},v=async e=>{h(!0),f({});try{await n(e),i()}catch(r){let e=r instanceof rG?r.code:void 0,t=gy(s,e,r instanceof Error?r.message:String(r)),n="invalid_balance"===e?"amount":"invalid_observed_at"===e||"observed_at_in_future"===e?"observedAt":"form";f({[n]:"form"===n?s("credits.saveFailed",{reason:t}):t})}finally{h(!1)}};return(0,r.jsxs)("form",{className:"mt-2 grid gap-2 border border-border bg-bg-raised p-2.5","aria-label":s("credits.balance.formLabel",{wallet:e}),noValidate:!0,"data-dismissible-layer":!0,onKeyDown:e=>{"Escape"!==e.key||p||(e.preventDefault(),i())},onSubmit:e=>{e.preventDefault();let t=function(e){let t=Number(e.amountUsd.replace(/[$,\s]/g,""));if(!e.amountUsd.trim()||!Number.isFinite(t))return{error:"amount"};let n=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(e.observedAt.trim())?new Date(e.observedAt.trim()).getTime():NaN;return Number.isFinite(n)?{value:{amountUsd:t,observedAt:n}}:{error:"observedAt"}}({amountUsd:l,observedAt:d});"error"in t?f({[t.error]:s("amount"===t.error?"credits.invalid.amount":"credits.invalid.observedAt")}):v(t.value)},children:[(0,r.jsxs)("div",{className:"grid gap-1",children:[(0,r.jsx)("label",{className:"text-[11px] text-text-muted",htmlFor:x.amount,children:s("credits.balance.amount")}),(0,r.jsx)("input",{id:x.amount,className:g,inputMode:"decimal",autoComplete:"off",value:l,onChange:e=>c(e.target.value),"aria-invalid":!!m.amount||void 0,"aria-describedby":m.amount?x.amountError:void 0,autoFocus:!0,required:!0}),m.amount?(0,r.jsx)("p",{id:x.amountError,className:"m-0 text-xs text-danger",role:"alert",children:m.amount}):null]}),(0,r.jsxs)("div",{className:"grid gap-1",children:[(0,r.jsx)("label",{className:"text-[11px] text-text-muted",htmlFor:x.observedAt,children:s("credits.balance.observedAt")}),(0,r.jsx)("input",{id:x.observedAt,className:g,type:"datetime-local",value:d,onChange:e=>u(e.target.value),"aria-invalid":!!m.observedAt||void 0,"aria-describedby":m.observedAt?x.observedAtError:x.hint,required:!0}),m.observedAt?(0,r.jsx)("p",{id:x.observedAtError,className:"m-0 text-xs text-danger",role:"alert",children:m.observedAt}):(0,r.jsx)("p",{id:x.hint,className:"m-0 text-[11px] text-text-muted",children:s("credits.balance.observedAtHint")})]}),m.form?(0,r.jsx)("div",{className:"text-xs text-danger",role:"alert",children:m.form}):null,(0,r.jsxs)("div",{className:"flex flex-wrap justify-end gap-1.5",children:[t?(0,r.jsx)("button",{type:"button",className:ge(f7,f9,"me-auto"),disabled:p,onClick:()=>{v(null)},children:s("credits.clear")}):null,(0,r.jsx)("button",{type:"button",className:ge(f7,f9),disabled:p,onClick:i,children:s("credits.cancel")}),(0,r.jsx)("button",{type:"submit",className:ge(f7,f9),disabled:p,children:p?s("credits.saving"):s("credits.save")})]})]})}function gR({balance:e,walletName:t,now:n,onSave:i,t:o}){let[l,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=e.recorded,p=(0,a.useRef)(!1);(0,a.useLayoutEffect)(()=>{!l&&p.current&&(p.current=!1,d.current?.focus())},[l]);let h="unverified"===e.evidence?o("credits.evidence.unverified"):null!==e.lastPaidUseAt?o("credits.evidence.lastPaidUse",{time:gI(e.lastPaidUseAt)}):null;return(0,r.jsxs)("div",{"data-balance-source":e.source,"data-balance-state":u?"recorded":"unknown",children:[(0,r.jsxs)("p",{className:"m-0 mt-0.5 text-xs text-text-muted","data-balance-evidence":e.evidence,children:[o(`credits.route.${e.wallet}`),h?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("br",{}),h]}):null]}),(0,r.jsxs)("div",{className:"mt-2 flex min-w-0 items-baseline justify-between gap-2",children:[(0,r.jsxs)("span",{className:"min-w-0 text-[13px] text-text-muted",children:[o("credits.balance.label"),(0,r.jsx)("span",{className:"ms-1.5 border border-border px-1 text-[11px]",children:o("credits.balance.source")})]}),u?(0,r.jsx)("span",{className:"shrink-0 font-mono text-sm font-semibold tabular-nums text-text","data-balance-amount":!0,children:`$${u.amountUsd.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}):(0,r.jsx)("span",{className:"shrink-0 text-xs text-text-muted",children:o("credits.balance.none")})]}),(0,r.jsxs)("div",{className:"mt-1 flex min-w-0 flex-wrap items-center justify-between gap-x-2 gap-y-1",children:[u?(0,r.jsx)("time",{className:"min-w-0 text-[11px] tabular-nums text-text-muted",dateTime:new Date(u.observedAt).toISOString(),children:`${o("credits.balance.observed",{time:gI(u.observedAt)})} \xb7 ${function(e,t,n){let r=Math.max(0,Math.floor((n-t)/6e4));if(r<1)return e("credits.balance.age.now");if(r<60)return e("credits.balance.age.minutes",{count:r});let a=Math.floor(r/60);return a<48?e("credits.balance.age.hours",{count:a}):e("credits.balance.age.days",{count:Math.floor(a/24)})}(o,u.observedAt,n)}`}):(0,r.jsx)("span",{}),l?null:(0,r.jsx)(s.r,{ref:d,variant:"neutralWeak",size:"xsmall",className:f9,onClick:()=>c(!0),"aria-label":`${t} ${o(u?"credits.balance.edit":"credits.balance.record")}`,children:o(u?"credits.balance.edit":"credits.balance.record")})]}),l?(0,r.jsx)(gM,{walletName:t,recorded:u,onSave:t=>i(e.wallet,t),onClose:()=>{p.current=!0,c(!1)},t:o}):null]})}function gE({balance:e,now:t,onSaveBalance:n,t:i}){let s=(0,a.useId)(),o=i(`credits.wallet.${e.wallet}`);return(0,r.jsxs)("section",{className:"border-b border-border-strong px-4 py-3 last:border-b-0","aria-labelledby":s,"data-credit-wallet":e.wallet,children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("h3",{id:s,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:o}),(0,r.jsx)(gN,{wallet:e.wallet,walletName:o,t:i})]}),(0,r.jsx)(gR,{balance:e,walletName:o,now:t,onSave:n,t:i})]})}function gL({state:e,loading:t,now:n,onSave:a,onSaveBalance:i,t:s}){let o=e.data,l=new Map((o?.balances&&!o.balancesError?o.balances:[]).map(e=>[e.wallet,e])),c=e=>{let t=l.get(e);return t?(0,r.jsx)(gE,{balance:t,now:n,onSaveBalance:i,t:s}):null},d=o?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(gj,{wallet:o.hive,setting:o.settings.hive,balance:l.get("hive")??null,now:n,onSave:a,onSaveBalance:i,t:s}),c("exa"),c("typesafe"),o.anthropic?(0,r.jsx)(gT,{wallet:o.anthropic,balance:l.get("anthropic")??null,now:n,onSaveBalance:i,t:s}):null]}):null;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h2",{className:"resource-group-heading",children:s("credits.heading")}),(0,r.jsx)("p",{className:"m-0 border-b border-border px-4 py-2 text-xs text-text-muted",children:s("credits.estimateNote")}),t&&"idle"===e.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:s("credits.loading")}):null,"error"===e.status||"stale"===e.status?(0,r.jsx)("div",{className:"border-b border-border px-4 py-2 text-xs text-text",role:"alert",children:s("credits.loadFailed",{reason:e.error.message})}):null,o?.settingsError?(0,r.jsx)("div",{className:"border-b border-border px-4 py-2 text-xs text-text",role:"alert",children:s("credits.settingsError")}):null,o?.balancesError?(0,r.jsx)("div",{className:"border-b border-border px-4 py-2 text-xs text-text",role:"alert",children:gy(s,o.balancesError)}):null,d]})}function g$({refreshToken:e}){let{t}=(0,z.s)(),[n,i]=(0,a.useState)({status:"idle",data:null,error:null}),[s,o]=(0,a.useState)(!1),l=(0,a.useRef)(n),c=(0,a.useRef)(null);l.current=n;let d=(0,a.useCallback)(async e=>{c.current?.abort();let t=new AbortController;c.current=t,o(!0);let n=await r8({refresh:e,previous:l.current.data,signal:t.signal});c.current!==t||t.signal.aborted||(i(n),o(!1))},[]);(0,a.useEffect)(()=>{d(e>0)},[d,e]),(0,a.useEffect)(()=>()=>c.current?.abort(),[]);let u=(0,a.useCallback)(async e=>{await r4(e),await d(!1)},[d]),p=(0,a.useCallback)(async(e,t)=>{await r5(e,t),await d(!1)},[d]),h=nw(6e4);return(0,r.jsx)(gL,{state:n,loading:s,now:h,onSave:u,onSaveBalance:p,t:t})}function gP({model:e}){var t,n;let a=Math.max(1,Math.min(100,100*e.costShare)),i="unpriced"!==e.pricing&&"partial"!==e.pricing,s="unpriced"===e.pricing?ga(0,!1):`${ga(e.cost,i)} \xb7 ${go(e.costShare)}`;return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,r.jsx)("h3",{className:"m-0 min-w-0 flex-1 truncate text-sm font-semibold text-text",title:e.model,children:e.model}),(0,r.jsx)("span",{className:"text-xs text-text-muted",children:e.provider}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:s})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${a}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(gd,{label:"요청",value:gi(e.requests)}),(0,r.jsx)(gd,{label:"요청당",value:ga(e.costPerRequest,i)}),(0,r.jsx)(gd,{label:"토큰/요청",value:gs(e.tokensPerRequest)}),(0,r.jsx)(gd,{label:"출력/요청",value:gs(e.outputPerRequest)}),(0,r.jsx)(gd,{label:"캐시율",value:(t=e.cacheRate,"not-reported"===(n=e.cacheStatus)?"미보고":"unknown"===n?"알 수 없음":go(t,1))}),(0,r.jsx)(gd,{label:"TTFT",value:gl(e.avgTtft)})]})]})}function gA({agent:e}){let t={main:"메인",subagent:"SubAgent",advisor:"advisor"}[e.agentType]??e.agentType,n=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:"border-b border-border px-4 py-3 last:border-b-0",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,r.jsx)("h3",{className:"m-0 text-sm font-semibold text-text",children:t}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[ga(e.cost,e.costComplete)," \xb7 ",go(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden border border-border-strong bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${n}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(gd,{label:"요청",value:gi(e.requests)}),(0,r.jsx)(gd,{label:"요청당",value:ga(e.costPerRequest,e.costComplete)}),(0,r.jsx)(gd,{label:"토큰/요청",value:gs(e.tokensPerRequest)})]})]})}function gF({day:e}){let t=e.models.slice(0,3).map(e=>e.model).join(", ");return(0,r.jsxs)("div",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-baseline gap-3 border-b border-border px-4 py-2 last:border-b-0",children:[(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text-muted",children:gc(e.timestamp)}),(0,r.jsx)("span",{className:"truncate text-xs text-text-muted",title:t,children:t}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:ga(e.cost,e.costComplete)})]})}function g_({state:e,loading:t}){let n=e.data,a=n?.overall.unpricedModels??0,i=n?.overall.cacheExcludedModels??0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(gu,{state:e,loading:t,subject:"모델 집계"}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{"aria-labelledby":"resource-overall-heading",children:[(0,r.jsx)("h2",{id:"resource-overall-heading",className:"m-0 border-b border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"전체"}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4 px-4 py-3",children:[(0,r.jsx)(gd,{label:"요청",value:gi(n.overall.requests)}),(0,r.jsx)(gd,{label:"추정 비용",value:ga(n.overall.cost,n.overall.costComplete)}),(0,r.jsx)(gd,{label:"토큰",value:gs(n.overall.tokens)}),(0,r.jsx)(gd,{label:i>0?"캐시율(일부)":"캐시율",value:go(n.overall.cacheRate,1)}),(0,r.jsx)(gd,{label:a>0?"캐시 절감(일부)":"캐시 절감",value:go(n.overall.cacheSavings,1)}),(0,r.jsx)(gd,{label:"평균 TTFT",value:gl(n.overall.avgTtft)})]})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-models-heading",children:[(0,r.jsx)("h2",{id:"resource-models-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"모델별"}),n.models.length?n.models.map(e=>(0,r.jsx)(gP,{model:e},`${e.provider}:${e.model}`)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"모델 기록이 없습니다."})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-agents-heading",children:[(0,r.jsx)("h2",{id:"resource-agents-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"에이전트 종류별"}),n.agents.length?n.agents.map(e=>(0,r.jsx)(gA,{agent:e},e.agentType)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"기록이 없습니다."})]}),n.daily.length?(0,r.jsxs)("section",{"aria-labelledby":"resource-daily-heading",children:[(0,r.jsx)("h2",{id:"resource-daily-heading",className:"m-0 border-y border-border bg-bg-raised px-4 py-2 text-[10px] font-semibold tracking-[0.08em] text-text-muted uppercase",children:"일별 추정 비용"}),n.daily.map(e=>(0,r.jsx)(gF,{day:e},e.timestamp))]}):null,(0,r.jsxs)("p",{className:"m-0 border-t border-border px-4 py-3 text-xs leading-5 text-text-dim",children:["`omp stats` 기준 누적값입니다. 금액은 토큰 단가로 계산한 추정치이며 실제 청구액이나 구독 사용량이 아닙니다. 구독 한도 %는 계정 한도 탭에서 확인하세요.",a>0?` 가격을 다 매기지 못한 모델이 ${a}개 있어 추정 비용\xb7비중\xb7캐시 절감은 단가를 아는 사용량만 셉니다. ≥가 붙은 금액은 추정 비용의 최솟값입니다. 에이전트 종류별 집계는 모델을 나누지 않아 모든 행에 ≥를 붙입니다.`:null,i>0?` 캐시 사용량을 보고하지 않거나 보고 여부를 알 수 없는 모델 ${i}개는 캐시율 계산에서 뺐습니다.`:null]})]}):null]})}function gz({reports:e,providerConnections:t}){return af(),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:"character-roster-intro","aria-labelledby":"character-roster-heading",children:[(0,r.jsx)("h2",{id:"character-roster-heading",children:"호출 가능한 캐릭터"}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"호출\xb7불러\xb7소환"}),"은 캐릭터를 SubAgent로 이 대화에 부릅니다.",(0,r.jsx)("strong",{children:" 교체"}),"는 이 대화의 Main을 바꿉니다."]})]}),(0,r.jsx)("div",{className:"character-roster",role:"list","aria-label":"호출 가능한 캐릭터 목록",children:rb.map(n=>{let a=`character-roster-${n.seed}`,i=`character-roster-${n.seed}-status`,s=`${n.provider}/${n.model}`,o=!1,l=!1;if(e){for(let t of e)if(t.provider===n.provider&&(o=!0,!0!==t.disabled)){l=!0;break}}let c="web6"!==n.provider&&(t?.get(n.provider)===!1||o&&!l);return(0,r.jsxs)("article",{className:ge("character-roster-item",c&&"is-unavailable"),role:"listitem","aria-labelledby":a,"aria-describedby":c?i:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(av,{seed:n.seed,size:48,provider:n.provider}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{id:a,children:n.alias}),c?(0,r.jsx)("span",{id:i,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,r.jsx)("p",{children:n.voice})]})]}),(0,r.jsxs)("dl",{className:"character-roster-model",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"모델"}),(0,r.jsx)("dd",{title:s,children:s})]}),void 0!==n.oauthPosition?(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"계정"}),(0,r.jsxs)("dd",{children:["OAuth ",n.oauthPosition]})]}):null]}),(0,r.jsxs)("dl",{className:"character-roster-examples",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"호출"}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("code",{children:n.summonExample}),(0,r.jsx)("span",{children:n.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"Main 교체"}),(0,r.jsxs)("dd",{children:[n.switchExample?(0,r.jsx)("code",{children:n.switchExample}):(0,r.jsx)("strong",{children:"교체 불가"}),(0,r.jsx)("span",{children:n.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},n.alias)})})]})}function gW({open:e,sessionId:t,activeTab:n,onTabChange:i,usage:o,className:l}){let c=(0,a.useId)(),d=o.state,u=o.loading,[p,h]=(0,a.useState)({status:"idle",data:null,error:null}),[m,f]=(0,a.useState)(null),[g,x]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null),[y,w]=(0,a.useState)(()=>new Map),[k,j]=(0,a.useState)(()=>new Map),[S,C]=(0,a.useState)(0),N=(0,a.useRef)(p),T=(0,a.useRef)(null),I=(0,a.useRef)(null),M=(0,a.useRef)(new Set),R=(0,a.useRef)(new Set);N.current=p,(0,a.useEffect)(()=>{if(!e||"characters"!==n)return;let t=new AbortController;return b(null),Promise.all([fetch("/api/auth/all-providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}),fetch("/api/auth/providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()})]).then(([e,n])=>{if(t.signal.aborted)return;let r=new Map(e.providers.map(e=>[e.id,e.configured]));for(let e of n.providers)r.set(e.id,!0===r.get(e.id)||e.loggedIn);b(r)}).catch(()=>{t.signal.aborted||b(null)}),()=>t.abort()},[n,e,d.data]),(0,a.useEffect)(()=>{var r;let a,i,s,o,l,c,d,u,p,h;if(f(null),!e||"usage"!==n||!t)return;let m=(i=(r={onClear(){f(null)},onResult(e){f("fresh"===e.status?e.data:null)}}).intervalMs??2500,s=r.setIntervalImpl??setInterval,o=r.clearIntervalImpl??clearInterval,l=null,c=null,d=0,u=!1,p=()=>{o(a),a=void 0},h=async e=>{c?.abort();let t=c=new AbortController,n=++d,a=await r1(e,{signal:t.signal,fetchImpl:r.fetchImpl});u||n!==d||l!==e||t.signal.aborted||r.onResult(a)},{setSessionId(e){u||e===l||(d+=1,c?.abort(),c=null,p(),l=e,r.onClear(e),e&&(h(e),a=s(()=>{l&&h(l)},i)))},stop(){u||(u=!0,d+=1,c?.abort(),c=null,p(),l=null)}});return T.current=m,m.setSessionId(t),()=>{m.stop(),T.current===m&&(T.current=null)}},[n,e,t]);let E=(0,a.useCallback)(async e=>{I.current?.abort();let t=new AbortController;I.current=t,x(!0);let n=await r2({refresh:e,previous:N.current.data,signal:t.signal});I.current!==t||t.signal.aborted||(h(n),x(!1))},[]);(0,a.useEffect)(()=>{e&&"models"===n&&("idle"===N.current.status||"error"===N.current.status)&&E(!1)},[n,e,E]),(0,a.useEffect)(()=>()=>{for(let e of(I.current?.abort(),M.current))e.abort()},[]);let L=(0,a.useCallback)(()=>{"models"===n?E(!0):(o.refresh(),C(e=>e+1))},[n,E,o]),$=(0,a.useCallback)(()=>o.refresh(),[o]),P=(0,a.useCallback)(async e=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let t=e.credentialId,n=r9(R.current,t);if(!n)return;let r=new AbortController;M.current.add(r),o.setPaused(!0),w(e=>new Map(e).set(t,"toggle")),j(e=>{let n=new Map(e);return n.delete(t),n});try{await r3(t,!0===e.disabled,{signal:r.signal});let n=await $();r.signal.aborted||j(r=>new Map(r).set(t,{tone:"status",message:"fresh"===n.status?`계정을 ${e.disabled?"켰습니다":"껐습니다"}.`:"계정 설정 저장됨 \xb7 표시 상태 새로고침 실패."}))}catch(e){if(!r.signal.aborted){let n=e instanceof rG&&("timeout"===e.kind||e.outcomeUnknown);j(r=>new Map(r).set(t,n?{tone:"error",message:"적용 여부 확인 필요 — 새로고침으로 계정 상태를 확인하세요."}:{tone:"error",message:`계정 전환 실패: ${e instanceof Error?e.message:String(e)}`}))}}finally{M.current.delete(r),n(),o.setPaused(R.current.size>0),w(e=>{let n=new Map(e);return n.delete(t),n})}},[$,o]),A=(0,a.useCallback)(async(e,t)=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let n=e.credentialId,r=r9(R.current,n);if(!r)return;let a=new AbortController;M.current.add(a),o.setPaused(!0),w(e=>new Map(e).set(n,"reset")),j(e=>{let t=new Map(e);return t.delete(n),t});try{let e=await r7(n,t,{signal:a.signal}),r=function(e){switch(e.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return e.code.startsWith("http_")?{tone:"error",message:`리셋 사용 실패: 서비스 응답 오류 (${e.code})`}:{tone:"error",message:`리셋 사용 실패: ${e.code}`}}}(e),i=await $();if(e.ok){let e="fresh"===i.status?i.data.reports.find(e=>e.credentialId===n):void 0,t=e?.savedReset?.availableCount;r.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}a.signal.aborted||j(e=>new Map(e).set(n,r))}catch(e){e instanceof rG&&(e.outcomeUnknown||"timeout"===e.kind)&&!a.signal.aborted&&await $(),a.signal.aborted||j(t=>new Map(t).set(n,function(e){if(e instanceof rG){if(e.outcomeUnknown||"timeout"===e.kind)return{tone:"error",message:"적용 여부 확인 필요 — 자동으로 다시 시도하지 않았습니다. 새로고침으로 남은 개수를 확인하세요."};switch(e.code){case"account_disabled":return{tone:"error",message:"리셋 사용 실패: 꺼둔 계정에서는 사용할 수 없습니다."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return{tone:"error",message:`리셋 사용 실패: ${e.message}`}}}return{tone:"error",message:`리셋 사용 실패: ${e instanceof Error?e.message:String(e)}`}}(e)))}finally{M.current.delete(a),r(),o.setPaused(R.current.size>0),w(e=>{let t=new Map(e);return t.delete(n),t})}},[$,o]);if(!e)return null;let F="models"===n?p.data?.generatedAt:d.data?.generatedAt,_="models"===n?p.data?.range:void 0,z=_?.from&&_.to?`${gc(_.from)}~${gc(_.to)}`:F?new Date(F).toLocaleTimeString():"",W="models"===n?g:"usage"===n&&u,O=W?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:ge("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",l),"aria-labelledby":c,"aria-busy":W,children:[(0,r.jsx)("h1",{id:c,className:"sr-only",children:"캐릭터"}),(0,r.jsxs)(fT.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>i(e),children:[(0,r.jsxs)(fT.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(fT.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(fT.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(fT.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(fT.J.Indicator,{})]}),(0,r.jsx)(fT.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(gz,{reports:d.data?.reports,providerConnections:v})}),(0,r.jsxs)(fT.J.Content,{value:"usage",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:z}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:L,disabled:W,children:O})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(gx,{state:d,loading:u,accountState:m?.sessionId===t?m:null,pendingActions:y,feedbackByCredential:k,onToggle:e=>{P(e)},onReset:A}),(0,r.jsx)(g$,{refreshToken:S})]}),(0,r.jsxs)(fT.J.Content,{value:"models",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:z}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:L,disabled:W,children:O})]}),(0,r.jsx)(g_,{state:p,loading:g})]})]})]})}let gO="unknown",gD="/api/runs";class gH extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let gU=["completed","error","aborted","interrupted","running"],gB=["main","maker","checker","advisor","unattributed"],gq=["primary","rework","review"],gV=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],gK=["all","attributed"],gG=["single","unknown"],gJ=["config","harness"];function gZ(e){return"object"==typeof e&&null!==e}function gY(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function gX(e){return!!gZ(e)&&"string"==typeof e.runId&&"string"==typeof e.sessionId&&"string"==typeof e.entryId&&"number"==typeof e.index&&Number.isFinite(e.index)&&(null===e.title||"string"==typeof e.title)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&(null===e.endedAt||"number"==typeof e.endedAt&&Number.isFinite(e.endedAt))&&"number"==typeof e.wallClockMs&&Number.isFinite(e.wallClockMs)&&"string"==typeof e.outcome&&gU.includes(e.outcome)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.childCount&&Number.isFinite(e.childCount)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"string"==typeof e.configSignature&&(null===e.harnessRevision||"string"==typeof e.harnessRevision)}function gQ(e){return!!gZ(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&gB.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&gq.includes(e.purpose))&&gY(e.models)&&gY(e.efforts)&&"number"==typeof e.requestCount&&Number.isFinite(e.requestCount)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.spanMs&&Number.isFinite(e.spanMs)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&"number"==typeof e.endedAt&&Number.isFinite(e.endedAt)&&"number"==typeof e.inputTokens&&Number.isFinite(e.inputTokens)&&"number"==typeof e.outputTokens&&Number.isFinite(e.outputTokens)&&"number"==typeof e.cacheReadTokens&&Number.isFinite(e.cacheReadTokens)&&"number"==typeof e.cacheWriteTokens&&Number.isFinite(e.cacheWriteTokens)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"number"==typeof e.untimedRequests&&Number.isFinite(e.untimedRequests)&&"number"==typeof e.errorCount&&Number.isFinite(e.errorCount)&&"number"==typeof e.abortedCount&&Number.isFinite(e.abortedCount)&&"number"==typeof e.toolCalls&&Number.isFinite(e.toolCalls)}function g0(e){return!!gZ(e)&&("role-busy"===e.kind||"unmeasured-gap"===e.kind)&&"string"==typeof e.id&&"number"==typeof e.ms&&Number.isFinite(e.ms)&&"number"==typeof e.relative&&Number.isFinite(e.relative)}function g1(e){return!!gZ(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.failed&&Number.isFinite(e.failed)&&"number"==typeof e.noMatch&&Number.isFinite(e.noMatch)&&"number"==typeof e.cancelled&&Number.isFinite(e.cancelled)}function g2(e){return!!gZ(e)&&"string"==typeof e.kind&&gB.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)&&gY(e.models)&&gY(e.efforts)&&gG.includes(e.pairing)}function g8(e){return!!gZ(e)&&(null===e.revision||"string"==typeof e.revision)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)}function g4(e){return!!gZ(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(g2)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.medianWallClockMs&&Number.isFinite(e.medianWallClockMs)&&"number"==typeof e.medianBusyMs&&Number.isFinite(e.medianBusyMs)&&"number"==typeof e.medianTotalTokens&&Number.isFinite(e.medianTotalTokens)&&"number"==typeof e.medianEstimatedCostUsd&&Number.isFinite(e.medianEstimatedCostUsd)&&"number"==typeof e.totalEstimatedCostUsd&&Number.isFinite(e.totalEstimatedCostUsd)&&"number"==typeof e.unpricedRuns&&Number.isFinite(e.unpricedRuns)&&"number"==typeof e.untimedRuns&&Number.isFinite(e.untimedRuns)&&"number"==typeof e.reworkRuns&&Number.isFinite(e.reworkRuns)&&"number"==typeof e.errorRuns&&Number.isFinite(e.errorRuns)&&"number"==typeof e.childRunsAvg&&Number.isFinite(e.childRunsAvg)&&"number"==typeof e.firstSeenAt&&Number.isFinite(e.firstSeenAt)&&"number"==typeof e.lastSeenAt&&Number.isFinite(e.lastSeenAt)&&Array.isArray(e.harnesses)&&e.harnesses.every(g8)}function g5(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&gV.includes(e))}async function g6(e){try{return await e.json()}catch{throw new gH("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}let g3={groupBy:"config",harness:null};function g7(e,t){return e instanceof gH||e instanceof Error?e.message:t}function g9(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function xe(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function xt(e){if("number"!=typeof e||!Number.isFinite(e))return"—";let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;let n=Math.round(t/1e3);if(n<60)return`${(t/1e3).toFixed(1)}s`;let r=Math.floor(n/60),a=n-60*r;return r<60?0===a?`${r}m`:`${r}m ${a}s`:`${Math.floor(r/60)}h ${r%60}m`}let xn={injection:"efficiency.sawKindInjection",developer:"efficiency.sawKindDeveloper",user:"efficiency.sawKindUser",compaction:"efficiency.sawKindCompaction",model:"efficiency.sawKindModel",effort:"efficiency.sawKindEffort",prompt:"efficiency.sawKindPrompt",rules:"efficiency.sawKindRules",memory:"efficiency.sawKindMemory"},xr={ok:"efficiency.sawToolOk",failed:"efficiency.sawToolFailed",noMatch:"efficiency.sawToolNoMatch",cancelled:"efficiency.sawToolCancelled",missing:"efficiency.sawToolMissing"},xa={failed:"critical",noMatch:"neutral",cancelled:"neutral",missing:"warning"};async function xi(e,t){let n,r=await fetch(e,{method:"GET",signal:t});try{n=await r.json()}catch{throw Error(`HTTP ${r.status}: invalid JSON`)}if(!r.ok)throw Error(n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error?n.error:`HTTP ${r.status}`);if(null===n)throw Error(`HTTP ${r.status}: empty body`);return n}function xs(e,t,n){return`${gD}/${encodeURIComponent(e)}/${t}?${new URLSearchParams(n).toString()}`}function xo(e){return e>0?new Date(e).toLocaleTimeString(void 0,{hour12:!1}):"—"}function xl({runId:e,role:t,entryId:n,call:i,label:s,t:o}){let[l,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)({status:"idle",value:null,error:null});return(0,r.jsxs)("div",{className:"run-saw-full-wrap",children:[(0,r.jsx)("button",{type:"button",className:"run-saw-link","aria-expanded":l,onClick:()=>{let r=!l;if(c(r),!r||"ready"===d.status||"loading"===d.status)return;u({status:"loading",value:null,error:null});let a={role:t,entry:n};i&&(a.call=i),xi(xs(e,"turns",a)).then(e=>u({status:"ready",value:e,error:null})).catch(e=>u({status:"error",value:null,error:e instanceof Error?e.message:String(e)}))},children:l?o("efficiency.sawHideFull"):s}),l?"ready"===d.status&&d.value?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("pre",{className:"run-saw-full",children:d.value.text}),d.value.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:o("efficiency.sawTruncated",{value:g9(d.value.text.length)})}):null]}):"error"===d.status?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:d.error}):(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:o("efficiency.sawLoading")}):null]})}function xc({event:e,runId:t,role:n,t:a}){let i=e.preview;if("compaction"===e.kind&&(null!=e.tokensBefore||null!=e.tokensAfter)){let t=a("efficiency.sawCompactionValue",{before:xe(e.tokensBefore??null),after:xe(e.tokensAfter??null)});i=i?`${t} \xb7 ${i}`:t}else void 0!==e.memoryIds&&(i=a("efficiency.sawMemoryIds",{value:e.memoryIds}));return(0,r.jsxs)("li",{className:"run-saw-event",children:[(0,r.jsxs)("div",{className:"run-saw-event-head",children:[(0,r.jsx)("span",{className:"run-saw-kind",children:a(xn[e.kind])}),(0,r.jsx)("span",{className:"run-saw-source",children:e.source}),(0,r.jsx)("span",{className:"run-saw-dim",children:xo(e.at)}),e.hiddenFromChat?(0,r.jsx)("span",{className:"run-saw-dim",children:a("efficiency.sawHiddenFromChat")}):null,e.sentToModel?null:(0,r.jsx)("span",{className:"run-saw-dim",children:a("efficiency.sawNotSent")})]}),i?(0,r.jsx)("p",{className:"run-saw-preview",children:i}):null,e.chars>e.preview.length?(0,r.jsx)(xl,{runId:t,role:n,entryId:e.entryId,call:null,label:a("efficiency.sawShowFull"),t:a}):null]})}function xd({call:e,runId:t,role:n,turnEntryId:a,t:i}){return(0,r.jsxs)("li",{className:"run-saw-tool",children:[(0,r.jsxs)("div",{className:"run-saw-tool-head",children:[(0,r.jsx)("span",{className:"run-saw-tool-name",children:e.name}),(0,r.jsx)("span",{className:"run-saw-num",children:xt(e.durationMs)}),null!==e.resultChars?(0,r.jsx)("span",{className:"run-saw-dim",children:i("efficiency.sawResultChars",{value:g9(e.resultChars)})}):null,"ok"!==e.status?(0,r.jsx)(nI.E,{tone:xa[e.status],variant:"weak",size:"medium",children:i(xr[e.status])}):null]}),(0,r.jsx)("code",{className:"run-saw-args",children:e.argsPreview}),(0,r.jsxs)("div",{className:"run-saw-tool-actions",children:[e.argsChars>e.argsPreview.length?(0,r.jsx)(xl,{runId:t,role:n,entryId:a,call:e.toolCallId,label:i("efficiency.sawShowArgs"),t:i}):null,e.resultEntryId?(0,r.jsx)(xl,{runId:t,role:n,entryId:e.resultEntryId,call:null,label:i("efficiency.sawShowResult"),t:i}):null]})]})}function xu({turn:e,runId:t,role:n,t:a}){let i=[e.model,xt(e.durationMs),e.usage?a("efficiency.sawUsage",{input:xe(e.usage.input),output:xe(e.usage.output),cacheRead:xe(e.usage.cacheRead)}):null,e.stopReason?a("efficiency.sawStop",{value:e.stopReason}):null].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"run-saw-turn",children:[(0,r.jsxs)("div",{className:"run-saw-turn-head",children:[(0,r.jsx)("span",{className:"run-saw-turn-label",children:a("efficiency.sawTurnLabel",{index:e.index})}),(0,r.jsx)("span",{className:"run-saw-dim",children:xo(e.at)})]}),(0,r.jsx)("p",{className:"run-saw-turn-meta",children:i}),e.toolsAdded.length>0||e.toolsRemoved.length>0?(0,r.jsx)("p",{className:"run-saw-dim",title:[...e.toolsAdded.map(e=>`+${e}`),...e.toolsRemoved.map(e=>`−${e}`)].join(" "),children:a("efficiency.sawToolsChanged",{added:e.toolsAdded.join(", ")||"0",removed:e.toolsRemoved.join(", ")||"0"})}):null,e.before.length>0?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:a("efficiency.sawBefore")}),(0,r.jsx)("ul",{className:"run-saw-events",children:e.before.map(e=>(0,r.jsx)(xc,{event:e,runId:t,role:n,t:a},e.entryId))})]}):null,e.toolCalls.length>0?(0,r.jsx)("ul",{className:"run-saw-tools",children:e.toolCalls.map(i=>(0,r.jsx)(xd,{call:i,runId:t,role:n,turnEntryId:e.entryId,t:a},i.toolCallId))}):null]})}function xp({runId:e,role:t,t:n}){let[i,o]=(0,a.useState)(null),[l,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let n=new AbortController;return o(null),c(null),xi(xs(e,"prelude",{role:t}),n.signal).then(o).catch(e=>{n.signal.aborted||c(e instanceof Error?e.message:String(e))}),()=>n.abort()},[e,t]);let p=i?.recorded.digests.at(-1)??null,h=i?.rebuilt;return(0,r.jsxs)("section",{className:"run-saw-prelude","aria-label":n("efficiency.sawPreludeTitle"),children:[(0,r.jsx)("h4",{className:"run-saw-subtitle",children:n("efficiency.sawPreludeTitle")}),l?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:l}):null,i||l?null:(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:n("efficiency.sawLoading")}),i?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:n("efficiency.sawPreludeRecorded")}),(0,r.jsx)("p",{className:"run-saw-line",children:p?n("efficiency.sawPreludeDigest",{value:p.digest}):n("efficiency.sawPreludeDigestNone")}),i.recorded.activeTools?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeTools",{value:i.recorded.activeTools.length})}),(0,r.jsx)("p",{className:"run-saw-names",children:i.recorded.activeTools.join(" \xb7 ")})]}):null,i.recorded.memoryRecall?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeMemory")}),(0,r.jsx)("p",{className:"run-saw-preview",children:i.recorded.memoryRecall.preview}),i.recorded.memoryRecall.chars>i.recorded.memoryRecall.preview.length?(0,r.jsx)(xl,{runId:e,role:t,entryId:i.recorded.memoryRecall.entryId,call:null,label:n("efficiency.sawShowFull"),t:n}):null]}):null,h?.status==="not-loaded"?(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeNotLoaded")}):h?.status==="available"?(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{u(!0),xi(xs(e,"prelude",{role:t,rebuild:"1"})).then(o).catch(e=>c(e instanceof Error?e.message:String(e))).finally(()=>u(!1))},disabled:d,children:n(d?"efficiency.sawPreludeLoading":"efficiency.sawPreludeReconstruct")})}):h?.status==="rebuilt"?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeApprox")}),null!==h.matchesRecorded?(0,r.jsx)("p",{className:"run-saw-line",children:n(h.matchesRecorded?"efficiency.sawPreludeMatch":"efficiency.sawPreludeMismatch")}):null,(0,r.jsx)("pre",{className:"run-saw-full",children:h.text}),h.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:n("efficiency.sawTruncated",{value:g9(h.text.length)})}):null]}):null]}):null]})}let xh={status:"idle",page:null,turns:[],loadingMore:!1,error:null};function xm({runId:e,t}){let[n,i]=(0,a.useState)(!1),[o,c]=(0,a.useState)("main"),[d,u]=(0,a.useState)(!1),[p,h]=(0,a.useState)(xh),m=(0,a.useRef)(null),f=(0,a.useCallback)(t=>{m.current?.abort();let n=new AbortController;m.current=n,h(e=>0===t?{...xh,status:"loading"}:{...e,loadingMore:!0});let r={role:o,offset:String(t),limit:String(30)};d&&(r.injectedOnly="1"),xi(xs(e,"turns",r),n.signal).then(e=>h(n=>({status:"ready",page:e,turns:0===t?e.turns:[...n.turns,...e.turns],loadingMore:!1,error:null}))).catch(e=>{n.signal.aborted||h(n=>({...n,status:0===t?"error":n.status,loadingMore:!1,error:e instanceof Error?e.message:String(e)}))})},[e,o,d]);(0,a.useEffect)(()=>{n&&f(0)},[n,f]),(0,a.useEffect)(()=>()=>m.current?.abort(),[]);let g=p.page,x=g?g.total-p.turns.length:0,v=g?Object.entries(g.counts.bySource).sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])):[];return(0,r.jsxs)("section",{className:"run-saw","aria-label":t("efficiency.sawSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.sawSection")}),(0,r.jsx)("p",{className:"run-saw-approx",children:t("efficiency.sawApproxNote")}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"run-saw-controls",children:[g&&g.roles.length>1?(0,r.jsxs)("label",{className:"run-saw-role",children:[(0,r.jsx)("span",{children:t("efficiency.sawRole")}),(0,r.jsx)("select",{className:"efficiency-folder-select",value:o,onChange:e=>c(e.target.value),children:g.roles.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]}):null,(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:d,onPressedChange:u,children:t("efficiency.sawOnlyInjected")})]}),"loading"===p.status||"idle"===p.status?(0,r.jsx)("p",{className:"efficiency-empty",role:"status",children:t("efficiency.sawLoading")}):"error"===p.status?(0,r.jsxs)("div",{className:"efficiency-empty",role:"alert",children:[(0,r.jsx)("div",{children:t("efficiency.sawError")}),(0,r.jsx)("div",{className:"run-saw-dim",children:p.error})]}):g?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-summary",children:t("efficiency.sawSummary",{turns:g.counts.turns,injections:g.counts.injections,tools:g.counts.toolCalls,failed:g.counts.toolFailures})}),v.length>0?(0,r.jsx)("p",{className:"run-saw-names",children:v.map(([e,t])=>`${e} ${t}`).join(" \xb7 ")}):null,(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",children:t("efficiency.sawSecretsMasked")}),0===p.turns.length?(0,r.jsx)("p",{className:"efficiency-empty",children:t(d?"efficiency.sawFilterEmpty":"efficiency.sawEmpty")}):(0,r.jsx)("ol",{className:"run-saw-turns",children:p.turns.map(n=>(0,r.jsx)(xu,{turn:n,runId:e,role:g.role,t:t},n.entryId))}),g.trailing.length>0&&x<=0?(0,r.jsxs)("div",{className:"run-saw-group run-saw-trailing",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:t("efficiency.sawTrailing")}),(0,r.jsx)("ul",{className:"run-saw-events",children:g.trailing.map(n=>(0,r.jsx)(xc,{event:n,runId:e,role:g.role,t:t},n.entryId))})]}):null,(0,r.jsxs)("div",{className:"run-saw-actions",children:[(0,r.jsx)("span",{className:"run-saw-dim",children:t("efficiency.sawShown",{shown:p.turns.length,total:g.total})}),x>0?(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>f(p.turns.length),disabled:p.loadingMore,children:p.loadingMore?t("efficiency.sawLoading"):t("efficiency.sawMore",{value:Math.min(x,30)})}):null]}),p.error?(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",role:"alert",children:p.error}):null,(0,r.jsx)(xp,{runId:e,role:g.role,t:t})]}):null]}):(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>i(!0),children:t("efficiency.sawOpen")})})]})}let xf={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},xg={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function xx(...e){return e.filter(Boolean).join(" ")}function xv(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function xb(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function xy(e,t){return null===e?t("efficiency.harnessUnknown"):e.slice(0,7)}function xw({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0",children:[(0,r.jsx)("dt",{className:"min-w-0 flex-1 text-xs text-text-muted [overflow-wrap:anywhere]",children:e}),(0,r.jsx)("dd",{className:"m-0 flex-none text-right font-mono text-xs tabular-nums text-text",children:t})]})}function xk({share:e,label:t}){let n=Number.isFinite(e)?Math.max(1,Math.min(100,100*e)):1;return(0,r.jsxs)("div",{className:"efficiency-bar","aria-hidden":"true",children:[(0,r.jsx)("div",{className:"efficiency-bar-fill",style:{width:`${n}%`}}),(0,r.jsx)("span",{className:"efficiency-bar-value",children:t})]})}function xj({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",xv(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function xS({outcome:e,t}){return(0,r.jsx)(nI.E,{tone:xf[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function xC({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(nI.E,{tone:"rework"===e?"warning":"neutral",variant:"weak",size:"medium",children:t({primary:"efficiency.purposePrimary",rework:"efficiency.purposeRework",review:"efficiency.purposeReview"}[e]??"efficiency.unmeasuredShort")})}function xN({run:e,selected:t,onSelect:n,t:a}){let i=e.title&&e.title.trim().length>0?e.title:a("efficiency.noTitle");return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",onClick:n,"aria-current":t?"true":void 0,className:xx("efficiency-run-item",t&&"is-selected"),children:[(0,r.jsxs)("span",{className:"efficiency-run-top",children:[(0,r.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,r.jsx)("span",{className:"efficiency-run-title",title:i,children:i}),(0,r.jsx)(xS,{outcome:e.outcome,t:a})]}),(0,r.jsxs)("span",{className:"efficiency-run-meta",children:[(0,r.jsx)("span",{className:"font-mono tabular-nums",children:a("efficiency.elapsedValue").replace("{value}",xt(e.wallClockMs))}),(0,r.jsx)(xj,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:a}),(0,r.jsx)("span",{className:"font-mono tabular-nums",title:e.harnessRevision??a("efficiency.harnessUnknown"),children:a("efficiency.harnessValue").replace("{value}",xy(e.harnessRevision,a))})]})]})})}function xT({role:e,t}){let n=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),a=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort"),i=e.outputTokens-e.helpers.reduce((e,t)=>e+t.outputTokens,0),s=t(`efficiency.role${"main"===e.kind?"Main":"maker"===e.kind?"Maker":"checker"===e.kind?"Checker":"advisor"===e.kind?"Advisor":"Unattributed"}`);return(0,r.jsxs)("details",{className:"efficiency-role",children:[(0,r.jsxs)("summary",{className:"efficiency-role-summary",children:[(0,r.jsxs)("span",{className:"efficiency-role-head",children:[(0,r.jsx)("span",{className:"efficiency-role-id",children:e.id}),(0,r.jsx)(nI.E,{tone:xg[e.kind]??"neutral",variant:"weak",size:"medium",children:s}),(0,r.jsx)(xC,{purpose:e.purpose,t:t})]}),(0,r.jsx)("span",{className:"efficiency-model-line",title:n,children:n}),(0,r.jsxs)("span",{className:"efficiency-role-stats",children:[(0,r.jsxs)("span",{children:[t("efficiency.busyTime")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:xt(e.busyMs)})]}),(0,r.jsxs)("span",{children:[t("efficiency.estimatedCost")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:xv(e.estimatedCostUsd)})]}),(0,r.jsxs)("span",{children:[t("efficiency.tokens")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:xe(e.totalTokens)})]})]})]}),(0,r.jsxs)("div",{className:"efficiency-role-body",children:[(0,r.jsxs)("p",{className:"efficiency-dim",children:[t("efficiency.effortLabel").replace("{value}",a),` \xb7 ${t("efficiency.requestsValue").replace("{value}",String(e.requestCount))}`,` \xb7 ${t("efficiency.toolCallsValue").replace("{value}",String(e.toolCalls))}`]}),(0,r.jsxs)("dl",{className:"efficiency-metrics",children:[(0,r.jsx)(xw,{label:t("efficiency.unpricedRequests"),value:g9(e.unpricedRequests)}),(0,r.jsx)(xw,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?xt(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,r.jsx)(xw,{label:t("efficiency.outputTokens"),value:xe(i)})]}),e.ttftRequests>0&&e.ttftRequests<e.requestCount?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.firstTokenPartial",{recorded:e.ttftRequests,total:e.requestCount})}):null,e.untimedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.untimedLowerBound").replace("{value}",g9(e.untimedRequests))}):null,e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.unpricedLowerBound")}):null,e.helpers.length>0?(0,r.jsxs)("section",{className:"efficiency-helpers","aria-label":t("efficiency.helpersTitle"),children:[(0,r.jsx)("h4",{className:"efficiency-helpers-title",children:t("efficiency.helpersTitle")}),(0,r.jsx)("ul",{className:"efficiency-helper-list",children:e.helpers.map(e=>(0,r.jsxs)("li",{className:"efficiency-helper",children:[(0,r.jsx)("span",{className:"efficiency-helper-name",children:`${e.purpose} \xb7 ${e.model}`}),(0,r.jsx)("span",{className:"efficiency-helper-value",children:t("efficiency.helperCallsValue",{count:e.requestCount,output:xe(e.outputTokens),tokens:xe(e.totalTokens),cost:xv(e.estimatedCostUsd)})})]},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.helpersIncludedNote")})]}):null]})]})}function xI({item:e,t}){let n="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,r.jsxs)("li",{className:"efficiency-bottleneck","data-kind":e.kind,children:[(0,r.jsx)("span",{className:"efficiency-bottleneck-label",children:n}),(0,r.jsx)("span",{className:"efficiency-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"efficiency-meter-fill",style:{inlineSize:`${Number.isFinite(e.relative)?Math.max(1,Math.min(100,100*e.relative)):1}%`}})}),(0,r.jsx)("span",{className:"efficiency-bottleneck-value",children:xt(e.ms)})]})}function xM({detail:e,t}){return(0,r.jsxs)("div",{className:"efficiency-detail",children:[(0,r.jsxs)("section",{"aria-label":t("efficiency.summarySection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.summarySection")}),(0,r.jsxs)("div",{className:"efficiency-dual",children:[(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.elapsed")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:xt(e.wallClockMs)})]}),(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.busyTotal")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:xt(e.busyMs)})]})]}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,r.jsxs)("dl",{className:"efficiency-metrics",children:[(0,r.jsx)(xw,{label:t("efficiency.estimatedCost"),value:xv(e.estimatedCostUsd)}),(0,r.jsx)(xw,{label:t("efficiency.tokens"),value:xe(e.totalTokens)}),(0,r.jsx)(xw,{label:t("efficiency.harness"),value:xy(e.harnessRevision,t)})]}),e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.bottlenecksSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.bottlenecksSection")}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.bottleneckOrderNote")}),e.bottlenecks.length>0?(0,r.jsx)("ol",{className:"efficiency-bottlenecks",children:e.bottlenecks.map(e=>(0,r.jsx)(xI,{item:e,t:t},`${e.kind}:${e.id}`))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.bottlenecksEmpty")}),e.unmeasuredMs>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unmeasuredGapValue").replace("{value}",xt(e.unmeasuredMs))}):null]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.rolesSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.rolesSection")}),e.roles.length>0?(0,r.jsx)("div",{className:"efficiency-roles",children:e.roles.map(e=>(0,r.jsx)(xT,{role:e,t:t},e.id))},e.runId):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),e.toolTotals.length>0?(0,r.jsxs)("section",{"aria-label":t("efficiency.toolsSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.toolsSection")}),(0,r.jsx)("dl",{className:"efficiency-metrics",children:e.toolTotals.map(e=>(0,r.jsx)(xw,{label:[e.toolName,t("efficiency.toolFailedValue").replace("{value}",String(e.failed)),...e.noMatch>0?[t("efficiency.toolNoMatchValue").replace("{value}",String(e.noMatch))]:[],...e.cancelled>0?[t("efficiency.toolCancelledValue").replace("{value}",String(e.cancelled))]:[]].join(" \xb7 "),value:g9(e.calls)},e.toolName))})]}):null,(0,r.jsx)(xm,{runId:e.runId,t:t},e.runId)]})}function xR(e){return e.map(e=>{let t=e.effort??"–",n=e.count>1?` x${e.count}`:"";return`${e.kind} ${e.model}:${t}${n}`}).join(" \xb7 ")}function xE({response:e,t}){return(0,r.jsx)("section",{className:"efficiency-card",children:(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(xw,{label:t("efficiency.scopeSessions"),value:g9(e.sessionCount)}),(0,r.jsx)(xw,{label:t("efficiency.scopeRuns"),value:g9(e.runCount)}),(0,r.jsx)(xw,{label:t("efficiency.scopeExcludedRuns"),value:g9(e.excludedRunCount)})]})})}function xL({config:e,baselineRuns:t,t:n}){let a=t>0?e.runCount/t:0,i=e.runCount>0?e.reworkRuns/e.runCount:0,s=e.runCount>0?e.errorRuns/e.runCount:0,o=function(e,t){if(1===e.length)return{text:xy(e[0].revision,t),full:e[0].revision??t("efficiency.harnessUnknown")};let n=e.map(e=>`${xy(e.revision,t)} \xd7${e.runCount}`),r=n.slice(0,4).join(" \xb7 ");return{text:n.length>4?`${r} \xb7 +${n.length-4}`:r,full:e.map(e=>`${e.revision??t("efficiency.harnessUnknown")} \xd7${e.runCount}`).join("\n")}}(e.harnesses,n);return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsx)("p",{className:"efficiency-model-line",title:xR(e.roles),children:xR(e.roles)}),(0,r.jsx)("p",{className:"efficiency-dim font-mono tabular-nums",title:o.full,children:n("efficiency.harnessValue").replace("{value}",o.text)}),e.roles.some(e=>"unknown"===e.pairing)?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.mixedPairingNote")}):null,(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-dim",children:n("efficiency.runsValue").replace("{value}",String(e.runCount))}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:xb(a)})]}),(0,r.jsx)(xk,{share:a,label:xb(a)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(xw,{label:n("efficiency.medianElapsed"),value:xt(e.medianWallClockMs)}),(0,r.jsx)(xw,{label:n("efficiency.medianBusy"),value:xt(e.medianBusyMs)}),(0,r.jsx)(xw,{label:n("efficiency.medianTokens"),value:xe(e.medianTotalTokens)}),(0,r.jsx)(xw,{label:n("efficiency.medianEstimatedCost"),value:xv(e.medianEstimatedCostUsd)}),(0,r.jsx)(xw,{label:n("efficiency.totalEstimatedCost"),value:xv(e.totalEstimatedCostUsd)}),(0,r.jsx)(xw,{label:n("efficiency.reworkRate"),value:xb(i,1)}),(0,r.jsx)(xw,{label:n("efficiency.errorRate"),value:xb(s,1)}),(0,r.jsx)(xw,{label:n("efficiency.unpricedRuns"),value:g9(e.unpricedRuns)}),(0,r.jsx)(xw,{label:n("efficiency.untimedRuns"),value:g9(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",g9(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function x$({open:e,sessionId:t,activeTab:n,onTabChange:i,client:o,className:c}){let d=(0,a.useId)(),u=(0,a.useId)(),{t:p}=(0,z.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[i]=(0,a.useState)(()=>r??function(e=(e,t)=>fetch(e,t)){let t=async(t,n)=>{let r;try{r=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new gH("unreachable","효율 기록에 연결할 수 없습니다.")}let a=await g6(r);if(!r.ok){var i;throw new gH("http",(i=`HTTP ${r.status}`,null!==a&&"object"==typeof a&&"error"in a&&"string"==typeof a.error&&a.error?a.error:i),r.status)}return{response:r,body:a}};return{async listRuns(e,n,r){let{response:a,body:i}=await t(`${gD}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!gZ(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(gX)&&g5(e.unmeasured)))throw new gH("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new gH("invalid-response",t,n)}}(i,"실행 목록 응답이 올바르지 않습니다.",a.status)},async getRun(e,n){let{response:r,body:a}=await t(`${gD}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!gX(e)||!(Array.isArray(e.roles)&&e.roles.every(gQ)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(g0)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(g1)&&g5(e.unmeasured)))throw new gH("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new gH("invalid-response",t,n)}}(a,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,a,i){let s=new URLSearchParams;null!==e&&""!==e&&s.set("folder",e),s.set("sessions",String(n)),s.set("scope",r),i?.groupBy==="harness"&&s.set("groupBy","harness"),i?.harness&&s.set("harness",i.harness);let{response:o,body:l}=await t(`/api/experiments?${s.toString()}`,{method:"GET",signal:a});return function(e,t,n=null){try{if(!gZ(e)||!((null===e.folder||"string"==typeof e.folder)&&gY(e.folders)&&"string"==typeof e.scope&&gK.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(g4)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&"string"==typeof e.groupBy&&gJ.includes(e.groupBy)&&(null===e.harness||"string"==typeof e.harness)&&Array.isArray(e.harnesses)&&e.harnesses.every(g8)&&g5(e.unmeasured)))throw new gH("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new gH("invalid-response",t,n)}}(l,"구성 비교 응답이 올바르지 않습니다.",o.status)}}}()),[s,o]=(0,a.useState)({status:"idle",runs:[],error:null}),[l,c]=(0,a.useState)({status:"idle",runId:null,detail:null,error:null}),[d,u]=(0,a.useState)({status:"idle",response:null,error:null}),[p,h]=(0,a.useState)(null),[m,f]=(0,a.useState)(null),g=(0,a.useRef)(null),x=(0,a.useRef)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null);(0,a.useEffect)(()=>{x.current?.abort(),x.current=null,h(null),c({status:"idle",runId:null,detail:null,error:null}),o({status:"idle",runs:[],error:null})},[e]);let y=(0,a.useCallback)(()=>{if(!t||"governor"!==n||!e)return;g.current?.abort();let r=new AbortController;g.current=r,o(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),i.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&g.current===r){if(0===e.runs.length)return void o({status:"empty",runs:[],error:null});o({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||g.current!==r||o({status:"error",runs:[],error:g7(e,"실행 목록을 불러오지 못했습니다.")})})},[n,i,e,t]),w=(0,a.useCallback)(e=>{if(!t)return;x.current?.abort();let n=new AbortController;x.current=n,c({status:"loading",runId:e,detail:null,error:null}),i.getRun(e,n.signal).then(t=>{n.signal.aborted||x.current!==n||c({status:"ready",runId:e,detail:t,error:null})}).catch(t=>{n.signal.aborted||x.current!==n||c({status:"error",runId:e,detail:null,error:g7(t,"실행 상세를 불러오지 못했습니다.")})})},[i,t]),k=(0,a.useCallback)((e,r="all",a=g3)=>{if(!t||"lab"!==n)return;v.current?.abort();let s=new AbortController;v.current=s,u(e=>({status:"loading",response:"ready"===e.status||"empty"===e.status?e.response:null,error:null})),i.listExperiments(e,30,r,s.signal,a).then(e=>{if(!s.signal.aborted&&v.current===s){if(0===e.configs.length)return void u({status:"empty",response:e,error:null});u({status:"ready",response:e,error:null})}}).catch(e=>{s.signal.aborted||v.current!==s||u({status:"error",response:null,error:g7(e,"구성 비교를 불러오지 못했습니다.")})})},[n,i,t]);(0,a.useEffect)(()=>{if(t&&"governor"===n)return y(),()=>{g.current?.abort(),g.current=null}},[n,y,e,t]),(0,a.useEffect)(()=>{if(t&&"lab"===n)return k(b.current),()=>{v.current?.abort(),v.current=null}},[n,k,t]),(0,a.useEffect)(()=>{if(t&&"governor"===n&&null!==p)return w(p),()=>{x.current?.abort(),x.current=null}},[n,w,p,t]),(0,a.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,a.useCallback)(e=>{x.current?.abort(),x.current=null,h(e),null===e&&c({status:"idle",runId:null,detail:null,error:null})},[]);return{list:s,detail:l,experiments:d,selectedRunId:p,selectRun:j,refreshRuns:(0,a.useCallback)(()=>{y()},[y]),refreshExperiments:(0,a.useCallback)((e,t="all",n=g3)=>{let r=void 0===e?b.current:e;void 0!==e&&(b.current=e,f(e)),k(r,t,n)},[k]),experimentFolder:m}}({sessionId:t,visible:e,activeTab:n,client:o}),[m,f]=(0,a.useState)(""),g=(0,a.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),x=(0,a.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),v=h.experimentFolder,b=h.experiments.response?.scope??"all",y={groupBy:h.experiments.response?.groupBy??"config",harness:h.experiments.response?.harness??null},w=h.experiments.response?.harnesses??[];if(!e)return null;let k="governor"===n&&"loading"===h.list.status||"lab"===n&&"loading"===h.experiments.status,j=k?p("efficiency.refreshing"):p("efficiency.refresh"),S="governor"===n?h.list.runs.length>0?p("efficiency.runsValue").replace("{value}",String(h.list.runs.length)):"":h.experiments.response?p("efficiency.runsValue").replace("{value}",String(h.experiments.response.runCount)):"";return(0,r.jsxs)("section",{className:xx("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",c),"aria-labelledby":d,"aria-busy":k,children:[(0,r.jsxs)("header",{className:"flex min-h-12 items-center gap-3 border-b border-border bg-bg px-3",children:[(0,r.jsx)("h1",{id:d,className:"m-0 text-sm font-semibold text-text",children:p("efficiency.title")}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-right font-mono text-[11px] tabular-nums text-text-dim",children:S}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===n?h.refreshRuns():h.refreshExperiments(void 0,b,y)},disabled:k,children:j})]}),(0,r.jsx)("div",{className:"grid grid-cols-2 border-b border-border bg-bg",role:"tablist","aria-label":p("efficiency.title"),children:["governor","lab"].map(e=>(0,r.jsx)("button",{type:"button",role:"tab","aria-selected":n===e,id:`${u}-${e}-tab`,"aria-controls":u,className:xx("min-h-10 border-0 border-r border-border bg-bg px-4 text-sm text-text-muted last:border-r-0 hover:bg-bg-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent",n===e&&"bg-bg-selected font-semibold text-text"),onClick:()=>i(e),children:"governor"===e?p("efficiency.governor"):p("efficiency.lab")},e))}),"lab"===n?(0,r.jsxs)("div",{className:"efficiency-folderbar",children:[(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-folder`,children:p("efficiency.folder")}),(0,r.jsxs)("select",{id:`${u}-folder`,className:"efficiency-folder-select",value:v??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;f(t??""),h.refreshExperiments(t,b,y)},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.folderAll")}),g.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),v&&!g.includes(v)?(0,r.jsx)("option",{value:v,children:v}):null]}),(0,r.jsx)("input",{className:"efficiency-folder-input",value:m,placeholder:p("efficiency.folderPlaceholder"),"aria-label":p("efficiency.folder"),onChange:e=>f(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===m.trim()?null:m.trim();h.refreshExperiments(e,b,y)}}}),(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${u}-harness`,children:p("efficiency.harness")}),(0,r.jsxs)("select",{id:`${u}-harness`,className:"efficiency-folder-select font-mono",value:y.harness??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;h.refreshExperiments(void 0,b,{groupBy:y.groupBy,harness:t})},children:[(0,r.jsx)("option",{value:"",children:p("efficiency.harnessAll")}),w.map(e=>(0,r.jsx)("option",{value:e.revision??gO,children:`${xy(e.revision,p)} (${e.runCount})`},e.revision??gO)),y.harness&&!w.some(e=>(e.revision??gO)===y.harness)?(0,r.jsx)("option",{value:y.harness,children:y.harness===gO?p("efficiency.harnessUnknown"):y.harness.slice(0,7)}):null]}),(0,r.jsxs)("div",{className:"col-span-full flex flex-col items-start gap-2",children:[(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===b,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all",y),children:p("efficiency.scopeAttributed")}),(0,r.jsx)(nI.E,{tone:"attributed"===b?"informative":"neutral",variant:"weak",size:"medium",children:p("attributed"===b?"efficiency.scopeAttributed":"efficiency.scopeAll")}),(0,r.jsx)(l.f,{variant:"neutralWeak",size:"xsmall",pressed:"harness"===y.groupBy,onPressedChange:e=>h.refreshExperiments(void 0,b,{groupBy:e?"harness":"config",harness:y.harness}),children:p("efficiency.groupByHarness")})]})]}):null,(0,r.jsx)("div",{id:u,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",role:"tabpanel","aria-labelledby":`${u}-${n}-tab`,children:"governor"===n?t?"idle"===h.list.status||"loading"===h.list.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingRuns")}):"error"===h.list.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.runsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.list.error})]}):"empty"===h.list.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.runsEmpty")}):(0,r.jsxs)("div",{className:"efficiency-governor",children:[(0,r.jsx)("ul",{className:"efficiency-run-list",children:h.list.runs.map(e=>(0,r.jsx)(xN,{run:e,selected:h.selectedRunId===e.runId,onSelect:()=>h.selectRun(h.selectedRunId===e.runId?null:e.runId),t:p},e.runId))}),(0,r.jsx)("div",{className:"efficiency-detail-pane",children:null===h.selectedRunId||"idle"===h.detail.status?(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.selectRun")}):"loading"===h.detail.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingDetail")}):"error"===h.detail.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.detailError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.detail.error})]}):h.detail.detail?(0,r.jsx)(xM,{detail:h.detail.detail,t:p}):null})]}):(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.noSession")}):(()=>{if("idle"===h.experiments.status||"loading"===h.experiments.status)return(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:p("efficiency.loadingExperiments")});if("error"===h.experiments.status)return(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:p("efficiency.experimentsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.experiments.error})]});let e=h.experiments.response;return"empty"!==h.experiments.status&&e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")}),(0,r.jsxs)("div",{className:"efficiency-stack",children:[(0,r.jsx)(xE,{response:e,t:p}),e.configs.map(t=>(0,r.jsx)(xL,{config:t,baselineRuns:x,t:p},JSON.stringify([t.roles.map(e=>[e.kind,e.models,e.efforts,e.count]),"harness"===e.groupBy?t.harnesses[0]?.revision??null:null])))]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-empty",children:p("efficiency.experimentsEmpty")}),e?(0,r.jsx)("div",{className:"efficiency-stack",children:(0,r.jsx)(xE,{response:e,t:p})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.difficultyNote")}),(0,r.jsx)("p",{className:"efficiency-note",children:p("efficiency.harnessNote")})]})})()})]})}var xP=n(96607),xA=n(29213),xF=n.n(xA);let x_="cuelo-plugin-lab-open",xz="/api/plugin-lab",xW=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 8a5 5 0 1 1-1.46-3.54M13 2.5v3h-3"})});async function xO(e){try{let t=await e.json();if("string"==typeof t.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}function xD(e){return e.hasPanel&&e.enabled}let xH=new Map;function xU({title:e,visible:t,sessionId:n,labWidgets:i,onInsertDraft:o}){let{t:l}=(0,z.s)(),[c,d]=(0,a.useState)({kind:"loading"}),[u,p]=(0,a.useState)(()=>new Set),[h,m]=(0,a.useState)({}),[f,g]=(0,a.useState)(null),x=(0,a.useRef)(0);(0,a.useEffect)(()=>{g(function(){try{return window.localStorage.getItem(x_)}catch{return null}}())},[]);let v=(0,a.useCallback)(async()=>{let e=++x.current;d(e=>"ready"===e.kind?e:{kind:"loading"});try{let t=await fetch(xz,{cache:"no-store"});if(!t.ok)throw Error(await xO(t));let n=await t.json();e===x.current&&d({kind:"ready",plugins:n.plugins??[]})}catch(t){e===x.current&&d({kind:"error",message:t instanceof Error?t.message:String(t)})}},[]);(0,a.useEffect)(()=>{t&&v()},[t,v]);let b=(0,a.useCallback)(async(e,t)=>{p(t=>new Set(t).add(e.id)),m(t=>({...t,[e.id]:null}));try{let n=await fetch(`${xz}/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:t})});if(!n.ok)throw Error(await xO(n));let r=await n.json();d(e=>"ready"===e.kind?{kind:"ready",plugins:e.plugins.map(e=>e.id===r.plugin.id?r.plugin:e)}:e),v()}catch(t){m(n=>({...n,[e.id]:t instanceof Error?t.message:String(t)}))}finally{p(t=>{let n=new Set(t);return n.delete(e.id),n})}},[v]),y=(0,a.useCallback)(e=>{g(e);try{e?window.localStorage.setItem(x_,e):window.localStorage.removeItem(x_)}catch{}},[]),w="ready"===c.kind?c.plugins:[],k=f?w.find(e=>e.id===f&&xD(e))??null:null;if(k)return(0,r.jsx)(xq,{plugin:k,sessionId:n,labWidgets:i,onInsertDraft:o,onBack:()=>y(null)});let j=w.some(e=>e.hasExtension);return(0,r.jsxs)("section",{className:xF().view,"aria-label":e,children:[(0,r.jsx)(p5,{title:e,subtitle:"ready"===c.kind?l("pluginLab.counts",{count:w.length}):void 0,actions:[{id:"refresh",label:l("pluginLab.refresh"),icon:xW,onClick:()=>void v()}]}),(0,r.jsxs)("div",{className:xF().toolbar,children:[(0,r.jsx)(s.r,{variant:"neutralWeak",size:"small",disabled:!o,onClick:()=>o?.(l("pluginLab.starter")),title:o?l("pluginLab.createHint"):l("pluginLab.noComposer"),children:l("pluginLab.create")}),j&&(0,r.jsx)("p",{className:xF().hint,children:l("pluginLab.applyHint")})]}),(0,r.jsxs)("div",{className:xF().body,children:["loading"===c.kind&&(0,r.jsx)("p",{className:xF().message,role:"status",children:l("pluginLab.loading")}),"error"===c.kind&&(0,r.jsxs)("div",{className:xF().message,role:"alert",children:[(0,r.jsx)("p",{className:xF().errorText,children:l("pluginLab.loadFailed",{error:c.message})}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"small",onClick:()=>void v(),children:l("pluginLab.retry")})]}),"ready"===c.kind&&0===w.length&&(0,r.jsx)("p",{className:xF().message,children:l("pluginLab.empty")}),"ready"===c.kind&&w.length>0&&(0,r.jsx)("ul",{className:xF().list,"aria-label":l("pluginLab.listLabel"),children:w.map(e=>(0,r.jsx)(xB,{plugin:e,busy:u.has(e.id),error:h[e.id]??null,onToggle:t=>void b(e,t),onOpen:()=>y(e.id)},e.id))})]})]})}function xB({plugin:e,busy:t,error:n,onToggle:a,onOpen:i}){var o;let l,{t:c,locale:d}=(0,z.s)(),u=e.enabled;return(0,r.jsxs)("li",{className:xF().card,"data-enabled":u?"true":"false","aria-busy":t||void 0,children:[(0,r.jsxs)("div",{className:xF().cardHead,children:[(0,r.jsxs)("div",{className:xF().titleBlock,children:[(0,r.jsx)("div",{className:xF().titleLine,children:(0,r.jsx)("span",{className:xF().name,title:e.name,children:e.name})}),(0,r.jsx)("span",{className:xF().id,title:e.id,children:e.id})]}),(0,r.jsx)("div",{className:xF().control,children:(0,r.jsxs)(xP.h.Root,{className:xF().switch,size:"24",tone:"brand",checked:e.enabled,disabled:t,onCheckedChange:a,"aria-label":c("pluginLab.toggleLabel",{name:e.name}),children:[(0,r.jsx)(xP.h.HiddenInput,{}),(0,r.jsx)(xP.h.Label,{className:xF().switchLabel,children:c(t?"pluginLab.saving":e.enabled?"pluginLab.on":"pluginLab.off")}),(0,r.jsx)(xP.h.Control,{children:(0,r.jsx)(xP.h.Thumb,{})})]})})]}),e.description&&(0,r.jsx)("p",{className:xF().description,children:e.description}),e.lastEnhancement&&(0,r.jsxs)("div",{className:xF().enhancement,children:[(0,r.jsxs)("p",{className:xF().enhancementHead,children:[(0,r.jsx)("span",{className:xF().metaLabel,children:c("pluginLab.lastEnhancement")}),(0,r.jsx)("time",{className:xF().enhancementDate,dateTime:e.lastEnhancement.at,title:c("pluginLab.lastEnhancementHint"),children:(o=e.lastEnhancement.at,(l=xH.get(d))||(l=new Intl.DateTimeFormat(d,{dateStyle:"medium"}),xH.set(d,l)),l.format(new Date(o)))})]}),(0,r.jsx)("p",{className:xF().enhancementSummary,children:e.lastEnhancement.summary})]}),e.tools.length>0&&(0,r.jsxs)("div",{className:xF().tools,children:[(0,r.jsx)("span",{className:xF().metaLabel,children:c("pluginLab.tools")}),(0,r.jsx)("ul",{className:xF().toolList,"aria-label":c("pluginLab.tools"),children:e.tools.map(e=>(0,r.jsx)("li",{className:xF().tool,children:e},e))})]}),e.problem&&(0,r.jsxs)("p",{className:xF().problem,children:[(0,r.jsx)("span",{className:xF().problemLabel,children:c("pluginLab.problem")}),(0,r.jsx)("span",{children:e.problem})]}),n&&(0,r.jsx)("p",{className:xF().problem,role:"alert",children:c("pluginLab.toggleFailed",{error:n})}),xD(e)&&(0,r.jsx)("div",{className:xF().cardActions,children:(0,r.jsx)(s.r,{variant:"neutralWeak",size:"small",onClick:i,"aria-label":c("pluginLab.openPanelLabel",{name:e.name}),children:c("pluginLab.openPanel")})})]})}function xq({plugin:e,sessionId:t,labWidgets:n,onInsertDraft:i,onBack:s}){let{t:o}=(0,z.s)(),{theme:l}=nm(),c=(0,a.useRef)(null),d=(0,a.useMemo)(()=>{var r,a;return n.sessionId===t?(r=n.widgets,a=e.id,r.filter(e=>cz(e.key)===a).flatMap(e=>[...e.lines])):[]},[n,t,e.id]),u=(0,a.useRef)({sessionId:null,lines:[],theme:"light"}),p=(0,a.useRef)(i),[h,m]=(0,a.useState)(null);(0,a.useEffect)(()=>{p.current=i},[i]);let f=(0,a.useMemo)(()=>{var t;let n;return t={frame:()=>c.current?.contentWindow??null,state:()=>u.current,insertDraft:e=>{let t=p.current;return t?(t(e),m(o("pluginLab.draftInserted")),!0):(m(o("pluginLab.noComposer")),!1)},recordDraft:()=>{fetch(`${xz}/${encodeURIComponent(e.id)}/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"draft"})}).then(e=>{e.ok||m(o("pluginLab.draftNotRecorded"))},()=>m(o("pluginLab.draftNotRecorded")))}},{publishState:n=()=>{let e=t.frame();if(!e)return;let{sessionId:n,lines:r,theme:a}=t.state();e.postMessage({type:"cuelo-lab:state",sessionId:n,lines:[...r],...a?{theme:a}:{}},"*")},handleMessage(e){let r=function(e,t){if(!t||e.source!==t||"null"!==e.origin||"object"!=typeof e.data||null===e.data||Array.isArray(e.data))return null;let n=e.data,r=Object.keys(n).sort().join(",");if("cuelo-lab:ready"===n.type)return"type"===r?{type:"cuelo-lab:ready"}:null;if("cuelo-lab:draft"!==n.type||"text,type"!==r||"string"!=typeof n.text)return null;let a=function(e){if(e.length<=4e3)return e;let t=e.slice(0,4e3),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319?t.slice(0,-1):t}(n.text);return a.trim()?{type:"cuelo-lab:draft",text:a}:null}(e,t.frame());if(r){if("cuelo-lab:ready"===r.type)return void n();t.insertDraft(r.text)&&t.recordDraft()}}}},[e.id,o]);return(0,a.useEffect)(()=>(window.addEventListener("message",f.handleMessage),()=>window.removeEventListener("message",f.handleMessage)),[f]),(0,a.useEffect)(()=>{u.current={sessionId:t,lines:d,theme:l},f.publishState()},[f,t,d,l]),(0,r.jsxs)("section",{className:xF().view,"aria-label":o("pluginLab.frameTitle",{name:e.name}),children:[(0,r.jsx)(p5,{back:{label:o("pluginLab.back"),onClick:s},title:e.name,subtitle:o("pluginLab.panelSubtitle",{id:e.id})}),(0,r.jsx)("div",{className:xF().stage,children:(0,r.jsx)("iframe",{ref:c,className:xF().frame,title:o("pluginLab.frameTitle",{name:e.name}),src:`${xz}/${encodeURIComponent(e.id)}/panel`,sandbox:"allow-scripts",referrerPolicy:"no-referrer"})}),(0,r.jsxs)("div",{className:xF().status,children:[(0,r.jsx)("span",{className:xF().lines,"data-live":d.length>0?"true":"false",children:d.length>0?o("pluginLab.lines",{count:d.length}):o("pluginLab.noLines")}),(0,r.jsx)("span",{role:"status",className:xF().notice,children:h})]})]})}function xV(e){return`request:${e}`}function xK(e){return`memory:${e}`}function xG(e){return`doc:${e}`}function xJ(e){return`file:${e}`}var xZ=n(2498),xY=n.n(xZ);let xX="cuelo-memory-trace-scope",xQ="cuelo-memory-trace-request:";function x0(e){return e.replace(/\b[\w.-]+=[0-9a-f]{12,}\b/gi,"").replace(/\b[0-9a-f]{16,}\b/gi,"").replace(/\s{2,}/g," ").trim()}function x1(e){return e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/`+/g,"").replace(/\*\*|__/g,"").replace(/(^|\n)[ \t]*(?:#{1,6}|[-*+]|\d+[.)])[ \t]+/g,"$1").replace(/\s+/g," ").trim()}let x2=/^\[(하네스 통지|자동 재개)\]\s*/;function x8(e){let t=/^(\S+) · ([\s\S]*)$/.exec(e);return t?`${t[1]} \xb7 ${x1(t[2])}`:x1(e)}let x4=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 8a5 5 0 1 1-1.46-3.54M13 2.5v3h-3"})}),x5=["recall","jev","docmap","docs","lessons","saved"],x6={recall:"memoryTrace.stageRecall",jev:"memoryTrace.stageJev",docmap:"memoryTrace.stageDocmap",docs:"memoryTrace.stageDocs",lessons:"memoryTrace.stageLessons",saved:"memoryTrace.stageSaved"};function x3(e,t){let n=e=>e.some(e=>xK(e.id)===t);return n(e.recalled)||e.explicit.some(e=>n(e.memories))?"recall":e.lessons.some(e=>xJ(e.file)===t||xG(e.file)===t||n(e.memories))?"lessons":e.docs.some(e=>xG(e.path)===t)?"docs":e.candidates.some(e=>xG(e.path)===t)?"docmap":e.saved.some(e=>e.nodeId===t)?"saved":[...e.verdicts.keys()].some(e=>xK(e)===t)?"jev":null}async function x7(e){try{let t=await e.json();if("string"==typeof t.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}function x9({title:e,visible:t,sessionId:n}){let i,{t:o,locale:l}=(0,z.s)(),[c,d]=(0,a.useState)({kind:"idle"}),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)("request"),b=(0,a.useRef)(0),y=(0,a.useRef)(null),w=(0,a.useRef)(null),k=(0,a.useRef)(null),[j,S]=(0,a.useState)(!1),C=(0,a.useCallback)(()=>{let e=k.current;S(!!(e&&e.scrollTop+e.clientHeight<e.scrollHeight-2))},[]);(0,a.useEffect)(()=>{v(function(){try{return"session"===window.localStorage.getItem(xX)?"session":"request"}catch{return"request"}}())},[]),(0,a.useEffect)(()=>{p(n?function(e){try{return window.sessionStorage.getItem(xQ+e)}catch{return null}}(n):null),g(null)},[n]);let N=(0,a.useCallback)(async()=>{let e=++b.current;if(y.current?.abort(),!n)return void d({kind:"idle"});let t=new AbortController;y.current=t,d(e=>"ready"===e.kind&&e.trace.sessionId===n?e:{kind:"loading"});try{let r=await fetch(`/api/sessions/${encodeURIComponent(n)}/memory-trace`,{cache:"no-store",signal:t.signal});if(!r.ok)throw Error(await x7(r));let a=await r.json();e===b.current&&d({kind:"ready",trace:a})}catch(n){if(t.signal.aborted)return;e===b.current&&d({kind:"error",message:n instanceof Error?n.message:String(n)})}},[n]);(0,a.useEffect)(()=>t?(N(),()=>y.current?.abort()):void 0,[t,N]);let T="ready"===c.kind&&c.trace.sessionId===n?c.trace:null,I=(0,a.useMemo)(()=>T?T.requests.map((e,t)=>{let n,r,a;return n={index:t+1,request:e,recalled:[],explicit:[],verdicts:new Map,jev:[],candidates:[],docs:[],lessons:[],saved:[],counts:{recall:0,jev:0,docmap:0,docs:0,lessons:0,saved:0},happened:{recall:!1,jev:!1,docmap:!1,docs:!1,lessons:!1,saved:!1}},r=new Map,a=new Set,e.steps.forEach((e,t)=>{switch(e.kind){case"recall":for(let t of e.memories)a.has(t.id)||(a.add(t.id),n.recalled.push(t));break;case"explicit-recall":for(let t of(n.explicit.push({target:e.target,query:e.query,memories:e.memories}),e.memories))a.add(t.id);break;case"jev":for(let t of(n.jev.push({buckets:e.buckets,unknown:e.unknownCount,unrelated:e.unrelatedCount}),e.buckets))for(let e of t.ids)n.verdicts.set(e,{short:t.shortLabel,label:t.label});break;case"docmap":for(let t of e.candidates)n.candidates.some(e=>e.path===t.path)||n.candidates.push(t);break;case"doc-read":{let t=r.get(e.path);t?e.selector&&!t.selectors.includes(e.selector)&&t.selectors.push(e.selector):r.set(e.path,{path:e.path,selectors:e.selector?[e.selector]:[],candidate:e.candidate});break}case"edit-lesson":n.lessons.push({file:e.file,memories:e.memories});break;case"saved":var i;n.saved.push({nodeId:(i=e.entryId,`saved:${i}:${t}`),source:e.source,text:e.text})}}),n.docs=[...r.values()],n.counts={recall:a.size,jev:n.jev.reduce((e,t)=>e+t.buckets.reduce((e,t)=>e+t.ids.length,0),0),docmap:n.candidates.length,docs:n.docs.length,lessons:n.lessons.reduce((e,t)=>e+t.memories.length,0),saved:n.saved.length},n.happened={recall:n.recalled.length>0||n.explicit.length>0,jev:n.jev.length>0,docmap:n.candidates.length>0,docs:n.docs.length>0,lessons:n.lessons.length>0,saved:n.saved.length>0},n}):[],[T]),M=(0,a.useMemo)(()=>I.filter(e=>e.request.steps.length>0),[I]),R=(0,a.useMemo)(()=>[...M].reverse(),[M]),E=M.find(e=>e.request.entryId===u)??R[0]??null;(0,a.useEffect)(()=>{let e=k.current;if(!e)return;C();let t=new ResizeObserver(C);return t.observe(e),()=>t.disconnect()},[C,R]),(0,a.useEffect)(()=>{E&&m(e=>e&&E.happened[e]?e:x5.find(e=>E.happened[e])??"recall")},[E]),(0,a.useEffect)(()=>{if(!f)return;let e=CSS.escape(f),t=w.current?.querySelector(`[data-node="${e}"], [data-alt-node="${e}"]`);t?.scrollIntoView({block:"nearest"})},[f,h,E]);let L=e=>{if(p(e),n)try{window.sessionStorage.setItem(xQ+n,e)}catch{}},$=(0,a.useMemo)(()=>new Intl.DateTimeFormat(l,{hour:"2-digit",minute:"2-digit"}),[l]);return i=n?"error"===c.kind?(0,r.jsxs)("div",{className:xY().message,role:"alert",children:[(0,r.jsx)("p",{className:xY().errorText,children:o("memoryTrace.error",{error:c.message})}),(0,r.jsx)(s.r,{variant:"neutralOutline",size:"small",onClick:()=>void N(),children:o("memoryTrace.retry")})]}):T?0===M.length?(0,r.jsx)("p",{className:xY().message,children:o("memoryTrace.empty")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:xY().requests,"aria-label":o("memoryTrace.requestsLabel"),children:[(0,r.jsxs)("h3",{className:xY().sectionTitle,children:[o("memoryTrace.requestsLabel"),(0,r.jsx)("span",{className:xY().sectionCount,children:M.length})]}),(0,r.jsx)("div",{className:xY().requestScroller,"data-more":j?"true":void 0,children:(0,r.jsx)("ul",{className:xY().requestList,ref:k,onScroll:C,children:R.map(e=>{let t=e===E;return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:xY().requestRow,"aria-current":t?"true":void 0,onClick:()=>{L(e.request.entryId),g(null)},title:e.request.preview,children:[(0,r.jsxs)("span",{className:xY().requestIndex,children:["#",e.index]}),(0,r.jsx)("span",{className:xY().requestTime,children:e.request.at?$.format(e.request.at):""}),(0,r.jsx)(vt,{preview:e.request.preview,className:xY().requestPreview}),(0,r.jsx)("span",{className:xY().miniRail,"aria-hidden":"true",children:x5.map(t=>(0,r.jsx)("span",{"data-on":e.happened[t]?"true":"false"},t))})]})},e.request.entryId)})})})]}),E&&(0,r.jsxs)("section",{className:xY().flow,"aria-label":o("memoryTrace.flowLabel"),children:[(0,r.jsxs)("h3",{className:xY().sectionTitle,children:[(0,r.jsx)("span",{className:xY().titleText,children:o("memoryTrace.requestHeading",{index:E.index})}),(0,r.jsx)(vt,{preview:E.request.preview,className:xY().flowPreview})]}),(0,r.jsx)("ol",{className:xY().rail,children:x5.map((e,t)=>{let n=E.counts[e],a=h===e;return(0,r.jsx)("li",{className:xY().station,"data-filled":E.happened[e]?"true":"false","data-open":a?"true":void 0,children:(0,r.jsxs)("button",{type:"button",className:xY().stationButton,"aria-expanded":a,"aria-controls":"memory-trace-detail",onClick:()=>{m(e),g(null)},children:[(0,r.jsx)("span",{className:xY().stationStep,"aria-hidden":"true",children:t+1}),(0,r.jsx)("span",{className:xY().stationCount,children:n}),(0,r.jsx)("span",{className:xY().stationLabel,children:o(x6[e])}),"docmap"===e&&E.candidates.length>0&&(0,r.jsx)("span",{className:xY().stationNote,children:o("memoryTrace.openedSummary",{opened:E.candidates.filter(e=>e.opened).length,skipped:E.candidates.filter(e=>!e.opened).length})})]})},e)})}),(0,r.jsx)("div",{id:"memory-trace-detail",className:xY().detail,ref:w,role:"region","aria-label":h?o(x6[h]):void 0,children:h&&(0,r.jsx)(vr,{flow:E,stage:h,focusNode:f})})]}),T&&E&&(0,r.jsx)(vl,{trace:T,selected:E,scope:x,onScopeChange:e=>{v(e);try{window.localStorage.setItem(xX,e)}catch{}},focusNode:f,onSelectNode:e=>{if("request"===e.kind){L(e.id.slice(8)),g(null);return}let t=t=>e.edited?"lessons"===x3(t,e.id):null!==x3(t,e.id),n=(E&&t(E)?E:R.find(t))??(E&&x3(E,e.id)?E:R.find(t=>null!==x3(t,e.id)))??null;n&&(L(n.request.entryId),m(x3(n,e.id)),g(e.id))}})]}):(0,r.jsx)("p",{className:xY().message,role:"status",children:o("memoryTrace.loading")}):(0,r.jsx)("p",{className:xY().message,children:o("memoryTrace.noSession")}),(0,r.jsxs)("section",{className:xY().view,"aria-label":e,children:[(0,r.jsx)(p5,{title:e,subtitle:T?o("memoryTrace.requests",{count:M.length}):void 0,actions:n?[{id:"refresh",label:o("memoryTrace.refresh"),icon:x4,onClick:()=>void N(),disabled:"loading"===c.kind}]:[]}),(0,r.jsx)("div",{className:xY().body,"aria-busy":"loading"===c.kind?"true":void 0,children:i})]})}function ve({memory:e,verdict:t,focused:n}){let{t:a}=(0,z.s)();return(0,r.jsxs)("li",{className:xY().item,"data-node":xK(e.id),"data-focused":n?"true":void 0,children:[(0,r.jsxs)("div",{className:xY().itemHead,children:[(0,r.jsx)("code",{className:xY().memoryId,children:e.id}),e.date&&(0,r.jsx)("span",{className:xY().itemMeta,children:e.date}),t&&(0,r.jsx)(nI.E,{size:"medium",variant:"weak",tone:"neutral",title:t.label,children:t.short})]}),(0,r.jsx)("p",{className:xY().itemText,"data-empty":e.preview?void 0:"true",children:e.preview?x1(e.preview):a("memoryTrace.noMemoryText")})]})}function vt({preview:e,className:t}){let n,{t:a}=(0,z.s)(),{notice:i,text:s}=(n=x2.exec(e))?{notice:"자동 재개"===n[1]?"resume":"harness",text:e.slice(n[0].length)}:{notice:null,text:e},o=x0(s);return(0,r.jsxs)("span",{className:t,title:e,children:[i&&(0,r.jsx)("span",{className:xY().noticeChip,children:a("harness"===i?"memoryTrace.noticeHarness":"memoryTrace.noticeResume")}),o||(i?"":a("memoryTrace.noPreview"))]})}function vn({path:e}){return(0,r.jsx)("span",{className:xY().path,title:e,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:e})})}function vr({flow:e,stage:t,focusNode:n}){let{t:a}=(0,z.s)();if(!e.happened[t])return(0,r.jsx)("p",{className:xY().stageEmpty,children:a("memoryTrace.stageEmpty")});switch(t){case"recall":return(0,r.jsxs)(r.Fragment,{children:[e.recalled.length>0&&(0,r.jsxs)("div",{className:xY().group,children:[(0,r.jsx)("h4",{className:xY().groupTitle,children:a("memoryTrace.autoRecall")}),(0,r.jsx)("ul",{className:xY().items,children:e.recalled.map(t=>(0,r.jsx)(ve,{memory:t,verdict:e.verdicts.get(t.id),focused:n===xK(t.id)},t.id))})]}),e.explicit.map((t,i)=>(0,r.jsxs)("div",{className:xY().group,children:[(0,r.jsxs)("h4",{className:xY().groupTitle,children:[a("memoryTrace.explicitRecall"),(0,r.jsx)("code",{className:xY().groupCode,children:t.target})]}),t.query&&(0,r.jsxs)("p",{className:xY().query,children:[a("memoryTrace.query")," \xb7 ",t.query]}),0===t.memories.length?(0,r.jsx)("p",{className:xY().itemMeta,children:a("memoryTrace.noResults")}):(0,r.jsx)("ul",{className:xY().items,children:t.memories.map(t=>(0,r.jsx)(ve,{memory:t,verdict:e.verdicts.get(t.id),focused:n===xK(t.id)},t.id))})]},`${t.target}-${i}`))]});case"jev":return(0,r.jsx)(r.Fragment,{children:e.jev.map((e,t)=>(0,r.jsxs)("div",{className:xY().group,children:[e.buckets.map(e=>(0,r.jsxs)("div",{className:xY().bucket,children:[(0,r.jsxs)("h4",{className:xY().groupTitle,title:e.label,children:[e.shortLabel,(0,r.jsx)("span",{className:xY().sectionCount,children:e.ids.length})]}),(0,r.jsx)("ul",{className:xY().idList,children:e.ids.map(e=>(0,r.jsx)("li",{"data-node":xK(e),"data-focused":n===xK(e)?"true":void 0,children:(0,r.jsx)("code",{className:xY().memoryId,children:e})},e))})]},e.label)),(0,r.jsxs)("p",{className:xY().itemMeta,children:[null!==e.unknown&&a("memoryTrace.jevUnknown",{count:e.unknown}),null!==e.unknown&&null!==e.unrelated&&" \xb7 ",null!==e.unrelated&&a("memoryTrace.jevUnrelated",{count:e.unrelated})]})]},t))});case"docmap":return(0,r.jsx)("ul",{className:xY().items,children:e.candidates.map(e=>(0,r.jsxs)("li",{className:xY().item,"data-node":xG(e.path),"data-focused":n===xG(e.path)?"true":void 0,"data-skipped":e.opened?void 0:"true",children:[(0,r.jsxs)("div",{className:xY().itemHead,children:[(0,r.jsx)(vn,{path:e.path}),(0,r.jsx)(nI.E,{size:"medium",variant:e.opened?"solid":"weak",tone:e.opened?"positive":"neutral",children:e.opened?a("memoryTrace.opened"):a("memoryTrace.candidateOnly")})]}),(e.status||e.map)&&(0,r.jsxs)("p",{className:xY().itemText,children:[e.status&&(0,r.jsxs)("span",{className:xY().itemMeta,children:["STATUS ",e.status]}),e.status&&e.map&&" \xb7 ",e.map]})]},e.path))});case"docs":return(0,r.jsx)("ul",{className:xY().items,children:e.docs.map(e=>(0,r.jsxs)("li",{className:xY().item,"data-node":xG(e.path),"data-focused":n===xG(e.path)?"true":void 0,children:[(0,r.jsxs)("div",{className:xY().itemHead,children:[(0,r.jsx)(vn,{path:e.path}),e.candidate&&(0,r.jsx)(nI.E,{size:"medium",variant:"weak",tone:"informative",children:a("memoryTrace.fromMap")})]}),e.selectors.length>0&&(0,r.jsx)("p",{className:xY().itemMeta,children:a("memoryTrace.lines",{lines:e.selectors.join(", ")})})]},e.path))});case"lessons":return(0,r.jsx)(r.Fragment,{children:e.lessons.map((e,t)=>(0,r.jsxs)("div",{className:xY().group,"data-node":xJ(e.file),"data-alt-node":xG(e.file),"data-focused":n===xJ(e.file)||n===xG(e.file)?"true":void 0,children:[(0,r.jsxs)("h4",{className:xY().groupTitle,children:[a("memoryTrace.lessonFor"),(0,r.jsx)(vn,{path:e.file})]}),(0,r.jsx)("ul",{className:xY().items,children:e.memories.map(e=>(0,r.jsx)(ve,{memory:e,focused:n===xK(e.id)},e.id))})]},`${e.file}-${t}`))});case"saved":return(0,r.jsx)("ul",{className:xY().items,children:e.saved.map(e=>(0,r.jsxs)("li",{className:xY().item,"data-node":e.nodeId,"data-focused":n===e.nodeId?"true":void 0,children:[(0,r.jsx)("div",{className:xY().itemHead,children:(0,r.jsx)(nI.E,{size:"medium",variant:"weak",tone:"neutral",children:"autolearn"===e.source?a("memoryTrace.savedAuto"):e.source})}),(0,r.jsx)("p",{className:xY().itemText,children:x1(e.text)})]},e.nodeId))})}}let va=["apply","excepted","conflict","unconfirmed","unlisted"],vi={apply:"memoryTrace.verdictApply",excepted:"memoryTrace.verdictExcepted",conflict:"memoryTrace.verdictConflict",unconfirmed:"memoryTrace.verdictUnconfirmed",unlisted:"memoryTrace.verdictUnlisted"};function vs(e){return/[\u1100-\u11ff\u3000-\u9fff\uac00-\ud7af\uff00-\uffef]/.test(e)?12:6.8}function vo({kind:e}){switch(e){case"memory":return(0,r.jsx)("circle",{r:5});case"doc":return(0,r.jsx)("rect",{x:-5,y:-5,width:10,height:10,rx:1.5});case"file":return(0,r.jsx)("rect",{x:-5,y:-5,width:10,height:10,transform:"rotate(45)",rx:1});case"request":return(0,r.jsx)("rect",{x:-20,y:-9,width:40,height:18,rx:9})}}function vl({trace:e,selected:t,scope:n,onScopeChange:i,focusNode:s,onSelectNode:o}){let{t:l}=(0,z.s)(),c=(0,a.useRef)(null),[d,u]=(0,a.useState)(0),[p,h]=(0,a.useState)(280),[m,f]=(0,a.useState)(null),g=(0,a.useCallback)(()=>{let e=c.current,t=e?.closest(`.${xY().body}`);if(!e||!t)return;let n=e.getBoundingClientRect().top-t.getBoundingClientRect().top+t.scrollTop,r=Number.parseFloat(getComputedStyle(t).paddingBlockEnd)||0,a=Math.max(280,Math.floor(t.clientHeight-n-r-2));h(e=>Math.abs(e-a)>1?a:e)},[]);(0,a.useLayoutEffect)(g),(0,a.useEffect)(()=>{let e=c.current,t=e?.closest(`.${xY().body}`);if(!e)return;let n=new ResizeObserver(()=>{u(Math.round(e.getBoundingClientRect().width)-2),g()});return n.observe(e),t&&n.observe(t),()=>n.disconnect()},[g]);let x=(0,a.useMemo)(()=>new Map(e.requests.map((e,t)=>[xV(e.entryId),t+1])),[e]),v=(0,a.useMemo)(()=>{let t=new Map(e.nodes.filter(e=>"doc"===e.kind).map(e=>[e.title,e.id])),n=new Map;for(let r of e.nodes){let e="file"===r.kind?t.get(r.title):void 0;e&&n.set(r.id,e)}let r=new Set(n.values());return{nodes:e.nodes.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,edited:!0}:e),edges:e.edges.map(e=>({...e,from:n.get(e.from)??e.from,to:n.get(e.to)??e.to})),alias:n}},[e]),{nodes:b,edges:y}=(0,a.useMemo)(()=>{if("session"===n){let e=new Set(v.edges.flatMap(e=>[e.from,e.to]));return{nodes:v.nodes.filter(t=>e.has(t.id)),edges:v.edges}}let e=xV(t.request.entryId),r=new Set([e]),a=v.edges.filter(t=>t.from===e);for(let e of a)r.add(e.to);let i=new Set(t.lessons.flatMap(e=>e.memories.map(t=>{let n;return`${n=e.file,v.alias.get(xJ(n))??xJ(n)}\u0000${xK(t.id)}`}))),s=v.edges.filter(e=>"lesson"===e.kind&&i.has(`${e.from}\u0000${e.to}`));for(let e of s)r.add(e.to);return{nodes:v.nodes.filter(e=>r.has(e.id)),edges:[...a,...s]}},[v,n,t]),w=(0,a.useMemo)(()=>d>0?function(e,t,n,r,a){let i=e.filter(e=>"request"===e.kind).sort((e,t)=>(a.get(t.id)??0)-(a.get(e.id)??0)),s=new Map(i.map((e,t)=>[e.id,t])),o=new Map;for(let e of t)(o.get(e.from)??o.set(e.from,[]).get(e.from)).push(e.to),(o.get(e.to)??o.set(e.to,[]).get(e.to)).push(e.from);let l=new Map(e.map((e,t)=>[e.id,t])),c=e=>e.map(e=>({node:e,w:(e=>{let t=[];for(let n of o.get(e)??[]){let e=s.get(n);if(void 0!==e)t.push(e);else for(let e of o.get(n)??[]){let n=s.get(e);void 0!==n&&t.push(n)}}return t.length>0?t.reduce((e,t)=>e+t,0)/t.length:Number.MAX_SAFE_INTEGER})(e.id)})).sort((e,t)=>e.w-t.w||(l.get(e.node.id)??0)-(l.get(t.node.id)??0)).map(e=>e.node),d=[c(e.filter(e=>"memory"===e.kind)),i,[...c(e.filter(e=>"doc"===e.kind)),...c(e.filter(e=>"file"===e.kind))]],u=Math.max(1,...d.map(e=>e.length)),p=Math.min(60,Math.max(36,(r-30-16)/u)),h=Math.ceil(30+u*p+16),m=Math.min(160,Math.max(28,Math.round(.1*n))),f=Math.max(0,n-32-22-40-2*m),g=Math.round(.56*f),x=16+g+6+5,v=x+m+20,b=[x,v,v+20+m],y=new Map;return d.forEach((e,t)=>{let n=30+(u-e.length)*p/2+p/2;e.forEach((e,r)=>{y.set(e.id,{node:e,x:b[t],y:Math.round(n+r*p),column:t})})}),{placed:y,height:h,xs:b,neighbours:o,rowH:p,leftLabel:g,rightLabel:f-g}}(b,y,d,p,x):null,[b,y,d,p,x]),k=(0,a.useMemo)(()=>{let e=new Map;if(!t.happened.jev)return e;for(let n of t.recalled)e.set(xK(n.id),"unlisted");for(let[r,a]of t.verdicts){var n;e.set(xK(r),(n=a.label).includes("충돌")?"conflict":n.includes("불충족")||n.includes("예외")?"excepted":n.startsWith("적용")?"apply":"unconfirmed")}return e},[t]),j=(0,a.useMemo)(()=>{let e=new Set(b.flatMap(e=>k.get(e.id)??[]));return va.filter(t=>e.has(t))},[b,k]),S=m??s,C=(0,a.useMemo)(()=>S&&w?new Set([S,...w.neighbours.get(S)??[]]):null,[S,w]),N=(0,a.useMemo)(()=>{if("request"===n||!w)return null;let e=S??xV(t.request.entryId),r=new Set([e]);for(let t of w.neighbours.get(e)??[])if(r.add(t),t.startsWith("file:")||t.startsWith("doc:"))for(let e of w.neighbours.get(t)??[])e.startsWith("memory:")&&r.add(e);return r},[n,w,S,t]),T={request:l("memoryTrace.legendRequest"),memory:l("memoryTrace.legendMemory"),doc:l("memoryTrace.legendDoc"),file:l("memoryTrace.legendFile")},I=e=>e.edited?`${T.doc} \xb7 ${T.file}`:T[e.kind],M=(0,a.useMemo)(()=>{let e=new Map;if(!w)return e;for(let t of y){let n=w.placed.get(t.from),r=w.placed.get(t.to);if(!n||!r)continue;let a=n.x<=r.x?`${t.from}|${t.to}`:`${t.to}|${t.from}`;(e.get(a)??e.set(a,[]).get(a)).push(t.kind)}return e},[y,w]),R=`memory-trace-arrow-${(0,a.useId)().replace(/[^a-zA-Z0-9_-]/g,"")}`,E=S&&w?w.placed.get(S)?.node??null:null,L=E?k.get(E.id):void 0;return(0,r.jsxs)("section",{className:xY().graph,"aria-label":l("memoryTrace.graphLabel"),children:[(0,r.jsxs)("div",{className:xY().graphHead,children:[(0,r.jsx)("h3",{className:xY().sectionTitle,children:l("memoryTrace.graphLabel")}),(0,r.jsxs)(pX.A.Root,{className:xY().scopeSwitch,"aria-label":l("memoryTrace.graphScope"),value:n,onValueChange:e=>i(e),children:[["request","session"].map(e=>(0,r.jsxs)(pX.A.Item,{value:e,children:[(0,r.jsx)(pX.A.ItemHiddenInput,{}),"request"===e?l("memoryTrace.scopeRequest"):l("memoryTrace.scopeSession")]},e)),(0,r.jsx)(pX.A.Indicator,{})]})]}),(0,r.jsxs)("ul",{className:xY().legend,children:[["request","memory","doc","file"].map(e=>(0,r.jsxs)("li",{"data-kind":e,children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"-7 -7 14 14","aria-hidden":"true",children:(0,r.jsx)("g",{className:xY().legendMark,children:"request"===e?(0,r.jsx)("rect",{x:-6,y:-4,width:12,height:8,rx:4}):(0,r.jsx)(vo,{kind:e})})}),T[e]]},e)),["recalled","opened","lesson","candidate"].map(e=>(0,r.jsxs)("li",{"data-kind":`edge-${e}`,children:[(0,r.jsx)("svg",{width:"20",height:"8","aria-hidden":"true",children:(0,r.jsx)("line",{x1:"1",y1:"4",x2:"19",y2:"4"})}),l("recalled"===e?"memoryTrace.edgeRecalled":"opened"===e?"memoryTrace.opened":"lesson"===e?"memoryTrace.edgeLesson":"memoryTrace.candidateOnly")]},e)),b.some(e=>e.edited)&&(0,r.jsxs)("li",{"data-kind":"edited",children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"-7 -7 14 14","aria-hidden":"true",children:(0,r.jsx)("g",{className:xY().legendMark,children:(0,r.jsx)(vo,{kind:"doc"})})}),l("memoryTrace.legendDocEdited")]})]}),j.length>0&&(0,r.jsxs)("ul",{className:xY().legend,"aria-label":l("memoryTrace.verdictLegend"),children:[(0,r.jsx)("li",{className:xY().legendTitle,children:l("memoryTrace.verdictLegend")}),j.map(e=>(0,r.jsxs)("li",{"data-verdict":e,children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"-8 -8 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{className:xY().ring,r:7.5}),(0,r.jsx)("circle",{className:xY().legendMemory,r:4})]}),l(vi[e])]},e))]}),(0,r.jsx)("p",{className:xY().graphCaption,"aria-live":"polite",children:E?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:xY().captionKind,children:["request"===E.kind?`#${x.get(E.id)??""}`:I(E),L?` \xb7 ${l(vi[L])}`:""]}),"request"===E.kind?x0(E.title):"memory"===E.kind?x8(E.title):E.title]}):l("memoryTrace.graphHint")}),(0,r.jsx)("div",{className:xY().graphFrame,ref:c,children:b.length<=1?(0,r.jsx)("p",{className:xY().stageEmpty,children:l("memoryTrace.graphEmpty")}):w&&(0,r.jsxs)("svg",{className:xY().graphSvg,width:d,height:w.height,viewBox:`0 0 ${d} ${w.height}`,role:"group","aria-label":l("memoryTrace.graphLabel"),onPointerLeave:()=>f(null),children:[(0,r.jsx)("defs",{children:(0,r.jsx)("marker",{id:R,viewBox:"0 0 8 8",refX:"7",refY:"4",markerWidth:"7",markerHeight:"7",orient:"auto-start-reverse",children:(0,r.jsx)("path",{className:xY().arrow,d:"M0,0.5 L8,4 L0,7.5 z"})})}),(0,r.jsxs)("g",{className:xY().columnHeads,"aria-hidden":"true",children:[(0,r.jsx)("text",{x:w.xs[0],y:16,textAnchor:"end",children:T.memory}),(0,r.jsx)("text",{x:w.xs[1],y:16,textAnchor:"middle",children:T.request}),(0,r.jsxs)("text",{x:w.xs[2],y:16,textAnchor:"start",children:[T.doc," \xb7 ",T.file]})]}),(0,r.jsx)("g",{className:xY().edges,"aria-hidden":"true",children:y.map(e=>{let t=w.placed.get(e.from),n=w.placed.get(e.to);if(!t||!n)return null;let[a,i]=t.x<=n.x?[t,n]:[n,t],s=M.get(`${a.node.id}|${i.node.id}`)??[e.kind],o=(s.indexOf(e.kind)-(s.length-1)/2)*4,l=a.y+o,c=i.y+o,d=1===a.column?a.x+(a.x<i.x?20:-20):a.x+5,u=0===a.column&&2===i.column,p=1===i.column?i.x-20:i.x-5-3*!!u,h=(d+p)/2,m=u?d+Math.max(12,(w.xs[1]-20-d)*.4):null,f=u&&[...w.placed.values()].some(e=>1===e.column&&12>Math.abs(e.y-c)),g=c+(c+w.rowH/2>w.height-16?-1:1)*(w.rowH/2),x=w.xs[1]+20+8,v=null===m?`M${d},${l} C${h},${l} ${h},${c} ${p},${c}`:f?`M${d},${l} C${(d+m)/2},${l} ${(d+m)/2},${g} ${m},${g} L${x},${g} C${(x+p)/2},${g} ${(x+p)/2},${c} ${p},${c}`:`M${d},${l} C${(d+m)/2},${l} ${(d+m)/2},${c} ${m},${c} L${p},${c}`,b=null!==S&&(e.from===S||e.to===S),y=null!==N&&!(N.has(e.from)&&N.has(e.to));return(0,r.jsx)("path",{d:v,"data-kind":e.kind,"data-on":b?"true":void 0,"data-dim":y&&!b?"true":void 0,markerEnd:u?`url(#${R})`:void 0},`${e.from}|${e.to}|${e.kind}`)})}),(0,r.jsx)("g",{className:xY().nodes,children:[...w.placed.values()].map(({node:e,x:n,y:a,column:i})=>{let s=w.neighbours.get(e.id)?.length??0,c=0===i?w.leftLabel:w.rightLabel,d="request"===e.kind?[`#${x.get(e.id)??""}`]:"memory"===e.kind?function(e,t,n=2){if(t<24)return[];let r=[],a="",i=0;for(let s of e.trim()){let e=vs(s);if(i+e>t){if(r.length===n-1)return r.push(`${a.slice(0,-1).trimEnd()}…`),r;let e=a.lastIndexOf(" "),t=e>0?a.slice(0,e):a;r.push(t),i=[...a=a.slice(t.length).trimStart()].reduce((e,t)=>e+vs(t),0)}a+=s,i+=e}return a&&r.push(a),r}(x1(e.label),c):[function(e,t){let n=[...e];if(n.reduce((e,t)=>e+vs(t),0)<=t)return e;let r=vs("…"),a=n.length;for(;a>0&&r+vs(n[a-1])<=t;)a-=1,r+=vs(n[a]);return`…${n.slice(a).join("")}`}(e.title,c)],u=k.get(e.id),p=w.rowH-4,h=0===i?-11:11*(2===i);return(0,r.jsxs)("g",{className:xY().node,"data-kind":e.kind,"data-on":C?.has(e.id)?"true":void 0,"data-dim":N&&!N.has(e.id)?"true":void 0,"data-current":e.id===xV(t.request.entryId)?"true":void 0,"data-verdict":u,"data-edited":e.edited?"true":void 0,transform:`translate(${n},${a})`,tabIndex:0,role:"button","aria-label":l("memoryTrace.nodeLabel",{kind:I(e),label:"memory"===e.kind?x8(e.title):e.title,count:s}),onPointerEnter:()=>f(e.id),onFocus:()=>f(e.id),onBlur:()=>f(null),onClick:()=>o(e),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),o(e))},children:[(0,r.jsx)("title",{children:"request"===e.kind?x0(e.title):"memory"===e.kind?x8(e.title):e.title}),(0,r.jsx)("rect",{className:xY().hit,x:0===i?-11-c-4:1===i?-24:-9,y:-p/2,width:1===i?48:c+10+6+8,height:p}),u&&(0,r.jsx)("circle",{className:xY().ring,r:8}),(0,r.jsx)("g",{className:xY().mark,children:(0,r.jsx)(vo,{kind:e.kind})}),(0,r.jsx)("text",{className:xY().nodeText,x:h,y:4-(d.length-1)*14/2,textAnchor:0===i?"end":2===i?"start":"middle",children:d.map((e,t)=>(0,r.jsx)("tspan",{x:h,dy:14*(0!==t),children:e},t))})]},e.id)})})]})})]})}function vc({cwd:e,onOpenFile:t}){let n,{t:i}=(0,z.s)(),[s,o]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(!e)return;let t=new AbortController;return fetch(`/api/project-docs?cwd=${encodeURIComponent(e)}`,{signal:t.signal}).then(async n=>{let r=await n.json();t.signal.aborted||(403===n.status?o({kind:"denied",cwd:e}):n.ok?o({kind:"ready",cwd:e,docs:r}):o({kind:"error",cwd:e,message:r.error??`HTTP ${n.status}`}))}).catch(n=>{t.signal.aborted||o({kind:"error",cwd:e,message:n instanceof Error?n.message:String(n)})}),()=>t.abort()},[e]);let l=e&&s?.cwd===e?s:null,c=(e,n,a)=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:"found"===a.state&&a.path?(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:a.path,"aria-label":`${e} — ${a.path}`,onClick:()=>t(a.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:n})]}):(0,r.jsxs)("div",{className:"file-doc-shortcuts-unavailable",title:a.path??void 0,children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:"denied"===a.state?i("files.docs.denied",{file:n}):i("files.docs.missing",{file:n})})]})});if(e)if(l)if("denied"===l.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:i("files.docs.projectDenied")});else if("error"===l.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"alert",children:i("files.docs.loadFailed",{error:l.message})});else{let{docs:e}=l,a="missing"===e.handoff.state&&"missing"===e.docMap.state&&"missing"===e.history.state;n=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"file-doc-shortcuts-project",title:e.projectDir,children:i("files.docs.projectDir",{path:e.projectDir})}),a?(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:i("files.docs.noneFound")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("ul",{className:"file-doc-shortcuts-list",children:[c(i("files.docs.current"),"HANDOFF.md",e.handoff),c(i("files.docs.map"),"doc/README.md",e.docMap)]}),(0,r.jsx)("h3",{className:"file-doc-shortcuts-heading",id:"file-doc-shortcuts-records",children:i("files.docs.records")}),e.history.records.length>0?(0,r.jsx)("ul",{className:"file-doc-shortcuts-list","aria-labelledby":"file-doc-shortcuts-records",children:e.history.records.map(e=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:e.path,"aria-label":`${i("files.docs.records")} ${e.date} ${e.topic} — ${e.fileName}`,onClick:()=>t(e.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-date",children:e.date}),(0,r.jsxs)("span",{className:"file-doc-shortcuts-file",children:[e.topic,"main.md"===e.fileName?"":` \xb7 ${e.fileName}`]})]})},e.path))}):(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:"denied"===e.history.state?i("files.docs.denied",{file:"doc/history"}):i("files.docs.missing",{file:"doc/history"})})]})]})}else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"status",children:i("files.docs.loading")});else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:i("files.docs.noProject")});return(0,r.jsxs)("section",{className:"file-doc-shortcuts","aria-labelledby":"file-doc-shortcuts-title",children:[(0,r.jsx)("h2",{className:"file-doc-shortcuts-title",id:"file-doc-shortcuts-title",children:i("files.noneOpen")}),n]})}function vd(e){return"message"===e.type&&"message"in e}function vu(e){let t=e,n=t.branchPreview,r=vd(t.entry)?t.entry:null,a=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&vd(t.entry)&&(r=t.entry),a+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:a,branchPreview:n,labelEntry:r??t.entry}}function vp({node:e,activePathIds:t,depth:n,isLast:a,parentLines:i,onSelect:s}){let{node:o,skipped:l,branchPreview:c,labelEntry:d}=vu(e),u=t.has(o.entry.id),p=t.has(e.entry.id)||t.has(o.entry.id),h=c?.text??function(e){if("message"===e.type&&"message"in e){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(d),m=c?c.role??null:vd(d)?d.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>s(o.entry.id),children:[i.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:a?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:"var(--radius-control)",padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),l>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",l]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":p?"var(--text-muted)":"var(--text-dim)",fontWeight:u?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:h})]}),o.children.map((e,l)=>(0,r.jsx)(vp,{node:e,activePathIds:t,depth:n+1,isLast:l===o.children.length-1,parentLines:[...i,!a],onSelect:s},e.entry.id))]})}function vh({tree:e,activeLeafId:t,onLeafChange:n,hasSession:i}){let{t:s}=(0,z.s)(),o=(0,a.useMemo)(()=>t?new Set(function e(n,r){for(let a of n){let n=[...r,a.entry.id];if(a.entry.id===t||a.compressedEntryIds?.includes(t))return n;let i=e(a.children,n);if(i)return i}return null}(e,[])??[]):new Set,[e,t]),l=(0,a.useCallback)(e=>{n(e)},[n]),c=i?!function e(t){if(t.length>1)return!0;for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)?s("i18n.noBranches"):null:s("i18n.noActiveSession"),d=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=vu(e[0]).node;return t.children.length>1?t.children:[]}(e);return!c&&d.length>0?(0,r.jsx)("div",{className:"branch-navigator-tree",children:d.map((e,t)=>(0,r.jsx)(vp,{node:e,activePathIds:o,depth:0,isLast:t===d.length-1,parentLines:[],onSelect:l},e.entry.id))}):(0,r.jsx)("p",{className:"branch-navigator-empty",children:c??s("i18n.noBranches")})}function vm(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function vf(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function vg(e){let t=e.currentTime;[523.25,659.25].forEach((n,r)=>{let a=e.createOscillator(),i=e.createGain();a.connect(i),i.connect(e.destination),a.type="sine",a.frequency.value=n;let s=t+.18*r;i.gain.setValueAtTime(0,s),i.gain.linearRampToValueAtTime(.18,s+.02),i.gain.exponentialRampToValueAtTime(.001,s+.45),a.start(s),a.stop(s+.45)})}async function vx(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function vv(e){let t=e.window?.durationMs;if("number"==typeof t&&Number.isFinite(t)&&t>0)return t>=5184e5?"weekly":t<=432e5?"short":"other";let n=e.scope?.windowId,r=`${"string"==typeof n?n:""} ${e.id} ${e.label??""}`.toLowerCase();return/(^|[^0-9])7d\b|week|7 day|주간/.test(r)?"weekly":/(^|[^0-9])(5h|1h)\b|hour|시간/.test(r)?"short":"other"}let vb="omp-sidebar-usage-collapsed",vy="omp-sidebar-usage-order";function vw(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function vk(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function vj({direction:e}){return(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"up"===e?"2.5 7.5 6 4 9.5 7.5":"2.5 4.5 6 8 9.5 4.5"})})}function vS({usage:e,onOpen:t,onRelogin:n}){var i,s;let o,l,c,d,{t:u}=(0,z.s)(),p=B(),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[x,v]=(0,a.useState)([]),[b,y]=(0,a.useState)(""),[w,k]=(0,a.useState)(null),j=(0,a.useRef)(null),[S,C]=(0,a.useState)(!0);(0,a.useEffect)(()=>{try{C("0"!==window.localStorage.getItem(vb))}catch{}v(function(){try{let e=JSON.parse(window.localStorage.getItem(vy)??"[]");return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}catch{return[]}}())},[]);let N=e.bai,T=e.state.data?.reports??[],I=nw(1e4),M=(o=rK(T),l=[],c=[],T.forEach((e,t)=>{let n=e.authError;if(!0===e.disabled&&!n)return;let r=o[t],a="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>I,i=!0===e.disabled?[]:e.limits??[],s=i.some(e=>e.scope?.shared===!0&&rd(e)),d=i.some(e=>null!==vw(e)&&"short"!==vv(e)),u=[];for(let e of i){let t=vw(e);null!==t&&(!d||"short"!==vv(e)||function(e){let t=e.amount?.usedFraction,n="number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null;return rd(e)||"warning"===e.status||null!==n&&n>=90}(e))&&u.push({key:e.id,label:e.label||e.id,percent:Math.round(100*t),state:a?"blocked":s?"account-spent":rd(e)?"spent":"usable"})}if(0===u.length&&!n)return;let p=n?"auth":a?"blocked":s?"account-spent":"ok",h={orderKey:"string"==typeof e.accountKey&&e.accountKey.length>0?`${e.provider}:${e.accountKey}`:void 0!==e.credentialId?`${e.provider}:#${e.credentialId}`:`${e.provider}:@${t}`,provider:e.provider,alias:r.alias,seed:r.seed,masked:r.masked,..."string"==typeof e.accountKey?{accountKey:e.accountKey}:{},rows:u,state:p,...n?{authError:n}:{},usable:"ok"===p&&u.some(e=>"usable"===e.state)};(h.usable?l:c).push(h)}),i=[...l,...c],d=new Map(x.map((e,t)=>[e,t])),[...i.filter(e=>d.has(e.orderKey)).sort((e,t)=>d.get(e.orderKey)-d.get(t.orderKey)),...i.filter(e=>!d.has(e.orderKey))]);(0,a.useEffect)(()=>{if(null===w)return;let e=[...j.current?.querySelectorAll("[data-order-key]")??[]].find(e=>e.dataset.orderKey===w.orderKey),t=e?.querySelector(`[data-direction="${w.direction}"]`),n=e?.querySelector(`[data-direction="${"up"===w.direction?"down":"up"}"]`);(t&&!t.disabled?t:n)?.focus(),k(null)},[w]);let R=(e,t)=>{let n,r,a,i="up"===t?e-1:e+1;if(i<0||i>=M.length)return;let s=M.map(e=>e.orderKey);[s[e],s[i]]=[s[i],s[e]];let o=(n=new Set(s),r=[...x,...s.filter(e=>!x.includes(e))],a=0,r.map(e=>n.has(e)?s[a++]:e));v(o);try{window.localStorage.setItem(vy,JSON.stringify(o))}catch{}y(u("usage.moved",{account:M[e].alias,position:i+1})),k({orderKey:M[e].orderKey,direction:t})},E=e=>Math.max(1,e.rows.length),L=0,$=h||f?M:M.filter(e=>!(L>=2)&&(L+=E(e),!0)),P=M.slice($.length).reduce((e,t)=>e+E(t),0),A=M.filter(e=>"auth"===e.state).length,F="measured"===N.status?(s=N.tokens)>=1e9?`${(s/1e9).toFixed(1)}B`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(Math.round(s)):u("empty"===N.status?"usage.baiEmpty":"usage.baiUnmeasured"),_="measured"===N.status&&null!==N.from&&null!==N.to?u("usage.baiRange",{from:vk(N.from),to:vk(N.to)}):null,W=e=>"auth"===e.state?u(e.authError?.reloginRequired?"usage.authExpired":"usage.authUnavailable"):"blocked"===e.state?u("usage.accountBlocked"):"account-spent"===e.state?u("usage.accountSpent"):null,O=e=>"spent"===e.state?u("usage.limitSpent"):null,D=u("usage.open",{rows:[...$.flatMap(e=>{let t=W(e);return 0===e.rows.length?[`${e.alias} (${t??""}${e.authError?`: ${e.authError.message}`:""})`]:e.rows.map(n=>{let r=O(n)??t;return`${e.alias} ${n.label} ${n.percent}%${null===r?"":` (${r})`}`})}),`${u("usage.bai")} ${F}${null===_?"":` \xb7 ${_}`}`].join(", ")})+(P>0?u("usage.openMore",{count:P}):""),H=M[0],U=void 0===H?{label:u("usage.bai"),value:F,danger:!1}:0===H.rows.length?{label:H.alias,value:W(H)??"",danger:!0}:{label:H.rows[0].label,value:`${H.rows[0].percent}%`,danger:H.rows[0].percent>=90},q=A>0?u("usage.authIssues",{count:A}):null,V=(0,r.jsxs)("div",{className:"navigator-usage",role:"group","aria-label":u("usage.title"),"data-editing":f?"":void 0,onClick:e=>{f||e.target instanceof Element&&e.target.closest("button, a")||t()},children:[(0,r.jsxs)("span",{className:"navigator-usage-header",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-open","aria-label":D,onClick:t,children:u("usage.title")}),null===q?null:(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),M.length>1&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-edit","data-active":f?"":void 0,onClick:()=>g(e=>!e),children:f?u("usage.reorderDone"):u("usage.reorder")})]}),(0,r.jsx)("div",{ref:j,role:f?"list":void 0,"aria-label":f?u("usage.reorderGroup"):void 0,className:"navigator-usage-groups",children:0===M.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:u("usage.none")}):$.map((e,t)=>{let a=W(e);return(0,r.jsxs)("div",{className:"navigator-usage-group","data-order-key":e.orderKey,role:f?"listitem":void 0,children:[(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(av,{seed:e.seed,size:24,provider:e.provider}),(0,r.jsx)("span",{className:"navigator-usage-alias",children:e.alias}),null===a?null:(0,r.jsx)("span",{className:"navigator-usage-state","data-tone":"auth"===e.state?"danger":void 0,children:a}),f&&(0,r.jsxs)("span",{className:"navigator-usage-moves",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"up","aria-label":u("usage.moveUp",{account:e.alias}),disabled:0===t,onClick:()=>R(t,"up"),children:(0,r.jsx)(vj,{direction:"up"})}),(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"down","aria-label":u("usage.moveDown",{account:e.alias}),disabled:t===M.length-1,onClick:()=>R(t,"down"),children:(0,r.jsx)(vj,{direction:"down"})})]})]}),e.authError&&(0,r.jsxs)("span",{className:"navigator-usage-auth",children:[(0,r.jsx)("span",{className:"navigator-usage-reason",children:e.authError.message}),e.authError.reloginRequired&&n&&!f&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-relogin","aria-label":u("usage.reloginFor",{account:e.alias}),onClick:()=>n({provider:e.provider,alias:e.alias,seed:e.seed,masked:e.masked,...e.accountKey?{accountKey:e.accountKey}:{},reason:e.authError?.message??""}),children:u("usage.relogin")})]}),e.rows.map(e=>{let t=O(e);return(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:e.label}),null===t?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:t}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,r.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)})]},e.orderKey)})}),!f&&(P>0||h)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":h,onClick:()=>m(e=>!e),children:h?u("usage.showLess"):u("usage.showMore",{count:P})}),(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:u("usage.bai")}),(0,r.jsx)("span",{className:"navigator-usage-value",style:"measured"===N.status?void 0:{color:"var(--text-muted)"},children:F})]}),null===_?null:(0,r.jsx)("span",{className:"navigator-usage-account",children:_})]}),(0,r.jsx)("span",{className:"navigator-usage-live","aria-live":"polite",children:b})]});return p?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!S,"aria-label":S?`${D}${null===q?"":`, ${q}`}`:u("usage.showLess"),onClick:()=>{let e=!S;C(e);try{window.localStorage.setItem(vb,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:S?U.label:u("usage.showLess")}),S&&(0,r.jsx)("span",{className:"navigator-usage-value",style:U.danger?{color:"var(--danger)"}:void 0,children:U.value}),S&&null!==q&&(0,r.jsx)("span",{className:"navigator-usage-alert",children:q}),(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:S?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),S?null:V]}):V}let vC=["casual","polite","formal","haggling","urgent"],vN=["male","female"],vT=["20s","30s","40s","50s","60s"],vI=["child","younger","older","parent","grandparent"],vM=(e,t)=>"string"==typeof t&&e.includes(t)?t:void 0;function vR(e){if(!e||"object"!=typeof e)return{};let t={},n=vM(vC,e.mood),r=vM(vN,e.gender),a=vM(vT,e.age),i=vM(vN,e.partnerGender),s=vM(vI,e.partnerAge);return n&&(t.mood=n),r&&(t.gender=r),a&&(t.age=a),i&&(t.partnerGender=i),s&&(t.partnerAge=s),t}let vE=[{code:"ko",tag:"ko-KR",englishName:"Korean",nativeName:"한국어"},{code:"en",tag:"en-US",englishName:"English",nativeName:"English"},{code:"vi",tag:"vi-VN",englishName:"Vietnamese",nativeName:"Tiếng Việt"},{code:"ja",tag:"ja-JP",englishName:"Japanese",nativeName:"日本語"},{code:"th",tag:"th-TH",englishName:"Thai",nativeName:"ไทย"},{code:"zh",tag:"zh-CN",englishName:"Chinese",nativeName:"中文"}];function vL(e){return"string"==typeof e?vE.find(t=>t.code===e):void 0}let v$=/[ăâđêôơưàáạảãằắặẳẵầấậẩẫèéẹẻẽềếệểễìíịỉĩòóọỏõồốộổỗờớợởỡùúụủũừứựửữỳýỵỷỹ]/giu,vP=/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9d]/u,vA={ko:/[\uac00-\ud7a3\u1100-\u11ff\u3130-\u318f]/gu,ja:/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9d\u4e00-\u9fff]/gu,zh:/[\u4e00-\u9fff]/gu,th:/[\u0e00-\u0e7f]/gu,vi:v$,en:/[a-z]/giu};function vF(e,t,n){let r=vA[t];return!r||"en"===t&&e.match(v$)||"zh"===t&&vP.test(e)||"ja"===t&&"zh"===n&&!vP.test(e)?0:e.match(r)?.length??0}function v_(e,t,n){let r=vF(e,t.code,n.code),a=vF(e,n.code,t.code);if(r!==a)return r>a?t:n}let vz=String.raw`\d(?:[\d,.:/-]*\d)?`,vW=String.raw`(?:[kK](?![A-Za-z])|%|만|억|천|백)`,vO=String.raw`(?:원|동|위안|달러|엔|바트|đồng|nghìn|ngàn|triệu|tỷ|VND|[$€£¥₩₫]|개|명|시|분|번|층|년|월|일|(?:kg|km|cm|ml|g|m)(?![A-Za-z]))`,vD=String.raw`[$€£¥₩₫]?`,vH=RegExp(`${vD}${vz}(?:\\s?${vW})*(?:\\s?${vz}(?:\\s?${vW})+)*(?:\\s?${vO}){0,2}`,"gu");function vU(e=[],t){return{turns:{},drafts:[],seen:e.filter(e=>"assistant"===e.role).map(e=>e.id),born:{},lastSegmentId:e.reduce((e,t)=>Math.max(e,t.id),-1),nextTurnId:t?.nextTurnId??0,nextDraftId:t?.nextDraftId??0}}let vB=e=>[...e.replace(/\s/gu,"")].slice(-24).join(""),vq=e=>e.match(/[\p{L}\p{N}]/gu)?.length??0,vV=e=>e.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^\p{L}\p{N}]/gu,""),vK=[["en","vi"],["ja","zh"]];function vG(e,t,n,r,a){let i=r.echo||v_(r.input,t.mine,t.theirs)?.code===n.code||function(e,t){let n=vV(e).slice(0,400),r=vV(t);if(n.length<8||r.length<8)return 0;let a=r.slice(0,Math.min(400,n.length+Math.ceil(.15*n.length)));return 1-function(e,t){let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r+=1){let a=[r];for(let i=1;i<=t.length;i+=1)a[i]=Math.min(n[i]+1,a[i-1]+1,n[i-1]+ +(e[r-1]!==t[i-1]));n=a}return n[t.length]}(n,a)/Math.max(n.length,a.length)}(r.output,r.input)>=.8;r.echo=i;let s=e.drafts.findIndex(e=>e.language.code===n.code&&e.turnId===r.id),o=r.output.trim();if(i||r.dead){if(s<0)return e;let t=e.drafts.flatMap((e,t)=>t!==s?[e]:null===e.matched?[]:[{...e,text:""}]);return{...e,drafts:t}}if(!o||s<0&&vZ(r)&&a-r.outputSince<800)return e;if(s>=0)return e.drafts[s].text===o?e:{...e,drafts:e.drafts.map((e,t)=>t===s?{...e,text:o}:e)};let l={id:e.nextDraftId,language:n,pair:t,turnId:r.id,text:o,createdAt:a,after:e.lastSegmentId,matched:null};return{...e,drafts:[...e.drafts,l],nextDraftId:e.nextDraftId+1}}function vJ(e,t,n){return{...e,turns:{...e.turns,[t.code]:n.slice(-12)}}}let vZ=e=>void 0===v_(e.input,e.pair.mine,e.pair.theirs),vY=(e,t)=>vZ(t)&&!t.echo&&!t.dead&&""!==t.output.trim()&&!e.drafts.some(e=>e.turnId===t.id&&e.language.code===t.target.code);function vX(e,t,n){let r=function(e,t){let n=e;for(let r of Object.values(e.turns))for(let e of r)vY(n,e)&&t-e.outputSince>=800&&(n=vG(n,e.pair,e.target,{...e},t));return n}(e,n),a=new Set(r.seen),i={...r.born},s=r.drafts.filter(e=>null===e.matched&&n-e.createdAt>2e4),o=r.drafts.filter(e=>!s.includes(e)),l=[...s],c=!1;for(let e of t){if("assistant"!==e.role||a.has(e.id)||vq(e.text)<(e.final?4:6))continue;let t=v_(vB(e.text),e.mine,e.theirs);if(t){i[e.id]?.code!==t.code&&(i[e.id]={at:n,code:t.code},c=!0);let r=()=>o.filter(n=>null===n.matched&&n.text&&n.language.code===t.code&&n.createdAt<=i[e.id].at);for(;r().length>1&&n-r()[0].createdAt>15e3;){let e=r()[0];l.push(e),o=o.filter(t=>t!==e)}let s=r()[0];if(s){o=o.map(t=>t===s?{...s,matched:e.id}:t),a.add(e.id),c=!0;continue}}e.final&&(a.add(e.id),c=!0)}let d=new Set(t.map(e=>e.id)),u=o.filter(e=>null===e.matched?n-e.createdAt>2e4:!d.has(e.matched));l.push(...u.filter(e=>null===e.matched)),o=o.filter(e=>!u.includes(e));let p=r.turns;if(l.length>0)for(let e of(p={...p},l))p[e.language.code]=(p[e.language.code]??[]).map(t=>t.id===e.turnId?{...t,dead:!0}:t);let h=t.reduce((e,t)=>Math.max(e,t.id),r.lastSegmentId);return c||0!==l.length||0!==u.length||h!==r.lastSegmentId?{...r,turns:p,drafts:o,seen:[...a],born:i,lastSegmentId:h}:r}function vQ(){return{segments:[],open:{user:null,assistant:null},nextId:0,call:0}}function v0(e){return{...e,open:{user:null,assistant:null},call:e.call+1}}function v1(e){return v_(e.text,e.mine,e.theirs)}function v2(e,t){let n=t.code===e.mine.code;return"user"===e.role===n?"me":"them"}let v8={worklet:"/interpreter-noise/rnnoiseWorklet.js",wasm:"/interpreter-noise/rnnoise.wasm",simdWasm:"/interpreter-noise/rnnoise_simd.wasm"};async function v4(e,t,r,a=v8){if("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode||"object"!=typeof WebAssembly)throw Error("AudioWorklet or WebAssembly is not available");if(0===e.getAudioTracks().length)throw Error("the stream has no audio track");let i=Promise.withResolvers();i.promise.catch(()=>{});let s=()=>i.reject(Error("setup cancelled"));r?.aborted?s():r?.addEventListener("abort",s,{once:!0});let o=e=>Promise.race([e,i.promise]),l=null,c=!1,d=null,u=null,p=null,h=null,m=()=>{if(c)return;c=!0;let e=l;e&&(e.onstatechange=null,u&&(u.onprocessorerror=null,u.destroy(),u.disconnect()),d?.disconnect(),p?.disconnect(),h?.stop(),"closed"!==e.state&&e.close().catch(()=>{}))};r?.addEventListener("abort",m,{once:!0});try{let i;if(r?.aborted)throw Error("setup cancelled");let s=await o(n.e(5211).then(n.bind(n,55211)));if(r?.aborted)throw Error("setup cancelled");let{RnnoiseWorkletNode:m,loadRnnoise:f}=s,g=new AudioContext({sampleRate:48e3,latencyHint:"interactive"});l=g;let[x]=await Promise.all([o(f({url:a.wasm,simdUrl:a.simdWasm},r?{signal:r}:void 0)),o(g.audioWorklet.addModule(a.worklet))]);if(c)throw Error("setup cancelled");if(i=new Uint8Array(x,0,Math.min(4,x.byteLength)),4!==i.length||0!==i[0]||97!==i[1]||115!==i[2]||109!==i[3])throw Error("the RNNoise wasm did not load");if(48e3!==g.sampleRate)throw Error(`the browser ran the context at ${g.sampleRate} Hz`);if(await o(g.resume()),"running"!==g.state||c)throw Error(`the audio context is ${g.state}`);d=g.createMediaStreamSource(e),u=new m(g,{maxChannels:2,wasmBinary:x}),p=g.createGain();let v=g.createMediaStreamDestination();if(d.connect(u),u.connect(p),p.connect(v),!(h=v.stream.getAudioTracks()[0]??null))throw Error("the audio graph produced no track");u.onprocessorerror=()=>{c||t("the RNNoise processor failed")},g.onstatechange=()=>{c||"running"===g.state||t(`the audio context is ${g.state}`)}}catch(e){throw m(),e}finally{r?.removeEventListener("abort",m),r?.removeEventListener("abort",s)}let f=p,g=!1;return{track:h,setMuted:e=>{c||e===g||(g=e,f.gain.setTargetAtTime(+!e,l.currentTime,.005))},close:m}}class v5{#e;#t;constructor(e=500){this.#t=-1/0,this.#e=e}update(e,t){return e&&(this.#t=t),t-this.#t<this.#e}reset(){this.#t=-1/0}}let v6=e=>{fetch(`/api/live/call/${encodeURIComponent(e)}`,{method:"DELETE"}).catch(()=>{})};async function v3(e,t){let n=e?.getSettings().noiseSuppression;if(e&&"boolean"==typeof n&&n!==t)try{await e.applyConstraints({echoCancellation:!0,noiseSuppression:t,autoGainControl:!0})}catch(e){console.warn("[interpreter] cannot change the browser noise suppression:",e instanceof Error?e.message:String(e))}}let v7=({mine:e,theirs:t,profile:n})=>`${e.code}>${t.code}|${n.mood??""}|${n.gender??""}|${n.age??""}|${n.partnerGender??""}|${n.partnerAge??""}`;async function v9(e,t,n){let r=await fetch("/api/live/draft-secret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mine:e.code,theirs:t.code}),signal:n});if(!r.ok)throw Error(`the secret request failed (${r.status})`);let a=await r.json(),i=a&&"object"==typeof a&&"sessions"in a&&Array.isArray(a.sessions)?a.sessions:[],s=[];for(let n of[e,t]){let e=i.find(e=>e&&"object"==typeof e&&"language"in e&&e.language===n.code),t=e&&"object"==typeof e&&"secret"in e?e.secret:void 0;if("string"!=typeof t||!t)throw Error("the secret answer was incomplete");s.push({language:n,secret:t})}return s}var be=n(66592),bt=n.n(be);async function*bn(e){let t=e.getReader(),n=new TextDecoder("utf-8",{fatal:!0}),r="";try{for(;;){let e,a=await t.read();for(r+=n.decode(a.value,{stream:!a.done});-1!==(e=r.indexOf("\n\n"));){let t=r.slice(0,e);if(r=r.slice(e+2),!t.startsWith("data: "))throw Error("Invalid interpreter stream frame");let n=JSON.parse(t.slice(6));if(!n||"delta"!==n.type&&"done"!==n.type&&"error"!==n.type)throw Error("Invalid interpreter stream event");if("delta"===n.type&&"string"!=typeof n.text)throw Error("Invalid interpreter delta");if("done"===n.type&&("string"!=typeof n.text||!n.text.trim()||"string"!=typeof n.source||"string"!=typeof n.target))throw Error("Invalid interpreter completion");if("error"===n.type&&"live-auth"!==n.error&&"live-upstream"!==n.error)throw Error("Invalid interpreter failure");if(yield n,"delta"!==n.type)return}if(a.done)throw Error("Interpreter stream ended before completion")}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}function br({mine:e,theirs:t,profile:n,visible:i}){let{tt:s}=ei(),[o,l]=(0,a.useState)(e.code),[c,d]=(0,a.useState)(""),[u,p]=(0,a.useState)([]),[h,m]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[x,v]=(0,a.useState)(null),b=(0,a.useRef)(null),y=(0,a.useRef)(!1),w=(0,a.useRef)(null),k=(0,a.useRef)(null),j=o===e.code?e:t,S=o===e.code?t:e;(0,a.useEffect)(()=>(i||(b.current?.abort(),b.current=null,m(!1),v(null)),()=>{b.current?.abort(),b.current=null}),[i]),(0,a.useEffect)(()=>{i&&w.current?.scrollIntoView({block:"nearest"})},[u,i,x?.translation]);let C=e=>{b.current?.abort(),b.current=null,m(!1),v(null),g(null),l(e)},N=async r=>{if(r.preventDefault(),y.current||b.current||!c.trim())return;let a=new AbortController;b.current=a,m(!0),g(null);let i=c.trim();v({source:j,target:S,original:i,translation:""});try{let r=await fetch("/api/live/interpret/text",{method:"POST",headers:{"Content-Type":"application/json"},signal:a.signal,body:JSON.stringify({mine:e.code,theirs:t.code,source:j.code,profile:n,text:i,history:u.flatMap(e=>[{role:"user",text:e.original},{role:"assistant",text:e.translation}]).slice(-24)})});if(!r.ok){let e=await r.json();b.current!==a||a.signal.aborted||g("live-auth"===e.error?"live-auth":"live-upstream");return}if(!r.body||!r.headers.get("Content-Type")?.includes("text/event-stream"))throw Error("Invalid translation response");for await(let e of bn(r.body)){if(b.current!==a||a.signal.aborted)return;if("delta"===e.type)v(t=>t?{...t,translation:t.translation+e.text}:null);else if("error"===e.type)g(e.error);else{if(e.source!==j.code||e.target!==S.code)throw Error("Invalid translation direction");p(t=>[...t,{source:j,target:S,original:i,translation:e.text}].slice(-12)),d("")}}}catch{b.current!==a||a.signal.aborted||g("live-upstream")}finally{b.current===a&&(b.current=null,m(!1),v(null),k.current?.focus())}};return(0,r.jsxs)("div",{className:bt().root,hidden:!i,children:[(0,r.jsxs)("div",{className:bt().results,role:"log","aria-label":s("translator.conversation"),children:[u.map((e,t)=>(0,r.jsxs)("article",{className:bt().turn,children:[(0,r.jsxs)("p",{className:bt().label,children:[s("translator.original")," — ",e.source.nativeName]}),(0,r.jsx)("p",{className:bt().original,lang:e.source.tag,children:e.original}),(0,r.jsxs)("p",{className:bt().label,children:[s("translator.translation")," — ",e.target.nativeName]}),(0,r.jsx)("p",{className:bt().translation,lang:e.target.tag,children:e.translation})]},t)),x?(0,r.jsxs)("article",{className:bt().turn,"aria-busy":"true",children:[(0,r.jsxs)("p",{className:bt().label,children:[s("translator.original")," — ",x.source.nativeName]}),(0,r.jsx)("p",{className:bt().original,lang:x.source.tag,children:x.original}),(0,r.jsxs)("p",{className:bt().label,children:[s("translator.typePending")," — ",x.target.nativeName]}),(0,r.jsx)("p",{className:bt().translation,lang:x.target.tag,children:x.translation})]}):null,(0,r.jsx)("div",{ref:w})]}),(0,r.jsxs)("form",{className:bt().composer,onSubmit:N,children:[(0,r.jsxs)("div",{className:bt().direction,children:[(0,r.jsxs)("label",{children:[s("translator.source"),(0,r.jsxs)("select",{value:o,onChange:e=>C(e.target.value),children:[(0,r.jsx)("option",{value:e.code,children:e.nativeName}),(0,r.jsx)("option",{value:t.code,children:t.nativeName})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>C(S.code),children:s("translator.swapDirection")}),(0,r.jsxs)("span",{"aria-live":"polite",children:["→ ",S.nativeName]})]}),(0,r.jsxs)("label",{className:bt().field,children:[s("translator.typeLabel"),(0,r.jsx)("textarea",{ref:k,value:c,lang:j.tag,maxLength:2e3,rows:3,readOnly:h,"aria-busy":h,placeholder:s("translator.typePlaceholder"),onChange:e=>d(e.target.value),onCompositionStart:()=>{y.current=!0},onCompositionEnd:()=>{y.current=!1}})]}),f?(0,r.jsx)("p",{className:bt().error,role:"alert",children:s("live-auth"===f?"translator.typeAuth":"translator.typeError")}):null,(0,r.jsx)("button",{className:bt().submit,type:"submit",disabled:h||!c.trim(),children:s(h?"translator.typePending":"translator.typeSubmit")})]})]})}let ba="cuelo-translator",bi=[.85,1,1.3];function bs(){let e={mine:vE[0],theirs:vE[1],profile:{},face:!1,size:1,voice:!1,echoGuard:!0,noiseSuppression:!1,fastDrafts:!1};try{let t=JSON.parse(window.localStorage.getItem(ba)??"null");if(!t||"object"!=typeof t)return e;let n=vL(t.mine)??e.mine,r=vL(t.theirs)??e.theirs,a=n.code===r.code?{mine:e.mine,theirs:e.theirs}:{mine:n,theirs:r},i="number"==typeof t.size&&Number.isInteger(t.size)&&t.size>=0&&t.size<bi.length?t.size:1;return{...a,profile:vR(t.profile),face:!0===t.face,size:i,voice:!0===t.voice,echoGuard:!1!==t.echoGuard,noiseSuppression:!0===t.noiseSuppression,fastDrafts:!0===t.fastDrafts}}catch{return e}}function bo(){return(0,r.jsxs)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),(0,r.jsx)("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v3"})]})}function bl(){return(0,r.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:(0,r.jsx)("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2.5"})})}function bc(){return(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M15 5l-7 7 7 7"})})}function bd(){return(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"2.5",width:"14",height:"19",rx:"2.5"}),(0,r.jsx)("path",{d:"M5 12h14M9 7.5h6M9 16.5h6M12 5.5v2M12 16.5v2"})]})}function bu(){return(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 9l6 6 6-6"})})}function bp(){return(0,r.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})})}let bh=e=>e.language??v1(e.segment),bm=e=>{var t;let n;return e.language?v2(e.segment,e.language):(n=v1(t=e.segment))?v2(t,n):void 0};function bf({lines:e,language:t,unknownLabel:n,flipped:a,emptyHint:i}){let s=e.map(e=>({line:e,known:bh(e)})).filter(({known:e})=>void 0===e||e.code===t.code).slice(-3);return(0,r.jsxs)("div",{className:"translator-face-pane","data-flipped":a?"true":void 0,lang:t.tag,children:[(0,r.jsx)("p",{className:"translator-face-label",children:t.nativeName}),(0,r.jsxs)("div",{className:"translator-face-lines",children:[0===s.length&&i?(0,r.jsx)("p",{className:"translator-face-empty",children:i}):null,s.map(({line:e,known:t},a)=>(0,r.jsxs)("p",{className:"translator-face-line","data-latest":a===s.length-1?"true":void 0,"data-side":bm(e)??"them","data-draft":e.draft?"true":void 0,"data-language":t?void 0:"unknown",lang:t?void 0:"",children:[t?null:(0,r.jsx)("span",{className:"translator-face-unknown",children:n}),(0,r.jsx)(bg,{text:e.segment.text})]},e.key))]})]})}function bg({text:e}){return(0,r.jsx)(r.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(vH)){let a=r.index??0;a>n&&t.push({text:e.slice(n,a),number:!1}),t.push({text:r[0],number:!0}),n=a+r[0].length}return n<e.length&&t.push({text:e.slice(n),number:!1}),t})(e).map((e,t)=>e.number?(0,r.jsx)("span",{className:"translator-number",children:e.text},t):e.text)})}function bx({role:e,label:t,lines:n,pending:i,jumpLabel:s,layoutKey:o}){let l=(0,a.useRef)(null),c=(0,a.useRef)(!0),[d,u]=(0,a.useState)(!1);return(0,a.useEffect)(()=>{let e=l.current;e&&c.current&&(e.scrollTop=e.scrollHeight)},[n,i,o]),(0,r.jsxs)("section",{className:"translator-stream","data-role":e,"aria-label":t,children:[(0,r.jsx)("h3",{className:"translator-stream-label",children:t}),(0,r.jsxs)("div",{ref:l,className:"translator-log",role:"log","aria-label":t,onScroll:()=>{let e=l.current;e&&(c.current=e.scrollHeight-e.scrollTop-e.clientHeight<=32,u(!c.current))},children:[n.map((t,a)=>{let i=bh(t);return(0,r.jsx)("div",{className:"translator-entry","data-side":bm(t)??"them","data-latest":a===n.length-1?"true":void 0,"data-draft":t.draft?"true":void 0,children:(0,r.jsx)("div",{className:"translator-bubble",children:(0,r.jsx)("p",{className:"assistant"===e?"translator-translation":"translator-original",lang:i?.tag,children:(0,r.jsx)(bg,{text:t.segment.text})})})},t.key)}),i?(0,r.jsx)("p",{className:"translator-pending",children:i}):null]}),d?(0,r.jsx)("button",{type:"button",className:"translator-jump",onClick:()=>{let e=l.current;e&&(e.scrollTop=e.scrollHeight)},children:s}):null]})}function bv({visible:e=!0,onBack:t}){let{tt:n,locale:i}=ei(),[o,l]=(0,a.useState)(bs),[c,d]=(0,a.useState)("voice"),{mine:u,theirs:p,profile:h,face:m,size:f,voice:g,echoGuard:x,noiseSuppression:v,fastDrafts:b}=o,[y,w]=(0,a.useState)([]),[k,j]=(0,a.useState)(!1),S=(0,a.useRef)(vQ()),[C,N]=(0,a.useState)(0),T=(0,a.useRef)(o);(0,a.useEffect)(()=>{window.localStorage.setItem(ba,JSON.stringify({mine:u.code,theirs:p.code,profile:h,face:m,size:f,voice:g,echoGuard:x,noiseSuppression:v,fastDrafts:b}))},[x,m,b,u,v,h,f,p,g]);let I=(0,a.useRef)(()=>{}),M=(0,a.useCallback)(e=>{S.current=function(e,t,n){let r=t.text.replace(/([.!?])(?=[\p{Lu}\p{Lo}])/gu,"$1 "),{segments:a,nextId:i}=e,s=e.open[t.role];if(null===s){if(!r.trim())return e;a=[...a,{id:s=i++,role:t.role,text:r,final:t.final,...n,call:e.call}]}else a=a.map(e=>e.id===s?{...e,text:r,final:t.final}:e);return{...e,segments:a,nextId:i,open:{...e.open,[t.role]:t.final?null:s}}}(S.current,e,T.current),w(S.current.segments),I.current(S.current.segments)},[]),R=function({onTranscript:e,getHistory:t,onReconnect:n,muteMicWhilePlaying:r=!1,playVoice:i=!0,suppressNoise:s=!1}){let[o,l]=(0,a.useState)("idle"),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[h,m]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(!1),[w,k]=(0,a.useState)(null),j=(0,a.useRef)(!1),S=(0,a.useRef)(new Set),C=(0,a.useCallback)(e=>{if(j.current!==e)for(let t of(j.current=e,S.current))t(e)},[]),N=(0,a.useRef)(null),T=(0,a.useRef)(null),I=(0,a.useRef)(null),M=(0,a.useRef)(null),R=(0,a.useRef)(null),E=(0,a.useRef)(null),L=(0,a.useRef)(null),$=(0,a.useRef)(null),P=(0,a.useRef)(null),A=(0,a.useRef)(!1),F=(0,a.useRef)(!1),_=(0,a.useRef)(!1),z=(0,a.useRef)(0),W=(0,a.useRef)([]),O=(0,a.useRef)(0),D=(0,a.useRef)(!1),H=(0,a.useRef)(void 0),U=(0,a.useRef)(void 0),B=(0,a.useRef)(0),q=(0,a.useRef)(e),V=(0,a.useRef)(t),K=(0,a.useRef)(n),G=(0,a.useRef)(r),J=(0,a.useRef)(i),Z=(0,a.useRef)(s),Y=(0,a.useRef)(null),X=(0,a.useRef)(null),Q=(0,a.useRef)(null),ee=(0,a.useRef)(Promise.resolve()),et=(0,a.useRef)(async()=>{});(0,a.useEffect)(()=>{q.current=e,V.current=t,K.current=n,G.current=r,J.current=i,R.current&&(R.current.muted=!i)},[t,r,n,e,i]),(0,a.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let en=(0,a.useCallback)(()=>{B.current+=1;let e=$.current;$.current=null,F.current=!1,_.current=!1,window.clearTimeout(U.current),U.current=void 0,window.clearTimeout(H.current),H.current=void 0,L.current?.close(),L.current=null,N.current?.close(),N.current=null,T.current=null,I.current=null,e&&v6(e)},[]),er=(0,a.useCallback)(()=>{let e=E.current;E.current=null,e&&(window.clearInterval(e.timer),e.source?.disconnect(),"closed"!==e.context.state&&e.context.close().catch(()=>{}))},[]),ea=(0,a.useCallback)(()=>{let e=Y.current;Y.current=null,e?.close()},[]),ei=(0,a.useCallback)(()=>{let e=E.current,t=M.current?.getAudioTracks()[0];if(!e||!t)return;e.analyser.getFloatTimeDomainData(e.samples);let n=e.gate.update(function(e){if(0===e.length)return 0;let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}(e.samples)>=.01,performance.now()),r=G.current&&J.current&&n;t.enabled===r&&(t.enabled=!r),C(r),Y.current?.setMuted(r)},[C]),es=(0,a.useCallback)(()=>{if(er(),"function"!=typeof window.AudioContext)return;let e=null;try{(e=new window.AudioContext).resume().catch(()=>{});let t=e.createAnalyser();t.fftSize=1024;let n=e.createGain();n.gain.value=0,t.connect(n),n.connect(e.destination),E.current={context:e,analyser:t,samples:new Float32Array(t.fftSize),source:null,remote:null,gate:new v5,timer:window.setInterval(ei,50)}}catch(t){e&&"closed"!==e.state&&e.close().catch(()=>{}),console.warn("[interpreter] echo guard unavailable:",t instanceof Error?t.message:String(t))}},[ei,er]),eo=(0,a.useCallback)(()=>{for(let e of(en(),er(),Q.current?.abort(),k(null),C(!1),ea(),X.current=null,P.current=null,A.current=!1,M.current?.getTracks()??[]))e.stop();M.current=null;let e=R.current;R.current=null,e&&(e.srcObject=null,e.remove())},[ea,en,C,er]),el=(0,a.useCallback)(e=>{eo(),g(!1),y(!1),l(e)},[eo]),ec=(0,a.useCallback)((e,t)=>{A.current?(d(e),p(t??null),el("error")):eo()},[eo,el]),ed=(0,a.useCallback)(()=>A.current&&F.current&&_.current,[]),eu=(0,a.useCallback)(e=>{B.current===e&&ed()&&(g(!1),D.current=!0,l("live"))},[ed]),ep=(0,a.useCallback)(()=>{let e=I.current;if(!e)return;let t=R.current;t&&t.srcObject!==e&&(t.srcObject=e);let n=E.current;if(n&&n.remote!==e){n.source?.disconnect(),n.source=null,n.remote=e;try{n.source=n.context.createMediaStreamSource(e),n.source.connect(n.analyser)}catch(e){console.warn("[interpreter] echo guard cannot read the interpreted voice:",e instanceof Error?e.message:String(e))}}},[]),eh=(0,a.useCallback)(async e=>{let t=e.getAudioTracks()[0]??null;if(!t)return null;if(Z.current&&!Y.current&&X.current!==e){let t=new AbortController;Q.current=t;let n=window.setTimeout(()=>t.abort(),3e3);try{Y.current=await v4(e,t=>{M.current===e&&(console.warn("[interpreter] noise suppression stopped, using the raw microphone:",t),X.current=e,ea(),et.current(B.current,e).catch(()=>{}))},t.signal)}catch(t){Z.current&&M.current===e&&(X.current=e,console.warn("[interpreter] noise suppression unavailable, using the raw microphone:",t instanceof Error?t.message:String(t)))}finally{window.clearTimeout(n),Q.current===t&&(Q.current=null)}M.current!==e&&ea()}return Z.current&&M.current===e&&Y.current?Y.current.track:t},[ea]),em=(0,a.useCallback)((e,t)=>{let n=async()=>{let n=T.current;if(B.current!==e||!n)return;let r=await eh(t);if(B.current!==e||T.current!==n)return;let a=t.getAudioTracks()[0]??null;await v3(a,r===a);try{await n.replaceTrack(r)}catch(e){if(r===a)throw e;console.warn("[interpreter] the call refused the denoised track, using the raw microphone:",e instanceof Error?e.message:String(e)),X.current=t,ea(),await v3(a,!0),await n.replaceTrack(a),k(a);return}k(r),Y.current&&Y.current.track!==r&&ea()},r=ee.current.then(n);return ee.current=r.catch(()=>{}),r},[eh,ea]);(0,a.useEffect)(()=>{et.current=em},[em]),(0,a.useEffect)(()=>{Z.current=s,X.current=null,s||Q.current?.abort();let e=M.current;e&&T.current&&em(B.current,e).catch(e=>{console.warn("[interpreter] cannot switch the microphone track:",e instanceof Error?e.message:String(e))})},[em,s]);let ef=(0,a.useCallback)(async(e,t)=>{if(B.current===e&&T.current){try{await em(e,t)}catch(t){B.current===e&&ec("failed",t instanceof Error?t.message:String(t));return}B.current===e&&(_.current=!0,ep(),eu(e))}},[ep,ec,em,eu]),eg=(0,a.useRef)(()=>{}),ex=(0,a.useCallback)((e,t)=>{A.current&&D.current&&M.current&&"auth"!==e?eg.current({reason:e,message:t}):ec(e,t)},[ec]),ev=(0,a.useCallback)(async(e,t)=>{try{let n,r,a=new RTCPeerConnection;if(N.current=a,T.current=a.addTransceiver("audio",{direction:"sendrecv"}).sender,a.ontrack=t=>{B.current===e&&N.current===a&&(I.current=t.streams[0]??new MediaStream([t.track]),ep())},a.onconnectionstatechange=()=>{B.current===e&&"failed"===a.connectionState&&ex("failed","connection failed")},await a.setLocalDescription(await a.createOffer()),await dr(a),B.current!==e)return!1;let i=a.localDescription?.sdp;if(!i)throw Error("The browser produced no offer SDP.");let s=await fetch("/api/live/interpret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:i,mine:t.mine.code,theirs:t.theirs.code,context:{profile:t.profile,history:function(e,t){if(0===t.length)return e;let n=new Set(t.map(e=>e.id));return e.filter(e=>!n.has(e.id))}(V.current(),W.current)}})}),o=await s.json().catch(()=>({})),c="",d="";if(o&&"object"==typeof o&&("error"in o&&(n=o.error),"message"in o&&"string"==typeof o.message&&(r=o.message),"callId"in o&&"string"==typeof o.callId&&(c=o.callId),"sdp"in o&&"string"==typeof o.sdp&&(d=o.sdp)),!s.ok||!c||!d)return B.current===e&&ex(da(s.status,n),r),!1;if(B.current!==e)return v6(c),!1;if(await a.setRemoteDescription({type:"answer",sdp:d}),B.current!==e)return a.close(),v6(c),!1;$.current=c;let u=new EventSource(`/api/live/events?callId=${encodeURIComponent(c)}`);return L.current=u,u.onmessage=t=>{let n;if(B.current===e){try{n=JSON.parse(t.data)}catch{return}if(n&&"object"==typeof n&&"type"in n){var r,a;if("state"===n.type&&"state"in n){if("string"!=typeof n.state||(r=n.state,!0!==dn[r]))return;"connecting"===n.state||"live"===n.state||"working"===n.state?ed()&&l(n.state):"error"===n.state?ex("upstream",n.state):A.current&&D.current&&M.current?eg.current():A.current?el(n.state):eo();return}if("transcript"===n.type&&"role"in n&&"text"in n&&"final"in n){A.current&&("user"===n.role||"assistant"===n.role)&&"string"==typeof n.text&&(n.text.trim()&&(z.current=0),"user"===n.role&&n.text.trim()&&(O.current=0),"assistant"===n.role&&n.text.trim()&&y(!1),q.current({role:n.role,text:n.text,final:!0===n.final}));return}if("generation-stopped"===n.type){let e;if(!A.current)return;y(!0),W.current.push(...(e=(a=V.current()).findLastIndex(e=>"user"===e.role))<0?[]:a.slice(e)),O.current+=1,O.current>2?ec("upstream","Codex stopped the interpretation repeatedly."):D.current&&M.current&&eg.current();return}"error"===n.type&&"message"in n&&"string"==typeof n.message&&ex("upstream",n.message)}}},u.onerror=()=>{B.current===e&&$.current&&ex("failed")},F.current=!0,eu(e),!0}catch(t){return B.current===e&&ex("failed",t instanceof Error?t.message:String(t)),!1}},[ep,ec,ed,ex,eo,eu,el]),eb=(0,a.useCallback)(e=>{let t=P.current,n=M.current;if(!A.current||!t||!n)return;if(z.current+=1,z.current>10)return void(e?ec(e.reason,e.message):(v("idle"),el("idle")));en();let r=B.current;g(!0),l("connecting"),K.current();let a=()=>{B.current===r&&ev(r,t).then(e=>{e&&ef(r,n)})};e?H.current=window.setTimeout(a,2e3):a()},[ef,en,ec,ev,el]);(0,a.useEffect)(()=>{eg.current=eb},[eb]);let ey=(0,a.useCallback)(async e=>{let t;try{t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!Z.current,autoGainControl:!0}})}catch(n){let t=n instanceof DOMException?n.name:"";B.current===e&&ec("NotAllowedError"===t||"SecurityError"===t?"mic-denied":"mic-unavailable");return}if(B.current!==e||!T.current){for(let e of t.getTracks())e.stop();return}M.current=t,await ef(e,t)},[ef,ec]),ew=(0,a.useCallback)((e,t,n)=>{let r={mine:e,theirs:t,profile:n};if(P.current&&v7(P.current)===v7(r)||A.current)return;eo(),P.current=r;let a=B.current;U.current=window.setTimeout(()=>{B.current!==a||A.current||eo()},25e3),ev(a,r)},[ev,eo]),ek=(0,a.useCallback)((e,t,n)=>{let r={mine:e,theirs:t,profile:n},a=null!==P.current&&v7(P.current)===v7(r)&&!A.current&&null!==N.current;a||(eo(),P.current=r),window.clearTimeout(U.current),U.current=void 0,A.current=!0,z.current=0,W.current=[],O.current=0,D.current=!1;let i=B.current;d(null),p(null),v(null),g(!1),y(!1),l("connecting");let s=document.createElement("audio");s.autoplay=!0,s.muted=!J.current,R.current=s,es(),ep(),a||ev(i,r),ey(i)},[ey,ep,ev,eo,es]),ej=(0,a.useCallback)(()=>el("idle"),[el]);return(0,a.useEffect)(()=>()=>eo(),[eo]),{state:o,failure:c,detail:u,supported:h,reconnecting:f,ended:x,skipped:b,sendTrack:w,isBlocked:(0,a.useCallback)(()=>j.current,[]),onBlockedChange:(0,a.useCallback)(e=>(S.current.add(e),()=>void S.current.delete(e)),[]),prepare:ew,start:ek,stop:ej}}({onTranscript:M,getHistory:(0,a.useCallback)(()=>S.current.segments.filter(e=>e.text.trim()).slice(-24).map(({id:e,role:t,text:n})=>({id:e,role:t,text:n})),[]),onReconnect:(0,a.useCallback)(()=>{S.current=v0(S.current),N(S.current.call)},[]),muteMicWhilePlaying:x,playVoice:g,suppressNoise:v}),E="connecting"===R.state||"live"===R.state||"working"===R.state,L=function({enabled:e,epoch:t,pairRef:n,segments:r,sendTrack:i,isBlocked:s,onBlockedChange:o}){let[l,c]=(0,a.useState)(()=>vU()),d=(0,a.useRef)(l),u=(0,a.useRef)(r),p=(0,a.useRef)(i),h=(0,a.useRef)(s),m=(0,a.useRef)(o),f=(0,a.useRef)(null),g=(0,a.useRef)(e),x=(0,a.useCallback)(e=>{d.current=e,c(e)},[]);(0,a.useEffect)(()=>{u.current=r,p.current=i,h.current=s,m.current=o,g.current=e});let v=(0,a.useCallback)(e=>{g.current&&x(vX(d.current,e,performance.now()))},[x]),b=(0,a.useCallback)(()=>{x(vU([],d.current))},[x]);(0,a.useEffect)(()=>{var t;let r,a,i,s,o,l,c,g,v,b,y,w,k,j,S,C,N;if(x(vU(u.current,d.current)),!e)return;let T=n.current,I=(t={mine:T.mine,theirs:T.theirs,isBlocked:()=>h.current(),onBlockedChange:e=>m.current(e),onInput:(e,t)=>x(function(e,t,n,r,a){let i;if(!r)return e;let s=(e.turns[n.code]??[]).map(e=>({...e})),o=s.at(-1),l=o?a-o.inputAt:1/0,c=void 0!==o&&l<=1500&&!(l>600&&function(e,t,n){if(vK.some(t=>t.includes(e.mine.code)&&t.includes(e.theirs.code)))return!1;let r=v_(t,e.mine,e.theirs),a=v_(n,e.mine,e.theirs);return void 0!==r&&void 0!==a&&r.code!==a.code}(t,o.input,r)),d=e;return c&&o?(i=o,i.input+=r,i.inputAt=a):(i={id:d.nextTurnId,pair:t,target:n,input:r,output:"",inputAt:a,outputAt:-1/0,outputSince:a,echo:!1,dead:!1},d={...d,nextTurnId:d.nextTurnId+1},s.push(i)),vG(vJ(d,n,s),t,n,i,a)}(d.current,T,e,t,performance.now())),onOutput:(e,t)=>x(function(e,t,n,r,a){if(!r)return e;let i=(e.turns[n.code]??[]).map(e=>({...e})),s=i.at(-1),o=[...i].reverse().find(e=>a-e.outputAt<=1200)??(s&&a-Math.max(s.inputAt,s.outputAt)<=1500?s:void 0),l=e;return o||(o={id:l.nextTurnId,pair:t,target:n,input:"",output:"",inputAt:a,outputAt:a,outputSince:a,echo:!1,dead:!1},l={...l,nextTurnId:l.nextTurnId+1},i.push(o)),o.output||(o.outputSince=a),o.output+=r,o.outputAt=a,vG(vJ(l,n,i),t,n,o,a)}(d.current,T,e,t,performance.now()))},i=new AbortController,s=[],o=null,l=null,c=null,g=null,v=0,b=!1,y=!1,w=()=>{for(let e of s.splice(0))e.onclose=null,e.onmessage=null,e.onerror=null,(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)},k=()=>{if(c?.disconnect(),c=null,o&&l&&g)try{(c=o.createMediaStreamSource(new MediaStream([g]))).connect(l)}catch{console.warn("[interpreter] draft captions cannot read the microphone")}},j=()=>{y=!0,r?.(),r=void 0,c?.disconnect(),c=null,l&&(l.port.onmessage=null),l?.disconnect(),l=null,o&&"closed"!==o.state&&o.close().catch(()=>{}),o=null},S=()=>{if(w(),!b&&void 0===a){if(v>=2){console.warn("[interpreter] draft captions stopped; the interpretation goes on without them"),j();return}v+=1,a=window.setTimeout(()=>{a=void 0,N()},2e3)}},C=()=>{b||(b=!0,i.abort(),window.clearTimeout(a),a=void 0,w(),j())},N=async()=>{if(!b)try{let e=await v9(t.mine,t.theirs,i.signal);if(b)return;let n=e=>void s.push(e);await Promise.all(e.map(e=>{var r;return r={onInput:t.onInput,onOutput:t.onOutput,onDown:S,register:n},new Promise((t,n)=>{let a=new WebSocket("wss://api.openai.com/v1/realtime/translations?model=gpt-realtime-translate",["realtime",`openai-insecure-api-key.${e.secret}`]);r.register(a);let i=!1;a.onopen=()=>{i=!0,a.send(JSON.stringify({type:"session.update",session:{audio:{input:{transcription:{model:"gpt-realtime-whisper"},noise_reduction:{type:"near_field"}},output:{language:e.language.code}}}})),t(a)},a.onmessage=t=>{let n;try{n=JSON.parse(String(t.data))}catch{return}if(!n||"object"!=typeof n||!("type"in n))return;let a="delta"in n&&"string"==typeof n.delta?n.delta:"";"session.input_transcript.delta"===n.type?r.onInput(e.language,a):"session.output_transcript.delta"===n.type?r.onOutput(e.language,a):"error"===n.type&&(console.warn("[interpreter] a draft session reported an error"),r.onDown())},a.onerror=()=>{i||n(Error("the draft socket could not open"))},a.onclose=()=>{i?r.onDown():n(Error("the draft socket closed before it opened"))}})})),b&&w()}catch{S()}},(async()=>{if("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode){console.warn("[interpreter] draft captions need AudioWorklet"),C();return}try{let e=new AudioContext({sampleRate:24e3});if(o=e,await e.audioWorklet.addModule("/interpreter-draft/capture.js"),b||y||(await e.resume().catch(()=>{}),b||y))return;let n=new AudioWorkletNode(e,"interpreter-draft-capture",{numberOfOutputs:0,processorOptions:{chunkSamples:2400}});n.port.onmessage=e=>{if(!s.some(e=>e.readyState===WebSocket.OPEN))return;let t=JSON.stringify({type:"session.input_audio_buffer.append",audio:function(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}(new Uint8Array(e.data))});for(let e of s)e.readyState===WebSocket.OPEN&&e.send(t)},l=n,n.port.postMessage({muted:t.isBlocked()}),r=t.onBlockedChange(e=>n.port.postMessage({muted:e})),k()}catch{console.warn("[interpreter] draft captions cannot capture the microphone"),C()}})(),N(),{setTrack:e=>{g=e,k()},close:()=>{C()}});return f.current=I,I.setTrack(p.current),()=>{I.close(),f.current=null,x(vU(u.current,d.current))}},[x,e,t,n]),(0,a.useEffect)(()=>{f.current?.setTrack(i)},[i]);let y=l.drafts.length>0||Object.values(l.turns).some(e=>e.some(e=>vY(l,e)));return(0,a.useEffect)(()=>{if(!y)return;let e=window.setInterval(()=>x(vX(d.current,u.current,performance.now())),250);return()=>window.clearInterval(e)},[x,y]),{state:l,reset:b,reconcile:v}}({enabled:b&&E,epoch:C,pairRef:T,segments:y,sendTrack:R.sendTrack,isBlocked:R.isBlocked,onBlockedChange:R.onBlockedChange}),{reconcile:$}=L;(0,a.useEffect)(()=>{I.current=$},[$]);let P=e=>{T.current=e,S.current=v0(S.current),N(S.current.call),R.start(e.mine,e.theirs,e.profile)},A=e=>{e.mine.code!==e.theirs.code&&(l(e),E&&P(e))},F=e=>{A({...o,profile:vR({...h,...e})})},{prepare:_,supported:z,stop:W}=R,O=(0,a.useRef)(W);(0,a.useEffect)(()=>{O.current=W}),(0,a.useEffect)(()=>{e||O.current()},[e]),(0,a.useEffect)(()=>{e&&"voice"===c&&!E&&!0===z&&window.isSecureContext&&_(u,p,h)},[E,u,c,_,h,z,p,e]),(0,a.useEffect)(()=>{"text"===c&&O.current()},[c]),(0,a.useEffect)(()=>{if(!E||!("wakeLock"in navigator))return;let e=null,t=!1,n=()=>{"visible"===document.visibilityState&&(!e||e.released)&&navigator.wakeLock.request("screen").then(n=>{t?n.release():e=n}).catch(()=>{})};return n(),document.addEventListener("visibilitychange",n),()=>{t=!0,document.removeEventListener("visibilitychange",n),e?.release()}},[E]);let D=!1===R.supported,H=!window.isSecureContext,U="error"===R.state&&R.failure?function(e,t,n){switch(t){case"mic-denied":return e("translator.micDenied");case"mic-unavailable":return e("translator.micUnavailable");case"auth":return e("translator.auth");case"upstream":return e("translator.upstream",{error:n??""});default:return e("translator.failed",{error:n??""})}}(n,R.failure,R.detail):R.skipped&&E?n("translator.generationSkipped"):"idle"!==R.ended||E?H?n("translator.insecure"):D?n("translator.unsupported"):null:n("translator.idleStopped"),B=y.at(-1),q=E&&void 0!==B&&B.call===C&&"user"===B.role,V="error"===R.state?"error":R.reconnecting?"reconnecting":"connecting"===R.state?"connecting":"live"===R.state||"working"===R.state?q?"translating":"listening":"idle",K="reconnecting"===V?n("translator.reconnecting"):"connecting"===V?n("translator.connecting"):"translating"===V?n("translator.translating"):"listening"===V?n("translator.live"):"error"===V?n("translator.errorStatus"):"",G="text"===c||E||y.length>0,J=!G||k,Z={"--translator-scale":String(bi[f]??1)},Y="ko"===i?"가":"A",X=E||!(D||H||null===R.supported),Q=(0,a.useMemo)(()=>(function(e,t){let n=new Map(t.drafts.filter(e=>null!==e.matched).map(e=>[e.matched,e])),r=[],a=t.drafts.some(e=>null===e.matched&&e.text);for(let i of e)!n.has(i.id)&&(a&&"assistant"===i.role&&!i.final&&!t.seen.includes(i.id)&&6>vq(i.text)||r.push({order:i.id,line:{key:`s${i.id}`,segment:i,draft:!1}}));for(let n of t.drafts){let t=n.after+.5+1e-6*n.id;if(null===n.matched){if(!n.text)continue;let e={id:-1-n.id,role:"assistant",text:n.text,final:!1,mine:n.pair.mine,theirs:n.pair.theirs,call:0};r.push({order:t,line:{key:`d${n.id}`,segment:e,draft:!0,language:n.language}});continue}let a=e.find(e=>e.id===n.matched);if(!a)continue;let i=""!==n.text&&!a.final&&a.text.trim().length<n.text.length;r.push({order:t,line:{key:`d${n.id}`,segment:i?{...a,text:n.text}:a,draft:i,language:n.language}})}return r.sort((e,t)=>e.order-t.order).map(e=>e.line)})(y,L.state),[y,L.state]),ee=(0,a.useMemo)(()=>Q.filter(e=>"assistant"===e.segment.role),[Q]),et=(0,a.useMemo)(()=>Q.filter(e=>"user"===e.segment.role),[Q]),en=`${f}|${J?"setup":""}|${E?"active":""}`,er=()=>{E?R.stop():(j(!1),P(o))},ea=e=>vE.map(t=>(0,r.jsx)("option",{value:t.code,disabled:t.code===e.code,children:t.nativeName},t.code)),es=(0,r.jsxs)("p",{className:"translator-status","data-phase":V,role:"status","aria-live":"polite",children:["idle"===V?null:(0,r.jsx)("span",{className:"translator-status-dot","aria-hidden":"true"}),K]}),eo=e=>(0,r.jsxs)("button",{type:"button",className:"translator-call-button","data-compact":e?"true":void 0,"aria-pressed":E,disabled:!X,onClick:er,children:[E?(0,r.jsx)(bl,{}):(0,r.jsx)(bo,{}),E?n("translator.stop"):n("translator.start")]});return m&&"voice"===c?(0,r.jsxs)("section",{className:"translator-view","data-face":"true","aria-label":n("translator.title"),hidden:!e,style:Z,children:[(0,r.jsx)("h2",{className:"sr-only",children:n("translator.title")}),(0,r.jsxs)("div",{className:"translator-face",role:"log","aria-label":n("translator.conversation"),children:[(0,r.jsx)(bf,{lines:Q,language:p,unknownLabel:n("translator.unknownLanguage"),flipped:!0}),(0,r.jsxs)("div",{className:"translator-face-bar",children:[U?(0,r.jsx)("p",{className:"translator-face-notice","data-tone":"error"===R.state?"danger":void 0,role:"error"===R.state?"alert":"status",children:U}):null,"idle"===V?null:es,(0,r.jsxs)("div",{className:"translator-face-controls",children:[eo(!0),(0,r.jsxs)("button",{type:"button",className:"translator-face-exit",onClick:()=>l({...o,face:!1}),children:[(0,r.jsx)(bp,{}),n("translator.faceExit")]})]})]}),(0,r.jsx)(bf,{lines:Q,language:u,unknownLabel:n("translator.unknownLanguage"),emptyHint:E?void 0:n("translator.empty")})]})]}):(0,r.jsxs)("section",{className:"translator-view","data-active":E?"true":void 0,"aria-label":n("translator.title"),hidden:!e,style:Z,children:[(0,r.jsxs)("header",{className:"translator-header",children:[(0,r.jsxs)("div",{className:`translator-bar ${bt().toolbar}`,children:[t?(0,r.jsx)("button",{type:"button",className:"translator-icon-button","aria-label":n("translator.back"),title:n("translator.back"),onClick:t,children:(0,r.jsx)(bc,{})}):null,(0,r.jsxs)("div",{className:bt().modes,role:"group","aria-label":n("translator.title"),children:[(0,r.jsx)("button",{type:"button","aria-pressed":"voice"===c,onClick:()=>d("voice"),children:n("translator.modeVoice")}),(0,r.jsx)("button",{type:"button","aria-pressed":"text"===c,onClick:()=>{R.stop(),j(!1),d("text")},children:n("translator.modeType")})]}),G?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h2",{className:"sr-only",children:n("translator.title")}),(0,r.jsxs)("button",{type:"button",className:"translator-pair","aria-expanded":k,"aria-controls":"translator-setup","aria-label":`${n("translator.setup")}: ${u.nativeName} ⇄ ${p.nativeName}`,onClick:()=>j(e=>!e),children:[(0,r.jsxs)("span",{className:"translator-pair-text",children:[(0,r.jsx)("span",{lang:u.tag,children:u.nativeName}),(0,r.jsx)("span",{"aria-hidden":"true",children:" ⇄ "}),(0,r.jsx)("span",{lang:p.tag,children:p.nativeName})]}),(0,r.jsx)(bu,{})]})]}):(0,r.jsx)("h2",{className:"translator-title",children:n("translator.title")}),(0,r.jsxs)("div",{className:"translator-tools",children:[(0,r.jsx)("button",{type:"button",className:"translator-icon-button translator-size-button","aria-label":n("translator.sizeDown"),title:n("translator.sizeDown"),disabled:f<=0,onClick:()=>l({...o,size:Math.max(0,f-1)}),children:(0,r.jsx)("span",{"aria-hidden":"true","data-size":"down",children:Y})}),(0,r.jsx)("button",{type:"button",className:"translator-icon-button translator-size-button","aria-label":n("translator.sizeUp"),title:n("translator.sizeUp"),disabled:f>=bi.length-1,onClick:()=>l({...o,size:Math.min(bi.length-1,f+1)}),children:(0,r.jsx)("span",{"aria-hidden":"true","data-size":"up",children:Y})}),"voice"===c?(0,r.jsx)("button",{type:"button",className:"translator-icon-button","aria-pressed":!1,"aria-label":n("translator.face"),title:n("translator.faceHint"),onClick:()=>l({...o,face:!0}),children:(0,r.jsx)(bd,{})}):null]})]}),J?(0,r.jsxs)("div",{id:"translator-setup",className:"translator-setup",children:[(0,r.jsxs)("div",{className:"translator-languages",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.me")}),(0,r.jsx)("select",{"aria-label":n("translator.myLanguage"),value:u.code,onChange:e=>{let t=vL(e.target.value);t&&A({...o,mine:t})},children:ea(p)})]}),(0,r.jsx)("button",{type:"button",className:"translator-swap","aria-label":n("translator.swap"),title:n("translator.swap"),onClick:()=>A({...o,mine:p,theirs:u}),children:"⇄"}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.them")}),(0,r.jsx)("select",{"aria-label":n("translator.theirLanguage"),value:p.code,onChange:e=>{let t=vL(e.target.value);t&&A({...o,theirs:t})},children:ea(u)})]})]}),(0,r.jsxs)("div",{className:"translator-context",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.mood")}),(0,r.jsxs)("select",{value:h.mood??"",onChange:e=>F({mood:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:n("translator.notSet")}),vC.map(e=>(0,r.jsx)("option",{value:e,children:n(`translator.mood.${e}`)},e))]})]}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.gender")}),(0,r.jsxs)("select",{value:h.gender??"",onChange:e=>F({gender:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:n("translator.notSet")}),vN.map(e=>(0,r.jsx)("option",{value:e,children:n(`translator.gender.${e}`)},e))]})]}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.age")}),(0,r.jsxs)("select",{value:h.age??"",onChange:e=>F({age:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:n("translator.notSet")}),vT.map(e=>(0,r.jsx)("option",{value:e,children:n(`translator.age.${e}`)},e))]})]})]}),(0,r.jsxs)("div",{className:"translator-context",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.partnerGender")}),(0,r.jsxs)("select",{value:h.partnerGender??"",onChange:e=>F({partnerGender:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:n("translator.notSet")}),vN.map(e=>(0,r.jsx)("option",{value:e,children:n(`translator.gender.${e}`)},e))]})]}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:n("translator.partnerAge")}),(0,r.jsxs)("select",{value:h.partnerAge??"",onChange:e=>F({partnerAge:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:n("translator.notSet")}),vI.map(e=>(0,r.jsx)("option",{value:e,children:n(`translator.partnerAge.${e}`)},e))]})]})]}),"voice"===c?(0,r.jsxs)("div",{className:"translator-options",children:[(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:g,"aria-describedby":"translator-voice-hint",onChange:e=>l({...o,voice:e.target.checked})}),(0,r.jsx)("span",{children:n("translator.voice")})]}),(0,r.jsx)("p",{id:"translator-voice-hint",className:"translator-options-note",children:n("translator.voiceHint")}),g?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:x,"aria-describedby":"translator-echo-guard-hint",onChange:e=>l({...o,echoGuard:e.target.checked})}),(0,r.jsx)("span",{children:n("translator.echoGuard")})]}),(0,r.jsx)("p",{id:"translator-echo-guard-hint",className:"translator-options-note",children:n("translator.echoGuardHint")})]}):null,(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:v,"aria-describedby":"translator-noise-suppression-hint",onChange:e=>l({...o,noiseSuppression:e.target.checked})}),(0,r.jsx)("span",{children:n("translator.noiseSuppression")})]}),(0,r.jsx)("p",{id:"translator-noise-suppression-hint",className:"translator-options-note",children:n("translator.noiseSuppressionHint")}),(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:b,"aria-describedby":"translator-fast-drafts-hint",onChange:e=>l({...o,fastDrafts:e.target.checked})}),(0,r.jsx)("span",{children:n("translator.fastDrafts")})]}),(0,r.jsx)("p",{id:"translator-fast-drafts-hint",className:"translator-options-note",children:n("translator.fastDraftsHint")})]}):null,y.length>0?(0,r.jsx)(s.r,{variant:"ghost",size:"small",className:"translator-clear",onClick:()=>{var e;e=S.current,S.current={...vQ(),call:e.call,nextId:e.nextId},w([]),L.reset()},children:n("translator.clear")}):null]}):null]}),"voice"===c&&U?(0,r.jsx)("p",{className:"translator-banner","data-tone":"error"===R.state?"danger":void 0,role:"error"===R.state?"alert":"status",children:U}):null,(0,r.jsx)(br,{mine:u,theirs:p,profile:h,visible:e&&"text"===c},`${u.code}>${p.code}`),"voice"===c&&(0!==y.length||E?(0,r.jsxs)("div",{className:"translator-streams","aria-label":n("translator.conversation"),children:[(0,r.jsx)(bx,{role:"assistant",label:n("translator.translation"),lines:ee,pending:"translating"===V?n("translator.translationPending"):null,jumpLabel:n("translator.jumpLatest"),layoutKey:en}),(0,r.jsx)(bx,{role:"user",label:n("translator.original"),lines:et,pending:null,jumpLabel:n("translator.jumpLatest"),layoutKey:en})]}):(0,r.jsx)("div",{className:"translator-log",children:(0,r.jsx)("p",{className:"translator-empty",children:n("translator.empty")})})),"voice"===c?(0,r.jsxs)("div",{className:"translator-dock",children:[es,eo(E)]}):null]})}function bb({onOpen:e}){let{tt:t}=ei();return(0,r.jsxs)("div",{id:"navigator-translator-panel",className:"translator-panel",children:[(0,r.jsx)("p",{className:"translator-panel-hint",children:t("translator.panelHint")}),e?(0,r.jsx)("button",{type:"button",className:"translator-panel-open",onClick:e,children:t("translator.open")}):null]})}let by="git pull --ff-only && node install.mjs setup",bw={done:!0,"handed-off":!0,"restart-required":!0,failed:!0};function bk(e){return"unknown"===e?e:`v${e}`}function bj(){let{locale:e,t}=(0,z.s)(),n=B(),[i,s]=(0,a.useState)(null),[o,l]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),h=(0,a.useRef)(null),m=(0,a.useRef)(null),f=(0,a.useRef)(null),g=(0,a.useRef)(null),[x,v]=(0,a.useState)(null),[b,y]=(0,a.useState)(null),[w,k]=(0,a.useState)(!1),[j,S]=(0,a.useState)(null),[C,N]=(0,a.useState)(!1),T=(0,a.useCallback)(()=>{let e=m.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=d6(e.top,e.bottom,t,d3(t,.72,620),{margin:12,minHeight:0}),a=Math.min(430,window.innerWidth-24),i=Math.max(12,window.innerWidth-a-12);v({left:Math.min(e.right+8,i),width:a,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,a.useEffect)(()=>o?(T(),window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),window.visualViewport?.addEventListener("resize",T),window.visualViewport?.addEventListener("scroll",T),()=>{window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0),window.visualViewport?.removeEventListener("resize",T),window.visualViewport?.removeEventListener("scroll",T)}):void v(null),[o,T]),(0,a.useEffect)(()=>{let e,t=!1,n=null,r=0,a=()=>{clearTimeout(e),e=void 0},i=()=>{a(),t||"visible"!==document.visibilityState||(e=setTimeout(()=>void o(),36e5))},o=async()=>{if(t||n)return;let e=new AbortController;n=e,r=Date.now();try{let n=await fetch("/api/updates",{cache:"no-store",signal:e.signal});if(!n.ok)return;let r=await n.json();t||s(r)}catch{}finally{n===e&&(n=null),i()}},l=()=>{"visible"!==document.visibilityState?a():n||(Date.now()-r>=1e4?o():void 0===e&&i())};return o(),document.addEventListener("visibilitychange",l),window.addEventListener("focus",l),window.addEventListener("online",l),()=>{t=!0,a(),n?.abort(),document.removeEventListener("visibilitychange",l),window.removeEventListener("focus",l),window.removeEventListener("online",l)}},[]);let I=(0,a.useCallback)(async e=>{try{let t=await fetch("/api/updates/apply",{cache:"no-store",signal:e});if(!t.ok)return null;return await t.json()}catch{return null}},[]);(0,a.useEffect)(()=>{let e=new AbortController;return I(e.signal).then(t=>{t&&!e.signal.aborted&&(y(t),t.running&&t.job&&S(t.job.currentVersion))}),()=>e.abort()},[I]);let M=(0,a.useCallback)(async e=>{d(null);let n=0;try{let e=await fetch("/api/agent/running",{cache:"no-store"});if(e.ok){let t=await e.json();n=t.runningSessionIds?.length??0}}catch{n=0}let r=n>0?t("updates.applyConfirmBusy",{version:bk(e),count:n}):t("updates.applyConfirm",{version:bk(e)});if(window.confirm(r)){k(!0);try{let e=await fetch("/api/updates/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),n=await e.json();if(!e.ok)return void d(n.error??t("updates.applyStartFailed",{reason:String(e.status)}));y(n),n.job&&S(n.job.currentVersion)}catch(e){d(t("updates.applyStartFailed",{reason:e instanceof Error?e.message:String(e)}))}finally{k(!1)}}},[t]);if((0,a.useEffect)(()=>{let e;if(!j)return;let t=!1,n=async()=>{let r=await I();if(!t){if(N(null===r),r){if(y(r),r.runningVersion!==j&&"unknown"!==r.runningVersion)return void window.location.reload();if(r.job&&bw[r.job.phase]&&!r.running)return void S(null)}e=setTimeout(()=>void n(),r?2e3:5e3)}};return e=setTimeout(()=>void n(),2e3),()=>{t=!0,clearTimeout(e)}},[j,I]),(0,a.useEffect)(()=>()=>{clearTimeout(h.current??void 0),h.current=null},[]),(0,a.useEffect)(()=>{if(!o)return;let e=e=>{m.current?.contains(e.target)||f.current?.contains(e.target)||l(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),l(!1),g.current?.focus({preventScroll:!0}))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[o]),!i?.updateAvailable||!i.latestRelease)return null;let R=i.latestRelease,E=R.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date(R.publishedAt)):null,L=R.body.trim()||R.name,$=b?.job??null,P=w||!!j||!!b?.running,A=async e=>{try{await nf(e),clearTimeout(h.current??void 0),p(e),h.current=setTimeout(()=>p(null),1600)}catch{d(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:m,"data-dismissible-layer":o?"":void 0,style:{position:"relative",width:"100%"},children:[(0,r.jsxs)("button",{ref:g,type:"button","aria-expanded":o,"aria-haspopup":"dialog",onClick:()=>{l(e=>!e),d(null)},title:t("updates.availableTitle",{version:bk(R.version)}),style:{width:"100%",minHeight:n?44:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"7px 10px",border:"1px solid color-mix(in srgb, var(--warning) 54%, var(--border))",borderRadius:"var(--radius-surface)",background:"color-mix(in srgb, var(--warning) 8%, transparent)",color:"var(--warning)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-mono)",transition:"background 0.12s, border-color 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 14%, var(--bg-hover))",e.currentTarget.style.borderColor="var(--warning)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 8%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--warning) 54%, var(--border))"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:"var(--warning)",boxShadow:"0 0 0 3px color-mix(in srgb, var(--warning) 14%, transparent)"}}),(0,r.jsx)("span",{children:t("updates.available")}),(0,r.jsx)("span",{style:{color:"var(--text)",fontVariantNumeric:"tabular-nums"},children:bk(R.version)})]}),o&&x&&(0,q.createPortal)((0,r.jsxs)("div",{ref:f,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:x.left,top:x.top,bottom:x.bottom,zIndex:700,width:x.width,maxHeight:x.maxHeight,display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"0 18px 46px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("div",{style:{padding:"13px 14px 11px",borderBottom:"1px solid var(--border)",background:"linear-gradient(135deg, color-mix(in srgb, var(--warning) 10%, var(--bg-panel)), var(--bg-panel) 65%)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.dialogEyebrow")}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text)",fontSize:15,fontWeight:650},children:t("updates.dialogTitle")})]}),(0,r.jsx)("div",{style:{color:"var(--warning)",fontFamily:"var(--font-mono)",fontSize:12,fontVariantNumeric:"tabular-nums"},children:bk(R.version)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 14px",marginTop:9,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:t("updates.current",{version:bk(i.currentAppVersion)})}),E&&(0,r.jsx)("span",{children:E})]})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10,letterSpacing:"0.08em",textTransform:"uppercase"},children:t("updates.changelog")}),(0,r.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,r.jsx)(ny,{children:L})})]}),(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px 12px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:9,marginBottom:10},children:(0,r.jsx)("a",{href:R.htmlUrl,target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",fontSize:11,textDecoration:"underline",textUnderlineOffset:3},children:t("updates.viewRelease")})}),b?.supported&&(0,r.jsxs)("div",{style:{marginBottom:11},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void M(R.version),disabled:P,style:{width:"100%",minHeight:n?44:32,padding:"6px 12px",border:"none",borderRadius:"var(--radius-control)",background:"var(--accent)",color:"var(--bg)",fontSize:12,fontWeight:600,cursor:P?"not-allowed":"pointer",opacity:P?.65:1},children:P?t("updates.applyBusy"):t("updates.apply")}),$&&(0,r.jsxs)("div",{style:{marginTop:8,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{color:"failed"===$.phase?"var(--danger)":"var(--text)",fontFamily:"var(--font-mono)"},children:[t(`updates.phase.${$.phase}`),$.targetRef?` \xb7 ${$.targetRef}`:""]}),"failed"===$.phase&&$.error&&(0,r.jsx)("div",{style:{marginTop:4,color:"var(--danger)",overflowWrap:"anywhere"},children:$.error}),"handed-off"===$.phase&&(0,r.jsx)("div",{style:{marginTop:4,color:"var(--text-muted)"},children:t("updates.handedOff")}),j&&(0,r.jsx)("div",{style:{marginTop:4,color:C?"var(--warning)":"var(--text-muted)"},children:t("updates.waitingForRestart")}),(0,r.jsx)("div",{style:{marginTop:4,color:"var(--text-dim)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)"},children:t("updates.logPath",{path:$.logPath})})]})]}),b&&!b.supported&&b.reason&&(0,r.jsxs)("div",{style:{marginBottom:10,color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,r.jsx)("div",{children:t("updates.unsupported")}),(0,r.jsx)("div",{style:{marginTop:4,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:t("updates.unsupportedReason",{reason:b.reason})})]}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)"},children:t("updates.manual")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,marginTop:6,padding:"6px 7px",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg)",fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("code",{style:{flex:1,minWidth:0,overflowWrap:"anywhere",color:"var(--text)"},children:by}),(0,r.jsx)("button",{type:"button",onClick:()=>void A(by),title:u===by?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":u===by?t("updates.commandCopied"):t("updates.copyCommand"),style:{flex:"0 0 auto",width:n?44:24,height:n?44:24,padding:0,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",color:u===by?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:u===by?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]}),c&&(0,r.jsx)("div",{role:"alert",style:{marginTop:9,color:"var(--danger)",fontSize:11,lineHeight:1.45},children:c})]})]}),document.body)]})}let bS={ok:"정상",watch:"주의",problem:"문제",unknown:"미확인"};function bC(e){let t=Date.parse(e);return Number.isNaN(t)?null:new Date(t+324e5).toISOString()}function bN(e){return bC(e)?.slice(0,10)??e}function bT(e){let t=bC(e);return t?`${t.slice(0,10)} ${t.slice(11,16)}`:e}function bI(e){let t=Date.parse(e);return Number.isNaN(t)?e:bN(new Date(t-1).toISOString())}function bM(e){let{currentStart:t,currentEnd:n,previousStart:r}=e.window;return{current:`${bN(t)} ~ ${bI(n)}`,previous:`${bN(r)} ~ ${bI(t)}`}}function bR(e){let[t,n]=String(e).split("."),r=t.startsWith("-")?"-":"",a=(r?t.slice(1):t).replace(/\B(?=(\d{3})+(?!\d))/g,",");return`${r}${a}${n?`.${n}`:""}`}function bE(e,t){let n=10**t;return Math.round(e*n)/n}function bL(e,t){if(null===t)return"측정 불가";switch(e){case"count":return`${bR(bE(t,2))}건`;case"ratio":return`${(100*t).toFixed(1)}%`;case"usd":return`$${bR(bE(t,2))}`;case"ms":return t>=1e3?`${bR(bE(t/1e3,1))}초`:`${bR(bE(t,0))}ms`;case"tokens":return`${bR(Math.round(t))} 토큰`}}function b$(e,t=""){let{unit:n,current:r,previous:a}=e;if(null===r||null===a)return null;let i=r-a;if(0===i)return"없음";let s=i>0?"+":"-";if("ratio"===n)return`${s}${(100*Math.abs(i)).toFixed(1)}%p`;let o=bL(n,Math.abs(i)),l=0===a?"":` (${s}${bE(Math.abs(i)/Math.abs(a)*100,0)}%)`;return`${s}${o}${t}${l}`}function bP(e){return e<36e5?`${Math.max(0,Math.floor(e/6e4))}분`:e<864e5?`${Math.floor(e/36e5)}시간`:`${bE(e/864e5,1)}일`}let bA="관찰 중";function bF(e,t){let n=t.perDay?"/일":"",r=(e,n)=>null!==e&&t.perDay?n>0?e/(n/864e5):null:e,a=r(e.current,t.afterMs),i=r(t.before,t.beforeMs),s=t=>`${bL(e.unit,t)}${null===t?"":n}`;return{after:t.observing?bA:s(a),before:s(i),afterWindow:bP(t.afterMs),beforeWindow:bP(t.beforeMs),change:t.observing?bA:b$({unit:e.unit,current:a,previous:i},n)}}let b_={date:0,"after-deploy":0,condition:1,none:2};function bz(e){return[...e].sort((e,t)=>e.overdue!==t.overdue?e.overdue?-1:1:e.dueDate&&t.dueDate&&e.dueDate!==t.dueDate?e.dueDate<t.dueDate?-1:1:!!e.dueDate!=!!t.dueDate?e.dueDate?-1:1:b_[e.dueKind]-b_[t.dueKind])}function bW(e){if("condition"===e.dueKind)return"조건이 생기면 점검";if(!e.dueDate)return"점검일 미기재";let t="after-deploy"===e.dueKind?"배포일 기준 계산":"점검일";return`${t} ${e.dueDate}${e.overdue?" \xb7 기한 지남":""}`}function bO(e,t){let n=e.sections.find(e=>e.id===t);if(!n)throw Error(`upkeep section not found: ${t}`);return n}function bD(e){return e.metrics.filter(e=>"ok"!==e.status&&!e.check)}function bH(e){let t=e.filter(e=>e.check);return t.length?["",`점검 완료 표시한 지표 ${t.length}개는 뺐습니다: ${t.map(e=>e.label).join(", ")}`]:[]}function bU(e){let t=bM(e);return[`- 최근 7일: ${t.current}`,`- 비교 기간(직전 7일): ${t.previous}`,`- 보고서 생성: ${bT(e.generatedAt)} (세션 파일 ${bR(e.scannedFiles)}개를 읽음)`]}function bB(e,t){if(!t||!e.timestamp)return null;let n=Date.parse(t.markedAt);return Date.parse(e.timestamp)<n?"고침 전":e.since&&Date.parse(e.since)<n?"고침 전 사용 포함":null}function bq(e,t){return[`${t} (${e.path}, 「${e.title}」):`,"```text",e.text,"```"]}function bV(e){let{fix:t}=e,n=t?null:b$(e),r=t?bF(e,t):null,a=t&&r?[`- 고침 표시: ${bT(t.markedAt)}. 판정은 이 시각 이후 기록만으로 냈습니다.`,`- 고침 뒤 값(표시 뒤 ${r.afterWindow}): ${r.after}`,`- 고침 전 값(최근 7일 중 표시 전 ${r.beforeWindow}): ${r.before}${!t.observing&&r.change?` (고침 전 대비 변화 ${r.change})`:""}`]:[`- 최근 7일 값: ${bL(e.unit,e.current)}`];return a.push(`- 직전 7일 값: ${bL(e.unit,e.previous)}${n?` (변화 ${n})`:""}`,`- 판정: ${bS[e.status]}`,`- 판정 기준: ${e.criterion}`),e.note&&a.push(`- 해석 주의: ${e.note}`),e.check&&a.push(`- 점검 완료: ${bT(e.check.checkedAt)}${e.check.note?` \xb7 ${e.check.note}`:""}. 원인을 확인했지만 고친 게 아니라 행 판정은 그대로이고, 섹션 판정과 전체\xb7섹션 프롬프트에서는 빠집니다.`),a.push(`- 지표 id(${e.fixable?"고침\xb7점검 표시용":"점검 표시용"}): \`${e.id}\``),e.handoff&&a.push("",...bq(e.handoff,"이 기준을 적은 HANDOFF 항목")),a.push("","근거 사례:"),e.evidence.length?a.push(...e.evidence.map(e=>{let n,r;return n=[e.label],void 0!==e.count&&n.push(`${bR(e.count)}회`),e.sessionId&&n.push(`세션 ${e.sessionId}`),e.sessionPath&&n.push(e.sessionPath),e.timestamp&&n.push(bT(e.timestamp)),(r=bB(e,t))&&n.push(r),e.detail&&n.push(e.detail),`- ${n.join(" \xb7 ")}`})):a.push("- 보고서에 사례가 없습니다. 아래 요청 1번에서 직접 찾아야 합니다."),a}function bK(e){return[`- 기한: ${bW(e)}`,`- 출처: ${e.ref.path}의 「${e.section}」 절`,"",...bq(e.ref,"HANDOFF 원문")]}function bG(e){return e.warnings.length?["","이 섹션을 만들 때 읽지 못한 자료:",...e.warnings.map(e=>`- ${e}`)]:[]}let bJ=["요청:","1. 위 근거 사례의 세션 파일과 경로를 직접 열어, 이 판정이 나온 원인을 찾아 주세요. 근거가 부족하면 그 사실부터 알려 주세요.","2. 원인이 CUELO-private 저장소 범위 안이면 고치고, 고친 동작을 실제로 검증해 주세요.","3. HANDOFF.md와 작업 기록(doc/history)에 원인\xb7조치\xb7검증 결과를 남겨 주세요.","4. 사용자 결정이 필요한 일(기준 변경, 비용\xb7배포\xb7삭제 등)이면 고치지 말고 멈춰서 저에게 물어봐 주세요.",'5. 고쳐서 live 배포와 검증까지 끝난 지표만 고침 표시를 남겨 주세요. 이 CUELO 서버의 `POST /api/upkeep`에 JSON `{"metricId": "<지표 id>", "at": "<고친 동작이 live에 들어간 시각, ISO>"}`을 보내면 됩니다(최근 7일 안, 미래 불가). 원인은 확인했지만 사용자 결정에 따른 사용량처럼 고친 게 아닌 지표는 고침 표시 대신 점검 표시를 남겨 주세요: `POST /api/upkeep/check`에 JSON `{"metricId": "<지표 id>", "note": "<확인한 원인 한 줄>"}`(행 판정은 그대로 두고, 7일 동안 「점검 완료」로 붙어 섹션 판정과 전체\xb7섹션 프롬프트에서 빠집니다). 비밀번호 잠금 등으로 API를 부를 수 없으면 표시 대신 지표 id와 시각\xb7사유를 결과에 적어 주세요.'],bZ=["요청:","1. 이 항목이 적어 둔 관찰\xb7점검을 지금 해 주세요. 판정은 원문에 적힌 조건과 기준으로만 내려 주세요.","2. 점검에서 결함이 나오고 CUELO-private 저장소 범위 안이면 고치고 검증해 주세요.","3. 결과에 맞게 HANDOFF.md 항목(끝났으면 정리, 남으면 다음 점검일)과 작업 기록(doc/history)을 고쳐 주세요.","4. 사용자 결정이 필요한 일이면 고치지 말고 멈춰서 저에게 물어봐 주세요."];function bY(e){let t=e.filter((t,n)=>""!==t||n>0&&""!==e[n-1]);for(;""===t[0];)t.shift();for(;""===t.at(-1);)t.pop();return t.join("\n")}let bX=e=>`보고서를 읽지 못했습니다: ${e}`,bQ=e=>`고침 표시를 바꾸지 못했습니다: ${e}`,b0=e=>`점검 표시를 바꾸지 못했습니다: ${e}`,b1="전체 점검 프롬프트",b2=(e,t)=>`${e} \xb7 ${t} 프롬프트`,b8=e=>`「${e}」`,b4="직전 7일",b5="기준",b6="고침 표시",b3="고침 취소",b7=(e,t)=>`${e} \xb7 「${t}」`,b9="점검 완료 표시",ye="점검 취소",yt=(e,t)=>`${e} (${t})`,yn="알림 닫기",yr={problem:0,watch:1,unknown:2,ok:4},ya=e=>e.check&&"ok"!==e.status?3:yr[e.status];function yi({status:e,text:t}){return(0,r.jsx)("span",{className:"upkeep-status","data-status":e,children:t})}function ys(e){return e.split(/(\([^()]{1,24}\))/).map((e,t)=>t%2?(0,r.jsx)("span",{className:"upkeep-nowrap",children:e},t):e)}function yo({build:e,onStart:t,target:n,label:i="작업 프롬프트로 새 세션",primary:s=!1,children:o}){let[l,c]=(0,a.useState)("idle");(0,a.useEffect)(()=>{if("idle"===l)return;let e=window.setTimeout(()=>c("idle"),2e3);return()=>window.clearTimeout(e)},[l]);let d="copied"===l?"복사함":"failed"===l?"복사 실패":"복사";return(0,r.jsxs)("div",{className:"upkeep-actions",children:[(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-variant":s?"primary":void 0,"aria-label":s?void 0:b2(i,n),onClick:()=>t(e()),children:i}),(0,r.jsx)("button",{type:"button",className:"upkeep-button","aria-label":b2(d,n),onClick:()=>{nf(e()).then(()=>c("copied"),()=>c("failed"))},children:(0,r.jsx)("span",{"aria-live":"polite",children:d})}),o]})}function yl({report:e,section:t,metric:n,sectionCriterion:a,onStart:i,onMark:s,busy:o}){let l,c,d,{fix:u,check:p}=n,h=u||n.fixable&&("watch"===n.status||"problem"===n.status)?(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-fix-metric":n.id,"aria-label":b7(u?b3:b6,n.label),disabled:o,onClick:()=>s("fix",n.id,!u,t.id),children:u?b3:b6}):null,m=p||"watch"===n.status||"problem"===n.status?(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-check-metric":n.id,"aria-label":b7(p?ye:b9,n.label),disabled:o,onClick:()=>s("check",n.id,!p,t.id),children:p?ye:b9}):null,f=h||m?(0,r.jsxs)(r.Fragment,{children:[h,m]}):null,g=b$(n),x=u?bF(n,u):null;return(0,r.jsxs)("li",{className:"upkeep-row","data-status":n.status,"data-metric-row":n.id,children:[(0,r.jsxs)("div",{className:"upkeep-row-head",children:[(0,r.jsx)("h4",{children:n.label}),(0,r.jsxs)("span",{className:"upkeep-row-marks",children:[p?(0,r.jsx)("span",{className:"upkeep-checked",children:(l=bT(p.checkedAt).slice(5),`점검 완료 ${l}`)}):null,(0,r.jsx)(yi,{status:n.status,text:bS[n.status]})]})]}),x?(0,r.jsxs)("dl",{className:"upkeep-values",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:yt("고침 뒤",x.afterWindow)}),(0,r.jsx)("dd",{children:x.after})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:yt("고침 전",x.beforeWindow)}),(0,r.jsx)("dd",{children:x.before})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"고침 전 대비"}),(0,r.jsx)("dd",{children:x.change??"—"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:b4}),(0,r.jsx)("dd",{children:bL(n.unit,n.previous)})]})]}):(0,r.jsxs)("dl",{className:"upkeep-values",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"최근 7일"}),(0,r.jsx)("dd",{children:bL(n.unit,n.current)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:b4}),(0,r.jsx)("dd",{children:bL(n.unit,n.previous)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"변화"}),(0,r.jsx)("dd",{children:g??"—"})]})]}),u?(0,r.jsx)("p",{className:"upkeep-line",children:(0,r.jsx)("span",{className:"upkeep-line-label",children:(c=bT(u.markedAt).slice(5),`고침 ${c} 이후 기준`)})}):null,p?.note?(0,r.jsxs)("p",{className:"upkeep-line",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:"점검 사유"}),p.note]}):null,n.criterion!==a?(0,r.jsxs)("p",{className:"upkeep-line",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:b5}),ys(n.criterion)]}):null,n.handoff?(0,r.jsxs)("p",{className:"upkeep-line",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:"HANDOFF 기준"}),n.handoff.path," \xb7 「",n.handoff.title,"」"]}):null,n.note?(0,r.jsx)("p",{className:"upkeep-line upkeep-note",children:ys(n.note)}):null,n.evidence.length?(0,r.jsxs)("details",{className:"upkeep-details",children:[(0,r.jsx)("summary",{children:(d=n.evidence.length,`근거 사례 ${d}건`)}),(0,r.jsx)("ul",{className:"upkeep-evidence",children:n.evidence.map((e,t)=>(0,r.jsxs)("li",{children:[(0,r.jsxs)("span",{className:"upkeep-evidence-label",children:[e.label,void 0!==e.count?` \xb7 ${e.count}회`:"",e.timestamp?` \xb7 ${bT(e.timestamp)}`:"",bB(e,u)?` \xb7 ${bB(e,u)}`:""]}),e.detail?(0,r.jsx)("span",{className:"upkeep-evidence-detail",children:e.detail}):null,e.sessionId?(0,r.jsxs)("a",{className:"upkeep-evidence-link",href:`/?session=${encodeURIComponent(e.sessionId)}`,target:"_blank",rel:"noopener",title:e.sessionPath??e.sessionId,children:["세션 열기"," \xb7 ",e.sessionId]}):e.sessionPath?(0,r.jsx)("span",{className:"upkeep-evidence-detail",children:e.sessionPath}):null]},`${e.sessionId??e.label}-${t}`))})]}):null,"ok"!==n.status?(0,r.jsx)(yo,{build:()=>(function(e,t,n){let r=bO(e,t),a=r.metrics.find(e=>e.id===n);if(!a)throw Error(`upkeep metric not found: ${t}/${n}`);return bY([`CUELO 보수 점검: ${r.title} › ${a.label}`,"","점검 기간:",...bU(e),"",`「${a.label}」 지표 판정이 「${bS[a.status]}」입니다.`,...bV(a),"",...bJ])})(e,t.id,n.id),onStart:i,target:b8(n.label),children:f}):f?(0,r.jsx)("div",{className:"upkeep-actions",children:f}):null]})}function yc({report:e,item:t,onStart:n}){let a,i;return(0,r.jsxs)("li",{className:"upkeep-row","data-status":t.overdue?"problem":"unknown",children:[(0,r.jsxs)("div",{className:"upkeep-row-head",children:[(0,r.jsx)("h4",{children:t.ref.title}),(0,r.jsx)(yi,{status:t.overdue?"problem":"unknown",text:bW(t)})]}),(0,r.jsx)("p",{className:"upkeep-line upkeep-note",children:(a=t.ref.path,i=t.section,`${a} \xb7 「${i}」`)}),(0,r.jsxs)("details",{className:"upkeep-details",children:[(0,r.jsx)("summary",{children:"원문 보기"}),(0,r.jsx)("pre",{className:"upkeep-quote",children:t.ref.text})]}),(0,r.jsx)(yo,{build:()=>bY([`CUELO 보수 점검: HANDOFF 점검 기한 › ${t.ref.title}`,"","점검 기간:",...bU(e),"",t.overdue?"HANDOFF에 적힌 점검일이 지났습니다.":"HANDOFF에 남아 있는 점검 항목입니다.",...bK(t),"",...bZ]),onStart:n,target:b8(t.ref.title)})]})}function yd({open:e,onClose:t,onStartSession:n}){let i,s,[o,l]=(0,a.useState)(null),[c,d]=(0,a.useState)({phase:"idle"}),u=(0,a.useRef)(null),p=(0,a.useRef)(null),h=(0,a.useRef)(null),[m,f]=(0,a.useState)(!1),g=(0,a.useCallback)(async(e,t,n={})=>{p.current?.abort();let r=new AbortController;p.current=r,d({phase:"loading"});try{let t=await fetch(e,{cache:"no-store",...n,signal:r.signal}),a=await t.json().catch(()=>null);if(!t.ok||!a||!Array.isArray(a.sections))throw Error(a?.error??`HTTP ${t.status}`);l(a),d({phase:"ready"})}catch(e){if(r.signal.aborted)return;d({phase:"error",error:t(e instanceof Error?e.message:String(e))})}},[]),x=(0,a.useCallback)(e=>g(`/api/upkeep${e?"?refresh=1":""}`,bX),[g]),v=(0,a.useCallback)((e,t,n,r)=>{h.current={kind:e,metricId:t,sectionId:r},g("fix"===e?"/api/upkeep":"/api/upkeep/check","fix"===e?bQ:b0,{method:n?"POST":"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({metricId:t})})},[g]);(0,a.useEffect)(()=>{let e=h.current,t=u.current;if(!e||!t||"loading"===c.phase)return;h.current=null;let n=CSS.escape(e.metricId),r=t.querySelector(`[data-${e.kind}-metric="${n}"]`)??t.querySelector(`[data-metric-row="${n}"] :is(button:not([disabled]), summary)`)??t.querySelector(`#upkeep-section-${e.sectionId} h3`);r?.focus()},[o,c.phase]),(0,a.useEffect)(()=>()=>p.current?.abort(),[]),(0,a.useEffect)(()=>{e&&!o&&"idle"===c.phase&&x(!1)},[x,c.phase,e,o]),(0,a.useEffect)(()=>{let t=u.current;if(!e||!t)return;let n=()=>Array.from(t.querySelectorAll("a[href], button:not([disabled]), summary, [tabindex]:not([tabindex='-1'])")).filter(e=>e.getClientRects().length>0);(n()[0]??t).focus();let r=e=>{if("Tab"!==e.key)return;let r=n();if(!r.length)return;let a=document.activeElement,i=r[0],s=r[r.length-1];e.shiftKey&&(a===i||!t.contains(a))?(e.preventDefault(),s.focus()):e.shiftKey||a!==s&&t.contains(a)||(e.preventDefault(),i.focus())};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[e]);let b=(0,a.useCallback)(e=>n(e,o?.repoCwd??null),[n,o?.repoCwd]),y="loading"===c.phase,w=o?bM(o):null,k=!!o&&o.sections.some(e=>bD(e).length>0||(e.items??[]).some(e=>e.overdue)||e.warnings.length>0);return(0,r.jsxs)("section",{ref:u,className:"upkeep-view",role:"dialog","aria-modal":"true","aria-labelledby":"upkeep-title",tabIndex:-1,hidden:!e,onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsxs)("header",{className:"upkeep-header",children:[(0,r.jsxs)("div",{className:"upkeep-header-bar",children:[(0,r.jsxs)("button",{type:"button",className:"upkeep-back",onClick:t,children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"15 18 9 12 15 6"})}),"대화로"]}),(0,r.jsx)("h2",{id:"upkeep-title",children:"보수 점검"}),(0,r.jsx)("button",{type:"button",className:"upkeep-button",onClick:()=>void x(!0),disabled:y,"aria-busy":y,children:y?"읽는 중…":"다시 읽기"})]}),o&&w?(0,r.jsxs)("p",{className:"upkeep-meta",children:[(0,r.jsxs)("span",{children:["최근 7일"," ",w.current]}),(0,r.jsxs)("span",{children:["직전 7일"," ",w.previous]}),(0,r.jsxs)("span",{children:["생성"," ",bT(o.generatedAt)]}),(0,r.jsx)("span",{children:(i=o.scannedFiles.toLocaleString("ko-KR"),s=(o.scanMs/1e3).toFixed(1),`세션 파일 ${i}개 \xb7 ${s}초`)})]}):null]}),(0,r.jsx)("div",{className:"upkeep-body","aria-busy":y,children:o?(0,r.jsxs)(r.Fragment,{children:["error"===c.phase?(0,r.jsx)("p",{className:"upkeep-banner",role:"alert",children:c.error}):null,null===o.repoCwd?(0,r.jsx)("p",{className:"upkeep-banner",children:"CUELO 저장소 경로를 찾지 못했습니다. 「작업 프롬프트로 새 세션」은 프롬프트를 복사만 합니다."}):null,(0,r.jsx)("nav",{className:"upkeep-strip","aria-label":"섹션별 상태",children:o.sections.map(e=>(0,r.jsxs)("button",{type:"button",className:"upkeep-strip-item","data-status":e.status,onClick:()=>{var t;let n;return t=e.id,n=u.current?.querySelector(`#upkeep-section-${t} h3`),void(n?.scrollIntoView({block:"start",behavior:"smooth"}),n?.focus({preventScroll:!0}))},children:[(0,r.jsx)("span",{className:"upkeep-strip-title",children:e.title}),(0,r.jsx)(yi,{status:e.status,text:bS[e.status]})]},e.id))}),(0,r.jsxs)("div",{className:"upkeep-full",children:[(0,r.jsx)("p",{children:k?b1:"정상이 아닌 지표와 기한 지난 항목이 없습니다."}),k?(0,r.jsx)(yo,{build:()=>(function(e){let t=["CUELO 보수 전체 점검","","점검 기간:",...bU(e),"","보수 대시보드에서 정상이 아닌 지표, 점검일이 지난 HANDOFF 항목, 읽지 못한 자료만 모았습니다. 섹션 순서대로 처리하고, 항목마다 원인과 조치를 따로 적어 주세요.",...bH(e.sections.flatMap(e=>e.metrics))],n=0;for(let r of e.sections){let e=bD(r),a=bz(r.items??[]).filter(e=>e.overdue);if(e.length||a.length||r.warnings.length){for(let i of(n+=e.length+a.length,t.push("",`# ${r.title} (${bS[r.status]})`),e))t.push("",`## ${i.label}`,...bV(i));for(let e of a)t.push("",`## 점검일 지남: ${e.ref.title}`,...bK(e));t.push(...bG(r))}}return n||t.push("","이번 보고서에는 정상이 아닌 지표와 기한 지난 항목이 없습니다."),t.push("",...bJ,"6. 점검일이 지난 HANDOFF 항목은 원문에 적힌 조건과 기준으로 판정하고, 결과에 맞게 그 항목을 고쳐 주세요."),bY(t)})(o),onStart:b,target:"전체 점검",label:`${b1}로 새 세션`,primary:!0}):null]}),o.sections.map(e=>{let t,n,a,i=bz(e.items??[]),s=i.filter(e=>e.overdue||e.dueDate),l=i.filter(e=>!e.overdue&&!e.dueDate),c=function(e){let t=new Map;for(let n of e)t.set(n.criterion,(t.get(n.criterion)??0)+1);let n=null;for(let[e,r]of t)(null===n||r>(t.get(n)??0))&&(n=e);return n}(e.metrics),d=e=>(0,r.jsx)(yc,{report:o,item:e,onStart:b},`${e.ref.path}-${e.ref.title}`);return(0,r.jsxs)("section",{id:`upkeep-section-${e.id}`,className:"upkeep-section","aria-labelledby":`upkeep-heading-${e.id}`,children:[(0,r.jsxs)("div",{className:"upkeep-section-head",children:[(0,r.jsxs)("div",{className:"upkeep-section-title",children:[(0,r.jsx)("h3",{id:`upkeep-heading-${e.id}`,tabIndex:-1,children:e.title}),(0,r.jsx)(yi,{status:e.status,text:bS[e.status]})]}),(0,r.jsx)("p",{className:"upkeep-summary",children:e.summary}),c?(0,r.jsxs)("p",{className:"upkeep-line",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:b5}),ys(c)]}):null,(0,r.jsx)(yo,{build:()=>(function(e,t){let n=bO(e,t),r=bD(n),a=r.length?r:n.metrics.filter(e=>!e.check),i=bz(n.items??[]),s=i.filter(e=>e.overdue),o=s.length?s:i,l=[`CUELO 보수 점검: ${n.title} 섹션`,"","점검 기간:",...bU(e),"",`섹션 판정: ${bS[n.status]} \xb7 ${n.summary}`];for(let e of(a.length&&l.push(r.length?"아래는 이 섹션에서 정상이 아닌 지표입니다.":"이 섹션에서 점검 완료 표시가 없는 지표는 모두 정상으로 나왔습니다. 판정이 맞는지 근거로 확인해 주세요."),l.push(...bH(n.metrics)),a))l.push("",`## ${e.label}`,...bV(e));if(o.length)for(let e of(l.push("",s.length?"점검일이 지난 HANDOFF 항목:":"남아 있는 HANDOFF 점검 항목:"),o))l.push("",`## ${e.ref.title}`,...bK(e));return l.push(...bG(n),"",...a.length?bJ:bZ),bY(l)})(o,e.id),onStart:b,target:(t=e.title,`${t} 섹션`),label:"섹션 프롬프트"})]}),e.warnings.length?(0,r.jsxs)("div",{className:"upkeep-warnings",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:"읽지 못한 자료"}),(0,r.jsx)("ul",{children:e.warnings.map(e=>(0,r.jsx)("li",{children:e},e))})]}):null,e.metrics.length?(0,r.jsx)("ul",{className:"upkeep-rows",children:[...e.metrics].sort((e,t)=>ya(e)-ya(t)).map(t=>(0,r.jsx)(yl,{report:o,section:e,metric:t,sectionCriterion:c,onStart:b,onMark:v,busy:y},t.id))}):"ops"!==e.id?(0,r.jsx)("p",{className:"upkeep-note",children:"이 섹션에는 지표가 없습니다."}):null,"ops"===e.id?i.length?(0,r.jsxs)(r.Fragment,{children:[s.length?(0,r.jsx)("ul",{className:"upkeep-rows",children:s.map(d)}):null,l.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"upkeep-button upkeep-fold","aria-expanded":m,"aria-controls":"upkeep-due-folded",onClick:()=>f(e=>!e),children:m?(n=l.length,`조건부\xb7날짜 없음 ${n}건 접기`):(a=l.length,`조건부\xb7날짜 없음 ${a}건 보기`)}),(0,r.jsx)("ul",{id:"upkeep-due-folded",className:"upkeep-rows",hidden:!m,children:l.map(d)})]}):null]}):(0,r.jsx)("p",{className:"upkeep-note",children:"HANDOFF에 남은 점검 항목이 없습니다."}):null]},e.id)})]}):"error"===c.phase?(0,r.jsxs)("div",{className:"upkeep-empty",role:"alert",children:[(0,r.jsx)("p",{children:c.error}),(0,r.jsx)("button",{type:"button",className:"upkeep-button",onClick:()=>void x(!1),children:"다시 시도"})]}):(0,r.jsx)("p",{className:"upkeep-empty",role:"status",children:"세션 기록을 읽는 중입니다. 몇 초 걸립니다."})})]})}function yu({message:e,onDismiss:t}){return((0,a.useEffect)(()=>{if(!e)return;let n=window.setTimeout(t,8e3);return()=>window.clearTimeout(n)},[e,t]),e)?(0,r.jsxs)("div",{className:"upkeep-notice",role:"status",children:[(0,r.jsx)("p",{children:e}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":yn,title:yn,children:"✕"})]}):null}let yp="pi-web:last-open-by-workspace";function yh(){try{return window.localStorage}catch{return null}}function ym(e){let t=e.getItem(yp);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function yf(e,t=yh()){if(t)try{let n=ym(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(yp):t.setItem(yp,JSON.stringify(n))}catch{}}let yg="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",yx="omp-web:wide-chat";function yv(){try{return fY(window.localStorage)}catch{return fY(null)}}function yb(e){let t=document.querySelector(`[data-dispatch-key="${CSS.escape(e)}"]`);return t&&0!==t.getClientRects().length?t.querySelector(".answer-dispatch-open")??t.closest(".answer-dispatch")?.querySelector(".answer-dispatch-toggle")??null:null}function yy({auxiliaryDeck:e,resourcePanel:t}={}){var n,p,m,f,k;let j,S,C,N,T,I,M,R,E,L,$,P,A,F,_,W,O,D,q,V,K,G=(0,i.useRouter)(),J=(0,i.useSearchParams)(),[Z]=(0,a.useState)(()=>{let e;return{requestedCwd:e=J.get("cwd")?.trim()||null,sessionId:e?null:J.get("session")}}),{preference:Y,toggleTheme:X}=nm(),{locale:Q,setLocale:ee,t:et,supportedLocales:en}=(0,z.s)(),er=function(){let[e,t]=(0,a.useState)(null),[n,r]=(0,a.useState)(!1),i=(0,a.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,a.useEffect)(()=>{try{r("1"===window.localStorage.getItem(fS))}catch{}return i(),window.addEventListener("focus",i),()=>window.removeEventListener("focus",i)},[i]),{permission:e,dismissed:n,request:(0,a.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission().then(t,i)},[i]),dismiss:(0,a.useCallback)(()=>{r(!0);try{window.localStorage.setItem(fS,"1")}catch{}},[])}}(),ea=(0,a.useSyncExternalStore)(H.subscribe,H.getSnapshot,U);(0,a.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{n=null,function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let a=.01>Math.abs(r-1);return e&&a&&t-n>1}({hasFocusedEditable:px(),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.setProperty("--app-viewport-height",`${e.height}px`):t.style.removeProperty("--app-viewport-height");let r=0!==window.scrollX||0!==window.scrollY,a=.01>Math.abs(e.scale-1);r&&a&&window.scrollTo(0,0)},a=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return a(),e.addEventListener("resize",a),e.addEventListener("scroll",a),window.addEventListener("resize",a),window.addEventListener("focusin",a),window.addEventListener("focusout",a),window.addEventListener("pageshow",a),()=>{e.removeEventListener("resize",a),e.removeEventListener("scroll",a),window.removeEventListener("resize",a),window.removeEventListener("focusin",a),window.removeEventListener("focusout",a),window.removeEventListener("pageshow",a),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]);let ei=pS(),es=B(),{soundEnabled:eo,onSoundToggle:el,playCueSound:ec,preloadCueSound:ed,unlockAudio:eu,soundEnabledRef:ep}=function(){let[e,t]=(0,a.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),n=(0,a.useRef)(e);(0,a.useEffect)(()=>{n.current=e},[e]);let r=(0,a.useRef)(null),i=(0,a.useRef)(null),s=(0,a.useRef)(0),o=(0,a.useRef)(new Map),l=(0,a.useRef)(new Map),c=(0,a.useRef)(new Map),d=(0,a.useRef)(null);af();let u=(0,a.useRef)(new Map),p=(0,a.useRef)(new Map),h=(0,a.useRef)(new Map),m=(0,a.useCallback)(e=>{let t=p.current.get(e);return t||(t=vx(e).catch(t=>{throw p.current.delete(e),t}),p.current.set(e,t)),t},[]),f=(0,a.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),g=(0,a.useCallback)(()=>(d.current??=ra(),d.current),[]);(0,a.useEffect)(()=>{g()},[g]);let x=(0,a.useCallback)(async e=>{if(!e)return;let t=await g(),r=r$(e);for(let a of n8){let i=r?rr(rL(r),r.id,a):rn(t,e,a);if(i){for(let e of i.stickers){if(h.current.has(e))continue;let t=new Image;t.decoding="async",t.src=e,h.current.set(e,t)}if(n.current)for(let e of i.voices)m(e).catch(()=>{})}}},[g,m]),v=(0,a.useCallback)(()=>{s.current+=1;let e=i.current;if(i.current=null,e)try{e.stop()}catch{}},[]),b=(0,a.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=f();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[f]);(0,a.useEffect)(()=>{let e=()=>b(),t={capture:!0,passive:!0};return window.addEventListener("pointerdown",e,t),window.addEventListener("keydown",e,t),()=>{window.removeEventListener("pointerdown",e,t),window.removeEventListener("keydown",e,t)}},[b]);let y=(0,a.useCallback)(()=>{let e=!n.current;e?b(!0):v(),n.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,b]),w=(0,a.useCallback)(e=>{if(!n.current)return;let t=f();if(!t)return;v();let r=s.current,a=()=>{if(r===s.current&&n.current&&(!e||e()))try{vg(t)}catch{}};"suspended"===t.state?t.resume().then(a).catch(()=>{}):a()},[f,v]);return{soundEnabled:e,onSoundToggle:y,playCueSound:(0,a.useCallback)(async(e,t="done",r)=>{let a=await g(),d=r$(e),p=null===t?null:d?rr(rL(d),d.id,t):rn(a,e,t),h=`${d?.alias??e??""}\u0000${t??""}`,x=p?ri(p.stickers,l.current.get(h)??null):null;null!==x&&l.current.set(h,x);let b=p?ri(p.voices,o.current.get(h)??null):null,y=b?p?.lines.get(b)??null:null;!b&&p&&null!==(y=ri(p.captions,c.current.get(h)??null))&&c.current.set(h,y);let k={sticker:x,text:y};if(!n.current||r&&!r())return k;let j=f();if(!j)return k;if(!b)return null!==t&&n5[t]||w(r),k;v();let S=s.current,C=()=>S!==s.current||!n.current||void 0!==r&&!r();return(async()=>{if(!("suspended"===j.state&&(await j.resume().catch(()=>{}),C())))try{let e=u.current.get(b);e||(e=m(b).then(e=>j.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(b),e}),u.current.set(b,e));let t=await e;if(C())return;let n=j.createBufferSource(),r=j.createGain();n.buffer=t,n.connect(r),r.connect(j.destination),r.gain.setValueAtTime(.82,j.currentTime),n.onended=()=>{i.current===n&&(i.current=null)},i.current=n,n.start(),o.current.set(h,b)}catch{if(C()||null!==t&&n5[t])return;try{vg(j)}catch{}}})(),k},[f,w,v,g,m]),preloadCueSound:x,unlockAudio:b,soundEnabledRef:n}}(),eh=function(){let[e,t]=(0,a.useState)({status:"idle",data:null,error:null}),[n,r]=(0,a.useState)(!0),[i,s]=(0,a.useState)(null),o=(0,a.useRef)(null),l=(0,a.useRef)(null),c=(0,a.useCallback)(()=>{l.current?.abort();let e=new AbortController;l.current=e,r2({signal:e.signal}).then(t=>{e.signal.aborted||s(t)})},[]);(0,a.useEffect)(()=>{var e;let n,a,i,s,d,u,p,h,m,f,g=(a=(e={onResult(e){t(e),r(!1)}}).intervalMs??6e4,i=e.setIntervalImpl??setInterval,s=e.clearIntervalImpl??clearInterval,d=e.initialData??null,u=null,p=0,h=!1,m=!1,f=async t=>{u?.abort(),u=new AbortController;let n=++p,r=await r0({refresh:t,previous:d,signal:u.signal,fetchImpl:e.fetchImpl});return h&&n===p&&(r.data&&(d=r.data),e.onResult(r)),r},{start(){h||(h=!0,f(!1),n=i(()=>{m||f(!1)},a))},refresh:()=>h?f(!0):Promise.resolve(rY(d,new rG("사용량 폴링이 중지되었습니다.","aborted"))),setPaused(e){m=e},stop(){h=!1,p+=1,u?.abort(),u=null,s(n),n=void 0}});return o.current=g,g.start(),c(),()=>{g.stop(),l.current?.abort(),o.current===g&&(o.current=null)}},[c]);let d=(0,a.useCallback)(async()=>{let e=o.current;if(!e)return{status:"error",data:null,error:new rG("사용량 폴링이 시작되지 않았습니다.","aborted")};r(!0),c();let t=await e.refresh();return r(!1),t},[c]);return{state:e,loading:n,refresh:d,setPaused:(0,a.useCallback)(e=>{o.current?.setPaused(e)},[]),bai:(0,a.useMemo)(()=>(function(e){let t=e?.data;if(!t)return{status:"unmeasured"};let n=t.models.filter(e=>"b-ai"===e.provider);return 0===n.length?{status:"empty"}:{status:"measured",tokens:n.reduce((e,t)=>e+t.tokens,0),from:"number"==typeof t.range?.from?t.range.from:null,to:"number"==typeof t.range?.to?t.range.to:null}})(i),[i])}}();n=eh.state.data?.reports,(0,a.useEffect)(()=>{au(n)},[n]);let[em,ef]=(0,a.useState)(!1),[ex,ev]=(0,a.useState)(!1),[eb,ey]=(0,a.useState)(!1),[ew,ek]=(0,a.useState)(!1),[ej,eS]=(0,a.useState)(null),eC=(0,a.useCallback)(()=>eS(null),[]),eN=(0,a.useRef)(new Set),eT=(0,a.useCallback)(()=>{ep.current&&ec(null,"done")},[ec,ep]),[eI,eM]=(0,a.useState)(null),[eR,eE]=(0,a.useState)(null),[eL,e$]=(0,a.useState)(null),eP=(0,a.useRef)(0),eA=(0,a.useRef)(null),[eF,e_]=(0,a.useState)(null),ez=(0,a.useRef)(0),eW=(0,a.useCallback)(e=>{e_(t=>t?.id===e?null:t)},[]),[eO,eD]=(0,a.useState)(!1);(0,a.useEffect)(()=>{try{eD("1"===window.localStorage.getItem(yx))}catch{}},[]);let eH=(0,a.useCallback)(()=>{eD(e=>{let t=!e;try{window.localStorage.setItem(yx,t?"1":"0")}catch{}return t})},[]),[eU,eB]=(0,a.useState)(null),[eq,eV]=(0,a.useState)(()=>Z.requestedCwd?"validating":"idle"),[eK,eG]=(0,a.useState)(null),[eJ,eZ]=(0,a.useState)(0),[eY,eX]=(0,a.useState)(0),[eQ,e0]=(0,a.useState)(0),[e1,e2]=(0,a.useState)(0),[e8,e4]=(0,a.useState)(!1),[e5,e6]=(0,a.useState)(null),[e3,e7]=(0,a.useState)(null),[e9]=(0,a.useState)(()=>{let e;return e=0,{reset(){e+=1,e7(null)},check(t,n){let r=++e;e7("checking"),t().then(t=>{r===e&&e7("fresh"===t.status?function(e,t){if(!t.accountKey)return"unknown";let n=e.filter(e=>e.provider===t.provider&&e.accountKey===t.accountKey);return n.some(e=>!0!==e.disabled&&!e.authError)?"recovered":n.length>0?"still-failing":"unknown"}(t.data.reports,n):"unknown")},()=>{r===e&&e7("unknown")})}}}),[te,tt]=(0,a.useState)(null),[tn,tr]=(0,a.useState)(0),ta=(0,a.useRef)(null),ti=(0,a.useRef)(null),[ts,to]=(0,a.useState)(!1),[tl,tc]=(0,a.useState)(!1),[td,tu]=(0,a.useState)(null),[tp,th]=(0,a.useReducer)(g,h),[tm,tf]=(0,a.useState)("characters"),[tg,tx]=(0,a.useState)("governor"),[tv,tb]=(0,a.useState)({sessionId:null,widgets:[]}),[ty,tw]=(0,a.useState)(()=>x(0)),[tk]=(0,a.useState)(yv),[tj]=(0,a.useState)(fX),[tS,tC]=(0,a.useState)([]),[tN,tT]=(0,a.useState)({sessions:[],complete:!1}),[tI,tM]=(0,a.useState)(!1),[tR,tE]=(0,a.useState)(!1),[tL,t$]=(0,a.useState)(0),tP=(0,a.useRef)(null),tA=(0,a.useRef)(null),tF=(0,a.useRef)(null),tz=(0,a.useCallback)(()=>{t$(e=>e+1)},[]),tW=(0,a.useCallback)(e=>{e&&ev(!0),ef(e),e||tz()},[tz]);(0,a.useEffect)(()=>{"translator"===new URLSearchParams(window.location.search).get("view")&&tW(!0)},[tW]);let tO=(0,a.useCallback)(e=>{e&&ek(!0),ey(e),e||tz()},[tz]);(0,a.useEffect)(()=>{"upkeep"===new URLSearchParams(window.location.search).get("view")&&tO(!0)},[tO]);let tD=(0,a.useCallback)(e=>{tA.current=e},[]),tH=(0,a.useRef)(!1),[tU,tB]=(0,a.useState)(!1),tq=(0,a.useRef)(!1),tV=(0,a.useRef)(!1),tK=(0,a.useRef)(0),[tG,tJ]=(0,a.useState)(!1),[tZ,tY]=(0,a.useState)(!1),tX=(0,a.useRef)(null),[tQ,t0]=(0,a.useState)(null),[t1,t2]=(0,a.useState)(null),t8=(0,a.useRef)(null),t4=(0,a.useRef)(!1);t8.current=tQ,(0,a.useEffect)(()=>{t0(u1())},[]),(0,a.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||tH.current||"IDLE"===n.phase||!n.requestId||!n.stageHash)return;let r=`${window.location.pathname}${window.location.search}${window.location.hash}`,a=function(e){let t=dM();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:uQ(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(uK,JSON.stringify(n))}catch(e){return{entered:!1,error:e instanceof Error?e.message:String(e)}}let r=new URLSearchParams({mode:"wait",requestId:n.requestId,stageHash:n.stageHash,clientId:n.clientId});return window.location.replace(`/api/update-maintenance?${r}`),{entered:!0}}({requestId:n.requestId,stageHash:n.stageHash,sessionId:eI?.id??null,resumeUrl:r});if(a.entered){tH.current=!0;return}t=a.error},r=async()=>{if(!e&&!tH.current)try{let o=t4.current?null:t8.current,l=await u8({sessionId:eI?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:o?{requestId:o.requestId,stageHash:o.stageHash}:null});tK.current=0;let c=(r=tq.current,a=tX.current,((i=l.serverBootId)&&a?i!==a:r)?"reload":r?"resume":"continue");if("reload"===c){var r,a,i,s=eI?.id??null;dM();try{sessionStorage.setItem(uJ,JSON.stringify({schemaVersion:1,sessionId:s,at:Date.now()}))}catch{}window.location.reload();return}"resume"===c&&(tq.current=!1,tB(!1),tJ(!1)),l.serverBootId&&(tX.current=l.serverBootId),tV.current=!0,!e&&l.update&&(t2(l.update),l.update.cleanup&&"running"!==l.update.cleanup.status&&(t4.current=!0)),n(l)}catch{tK.current+=1,!e&&tV.current&&tK.current>=2&&(tq.current=!0,tB(!0))}},a=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",a),r();let i=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(i),window.removeEventListener("ompweb:update-maintenance",a)}},[eI?.id]),(0,a.useEffect)(()=>{if(!tU)return;let e=window.setTimeout(()=>tJ(!0),12e4);return()=>window.clearTimeout(e)},[tU]),(0,a.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(uJ);if(!r)return!1;try{n=JSON.parse(r)}catch{n=null}return!n||1!==n.schemaVersion||"number"!=typeof n.at||t-n.at>6e4||null!==n.sessionId&&"string"!=typeof n.sessionId?(sessionStorage.removeItem(uJ),!1):n.sessionId===e&&(sessionStorage.removeItem(uJ),!0)})(eI?.id??null)&&tY(!0)},[eI?.id]),(0,a.useEffect)(()=>{if(!tZ)return;let e=window.setTimeout(()=>tY(!1),8e3);return()=>window.clearTimeout(e)},[tZ]);let t5=tQ?.requestId??null,t6=tQ?.dismissed??!0,t3=t1?.requestId??null,t7=t1?.deploymentCompleted??!1,t9=t1?.cleanup?.status??null;(0,a.useEffect)(()=>{if(!t5||t6||t3!==t5||!t7)return;let e=uX(t9);if(null===e)return;let t=window.setTimeout(()=>{t0(u2(t5))},e);return()=>window.clearTimeout(t)},[t5,t6,t3,t7,t9]),(0,a.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(uK);if(!e)return null;try{let t=JSON.parse(e);if(2!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"string"!=typeof t.clientId||"string"!=typeof t.resumeUrl||null!==t.sessionId&&"string"!=typeof t.sessionId)return null;return t}catch{return null}}();if(!e||e.sessionId&&eI?.id!==e.sessionId)return;let t=!1;return u5(e).then(e=>{t||"resumed"!==e||(t4.current=!1,t0(u1()),eZ(e=>e+1),e0(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[eI?.id]);let ne=(0,a.useCallback)(e=>{if("Tab"!==e.key)return;let t=tF.current;if(!t)return;let n=Array.from(t.querySelectorAll(yg));if(0===n.length)return;let r=e.shiftKey?n[0]:n[n.length-1],a=document.activeElement;a!==r&&t.contains(a)||(e.preventDefault(),(e.shiftKey?n[n.length-1]:n[0]).focus())},[]),[nt,nn]=(0,a.useState)(!0),[nr,na]=(0,a.useState)(!1),[ni,ns]=(0,a.useState)(!1),no=(0,a.useRef)(nt),nl=(0,a.useRef)(!1),nc=(0,a.useRef)(!0),nd=(0,a.useRef)(null);no.current=nt;let nu=(j=(p={clientPainted:nr,compactWorkspace:ea,requestedOpen:nt}).requestedOpen&&p.clientPainted,{laidOut:p.requestedOpen&&(!p.compactWorkspace||p.clientPainted),presented:j,drawer:j&&p.compactWorkspace}),np=(0,a.useCallback)(e=>{nl.current=e,nn(e),th(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),nh=(0,a.useRef)(null),ng=(0,a.useRef)(!1),nx=(0,a.useRef)(260),nv=(0,a.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let a=t<960;return Math.min(480,t-(a?320:420)-(!a&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:!1,rightPanelWidth:0}),[]),nb=function(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:i,getMaxWidth:s,growthDirection:o,maxWidth:l,minWidth:c,storageKey:d,widthRef:u}=e,p=(0,a.useRef)(null),h=(0,a.useRef)(null),m=(0,a.useRef)(!1),[f,g]=(0,a.useState)(r),[x,v]=(0,a.useState)(!1),b=(0,a.useCallback)(()=>Math.min(l,Math.max(c,s())),[s,l,c]),y=(0,a.useCallback)(e=>{var t;let n,r;return t=b(),n=Number.isFinite(e)?e:c,r=Math.max(c,t),Math.round(Math.max(c,Math.min(r,n)))},[b,c]),w=(0,a.useCallback)(e=>{u.current=e,p.current?.style.setProperty(n,`${e}px`)},[n,u]),k=(0,a.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,a=y(e),i=a!==u.current;return w(a),g(a),r&&(i||n)&&vf(d,a),a},[w,y,d,u]),j=(0,a.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),S=(0,a.useCallback)(e=>{let t=h.current;if(t&&t.pointerId===e){h.current=null,j(t),v(!1),k(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[k,j,u]),C=(0,a.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&S(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),h.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[S,u]),N=(0,a.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void S(e.pointerId);e.preventDefault();let n="right"===o?1:-1,r=y(t.startWidth+(e.clientX-t.startX)*n);w(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[w,y,S,o]),T=(0,a.useCallback)(e=>{S(e.pointerId)},[S]),I=(0,a.useCallback)(e=>{S(e.pointerId)},[S]),M=(0,a.useCallback)(e=>{S(e.pointerId)},[S]),R=(0,a.useCallback)(()=>{k(i?.()??r,{forcePersist:!0})},[k,r,i]),E=(0,a.useCallback)(()=>{k(u.current)},[k,u]),L=(0,a.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===o?"ArrowRight":"ArrowLeft",r="right"===o?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),k(u.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),k(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),k(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),k(b(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),R())},[k,b,o,c,R,u]);return(0,a.useEffect)(()=>{if(m.current)return;m.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(d),t=k(e??i?.()??r,{persist:!1});null!==e&&e!==t&&vf(d,t)},[k,r,i,d]),(0,a.useEffect)(()=>{if(!m.current)return;k(u.current);let e=()=>{k(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[k,u]),(0,a.useEffect)(()=>{if(!x)return;let e=()=>{let e=h.current;e&&S(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[S,x]),(0,a.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,j(e))},[j]),{isResizing:x,panelRef:p,reclampWidth:E,resetWidth:R,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":b(),"aria-valuemin":c,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:R,onKeyDown:L,onLostPointerCapture:M,onPointerCancel:I,onPointerDown:C,onPointerMove:N,onPointerUp:T,role:"separator",tabIndex:0},width:f}}({ariaLabel:et("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:nv,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:nx}),ny=nb.reclampWidth;(0,a.useEffect)(()=>{let e=nd.current;if(e===ea)return;ns(!0),null!==e&&(e?nl.current=no.current:nc.current=no.current),nd.current=ea;let t=ea?nl.current:nc.current;ea?np(t):nn(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>ns(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[ea,np]),(0,a.useEffect)(()=>{na(!0)},[]),(0,a.useEffect)(()=>{let e=ng.current;if(ng.current=nu.drawer,nu.drawer){let e=nb.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(yg)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||nh.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[nu.drawer,nb.panelRef]),(0,a.useEffect)(()=>{ny()},[ny,tp.activeView]),(0,a.useEffect)(()=>{let e=tP.current;if(!e)return;let t=e=>{tw(t=>{let n=x(e);return t.navigator===n.navigator&&t.deck===n.deck?t:n})};t(e.getBoundingClientRect().width);let n=new ResizeObserver(e=>{let n=e[0]?.contentRect.width;"number"==typeof n&&t(n)});return n.observe(e),()=>n.disconnect()},[]),(0,a.useEffect)(()=>{if(!tL)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>tA.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[tL]),(0,a.useEffect)(()=>{if("command-palette"!==tp.transientLayer)return;let e=tF.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(yg)?.focus()});return()=>cancelAnimationFrame(t)},[tp.transientLayer]),(0,a.useEffect)(()=>{ea||"navigator-drawer"!==tp.transientLayer||th({type:"close-layer"})},[ea,tp.transientLayer]),(0,a.useEffect)(()=>{let e=new AbortController;return tT(e=>({...e,complete:!1})),fetch("/api/sessions",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t.sessions))throw Error("Invalid session census");tC(t.sessions),tT({sessions:t.sessions.map(e=>({id:e.id,modified:e.modified})),complete:!0})}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load the complete session census:",e)}),()=>e.abort()},[eJ,eI?.id]);let nw=(0,a.useRef)(null),nk=(0,a.useRef)(null),[nj,nS]=(0,a.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),nC=(0,a.useRef)(null),nN=(0,a.useCallback)((e,t,n)=>{nC.current=n,nS(n=>{let r=nU.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),nT=(0,a.useCallback)(e=>{nS(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),nC.current?.(e)},[]),[nI,nR]=(0,a.useState)(null),nE=(0,a.useCallback)(e=>{nR(e)},[]),[nL,n$]=(0,a.useState)(null),[nP,nA]=(0,a.useState)([]),[nF,n_]=(0,a.useState)(null),[nz,nW]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let n=await t.json(),r=n.fields?.find(e=>"task.maxConcurrency"===e.path),a=r?.value??r?.defaultValue,i="number"==typeof a?a:"string"==typeof a?Number.parseInt(a,10):NaN;!e.signal.aborted&&Number.isFinite(i)&&i>0&&n_(i)}).catch(()=>{}),()=>e.abort()},[]);let[nO,nD]=(0,a.useState)({kind:"idle"}),nH=(0,a.useRef)(null),nU=(0,a.useRef)(eI?.id??null);nU.current=eI?.id??null;let nB=(0,a.useCallback)(e=>{n$(e)},[]),[nq,nV]=(0,a.useState)(null),nK=(0,a.useRef)(null),nG=(0,a.useCallback)((e,t)=>{nf(t).then(()=>{nK.current&&clearTimeout(nK.current),nV(e),nK.current=setTimeout(()=>nV(null),1400)})},[]);(0,a.useEffect)(()=>()=>{nK.current&&clearTimeout(nK.current),nH.current&&clearTimeout(nH.current)},[]),(0,a.useEffect)(()=>()=>eA.current?.abort(),[]);let[nJ,nZ]=(0,a.useState)(null),nY=(0,a.useCallback)(e=>{nZ(e)},[]),[nX,nQ]=(0,a.useState)(null),[n0,n1]=(0,a.useState)(null),[n2,n4]=(0,a.useState)(null),[n6,n3]=(0,a.useState)(!1),[n7,n9]=(0,a.useState)("subagents"),re=(0,a.useCallback)((e,t=!1)=>{th({type:"select-view",view:e}),n1(null),ea&&np(!1),(t||"chat"===e)&&tz()},[ea,tz,np]),rt=(0,a.useRef)(!1),rs=(0,a.useCallback)(()=>{rt.current=!0,th({type:"set-deck-expanded",expanded:!tp.deckExpanded})},[tp.deckExpanded]);(0,a.useEffect)(()=>{if(!rt.current)return;rt.current=!1;let e=requestAnimationFrame(()=>{[...document.querySelectorAll("#workspace-auxiliary-panel [data-panel-expand]")].find(e=>e.getClientRects().length>0)?.focus()});return()=>cancelAnimationFrame(e)},[tp.deckExpanded]);let[ro,rl]=(0,a.useState)(null),rc=(0,a.useCallback)((e,t=!0)=>{rl(e),t&&re("subagents")},[re]),rd=eI?.id??null;(0,a.useEffect)(()=>{rl(null)},[rd]);let[ru,rp]=(0,a.useState)(null),rh=(0,a.useCallback)(e=>{yb(e)||(tp.deckExpanded&&"pinned"===ty.deck?th({type:"set-deck-expanded",expanded:!1}):th({type:"select-view",view:"chat"})),rp(e)},[ty.deck,tp.deckExpanded]);(0,a.useEffect)(()=>{if(!ru)return;let e=requestAnimationFrame(()=>{yb(ru)?.focus(),rp(null)});return()=>cancelAnimationFrame(e)},[ru]);let rm=(0,a.useCallback)(e=>{let t=tp.transientLayer===e;n1(null),ea&&"navigator-drawer"===tp.transientLayer&&np(!1),th({type:"toggle-layer",layer:e}),t&&tz()},[ea,tz,np,tp.transientLayer]),rf=(0,a.useCallback)(()=>{if("chat"!==tp.activeView){n9(tp.activeView),re("chat",!0);return}re(n7,!0)},[n7,re,tp.activeView]),rg=(0,a.useCallback)(e=>{n1(null),th({type:"close-layer"}),ea&&np(!1),e9.reset(),e6(e)},[ea,e9,np]),rx=(0,a.useCallback)(()=>{e9.reset(),e6(null),tz()},[e9,tz]),rv=eh.refresh,rb=(0,a.useCallback)(()=>{null!==e5&&e9.check(rv,e5)},[rv,e9,e5]),ry=(0,a.useCallback)(()=>ts?(tl||(to(!1),tz()),!0):null!==e5?(rx(),!0):e8?(e4(!1),tz(),!0):n6?(n3(!1),tz(),!0):n0?(n1(null),tz(),!0):tp.transientLayer?("navigator-drawer"===tp.transientLayer&&np(!1),th({type:"close-layer"}),tz(),!0):tp.deckExpanded&&"pinned"===ty.deck&&document.activeElement?.closest("#workspace-auxiliary-panel")?(rt.current=!0,th({type:"set-deck-expanded",expanded:!1}),!0):"chat"!==tp.activeView&&(th({type:"select-view",view:"chat"}),tz(),!0),[rx,n6,e5,n0,tl,ts,tz,np,e8,tp.activeView,tp.transientLayer,tp.deckExpanded,ty.deck]),rw=(0,a.useCallback)(e=>{th({type:"close-layer"}),ea&&np(!1),n1(t=>t===e?null:e)},[ea,np]),rk=(0,a.useCallback)(()=>{th({type:"close-layer"}),ea&&np(!1),n1("session")},[ea,np]),rj=(0,a.useCallback)(()=>{if(n1(null),ea){let e="navigator-drawer"!==tp.transientLayer;np(e),e||tz();return}th({type:"close-layer"}),nn(e=>{let t=!e;return nc.current=t,t})},[ea,tz,np,tp.transientLayer]);(0,a.useEffect)(()=>{if(!n0||!nk.current)return;let e=()=>{let e=nk.current.getBoundingClientRect();n4({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(nk.current),()=>t.disconnect()},[n0]);let[rS,rC]=(0,a.useState)([]),[rN,rT]=(0,a.useState)(null),rE=(0,a.useRef)(new Map),rP=(0,a.useCallback)(()=>{"view-stack"===ty.deck&&th({type:"select-view",view:"chat"}),ea&&np(!1),tz()},[ea,ty.deck,tz,np]),rA=(0,a.useCallback)((e,t)=>{nw.current?.insertText(d2(e,t)),rP()},[rP]),rF=(0,a.useCallback)((e,t,n)=>{nw.current?.insertText(d8(e,t,n)),rP()},[rP]),r_=(0,a.useCallback)((e,t)=>{let n=nw.current;return!!n&&(n.addAttachments(e),t&&n.insertText(t),rP(),!0)},[rP]),rz=(0,a.useCallback)(e=>{nw.current?.insertText(e),rP()},[rP]),rW=(0,a.useCallback)((e,t)=>{tb({sessionId:e,widgets:t})},[]),rO=Z.sessionId,[rD,rH]=(0,a.useState)(null);nm({cwd:eI?.cwd??eU??rD,syncWithOmp:!0}),S=(0,a.useSyncExternalStore)(fc,fs,()=>!1),(0,a.useEffect)(()=>rM(()=>fl(rI().mode)),[]),(0,a.useEffect)(()=>{if(!S)return;let e=!0;return rR().then(t=>{e&&t&&fl(rI().mode)}),()=>{e=!1}},[S]);let rU=(0,a.useRef)(null),[rB,rq]=(0,a.useState)(()=>!rO),rV=(0,a.useRef)(!1),rK=(0,a.useRef)(0),rJ=(0,a.useCallback)(()=>{rK.current+=1},[]);(0,a.useEffect)(()=>{eI&&function(e,t,n=yh()){if(n)try{let r=ym(n);r[e]=t,n.setItem(yp,JSON.stringify(r))}catch{}}(eI.projectRoot??rU.current??eI.cwd,eI.id)},[eI]),(0,a.useEffect)(()=>{let e=Z.requestedCwd;if(!e)return;let t=new AbortController;return eV("validating"),eG(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);rV.current=!0,eB(t.cwd),eV("ready")}).catch(e=>{t.signal.aborted||(eG(e instanceof Error?e.message:String(e)),eV("error"))}),()=>t.abort()},[Z]);let rZ=(0,a.useCallback)(e=>{let t=++rK.current,n=function(e,t=yh()){if(!t)return null;try{let n=ym(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);n&&fetch("/api/sessions").then(e=>e.ok?e.json():null).then(r=>{if(t!==rK.current)return;let a=r?.sessions.find(e=>e.id===n);if(!a){r&&yf(e);return}(a.projectRoot??a.cwd)!==e?yf(e):(eM(a),eX(e=>e+1),new URLSearchParams(window.location.search).get("session")!==a.id&&G.replace(`?session=${encodeURIComponent(a.id)}`,{scroll:!1}))}).catch(()=>{})},[G]),rX=(0,a.useCallback)((e,t)=>{if(rJ(),rH(e),!e)return;let n=t??e,r=rU.current??(eI?eI.projectRoot??eI.cwd:null);if(rU.current=n,rV.current){rV.current=!1;return}r!==n&&(eP.current+=1,eA.current?.abort(),eA.current=null,eE(null),e$(null),eM(null),eB(t=>t&&t!==e?null:t),eX(e=>e+1),nS({sessionId:null,tree:[],leafId:null,navigation:0}),nR(null),n1(null),rC([]),rT(null),th({type:"select-view",view:"chat"}),rZ(n),G.replace("/",{scroll:!1}))},["/",G,eI,rJ,rZ]),rQ=(0,a.useCallback)((e,t,n)=>{eB(null),e$(n),eM(e),nS({sessionId:e.id,tree:[],leafId:null,navigation:0}),eX(e=>e+1),nR(null),rq(!0),ea&&!t&&(np(!1),th({type:"select-view",view:"chat"})),t&&(rV.current=!0),t||G.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[ea,G,np]),r1=(0,a.useCallback)((e,t=!1)=>{if(rU.current=e.projectRoot??e.cwd,rJ(),!t&&eI){let t=(eI.projectRoot??eI.cwd)===(e.projectRoot??e.cwd);if(eI.id===e.id&&t){eP.current+=1,eA.current?.abort(),eA.current=null,eE(null),ea&&np(!1);return}}if(!t&&eR?.id===e.id)return;eP.current+=1;let n=eP.current;if(eA.current?.abort(),t||!eI){eA.current=null,eE(null),rQ(e,t,null);return}let r=new AbortController;eA.current=r,eE(e);let a=new URLSearchParams({deferThinking:"1",deferMedia:"1"});fetch(`/api/sessions/${encodeURIComponent(e.id)}?${a}`,{cache:"no-store",signal:r.signal}).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();if(r.sessionId!==e.id)throw Error("Session preload returned the wrong session");eP.current===n&&rQ(e,!1,r)}).catch(t=>{r.signal.aborted||eP.current!==n||(console.error("Failed to preload session before switching:",t),rQ(e,!1,null))}).finally(()=>{eP.current===n&&(eA.current=null,eE(null))})},[rQ,rJ,ea,eR?.id,eI,np]),r8=(0,a.useCallback)((e,t)=>{eP.current+=1,eA.current?.abort(),eA.current=null,eE(null),e$(null),rJ(),eM(null),eB(t),eX(e=>e+1),nS({sessionId:null,tree:[],leafId:null,navigation:0}),nR(null),n1(null),th({type:"select-view",view:"chat"}),ea&&np(!1),G.replace("/",{scroll:!1})},["/",rJ,ea,G,np]),r4=(0,a.useCallback)((e,t)=>{if(ey(!1),!t){nf(e).then(()=>eS("CUELO 저장소를 찾지 못해 프롬프트를 복사했습니다. 사이드바에서 폴더를 고른 뒤 새 세션 입력창에 붙여 넣으세요."),()=>eS("CUELO 저장소를 찾지 못했고 프롬프트 복사도 실패했습니다. 보수 화면의 「복사」를 다시 눌러 보세요.")),ea&&np(!0);return}let n=`new:${t}`,r=dL(n);d$(n,{value:r?.value.trim()?`${r.value.trimEnd()}
|
|
76
|
+
|
|
77
|
+
${e}`:e,images:r?.images??[],documents:r?.documents??[]}),r8(`upkeep-${Date.now()}`,t),tz(),eS("프롬프트를 새 세션 입력창에 넣었습니다. 내용을 확인한 뒤 보내세요.")},[r8,ea,tz,np]),r5=(0,a.useCallback)(e=>{let t=eI?.projectRoot??rU.current??eI?.cwd??rD;if(!t||!eI)return;let n=tS.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===eI.id);if(r<0)return;let a=n[r+e];a&&(n1(null),th({type:"close-layer"}),r1(a),tz())},[rD,tS,r1,tz,eI]);m={onNewSession:e=>r8(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>rm("command-palette"),onToggleNavigator:rj,onToggleResources:()=>re("resource"===tp.activeView?"chat":"resource",!0),onSelectView:e=>re(e,!0),onCycleView:(0,a.useCallback)(e=>{let t=(d.indexOf(tp.activeView)+e+d.length)%d.length;re(d[t],!0)},[re,tp.activeView]),onNavigateSession:r5,onEscape:ry,enabled:!e8&&!ts&&null===e5,activeCwd:rD},(C=(0,a.useRef)(m)).current=m,(0,a.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let n=t.now?.()??Date.now();if(b||e.isComposing||229===e.keyCode||n-y<100)return;let r=e.target,a="u">typeof Element&&r instanceof Element?r:null,i=!!a?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!a?.closest("[data-dismissible-layer], [data-capture-keys], [role='listbox'], [role='menu'], [role='combobox'][aria-expanded='true'], [aria-haspopup][aria-expanded='true']")&&(t.onEscape?.()?(e.preventDefault(),e.stopPropagation()):!(i||a?.closest("[role='dialog']"))&&v&&(e.preventDefault(),v()));if(a?.closest("[data-capture-keys]")||!1===t.enabled)return;let s=e.key.toLowerCase(),o=(e.ctrlKey||e.metaKey)&&!e.altKey;if(o&&!e.shiftKey&&"k"===s)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(o&&!e.shiftKey&&"b"===s)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(o&&!e.shiftKey&&"u"===s)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(o&&!e.shiftKey&&/^[1-7]$/.test(s)){if(!t.onSelectView)return;let n=d[Number(s)-1];return n&&(e.preventDefault(),t.onSelectView(n))}o&&e.shiftKey&&("Period"===e.code||"Comma"===e.code)?t.onCycleView&&(e.preventDefault(),t.onCycleView("Period"===e.code?1:-1)):!e.altKey||e.ctrlKey||e.metaKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key?e.ctrlKey&&e.altKey&&!e.metaKey&&"n"===s&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,C.current)},t=()=>w(!0),n=()=>w(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",n,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",n,{capture:!0})}},[]);let r6=(0,a.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&eM(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),r3=(0,a.useCallback)(e=>{rJ(),eB(null),eM(e),eZ(e=>e+1),r6(e.id),G.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[rJ,G,r6]),r7=(0,a.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&uU({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&r1(e)}})},[r1]),r9=(0,a.useCallback)(e=>{eZ(e=>e+1),ta.current?.pending&&tr(e=>e+1),e0(e=>e+1),eI&&r6(eI.id),"completed"===e.outcome&&uD()&&r7({targetSession:eI,title:eI?.name??et("i18n.sessionComplete"),body:et("i18n.taskFinished")})},[r7,r6,eI,et]),ae=(0,a.useCallback)(e=>{var t;uD()&&(t=eN.current,!(!uH(e)||t.has(e.id))&&(t.add(e.id),1)&&r7({targetSession:eI,title:et("i18n.attentionNeeded"),body:"custom"===e.method?et("i18n.extensionInputNeeded"):"ask"===e.method?e.questions[0]?.question||et("i18n.extensionInputNeeded"):"form"===e.method?function(e){for(let t of e.sections){let n=cB(t.title),r="";for(let a of t.blocks){if("field"===a.kind){let t=e.fields[a.index],i=cB(t.label),s="choice"===t.kind&&1===t.options.length?cB(t.options[0].label):"";return(i||r||n||s||t.name).replace(/\s+/g," ").trim()}r="text"===a.kind?cB(a.spans):""}}return""}(e.form)||et("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[r7,eI,et]),at=(0,a.useCallback)(async()=>{let e=eI?.id;if(e&&"naming"!==nO.kind){nH.current&&clearTimeout(nH.current),n1(null),nD({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok||!n.title)throw Error(n.error||`HTTP ${t.status}`);let r=n.title.trim();if(eZ(e=>e+1),nU.current!==e)return;eM(t=>t?.id===e?{...t,name:r}:t),n$(t=>t?.sessionId===e?{...t,sessionName:r}:t),nD({kind:"success"}),nH.current=setTimeout(()=>nD({kind:"idle"}),1800)}catch(t){if(nU.current!==e)return;nD({kind:"error",message:t instanceof Error?t.message:String(t)}),nH.current=setTimeout(()=>nD({kind:"idle"}),5e3)}}},[nO.kind,eI?.id]);(0,a.useEffect)(()=>{nH.current&&clearTimeout(nH.current),nD({kind:"idle"})},[eI?.id]);let an=(0,a.useCallback)(e=>{rJ(),eZ(e=>e+1),eX(e=>e+1),eB(null),eM(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),r6(e),G.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[rJ,G,r6]),ar=(0,a.useCallback)(()=>{rq(!0)},[]),aa=(0,a.useCallback)(e=>{if(rJ(),eZ(e=>e+1),eI?.id===e){let e=eI.cwd;eM(null),eB(e??null),eX(e=>e+1),nS({sessionId:null,tree:[],leafId:null,navigation:0}),nR(null),n1(null),th({type:"select-view",view:"chat"}),tz(),G.replace("/",{scroll:!1})}},["/",rJ,tz,eI,G]),ai=(0,a.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,a=n?.modeHint,i=`file:${e}`;a&&rE.current.delete(i),rC(n=>{let s=n.find(e=>e.id===i);if(!s)return[...n,{id:i,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:a}];let o=!r||s.sourceSessionId===r,l=!a||s.initialDisplayMode===a;return o&&l?n:n.map(e=>{if(e.id!==i)return e;let t={...e};return r&&(t.sourceSessionId=r),a&&(t.initialDisplayMode=a),t})}),rT(i),th({type:"select-view",view:"files"}),n1(null),ea&&np(!1)},[ea,np]),as=(0,a.useCallback)(e=>{ai(e,t_(e),{sourceSessionId:eI?.id??null})},[ai,eI?.id]),ao=(0,a.useCallback)(e=>{rE.current.delete(e);let t=rS.filter(t=>t.id!==e);rC(t),rT(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===tp.activeView&&re("chat",!0)},[rS,re,tp.activeView]),al=(0,a.useCallback)(()=>{eI&&window.open(`/api/sessions/${encodeURIComponent(eI.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[eI]),ac=eU??(null===eI&&rD?rD:null),ad=null!==eI||null!==ac,ap="chat"!==tp.activeView,ah=eI?.cwd??ac,am=rB&&!ad,ag=(0,a.useCallback)((e,t)=>{ta.current=e,tt(e),tu(e.error?et("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&to(!1),e2(e=>e+1),eX(e=>e+1))},[et]);(0,a.useEffect)(()=>{let e=ti.current!==ah;if(ti.current=ah,e&&(ta.current=null,tt(null),to(!1),tu(null)),!ah)return;let t=ta.current,n=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(ah)}`,{signal:n.signal}).then(async e=>{let n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);ag(n,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>n.abort()},[ag,ah,tn]);let ax=(0,a.useCallback)(async e=>{if(ah&&!tl){tc(!0),tu(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:ah,action:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let r=ta.current;ag(n,r),(n.trusted||"cancel"===e)&&(to(!1),tz())}catch(e){tu(e instanceof Error?e.message:String(e))}finally{tc(!1)}}},[ag,tl,ah,tz]),av=rS.find(e=>e.id===rN)??null,ab=rD?t_(rD)||rD:null,ay=eI?.cwd??ac,aw=ay?t_(ay)||ay:null,ak=(eI?.name?.trim()||eI?.firstMessage?.trim()||(ac?et("i18n.newSession"):ab)||"CUELO").replace(/\s+/g," ").trim(),aj=ak.length>96?`${ak.slice(0,93)}…`:ak,aS=ab?`${aj} — ${ab} — CUELO`:`${aj} — CUELO`,aC=ab?`${ak} — ${ab}`:ak,aN=eI?.transient?`${aC} \xb7 ${et("session.inMemory")}`:aC,aT=nP.filter(e=>"pending"===e.status||"running"===e.status).length,aI=nz?et("workspace.mainAttention"):tR?et("workspace.mainWaiting"):tI?et("workspace.mainWorking"):et("workspace.mainIdle"),aM=`${nz?"⚠":tR?"○":tI?"●":"○"} Main ${aI} \xb7 Sub ${aT}${nF?`/${nF}`:""}`,aR=(0,a.useCallback)(e=>re(e,!0),[re]),aE=(T=(N=(f={deckVisible:ap,pinDecision:ty,deckExpanded:tp.deckExpanded}).deckVisible&&"pinned"===f.pinDecision.deck)&&f.deckExpanded,{replacesTranscript:f.deckVisible&&("view-stack"===f.pinDecision.deck||T),expandable:N,expanded:T,staleExpansion:f.deckExpanded&&!N}),aL=aE.replacesTranscript,a$=aE.expandable?{expanded:aE.expanded,onToggle:rs}:null,aP=aE.staleExpansion;(0,a.useEffect)(()=>{aP&&th({type:"set-deck-expanded",expanded:!1})},[aP]),(0,a.useEffect)(()=>{let e=()=>{document.title!==aS&&(document.title=aS)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[aS]);let aA="ko"===Q?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗",plugins:"플러그인",memory:"기억 추적"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat",plugins:"Plugins",memory:"Memory trace"},aF="chat"!==tp.activeView,a_=aF?aA[tp.activeView]:aA[n7],az=(I=nJ&&Number.isFinite(nJ.contextWindow)&&nJ.contextWindow>0?nJ.contextWindow:null,M=nJ&&"number"==typeof nJ.tokens&&Number.isFinite(nJ.tokens)?Math.max(0,nJ.tokens):null,E=null===(R=nJ&&"number"==typeof nJ.percent&&Number.isFinite(nJ.percent)?nJ.percent:null!==M&&null!==I?M/I*100:null)?"normal":R>90?"critical":R>70?"warning":"normal",L=null===M?"?":vm(M),$=null===I?"?":vm(I),P=null===R?"?":`${R.toFixed(0)}%`,{level:E,percent:R,fillPercent:null===R?0:Math.min(100,Math.max(0,R)),readout:null===I?null:`${P} \xb7 ${L}/${$}`,usedLabel:L,limitLabel:$,percentLabel:P}),aW=az.readout,aO=aW?et("chat.contextUsageTitle",{used:az.usedLabel,limit:az.limitLabel,percent:az.percentLabel}):null,aD="critical"===az.level?et("chat.contextUsageCritical"):"warning"===az.level?et("chat.contextUsageWarning"):null,aH=(k=nL?.userMessages,!eI||eI.transient?"unsaved":("number"==typeof k?k:0)>0||eI.messageCount>0?null:"no-messages"),aU="unsaved"===aH?et("title.unsaved"):"no-messages"===aH?et("title.noMessages"):null,aB=aU??("error"===nO.kind?nO.message:null),aq="naming"===nO.kind?et("title.generating"):"success"===nO.kind?et("title.updated"):"error"===nO.kind?et("title.failed"):et("title.generate"),aV=(0,r.jsxs)("div",{id:"workspace-file-view",className:"workspace-file-view",children:[(0,r.jsx)("div",{className:"workspace-file-tabs",children:(0,r.jsx)(hk,{tabs:rS,activeTabId:rN??"",onSelectTab:rT,onCloseTab:ao})}),(0,r.jsx)("div",{className:"workspace-file-content",children:av?.filePath?(0,r.jsx)(hy,{filePath:av.filePath,cwd:rD??void 0,sourceSessionId:av.sourceSessionId,gitRefreshKey:eQ,initialDisplayMode:av.initialDisplayMode,viewStateStore:rE.current,viewStateKey:av.id,onMentionLines:rF,onAtMention:rA,onInsertText:rz,onOpenFile:e=>ai(e,t_(e),{sourceSessionId:av.sourceSessionId})},av.id):(0,r.jsx)("div",{className:"workspace-file-empty",children:(0,r.jsx)(vc,{cwd:eI?.cwd??rD,onOpenFile:as})})})]}),aK=(0,r.jsx)(gW,{open:"resource"===tp.activeView,sessionId:eI?.id??null,activeTab:tm,onTabChange:tf,usage:eh}),aG=(0,r.jsx)(x$,{open:"efficiency"===tp.activeView,sessionId:eI?.id??null,activeTab:tg,onTabChange:tx}),aJ=(0,r.jsx)(xU,{title:aA.plugins,visible:"plugins"===tp.activeView,sessionId:eI?.id??null,labWidgets:tv,onInsertDraft:ad?rz:void 0}),aZ=(0,r.jsx)(x9,{title:aA.memory,visible:"memory"===tp.activeView,sessionId:eI?.id??null}),aY=(0,r.jsx)(fU,{title:aA.process,data:nX,onOpenFile:as}),aX=eI?eI.path?eI.path:nL?.sessionId===eI.id&&nL.sessionFile?nL.sessionFile:null:null,aQ=(0,r.jsx)(f3,{title:aA.sidechat,sessionId:eI?.id??null,sessionPath:aX,sessionName:eI?.name,historyStore:tk,flights:tj,sessionCensus:tN,visible:"sidechat"===tp.activeView}),a0=ap?(0,r.jsx)(fH,{activeView:tp.activeView,onViewChange:e=>re(e),viewLabels:aA,sessionId:eI?.id??null,sessionPath:aX,sessionName:eI?.name,sessionCwd:eI?.cwd??ac??void 0,liveSubagents:nP,processSlot:aY,fileSlot:aV,sideChatSlot:aQ,resourceSlot:t??aK,efficiencySlot:aG,pluginsSlot:aJ,memorySlot:aZ,visible:!0,onClose:()=>th({type:"select-view",view:"chat"}),onReturnFocus:tz,expand:a$,selectedMaker:ro,onSelectMaker:rl,onReturnToDispatch:rh,onOpenFile:as,fileOpen:!!av?.filePath}):null,a1=e??a0,a2=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(eg,{selectedSessionId:eR?.id??eI?.id??null,optimisticSession:eR??eI,onSelectSession:r1,onNewSession:r8,initialSessionId:rO,skipInitialProjectSelection:null!==Z.requestedCwd,onInitialRestoreDone:ar,refreshKey:eJ,onSessionDeleted:aa,selectedCwd:eI?.cwd??eU??null,onCwdChange:rX,onBackgroundTaskDone:eT,translatorPanel:(0,r.jsx)(bb,{onOpen:ea?()=>np(!1):void 0}),translatorActive:em,onTranslatorActiveChange:tW}),(0,r.jsxs)("div",{className:"navigator-footer",style:{padding:"8px",flexShrink:0},children:[(0,r.jsx)(vS,{usage:eh,onOpen:()=>{tf("usage"),re("resource",!1)},onRelogin:rg}),(0,r.jsx)(bj,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsxs)("button",{type:"button",className:"navigator-settings-action",onClick:()=>{ea&&np(!1),tO(!0)},title:"보수 점검 대시보드 열기",style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,cursor:"pointer",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.12s, color 0.12s, border-color 0.12s"},children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"})}),"보수"]}),(0,r.jsxs)("button",{className:"navigator-settings-action",onClick:()=>{n1(null),th({type:"close-layer"}),ea&&np(!1),e4(!0)},title:et("common.settings"),style:{width:"100%",height:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,background:"none",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.borderColor="var(--text-dim)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21h-4v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H3v-4h.09A1.7 1.7 0 0 0 4.6 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 9 4.6a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V3h4v.09A1.7 1.7 0 0 0 15.5 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.12.39.33.74.6 1 .3.28.69.42 1.1.4h.09v4h-.09A1.7 1.7 0 0 0 19.4 15Z"})]}),et("common.settings")]})]})]})]}),a8=tQ&&t1&&t1.requestId===tQ.requestId&&t1.deploymentCompleted?t1:null,a4=a8?.cleanup??null,a5=a8&&!tQ?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:uX(null)};let t=`${e.completedCount}/${e.totalCount} 완료`,n=`${Math.round(e.elapsedSeconds)}초 경과`;return"running"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 중",detail:`${t} \xb7 ${n} \xb7 현재 ${e.currentTarget??"대상 선택 중"}`,dismissible:!1,autoHideMs:null}:"failed"===e.status?{tone:"warning",title:"업데이트 완료 \xb7 산출물 정리 실패",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건 \xb7 실패 ${e.failureCount}건. 업데이트 자체는 성공했고 실패 증거는 보존했습니다.`,dismissible:!0,autoHideMs:uX(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:uX(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:uX(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:uX(e.status)}}(a4):null;return(0,r.jsxs)(nM.Provider,{value:r_,children:[tU?(0,r.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,r.jsxs)("div",{className:"server-restart-card",children:[(0,r.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,r.jsx)("strong",{children:et("restart.title")}),(0,r.jsx)("span",{children:et(tG?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:tP,className:"workspace-shell","data-active-view":tp.activeView,"data-deck-mode":ty.deck,"data-deck-visible":ap,"data-chat-wide":eO?"true":void 0,children:[(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${nu.drawer?" is-open":""}${nr?"":" sidebar-mobile-pending"}${ni?" sidebar-mode-shift":""}`,onClick:()=>{np(!1),tz()}}),(0,r.jsx)("div",{ref:nb.panelRef,id:"session-sidebar",className:`sidebar-container${nu.laidOut?" sidebar-open":" sidebar-closed"}${nr?"":" sidebar-mobile-pending"}${ni?" sidebar-mode-shift":""}${nb.isResizing?" sidebar-resizing":""}`,"aria-hidden":ea&&!nu.presented,inert:ea&&!nu.presented,style:{"--sidebar-width":`${nb.width}px`},children:a2}),nu.laidOut&&(0,r.jsx)("div",{...nb.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${nb.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${et("layout.resizeSidebar")}: ${et("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":tp.activeView,"aria-hidden":nu.drawer,inert:nu.drawer,children:[(0,r.jsxs)("div",{ref:nk,className:"workspace-header-stack","data-soft-keyboard":ei&&es?"open":void 0,children:[a5&&tQ&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":a5.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:a5.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:a5.detail}),a5.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>t0(u2(tQ.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),tZ&&!(a5&&tQ)&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":"positive",role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:et("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:et("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>tY(!1),"aria-label":et("restart.returnedDismiss"),children:et("i18n.close")})]}),(0,r.jsx)(fC,{variant:"banner",locale:Q,...er}),(0,r.jsxs)("header",{className:"workspace-header-seam",children:[(0,r.jsx)(s.r,{ref:nh,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:rj,"aria-controls":"session-sidebar","aria-expanded":nu.presented,title:nu.presented?et("sidebar.hide"):et("sidebar.show"),"aria-label":nu.presented?et("sidebar.hide"):et("sidebar.show"),children:nu.presented?(0,r.jsx)(o.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}):(0,r.jsx)(o.In,{size:"18px",svg:(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})})}),(0,r.jsxs)("div",{className:"workspace-session-identity",title:aN,children:[(0,r.jsxs)("div",{className:"workspace-session-identity-line",children:[aw&&(0,r.jsx)("em",{className:"workspace-session-project",children:aw}),(0,r.jsx)("strong",{children:aj})]}),(0,r.jsx)("span",{className:"workspace-session-status","aria-live":"polite",children:aM})]}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===nO.kind?nO.message:""}),ad&&te?.requiresTrust&&!te.trusted&&(0,r.jsxs)(s.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{tu(te.error?et("trust.applyFailed",{error:te.error}):null),n1(null),th({type:"close-layer"}),to(!0),te.pending&&tr(e=>e+1)},title:et("grant"===te.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":et("grant"===te.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),!ea&&(0,r.jsx)("span",{children:et("trust.resourcesNotLoaded")})]}),ad&&rd&&(0,r.jsx)(pB,{sessionId:rd,refreshKey:String(tI),compact:ea}),ad&&aW&&(0,r.jsxs)(s.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:rk,"aria-expanded":"session"===n0,title:aO??et("session.title"),"aria-label":aD?`${aO}. ${aD}`:aO??void 0,children:[(0,r.jsx)("span",{className:"workspace-context-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"workspace-context-meter-fill","data-level":az.level,style:{inlineSize:`${az.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":az.level,children:aW})]}),ad&&(0,r.jsx)(l.f,{className:"workspace-panel-toggle",variant:"neutralWeak",size:"small",pressed:aF,onPressedChange:rf,"aria-controls":"workspace-auxiliary-panel",title:"ko"===Q?"보조 패널":"Auxiliary panel",children:(0,r.jsx)("span",{className:"workspace-panel-toggle-label",children:a_})}),(0,r.jsxs)(c.k.Root,{open:n6,onOpenChange:e=>n3(e),placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===Q?"더 보기":"More","aria-label":"ko"===Q?"더 보기":"More",children:(0,r.jsx)(o.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"5",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"1"})]})})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":"ko"===Q?"세션 및 환경 메뉴":"Session and environment menu",children:(0,r.jsxs)(c.k.ScrollArea,{children:[(0,r.jsxs)(c.k.Group,{children:[(0,r.jsx)(c.k.GroupLabel,{children:"ko"===Q?"세션":"Session"}),(0,r.jsx)(c.k.Item,{onClick:rk,children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:et("session.title")})})}),(0,r.jsx)(c.k.Item,{onClick:al,disabled:!eI,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:et("history.label")}),!eI&&(0,r.jsx)(c.k.ItemDescription,{children:et("history.unsaved")})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>void at(),disabled:null!==aU||"naming"===nO.kind,children:(0,r.jsxs)(c.k.ItemBody,{children:[(0,r.jsx)(c.k.ItemLabel,{children:aq}),aB&&(0,r.jsx)(c.k.ItemDescription,{children:aB})]})}),(0,r.jsx)(c.k.Item,{onClick:()=>rw("branches"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:et("i18n.branches")})})}),(0,r.jsx)(c.k.Item,{onClick:()=>rw("system"),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:et("system.label")})})})]}),(0,r.jsxs)(c.k.Group,{children:[(0,r.jsx)(c.k.GroupLabel,{children:"ko"===Q?"환경":"Environment"}),(0,r.jsx)(fC,{variant:"menu",locale:Q,...er}),(0,r.jsx)(c.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();X({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:et("light"===Y?"theme.light":"dark"===Y?"theme.dark":"theme.auto")})})}),en.map(e=>(0,r.jsx)(c.k.Item,{role:"menuitemradio","aria-checked":Q===e.id,onClick:()=>ee(e.id),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id)),(0,r.jsx)(c.k.Item,{onClick:()=>{n1(null),th({type:"close-layer"}),ea&&np(!1),e4(!0)},children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:et("common.settings")})})})]})]})})})]})]}),n0&&n2&&(0,r.jsxs)("div",{style:{position:"fixed",top:n2.top,left:n2.left,width:n2.width,maxHeight:`calc(100dvh - ${n2.top}px - var(--omp-dock-h, 204px) - 8px)`,overflowY:"auto",zIndex:500},children:["branches"===n0&&(0,r.jsx)("div",{className:"workspace-top-panel","aria-label":et("i18n.branches"),children:(0,r.jsx)(vh,{tree:nj.sessionId===(eI?.id??null)?nj.tree:[],activeLeafId:nj.sessionId===(eI?.id??null)?nj.leafId:null,onLeafChange:nT,hasSession:!!eI})}),"system"===n0&&(0,r.jsx)("div",{style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:nI?(0,r.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:nI}):""===nI?(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:et("system.empty")}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:et("system.load")})}),"session"===n0&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",padding:"12px 16px"},children:nL?(A=nL.totalActiveMs??0,F=[...nL.sessionName?[{label:et("session.name"),value:nL.sessionName,copyField:null}]:[],{label:et("session.file"),value:nL.sessionFile??et("session.inMemory"),copyField:"file"},{label:et("session.id"),value:nL.sessionId,copyField:"id"},...A>0?[{label:et("session.totalActive"),value:(e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),a=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${a}s`:`${a}s`})(A),copyField:null}]:[]],_=[[et("session.user"),nL.userMessages.toLocaleString(Q)],[et("session.assistant"),nL.assistantMessages.toLocaleString(Q)],[et("session.toolCalls"),nL.toolCalls.toLocaleString(Q)],[et("session.toolResults"),nL.toolResults.toLocaleString(Q)],[et("session.total"),nL.totalMessages.toLocaleString(Q)]],W=[[et("session.input"),nL.tokens.input.toLocaleString(Q)],[et("session.output"),nL.tokens.output.toLocaleString(Q)],...nL.tokens.cacheRead>0?[[et("session.cacheRead"),nL.tokens.cacheRead.toLocaleString(Q)]]:[],...nL.tokens.cacheWrite>0?[[et("session.cacheWrite"),nL.tokens.cacheWrite.toLocaleString(Q)]]:[],[et("session.total"),nL.tokens.total.toLocaleString(Q)]],O=nJ??nL.contextUsage,D=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),q=[...nL.cost>0?[[et("session.cost"),`$${nL.cost.toFixed(4)}`]]:[],...O?.contextWindow?[[et("session.context"),`${null!==O.tokens?D(O.tokens):"?"} / ${D(O.contextWindow)}${null!==O.percent?` \xb7 ${O.percent.toFixed(1)}%`:""}`]]:[],...nL.tokens.cacheRead+nL.tokens.cacheWrite>0&&nL.tokens.cacheRead+nL.tokens.cacheWrite+nL.tokens.input>0?[[et("session.cacheHitRate"),`${(nL.tokens.cacheRead/(nL.tokens.cacheRead+nL.tokens.cacheWrite+nL.tokens.input)*100).toFixed(1)}%`]]:[]],V=(e,t,n="left",a=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:a?"max-content max-content":"auto minmax(0, 1fr)",columnGap:a?14:12,rowGap:4,justifyContent:a?"start":void 0},children:t.map(([t,i])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:a?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:i})]},`${e}:${t}`))})]}),K=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:et("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:F.map(e=>{var t,n;let a;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?(t=e.copyField,n=e.value,a=nq===t,(0,r.jsx)("button",{type:"button",title:a?et("session.copied"):et("file"===t?"session.copyFile":"session.copyId"),onClick:()=>nG(t,n),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:a?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=a?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:a?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})):null})]},`session-info:${e.label}`)})})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:ea?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:ea?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[K,V(et("session.messages"),_),V(et("session.tokens"),[...W,...q],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:et("session.load")})})]})]}),(0,r.jsxs)("div",{className:"chat-content-layout",children:[(0,r.jsxs)("div",{id:"workspace-transcript",className:"chat-session-column","data-translator-open":em?"true":void 0,children:[ad?(0,r.jsx)(pA,{session:eI,newSessionCwd:ac,initialSessionData:eL,transitioning:null!==eR,onAgentEnd:r9,onAttentionNeeded:ae,onSessionCreated:r3,onSessionForked:an,modelsRefreshKey:e1,chatInputRef:nw,onBranchDataChange:nN,onSystemPromptChange:nE,onSessionStatsChange:nB,onSessionStatsPanelOpen:rk,onContextUsageChange:nY,onSubagentsChange:nA,onLabWidgetsChange:rW,onOpenWorkspaceView:aR,onOpenSessionList:nu.presented?void 0:rj,onOpenMaker:rc,selectedMaker:ro,onProcessLogChange:nQ,onOpenFile:as,transcriptReplacement:aL?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:a1}):null,onComposerFocusChange:tD,onSessionBusyChange:tM,onWaitingChange:tE,onAttentionChange:nW,soundEnabled:eo,onSoundToggle:el,playCueSound:ec,preloadCueSound:ed,unlockAudio:eu,jumpRequest:eF,onJumpHandled:eW},eY):aL?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:a1}):"validating"===eq?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:et("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:Z.requestedCwd})]}):"error"===eq?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--danger)"},children:et("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:Z.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eK})]}):am?rD?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:et("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:et("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),et("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),et("workspace.addModels")]})]})]}):null,ex?(0,r.jsx)(bv,{visible:em,onBack:()=>tW(!1)}):null]}),"pinned"===ty.deck&&ap&&!aE.expanded&&(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:a1})]})]}),"command-palette"===tp.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(th({type:"close-layer"}),tz())},children:(0,r.jsxs)("div",{ref:tF,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:ne,"aria-label":"ko"===Q?"명령 팔레트":"Command palette",children:[(0,r.jsxs)("header",{children:[(0,r.jsx)("strong",{children:"ko"===Q?"명령 팔레트":"Command palette"}),(0,r.jsx)("kbd",{children:"Ctrl K"})]}),(0,r.jsx)(pq,{t:et,onPick:(e,t)=>{th({type:"close-layer"}),re("chat",!1),ez.current+=1,e_({id:ez.current,sessionId:e.id,entryId:t.entryId}),r1(e)}}),(0,r.jsxs)("div",{className:"workspace-command-list",children:[d.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>re(e,!0),children:[(0,r.jsx)("span",{children:aA[e]}),(0,r.jsx)("small",{children:tp.activeView===e?"ko"===Q?"현재 보기":"Current view":""})]},e)),u.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>{tf(e),re("resource",!1)},children:[(0,r.jsx)("span",{children:"characters"===e?"캐릭터":"usage"===e?"계정 한도":"모델 통계"}),(0,r.jsx)("small",{children:aA.resource})]},e)),(0,r.jsxs)("button",{type:"button",onClick:rj,children:[(0,r.jsx)("span",{children:nu.presented?et("sidebar.hide"):et("sidebar.show")}),(0,r.jsx)("small",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:eH,children:(0,r.jsx)("span",{children:et(eO?"palette.wideChatOff":"palette.wideChatOn")})}),(0,r.jsx)("button",{type:"button",onClick:()=>{th({type:"close-layer"}),e4(!0)},children:(0,r.jsx)("span",{children:et("common.settings")})})]})]})})]}),ew?(0,r.jsx)(yd,{open:eb,onClose:()=>tO(!1),onStartSession:r4}):null,(0,r.jsx)(yu,{message:ej,onDismiss:eC}),e8&&(0,r.jsx)(fk,{cwd:ah,sessionId:eI?.id??null,onClose:()=>{e4(!1),tr(e=>e+1),tz()},onModelsChanged:()=>e2(e=>e+1),onReloaded:()=>eX(e=>e+1)}),null!==e5&&(0,r.jsx)(mI,{cwd:ah,onClose:rx,onModelsChanged:()=>e2(e=>e+1),relogin:{target:e5,outcome:e3,onLoginSucceeded:rb}}),ts&&ah&&(0,r.jsx)(fN,{cwd:ah,busy:tl,scheduled:te?.pending==="grant",error:td,onCancel:()=>{tl||(to(!1),tz())},onConfirm:()=>void ax("grant"),onCancelSchedule:()=>void ax("cancel")})]})}},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,n)=>{Promise.resolve().then(n.bind(n,20098)),Promise.resolve().then(n.bind(n,92176))},92176:(e,t,n)=>{"use strict";n.d(t,{I18nProvider:()=>h,s:()=>m});var r=n(95155),a=n(12115);let i=JSON.parse('{"memoryTrace.refresh":"새로고침","memoryTrace.noSession":"세션을 고르면 기억을 찾은 과정이 보여요.","memoryTrace.loading":"세션 기록을 읽는 중…","memoryTrace.error":"기억 추적을 불러오지 못했어요. {error}","memoryTrace.retry":"다시 불러오기","memoryTrace.empty":"이 세션에는 기억\xb7지도 기록이 없어요","memoryTrace.requests":"기록 있는 요청 {count}개","memoryTrace.requestsLabel":"요청","memoryTrace.requestHeading":"요청 #{index}","memoryTrace.noPreview":"(글 없음)","memoryTrace.flowLabel":"요청 흐름","memoryTrace.stageRecall":"기억 불러옴","memoryTrace.stageJev":"JEV 대조","memoryTrace.stageDocmap":"지도 후보","memoryTrace.stageDocs":"연 문서","memoryTrace.stageLessons":"편집 전 교훈","memoryTrace.stageSaved":"새로 저장","memoryTrace.stageEmpty":"이 요청에서는 이 단계가 없었어요.","memoryTrace.openedSummary":"{opened}개 열어 봄 \xb7 {skipped}개 후보만","memoryTrace.opened":"열어 봄","memoryTrace.candidateOnly":"후보만","memoryTrace.fromMap":"지도 후보","memoryTrace.lines":"읽은 줄 {lines}","memoryTrace.autoRecall":"요청 전에 자동으로 불러옴","memoryTrace.explicitRecall":"작업 중 직접 찾음","memoryTrace.query":"질의","memoryTrace.noResults":"돌아온 기억이 없어요.","memoryTrace.noMemoryText":"이 기록에는 기억 글이 남아 있지 않아요.","memoryTrace.jevUnknown":"판정 불명 {count}개","memoryTrace.jevUnrelated":"무관 {count}개","memoryTrace.lessonFor":"편집 전에 띄운 기억","memoryTrace.savedAuto":"자동 저장","memoryTrace.graphLabel":"연결 그래프","memoryTrace.graphScope":"그래프 범위","memoryTrace.scopeRequest":"이 요청","memoryTrace.scopeSession":"세션 전체","memoryTrace.legendRequest":"요청","memoryTrace.legendMemory":"기억","memoryTrace.legendDoc":"지도 문서","memoryTrace.legendFile":"편집 파일","memoryTrace.graphEmpty":"이 범위에는 이어진 항목이 없어요.","memoryTrace.nodeLabel":"{kind}: {label}, 연결 {count}개","memoryTrace.edgeRecalled":"불러옴","memoryTrace.edgeLesson":"편집 전 교훈","memoryTrace.verdictLegend":"JEV 판정","memoryTrace.verdictApply":"적용 조건 일치","memoryTrace.verdictExcepted":"조건 불충족\xb7예외","memoryTrace.verdictConflict":"요청과 충돌","memoryTrace.verdictUnconfirmed":"조건 미확인","memoryTrace.verdictUnlisted":"무관\xb7판정 불명","memoryTrace.graphHint":"노드를 가리키거나 포커스하면 전체 글이 여기 나와요.","memoryTrace.legendDocEdited":"열고 편집한 파일","memoryTrace.noticeHarness":"하네스","memoryTrace.noticeResume":"자동 재개","cloudProjects.launch":"GitHub 저장소 열기","cloudProjects.title":"클라우드 프로젝트","cloudProjects.description":"GitHub 저장소를 가져와 이 서버에서 작업을 이어가세요.","cloudProjects.github":"GitHub 저장소","cloudProjects.serverFolder":"서버 폴더 열기","cloudProjects.account":"GitHub 연결","cloudProjects.connectTitle":"내 GitHub 저장소 연결","cloudProjects.connectHelp":"연결하면 비공개 저장소도 목록에서 선택할 수 있습니다.","cloudProjects.connected":"GitHub 연결됨","cloudProjects.refresh":"다시 확인","cloudProjects.waiting":"로그인 대기 중","cloudProjects.connect":"GitHub 연결","cloudProjects.deviceHelp":"아래 코드를 GitHub 로그인 화면에 입력하세요.","cloudProjects.copyCode":"코드 복사","cloudProjects.copied":"복사됨","cloudProjects.copyFailure":"코드를 복사하지 못했습니다. 코드를 선택해 직접 복사하세요.","cloudProjects.openLogin":"GitHub에서 로그인","cloudProjects.permissionHelp":"GitHub에서 계정과 요청 권한을 확인하고 승인하세요. 인증 토큰은 서버에만 저장됩니다.","cloudProjects.preparingCode":"로그인 코드를 준비하고 있습니다.","cloudProjects.repositories":"내 저장소","cloudProjects.search":"저장소 검색","cloudProjects.searchPlaceholder":"이름 또는 설명으로 찾기","cloudProjects.loading":"저장소를 불러오고 있습니다.","cloudProjects.private":"비공개","cloudProjects.public":"공개","cloudProjects.empty":"일치하는 저장소가 없습니다. 다른 이름으로 검색하거나 URL을 입력하세요.","cloudProjects.more":"더 보기","cloudProjects.urlLabel":"선택한 저장소 또는 GitHub URL","cloudProjects.publicHelp":"공개 저장소는 로그인 없이도 가져올 수 있습니다. 이미 가져온 저장소는 변경 없이 다시 엽니다.","cloudProjects.error":"작업을 완료하지 못했습니다.","cloudProjects.openingHelp":"저장소를 서버에 가져오고 있습니다. 크기에 따라 시간이 걸릴 수 있습니다.","cloudProjects.opening":"프로젝트 여는 중","cloudProjects.open":"프로젝트 열기","common.ok":"확인","common.language":"언어","common.models":"모델","common.skills":"스킬","common.plugins":"플러그인","common.settings":"설정","updates.available":"CUELO 업데이트 있음","updates.availableTitle":"CUELO {version} 릴리스가 나왔습니다","updates.dialogEyebrow":"CUELO 릴리스","updates.dialogTitle":"새 CUELO 버전","updates.current":"현재 CUELO {version}","updates.changelog":"변경 사항","updates.viewRelease":"릴리스 보기","updates.manual":"소스에서 실행 중이면 서버를 먼저 멈추고 아래 명령으로 갱신한 뒤 다시 시작하세요. 별도 --home 경로를 사용한다면 setup에도 같은 --home 옵션을 붙이세요.","updates.copyCommand":"명령어 복사","updates.commandCopied":"명령어 복사됨","updates.copyFailed":"명령어를 복사할 수 없습니다","updates.apply":"지금 업데이트","updates.applyBusy":"업데이트 중…","updates.applyConfirm":"CUELO {version}(으)로 업데이트하고 다시 시작할까요?\\n\\n업데이트하는 동안 서버가 잠시 멈추고 이 화면은 진행 상황을 보여 줍니다. 새 버전이 응답하면 자동으로 새로 고칩니다.","updates.applyConfirmBusy":"CUELO {version}(으)로 업데이트하고 다시 시작할까요?\\n\\n실행 중인 세션 {count}개가 중단되고 서버가 잠시 멈춥니다. 이 화면은 진행 상황을 보여 주며, 새 버전이 응답하면 자동으로 새로 고칩니다.","updates.unsupported":"이 설치 방식은 앱에서 바로 바꿀 수 없습니다. 아래 명령을 사용하세요.","updates.unsupportedReason":"감지 결과: {reason}","updates.phase.starting":"업데이트 준비 중","updates.phase.fetching":"새 버전 받는 중","updates.phase.installing":"패키지 설치 중","updates.phase.building":"빌드 중","updates.phase.restarting":"서버 다시 시작 중","updates.phase.done":"업데이트 완료","updates.phase.handed-off":"서비스 갱신으로 넘김","updates.phase.restart-required":"설치 완료 — CUELO를 직접 다시 시작하세요","updates.phase.failed":"업데이트 실패","updates.waitingForRestart":"서버가 다시 시작되기를 기다리고 있습니다. 새 버전이 응답하면 화면을 새로 고칩니다.","updates.handedOff":"WSL 서비스 갱신이 자체 대기 화면에서 진행됩니다. 끝나면 이 화면이 새로 고쳐집니다.","updates.logPath":"로그: {path}","updates.applyStartFailed":"업데이트를 시작하지 못했습니다: {reason}","sidebar.hide":"사이드바 숨기기","sidebar.show":"사이드바 표시","theme.light":"라이트 모드 (클릭하면 다크)","theme.dark":"다크 모드 (클릭하면 시스템)","theme.auto":"시스템 테마 (클릭하면 라이트)","theme.graphite":"흑연 테마 (배경화면)","theme.graphiteHint":"흑연색 화면에 지금 캐릭터 모드의 배경화면을 깝니다. 다크 모드에서만 적용되고 이 브라우저에만 저장됩니다.","history.full":"전체 기록","history.unsaved":"전체 기록은 세션 저장 후 사용할 수 있습니다","history.label":"전체 기록","title.generating":"생성 중...","title.updated":"제목 업데이트됨","title.failed":"생성 실패","title.generate":"제목 생성","title.unsaved":"제목 생성은 세션 저장 후 사용할 수 있습니다","title.noMessages":"세션 이름을 지정하기 전에 메시지를 보내세요","title.generateSession":"세션 제목 생성","system.prompt":"시스템 프롬프트","system.empty":"시스템 프롬프트가 비어 있습니다 (도구 비활성화됨)","system.load":"시스템 프롬프트를 불러오려면 메시지를 보내세요","system.label":"시스템","session.info":"세션 정보","session.name":"이름","session.file":"파일","session.inMemory":"메모리 내","session.id":"ID","session.user":"사용자","session.assistant":"어시스턴트","session.toolCalls":"도구 호출","session.toolResults":"도구 결과","session.total":"합계","session.input":"입력","session.output":"출력","session.cacheRead":"캐시 읽기","session.cacheWrite":"캐시 쓰기","session.cost":"비용","session.context":"컨텍스트","session.copy":"{value} 복사","session.copied":"복사됨","session.title":"세션 정보","session.load":"세션 정보를 불러오려면 메시지를 보내거나 /session을 실행하세요","session.infoSection":"세션 정보","session.messages":"메시지","session.tokens":"Token","session.copyFile":"파일 경로 복사","session.copyId":"세션 ID 복사","session.cacheHitRate":"평균 캐시 적중률","session.totalActive":"활동 시간","workspace.opening":"워크스페이스를 여는 중...","workspace.unable":"워크스페이스를 열 수 없습니다","workspace.selectSession":"사이드바에서 세션을 선택하세요","workspace.getStarted":"시작하기","workspace.selectProject":"사이드바에서 프로젝트 디렉터리를 선택하세요","workspace.addModels":"하단의 모델 버튼으로 모델을 추가하세요","workspace.stepProject":"사이드바에서 프로젝트 디렉터리를 선택하세요","workspace.stepModels":"하단의 모델 버튼으로 모델을 추가하세요","workspace.mainWorking":"작업중","workspace.mainWaiting":"대기중","workspace.mainIdle":"대기","workspace.mainAttention":"입력필요","files.hidePanel":"파일 패널 숨기기","files.showPanel":"파일 패널 표시","files.noneOpen":"열린 파일 없음","files.docs.noProject":"프로젝트를 선택하면 문서 바로가기가 보입니다.","files.docs.loading":"프로젝트 문서를 찾는 중…","files.docs.projectDenied":"이 프로젝트 폴더는 CUELO가 읽을 수 있는 폴더 밖에 있습니다.","files.docs.loadFailed":"프로젝트 문서를 불러오지 못했습니다: {error}","files.docs.projectDir":"프로젝트 폴더: {path}","files.docs.noneFound":"저장소 루트까지 HANDOFF.md가 없고, 이 폴더에 doc/README.md나 doc/history도 없습니다.","files.docs.current":"현재 상태","files.docs.map":"문서 지도","files.docs.records":"최근 기록","files.docs.missing":"{file} 없음","files.docs.denied":"{file}은(는) 읽기 허용 폴더 밖에 있습니다","layout.resizeSidebar":"사이드바 크기 조절","layout.resizeFilePanel":"파일 패널 크기 조절","layout.resizeHint":"드래그하여 크기를 조절합니다. 더블 클릭 또는 Enter 키로 초기화합니다.","sidebar.new":"새로 만들기","sidebar.newSessionTitle":"{path}에서 새 세션","sidebar.refresh":"새로고침","sidebar.projects":"프로젝트","subagents.title":"서브 Agent","subagents.running":"실행 중","subagents.finished":"완료됨","subagents.history":"기록","subagents.runningCount":"{count}개 실행 중","subagents.finishedCount":"{count}개 완료됨","subagents.failed":"실패","subagents.aborted":"중단됨","subagents.back":"서브 Agent 목록으로 돌아가기","subagents.retrying":"재시도 중 {attempt}/{max}","subagents.usingTool":"{tool} 사용 중","subagents.details":"서브 Agent 실행 상세","subagents.closeDetails":"서브 Agent 상세 닫기","subagents.noTask":"작업 설명 없음","subagents.tools":"도구 {count}개","subagents.tokens":"{count} Token","subagents.loadingTranscript":"실시간 기록을 불러오는 중…","subagents.noTranscript":"서브 Agent가 아직 기록 메시지를 작성하지 않았습니다.","subagents.transcriptUnavailable":"실시간 기록을 아직 사용할 수 없습니다. 서브 Agent가 실행되는 동안 재시도합니다.","sidebar.searchProjectsAndSessions":"프로젝트 및 세션 제목 검색…","sidebar.addProject":"사용자 지정 프로젝트 경로 추가","sidebar.projectActions":"프로젝트 작업","sidebar.projectAlias":"별칭","sidebar.projectAliasEdit":"별칭 편집","sidebar.projectHide":"숨기기","sidebar.projectUnhide":"숨김 해제","sidebar.projectShowHidden":"숨긴 프로젝트 표시","sidebar.temporaryProjects":"임시\xb7시스템 경로","sidebar.projectMoveUp":"위로 이동","sidebar.projectMoveDown":"아래로 이동","sidebar.projectMoveDisabledWhileFiltering":"프로젝트 순서를 변경하려면 검색 필터를 지우세요","sidebar.projectUpdateFailed":"프로젝트 변경 사항을 저장할 수 없습니다. 다시 시도하세요.","sidebar.expandProject":"프로젝트 펼치기","sidebar.collapseProject":"프로젝트 접기","sidebar.showMore":"더 보기","sidebar.showLess":"간략히 보기","sidebar.selectProject":"프로젝트 선택…","sidebar.filterProjects":"프로젝트 필터…","sidebar.noMatchingProjects":"일치하는 프로젝트 없음","sidebar.useDefaultDirectory":"기본 디렉터리 사용","sidebar.customPath":"사용자 지정 경로…","directoryPicker.selectDirectory":"디렉터리 선택","directoryPicker.goToParent":"상위 디렉터리로 이동","directoryPicker.directoryPath":"디렉터리 경로","directoryPicker.goToDirectory":"디렉터리로 이동","directoryPicker.go":"이동","directoryPicker.loadingDirectories":"디렉터리를 불러오는 중…","directoryPicker.noSubdirectories":"하위 디렉터리 없음","directoryPicker.openBeforeSelecting":"선택하기 전에 이 경로를 엽니다","directoryPicker.selectCurrentDirectory":"현재 디렉터리 선택","directoryPicker.selectThisFolder":"이 폴더 선택","directoryPicker.noDrives":"드라이브를 찾을 수 없음","sidebar.checking":"확인 중…","sidebar.open":"열기","sidebar.cancel":"취소","sidebar.openRepoRoot":"저장소 루트 열기","sidebar.openRepoRootTitle":"worktree를 관리하려면 저장소 루트를 여세요.","sidebar.gitRepoRootOnly":"Git 저장소 루트 전용","sidebar.gitRepoRootOnlyTitle":"worktree는 Git 저장소 루트에서만 사용할 수 있습니다.","sidebar.worktrees":"Worktree...","sidebar.checkingWorktrees":"이 디렉터리의 worktree를 확인합니다.","sidebar.filterWorktrees":"worktree 필터…","sidebar.noMatchingWorktrees":"일치하는 worktree 없음","sidebar.switchWorktree":"worktree 전환","sidebar.switchWorktreeTitle":"worktree 전환: {path}","sidebar.main":"main","sidebar.forceRemoveCheckout":"커밋되지 않은 변경 사항이 있습니다. 체크아웃을 강제로 제거할까요?","sidebar.force":"강제","sidebar.createWorktreeTitle":"Branch에 대한 worktree 체크아웃을 생성합니다","sidebar.newWorktree":"새 worktree…","sidebar.branchName":"Branch 이름","sidebar.creating":"생성 중…","sidebar.create":"생성","sidebar.loading":"불러오는 중...","sidebar.noSessions":"세션 없음","sidebar.agentRunning":"Agent 실행 중…","sidebar.newActivity":"새 활동","sidebar.newSessionActivity":"새 세션 활동","sidebar.deleteSession":"{title}을(를) 삭제할까요?","sidebar.rename":"이름 변경","sidebar.pin":"맨 위에 고정","sidebar.unpin":"고정 해제","sidebar.pinned":"고정됨","sidebar.delete":"삭제","sidebar.deleteWithShiftClick":"삭제 (Shift+클릭으로 확인 없이 삭제)","sidebar.clearProjectSessions":"세션 비우기","sidebar.clearPriorityList":"목록 비우기","navigator.resultsToCheck":"확인할 결과","navigator.resultsToCheckCount":"확인할 결과 {count}","navigator.resultsToCheckHint":"이 브라우저에서 마지막으로 연 뒤 새로 끝난 대화와, 답을 기다리는 대화","navigator.resultsToCheckEmpty":"확인할 결과가 없습니다.","navigator.acknowledgeResults":"모두 확인","navigator.acknowledgeResultsHint":"지금 확인할 결과로 보이는 대화를 모두 본 것으로 표시합니다. 답을 기다리는 대화는 남습니다.","sidebar.waitingForAnswer":"답 기다림","sidebar.waitingForAnswerHint":"질문이나 승인 요청에 답할 때까지 멈춰 있습니다","sidebar.newScratchSession":"새 세션","sidebar.newScratchSessionTitle":"프로젝트 없이 세션 시작 (홈 폴더의 날짜별 임시 폴더)","sidebar.newScratchSessionFailed":"임시 폴더를 만들지 못했습니다: {error}","sidebar.clearSessionsTitle":"세션 삭제 확인","sidebar.clearSessionsProjectBody":"{project} 프로젝트의 세션 {count}개를 영구 삭제합니다. 되돌릴 수 없습니다.","sidebar.clearSessionsPriorityBody":"우선순위 목록의 세션 {count}개를 영구 삭제합니다. 되돌릴 수 없습니다.","sidebar.clearSessionsRunningExcluded":"실행 중인 세션 {count}개는 삭제하지 않습니다.","sidebar.clearSessionsNone":"지금 삭제할 수 있는 세션이 없습니다.","sidebar.clearSessionsConfirm":"삭제","sidebar.clearSessionsCancel":"취소","sidebar.clearSessionsBusy":"삭제 중…","sidebar.clearSessionsFailed":"{count}개 세션을 삭제하지 못했습니다: {names}","sidebar.archive":"보관 (목록에서 숨김, 복원 가능)","sidebar.archived":"보관됨","sidebar.restore":"복원","sidebar.noArchivedSessions":"보관된 세션 없음","sidebar.expandForks":"Fork 펼치기","sidebar.collapseForks":"Fork 접기","sidebar.messagesCount":"메시지 {count}개","sidebar.worktreePath":"Worktree: {path}","sidebar.removeWorktreeTitle":"worktree 체크아웃 {path}을(를) 제거합니다. Branch는 유지됩니다","files.deleted":"삭제됨","files.insertPath":"채팅에 경로 삽입","files.mention":"멘션","chat.loadingSession":"세션 불러오는 중...","chat.runningTool":"도구 실행 중...","chat.runningNamedTool":"{name} 실행 중...","chat.runningTools":"{names} 실행 중...","chat.runningToolsMore":"{names} (+{count}) 실행 중...","chat.waitingModel":"모델 응답 대기 중...","todo.progress":"{percent}% \xb7 {total}개 중 {completed}개 완료 \xb7 {remaining}개 남음","todo.progressDone":"{percent}% \xb7 {total}개 중 {completed}개 완료","todo.allDone":"{count}개 모두 완료","todo.showCompleted":"완료 {count}개 보기","todo.hideCompleted":"완료 {count}개 접기","todo.ready":"지금 가능","todo.waiting":"선행 대기: {tasks}","chat.runningCommand":"명령 실행 중...","chat.thinking":"생각 중...","chat.contextUsageTitle":"컨텍스트 윈도우: {limit} Token 중 {used} 사용 ({percent})","chat.contextUsageWarning":"컨텍스트 윈도우가 거의 차고 있습니다","chat.contextUsageCritical":"컨텍스트 윈도우가 거의 가득 찼습니다","chat.processDetails":"프로세스 상세","chat.message":"메시지","chat.messages":"메시지","chat.toolCall":"도구 호출","chat.toolCalls":"도구 호출","chat.collapseProcess":"프로세스 상세 접기","chat.expandProcess":"프로세스 상세 펼치기","process.empty":"이 세션에는 아직 작업 과정 기록이 없습니다","process.turn":"턴","process.turns":"턴","chat.loadEarlier":"위로 스크롤하면 이전 메시지를 불러옵니다 ({count}개 숨김)","chat.extensionRequest":"확장 요청","chat.responseSending":"응답을 보내는 중...","chat.responseFailed":"응답이 Agent에 전달되지 않았습니다. 아직 기다리는 중이니 다시 시도하세요.","chat.cancel":"취소","chat.confirm":"확인","chat.submit":"제출","chat.agentQuestion":"Agent가 입력을 기다립니다","chat.agentQuestionHint":"옵션을 선택하거나 직접 응답을 입력하세요.","chat.askAutoSelectHint":"{seconds}초 동안 응답이 없으면 추천안으로 자동 선택합니다. 선택하거나 입력하면 대기 시간이 다시 시작됩니다.","chat.recommended":"추천","chat.customAnswer":"기타 응답 (선택)","chat.chatAboutThis":"이것에 대해 대화","chat.submitAnswer":"답변 제출","chat.agentFormHint":"양식을 채워 제출하세요.","chat.askFormAutoSubmitHint":"{seconds}초 동안 응답이 없으면 지금 입력된 값을 그대로 제출합니다. 입력하면 대기 시간이 다시 시작됩니다.","chat.formOther":"기타","chat.formOtherPlaceholder":"직접 입력","chat.formRequired":"필수","chat.formInvalid":"표시된 항목을 확인한 뒤 제출하세요.","chat.formImageUnavailable":"이미지를 불러오지 못했습니다","chat.formError.required":"필수 항목입니다","chat.formError.selectAtLeastOne":"하나 이상 선택하세요","chat.formError.enterNumber":"숫자를 입력하세요","chat.formError.min":"{value} 이상이어야 합니다","chat.formError.max":"{value} 이하여야 합니다","chat.formError.minLength":"{value}자 이상 입력하세요","chat.formError.maxLength":"{value}자 이하로 입력하세요","chat.formError.email":"이메일 주소를 입력하세요","chat.formError.url":"전체 URL을 입력하세요","chat.formError.pattern":"형식이 맞지 않습니다 ({pattern})","chat.planApproval":"계획 승인","chat.planFeedback":"추가 계획 수립을 위한 피드백 (선택)","chat.refinePlan":"계획 계속하기","chat.approvePlan":"승인 후 구현","chat.extensionInput":"확장 터미널 입력","chat.extensionPanel":"확장 패널","chat.close":"닫기","chat.queued":"대기 중 \xb7 {count}","chat.recall":"입력창으로 되돌리기","chat.recallTitle":"대기 중인 메시지를 모두 제거하고 편집할 수 있도록 입력창에 다시 넣습니다","chat.queueRemove":"이 대기 메시지만 취소","chat.retrying":"재시도 중 ({attempt}/{max})…","chat.loadingCommands":"명령 불러오는 중...","chat.slashCommands":"슬래시 명령 \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"명령이 없습니다","chat.match":"일치 1개","chat.matches":"일치 {count}개","chat.command":"명령 1개","chat.commands":"명령 {count}개","chat.loadingFiles":"파일 불러오는 중...","chat.files":"파일 \xb7 {label}{hint}","chat.searching":"검색 중…","chat.noMatchingFiles":"일치하는 파일 없음","chat.searchingAll":" \xb7 전체 파일 검색 중…","chat.indexTruncated":" \xb7 인덱스 일부 생략됨","chat.steerPlaceholder":"지금 지시하거나 후속 메시지를 대기열에 추가하세요...","chat.agentPlaceholder":"Agent 실행 중…","chat.messagePlaceholder":"메시지 입력… / 명령어 \xb7 @ 파일","chat.steer":"지시","chat.followUp":"후속 메시지","chat.send":"보내기","chat.attachImageLimit":"메시지 하나에 이미지를 최대 {count}개까지 첨부할 수 있습니다.","chat.attachImageTooLarge":"{name} 파일이 이미지당 {limit} 제한을 초과합니다.","chat.attachFile":"파일 첨부","chat.emptyProjectLabel":"작업 폴더","chat.emptyProjectHint":"첫 메시지를 보내면 이 폴더에서 새 세션이 시작됩니다.","chat.openSessionList":"세션 목록 열기","chat.attachments":"첨부 파일","chat.removeImage":"이미지 {index} 제거","chat.removeAttachment":"{name} 제거","chat.attachExtracting":"텍스트 추출 중","chat.attachExtractingWait":"첨부 파일 처리가 끝날 때까지 기다려 주세요","chat.attachLimit":"메시지 하나에 이미지를 제외한 첨부 파일을 최대 {count}개까지 넣을 수 있습니다.","chat.attachTooLarge":"{name} 파일이 문서당 {limit} 제한을 초과합니다.","chat.attachTotalTooLarge":"첨부 문서의 합계가 {limit} 제한을 초과합니다.","chat.attachTextTooLarge":"{name}에서 추출한 텍스트가 {limit}자 제한을 초과합니다.","chat.attachTooManyPages":"{name} 파일이 PDF {limit}페이지 제한을 초과합니다.","chat.attachNoPdfText":"{name}에서 추출할 수 있는 텍스트가 없습니다. 스캔 또는 이미지 전용 PDF에 필요한 OCR은 지원하지 않습니다.","chat.attachPasswordProtected":"{name}은(는) 암호로 보호되어 텍스트를 추출할 수 없습니다.","chat.attachExtractFailed":"{name}에서 텍스트를 추출하지 못했습니다.","chat.attachKindAudio":"음성","chat.attachKindFile":"파일","chat.attachUploading":"저장 중","chat.attachTranscribing":"받아쓰기 중","chat.attachTranscribeFailed":"받아쓰기 실패","chat.attachStoredTooLarge":"{name} 파일이 파일당 {limit} 제한을 초과합니다.","chat.attachUploadFailed":"{name} 파일을 저장하지 못했습니다: {error}","chat.attachTranscribePending":"선택 필요","chat.transcribeGroup":"음성 받아쓰기","chat.transcribeChecking":"길이 확인 중","chat.transcribeConfirmTitle":"{name} 받아쓰기를 시작할까요?","chat.transcribePlanSummary":"{duration} \xb7 받아쓰기 호출 약 {calls}회","chat.transcribeDurationUnknown":"길이 알 수 없음","chat.transcribeUsageNotice":"받아쓰기는 연결된 계정의 사용량에 포함됩니다. 시작을 누르기 전에는 아무것도 보내지 않습니다.","chat.transcribeStart":"받아쓰기 시작","chat.transcribeSkip":"받아쓰지 않기","chat.transcribeCancel":"받아쓰기 취소","chat.transcribeRunning":"{name} 받아쓰는 중","chat.transcribeRetry":"다시 시도","chat.transcribeAction":"받아쓰기","chat.transcribeSkipped":"{name}은(는) 받아쓰지 않고 저장된 파일 경로만 보냅니다.","chat.transcribeFailedRow":"{name} 받아쓰기 실패: {error}","chat.transcribeToolMissing":"음성 도구(ffmpeg)를 쓸 수 없어 이 음성을 받아쓰기용으로 준비하지 못했습니다.","chat.transcribePartialFailed":"{total}조각 중 {done}조각까지 처리하고 멈췄습니다. 일부 결과는 붙이지 않았습니다.","chat.transcribeTooLong":"받아쓴 내용이 다른 첨부와 합친 글자 수 제한을 넘습니다.","chat.transcribeFallbackTitle":"{name} 기본 받아쓰기에 실패했습니다. ChatGPT/Codex로 이어서 받아쓸까요?","chat.transcribeFallbackProgress":"{total}조각 중 {done}조각은 이미 받아써서 그대로 둡니다. 실패한 조각과 남은 조각만 보냅니다.","chat.transcribeFallbackUsageNotice":"ChatGPT/Codex는 기본 받아쓰기와 다른 제공자이며, 로그인한 계정의 사용량에 포함됩니다. ChatGPT/Codex로 받아쓰기를 누르기 전에는 아무것도 보내지 않습니다.","chat.transcribeFallbackStart":"ChatGPT/Codex로 받아쓰기","chat.transcribeFallbackExpired":"이 선택은 만료됐거나 이미 사용됐습니다. 아무것도 보내지 않았습니다. 다시 시도하면 기본 받아쓰기부터 시작합니다.","chat.attachmentSettingsNav":"첨부 파일","chat.attachmentSettingsTitle":"첨부 파일","chat.attachmentSettingsDescription":"대화에 첨부한 파일은 에이전트가 열 수 있도록 이 컴퓨터에 저장됩니다.","chat.attachmentSettingsLoadFailed":"첨부 설정을 불러오지 못했습니다","chat.attachmentUploadLimit":"파일당 업로드 한도(MB)","chat.attachmentUploadLimitHelp":"이보다 큰 파일은 보내기 전에 거절합니다. 메시지에 바로 읽어 넣는 텍스트는 따로 문서당 8MB, 합계 240,000자 한도를 지킵니다.","chat.attachmentUploadLimitInvalid":"1 이상의 정수(MB)를 입력하세요.","chat.attachmentAutoCleanup":"쓰이지 않는 첨부 자동 삭제","chat.attachmentAutoCleanupHelp":"대화\xb7분기\xb7보내지 않은 초안에서 쓰이는 첨부는 지우지 않습니다. 어디에서도 쓰이지 않는다고 확인된 때부터 {days}일이 지나면 삭제하고, 쓰임을 확인할 수 없는 파일은 남겨 둡니다.","chat.attachmentSettingsSaved":"저장했습니다","characterMode.nav":"캐릭터","characterMode.title":"캐릭터","characterMode.description":"화면에 보이는 캐릭터의 얼굴\xb7이름\xb7스티커\xb7완료 음성을 고릅니다.","characterMode.label":"캐릭터 세트","characterMode.default":"기본","characterMode.office":"사무실 모드","characterMode.help":"이 PC의 서버 전체에 적용됩니다. 사무실 모드에서는 이 PC 프로필에 등록된 캐릭터가 해당 자리의 얼굴\xb7이름\xb7말투\xb7스티커\xb7음성을 대신합니다. 등록되지 않은 자리는 그대로입니다.","characterMode.noRoster":"이 PC에는 사무실 캐릭터 세트가 없어 기본 캐릭터가 그대로 쓰입니다.","characterMode.saved":"저장했습니다","chat.steerTitle":"현재 실행을 중단하고 이 메시지를 바로 전달합니다","chat.followUpTitle":"Agent가 끝난 후 이 메시지를 전달하도록 대기열에 추가합니다","chat.filterModels":"모델 필터…","chat.noMatchingModels":"일치하는 모델 없음","chat.modelRoles":"역할","chat.allModels":"전체 모델","chat.mainPreset":"Main 프리셋","roles.title":"모델 역할","roles.description":"omp는 하나의 현재 모델이 아니라 역할별로 작업을 라우팅합니다. 각 역할에 모델을 지정하면 CUELO과 omp CLI 모두에서 사용됩니다.","roles.scope":"저장 위치","roles.scopeGlobal":"전역","roles.scopeProject":"이 프로젝트","roles.unset":"— 미설정 —","roles.needsProject":"모델 역할을 편집하려면 프로젝트를 여세요.","roles.source.global":"전역 설정에서","roles.source.project":"프로젝트 설정에서","roles.source.default":"omp 기본값","roles.thinking":"Thinking","roles.thinkingInherit":"설정된 기본 thinking 수준 사용","roles.harnessNote":"CUELO Maker\xb7도구 역할 자리는 지정하기 전에도 목록에 표시됩니다. 쓸 자리만 직접 모델을 고르세요. 저장해도 로그인하거나 모델을 시험 호출하지 않습니다.","roles.harnessUnset":"미설정","roles.harness.implSol":"Maker \xb7 방향이 정해진 코드 (NORMAL\xb7HARD 우선)","roles.harness.implSonnet":"Maker \xb7 NORMAL 비-UI 대안","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL 배경 작업\xb7대안","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD 코드 (열린 설계\xb7재작업)","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD 코드 대안","roles.harness.crossReviewOpenAI":"교차검수 \xb7 OpenAI 필수 검토 (openai / openai-codex)","roles.harness.crossReviewAnthropic":"교차검수 \xb7 Anthropic 필수 검토 (anthropic)","roles.harness.crossReviewAdvisory":"교차검수 \xb7 보조 검토, 기다리지 않음 (제공자 무관)","roles.harness.skim":"도구 \xb7 다중 파일 소스 읽기 (skim)","roles.harness.draft":"도구 \xb7 문서 초안 작성 (draft)","roles.harness.ocr":"도구 \xb7 이미지 글자 전사 (ocr)","roles.harness.interpreter":"도구 \xb7 한영 통역 (interpreter)","chat.moreControls":"실행 옵션","chat.collapseControls":"실행 옵션 닫기","chat.shell":"Shell","chat.outputLocal":"출력은 로컬에만 유지","chat.outputModel":"출력을 모델로 전송","chat.noTools":"도구 없음, 읽기 전용","chat.builtInTools":"코어: {tools} \xb7 그 외 등록된 도구는 계속 활성화됨","chat.allBuiltInTools":"코어: {tools} \xb7 그 외 등록된 도구는 계속 활성화됨","chat.changeReasoning":"추론 수준 변경: {level}","chat.changeReasoningLabel":"추론 수준 변경","chat.currentReasoning":"현재 추론 강도: {level}","chat.outputSpeed":"{rate} tok/s","chat.outputSpeedTitle":"마지막 답변의 출력 속도(초당 출력 토큰, 요청 시작부터 생성 끝까지 기준)","chat.outputSpeedLive":"~{rate} tok/s","chat.outputSpeedLiveTitle":"지금 답변의 출력 속도 추정(받은 글자를 토큰으로 어림, 요청 시작부터 지금까지 기준). 답변이 끝나면 실제 토큰 수로 바뀝니다","chat.fastModeActive":"Fast 켜짐 \xb7 이 모델에 적용 중. 우선 처리라 요금\xb7사용량이 더 들 수 있습니다. 누르면 끕니다","chat.fastModeInactive":"Fast 요청됨 \xb7 이 모델\xb7계정에는 적용되지 않음. 누르면 끕니다","chat.fastModeOff":"Fast 꺼짐 \xb7 누르면 우선 처리를 요청합니다(provider에 따라 요금\xb7사용량이 더 듭니다)","chat.fastModeUnknown":"Fast 상태 확인 전 \xb7 누르면 이 세션의 실제 상태를 읽고 바꿉니다","chat.fastModeBusy":"Fast 바꾸는 중","chat.changeToolPreset":"도구 프리셋 변경","chat.stopCompaction":"압축 중지","chat.compactContext":"컨텍스트 압축","chat.compacting":"압축 중…","chat.compact":"Compact","chat.stopAgent":"Agent 중지","chat.stop":"중지","chat.liveVoice":"라이브 음성","chat.liveStart":"라이브 음성 시작","chat.liveStop":"라이브 음성 종료","chat.liveConnecting":"연결 중","chat.liveOn":"통화 중","chat.liveWorking":"작업 수행 중","chat.liveUnsupported":"이 브라우저에서는 라이브 통화를 할 수 없습니다","chat.liveMicDenied":"마이크 권한이 거부됐습니다","chat.liveMicUnavailable":"사용할 수 있는 마이크가 없습니다","chat.liveAuthRequired":"라이브 음성을 쓰려면 Codex 로그인이 필요합니다","chat.liveUpstreamFailed":"Codex가 라이브 통화를 거부했습니다","chat.liveFailed":"라이브 통화를 시작하지 못했습니다","chat.liveNeedsSession":"먼저 폴더를 선택하세요 — 라이브 통화는 이 대화의 에이전트로 말합니다","chat.liveVoiceSettingsNav":"통화 음성","chat.liveVoiceSettingsTitle":"통화 음성","chat.liveVoiceSettingsDescription":"라이브 통화와 통역 통화에서 말할 Codex 목소리와 말 빠르기를 고릅니다. 선택은 다음 통화부터 적용됩니다.","chat.liveVoiceSpeakerGroup":"목소리","chat.liveVoiceCodexLabel":"Codex 목소리","chat.liveVoiceCodexHelp":"라이브 통화와 통역 통화에서 이 목소리로 말합니다.","chat.livePaceLabel":"말 빠르기","chat.livePaceHelp":"천천히를 고르면 또박또박 느리게 말합니다.","chat.livePaceNormal":"보통","chat.livePaceSlow":"천천히","chat.liveVoiceLoadFailed":"음성 설정을 불러오지 못했습니다","chat.disableSound":"완료 알림음 끄기","chat.enableSound":"완료 알림음 켜기","chat.thinkingAuto":"추론 강도 자동 선택","chat.thinkingAutoCapped":"자동 선택, 최대 {level}","chat.thinkingOff":"추론 끔","chat.thinkingMinimal":"최소 추론","chat.thinkingLow":"낮은 추론","chat.thinkingMedium":"중간 추론","chat.thinkingHigh":"높은 추론","chat.thinkingXhigh":"매우 높은 추론","chat.thinkingMax":"최대 추론","chat.builtIn":"기본 제공","chat.extensions":"확장","chat.customCommands":"사용자 지정 명령어","chat.mcpPrompts":"MCP 프롬프트","chat.prompts":"프롬프트","chat.fileCommands":"명령어 파일","chat.skills":"Skill","chat.dormant":"휴면","chat.commandCompact":"컨텍스트를 압축합니다. 선택적으로 지침을 지정할 수 있습니다","chat.commandReload":"확장, Skill, 프롬프트, 도구를 다시 불러옵니다","chat.commandName":"세션 표시 이름을 설정합니다","chat.commandSession":"세션의 메시지, Token, 비용 통계를 표시합니다","chat.commandCopy":"마지막 어시스턴트 메시지를 복사합니다","chat.goalLabel":"목표","chat.goalPaused":"일시정지됨","chat.goalBudgetLeft":"{left} 남음","chat.goalTokensUsed":"{used} 사용","chat.jumpToBottom":"맨 아래로 이동","chat.loadLater":"아래로 스크롤하면 이후 메시지를 불러옵니다 ({count}개 남음)","chat.jumpMissing":"이 메시지는 지금 대화 화면에 없습니다(다른 분기이거나 압축된 기록).","chat.questionRail":"내 질문","chat.searchPlaceholder":"대화에서 찾기","chat.searchNoResults":"결과 없음","chat.searchCount":"{index}/{total}","chat.searchPrevious":"이전 결과","chat.searchNext":"다음 결과","chat.searchClose":"찾기 닫기","chat.compactionLabel":"압축","chat.compactionProgress":"컨텍스트 압축 중 \xb7 {seconds}초","chat.compactionReason.manual":"수동","chat.compactionReason.threshold":"임계치","chat.compactionReason.overflow":"초과","chat.compactionReason.idle":"유휴","chat.compactionReason.incomplete":"미완료","chat.compactedFrom":"{tokens} 토큰에서 압축됨","chat.interruptedTitle":"지난 실행이 중단됐어요","chat.interruptedDetail":"서버나 PC가 꺼지는 등으로 실행 도중 멈췄습니다. 자동으로 이어지지 않으면 메시지를 보내 계속할 수 있어요.","chat.interruptedDismiss":"닫기","chat.frequentModels":"자주 쓰는 모델","chat.modelPickCount":"{count}회","palette.searchPlaceholder":"대화 내용 검색","palette.searchResults":"대화 검색 결과","palette.searching":"검색 중…","palette.searchFailed":"검색하지 못했습니다","palette.searchEmpty":"일치하는 메시지가 없습니다","palette.searchHits":"메시지 {count}개","palette.searchTruncated.time":"시간 한도로 세션 {total}개 중 {scanned}개까지만 검색","palette.searchTruncated.bytes":"크기 한도로 세션 {total}개 중 {scanned}개까지만 검색","palette.searchTruncated.results":"앞쪽 결과만 표시 중 \xb7 검색어를 좁혀 보세요","palette.searchCompacted":"압축된 기록의 {count}개는 제외","palette.searchRoleUser":"내 질문","palette.searchRoleAssistant":"답변","palette.wideChatOn":"넓은 대화 폭 사용","palette.wideChatOff":"기본 대화 폭 사용","chat.compacted":"압축됨","chat.tokensSaved":"{saved} 절약","chat.filesWritten":"변경된 파일","chat.openWrittenFile":"{name} 열기","chat.lessonsSaved":"[교훈 저장] 이번 턴에 에이전트가 직접 저장했습니다.","chat.savedLesson":"교훈: {memory}","chat.savedSkill":"스킬 {action}: {name}","i18n.close":"닫기","i18n.copy":"복사","i18n.copied":"복사됨","i18n.cancel":"취소","i18n.save":"저장","i18n.saving":"저장 중…","i18n.saved":"저장됨","i18n.remove":"제거","i18n.removing":"제거 중…","i18n.delete":"삭제","i18n.loading":"불러오는 중...","i18n.search":"검색","i18n.refresh":"새로고침","i18n.update":"업데이트","i18n.updating":"업데이트 중...","restart.title":"CUELO 재시작 중","restart.body":"서버가 돌아오면 이 페이지가 자동으로 새로고침됩니다.","restart.slow":"재시작이 2분 넘게 끝나지 않았습니다. 서버 PC의 %USERPROFILE%\\\\.omp\\\\restart-ompweb.log에서 READY/FAILED를 확인하세요. 서버가 돌아오면 이 페이지는 그대로 새로고침됩니다.","restart.returnedTitle":"CUELO 재시작 완료","restart.returnedBody":"서버가 돌아와 이 탭을 같은 대화로 다시 연결했습니다.","restart.returnedDismiss":"재시작 알림 닫기","i18n.check":"확인","i18n.checking":"확인 중...","i18n.install":"설치","i18n.installing":"설치 중...","i18n.noResults":"결과 없음","i18n.searchProviders":"Provider 검색…","i18n.noProviders":"일치하는 Provider 없음","i18n.newModel":"새 모델","i18n.addProvider":"Provider 추가","i18n.selectProviderModel":"Provider 또는 모델을 선택하세요","i18n.visibleInPrompt":"모델 프롬프트에 표시됨 — 클릭하여 비활성화","i18n.hiddenFromPrompt":"모델 프롬프트에서 숨겨짐 — 클릭하여 활성화","i18n.dormant":"휴면","i18n.hiddenButInvocable":"모델에서 숨겨졌지만 수동 호출은 가능합니다","i18n.skillSearchPlaceholder":"예: react, testing, deploy","i18n.searching":"검색 중…","i18n.noSkills":"Skill을 찾을 수 없음","i18n.checkUpdates":"업데이트 확인","i18n.updates":"업데이트","i18n.noResolvedResources":"확인된 리소스 없음","i18n.enablePackage":"패키지 활성화","i18n.disablePackage":"패키지 비활성화","i18n.filtered":"필터링됨","i18n.openSessionToReload":"다시 불러오려면 세션을 여세요","i18n.notFound":"찾을 수 없음","i18n.noPlugins":"구성된 Plugin 없음","trust.resourcesNotLoaded":"제한 모드","trust.trustProject":"프로젝트 신뢰","computerTakeover.allow":"가로채기 허용","computerTakeover.active":"가로채기 허용 중","computerTakeover.allowHint":"이 세션에서만 화면 가로채기를 허용합니다. 끄거나 세션이 닫히면 다시 거부로 돌아갑니다.","computerTakeover.activeHint":"이 세션은 화면 가로채기가 허용된 상태입니다. 누르면 끕니다.","computerTakeover.shared":"서버와 같은 폴더에서 연 세션은 따로 허용할 수 없습니다.","computerTakeover.failed":"가로채기 설정을 바꾸지 못했습니다: {error}","trust.trusting":"신뢰 처리 중...","trust.cancel":"취소","trust.dialogTitle":"이 프로젝트를 신뢰하시겠습니까?","trust.dialogBody":"프로젝트 리소스는 로컬 코드를 실행할 수 있습니다. 내용을 알고 있는 프로젝트만 신뢰하세요.","trust.skillsNotLoaded":"이 프로젝트가 신뢰되지 않아 프로젝트 Skill이 로드되지 않았습니다.","trust.pluginsNotLoaded":"이 프로젝트가 신뢰되지 않아 프로젝트 Plugin이 로드되지 않았습니다.","trust.projectScopeUnavailable":"프로젝트 리소스가 로드되지 않은 동안에는 프로젝트 설치를 사용할 수 없습니다.","trust.pendingBadge":"제한 모드 \xb7 신뢰 예약됨","trust.scheduledTitle":"신뢰가 예약됐습니다","trust.scheduledBody":"이 프로젝트는 아직 제한 모드입니다. 이 프로젝트의 모든 세션이 지금 하는 작업을 마치면 신뢰가 적용되며, 실행 중인 작업은 중단되지 않습니다.","trust.cancelSchedule":"예약 취소","trust.close":"닫기","trust.applyFailed":"예약한 신뢰를 적용하지 못해 프로젝트는 계속 제한 모드입니다: {error}. 다시 시도하려면 다시 신뢰하세요.","trust.settingsNav":"프로젝트 신뢰","trust.settingsDescription":"자체 확장\xb7hook\xb7도구\xb7MCP 서버가 있는 프로젝트는 신뢰한 뒤에만 그 코드를 불러옵니다. 세션이 작업 중일 때 바꾼 설정은 그 프로젝트의 모든 세션이 idle이 되면 적용되며, 실행 중인 작업은 중단되지 않습니다.","trust.settingsEmpty":"아직 신뢰 결정이 필요한 프로젝트가 없습니다.","trust.loadFailed":"프로젝트 신뢰 상태를 불러오지 못했습니다: {error}","trust.stateTrusted":"신뢰됨","trust.stateRestricted":"제한 모드","trust.stateNotRequired":"신뢰가 필요한 프로젝트 코드 없음","trust.pendingGrant":"신뢰를 승인했지만 아직 적용 전입니다. 세션들이 작업을 마칠 때까지 제한 모드가 유지됩니다.","trust.pendingRevoke":"신뢰 해제는 이미 저장됐습니다. 실행 중인 세션 {count}개가 아직 프로젝트 코드를 쓰고 있으며, 지금 작업이 끝나면 제한 모드로 다시 시작합니다.","trust.runtime":"실행 세션 {sessions} \xb7 작업 중 {running} \xb7 프로젝트 코드 로드 {loaded}","trust.revoke":"신뢰 해제","trust.trustAgain":"다시 신뢰","trust.confirm":"확인","trust.working":"저장 중…","trust.confirmGrant":"이 프로젝트를 신뢰할까요? 프로젝트의 확장\xb7hook\xb7도구\xb7MCP 서버가 이 컴퓨터에서 실행될 수 있습니다.","trust.confirmTrustAgain":"해제를 되돌리는 것은 새 신뢰 승인입니다. 프로젝트의 확장\xb7hook\xb7도구\xb7MCP 서버가 이 컴퓨터에서 실행될 수 있습니다.","trust.confirmRevoke":"신뢰를 해제할까요? 새 세션은 바로 제한 모드로 시작하고, 실행 중인 세션은 지금 작업을 마친 뒤 적용됩니다.","trust.doneApplied":"적용했습니다. 이 프로젝트의 세션은 이제 이 설정으로 시작합니다.","trust.doneCancelled":"예약을 취소했습니다. 프로젝트는 계속 제한 모드입니다.","trust.refresh":"새로고침","i18n.creatingSession":"새 세션 생성 중…","i18n.creating":"생성 중…","i18n.subscription":"구독","i18n.subscriptions":"구독 목록","i18n.customEndpoint":"사용자 지정 엔드포인트 형식","i18n.noChanges":"변경 사항 없음","i18n.branches":"Branch 목록","i18n.noActiveSession":"활성 세션 없음","i18n.noBranches":"이 세션에는 Branch가 없습니다","i18n.source":"소스","i18n.preview":"미리보기","i18n.diff":"Diff","i18n.downloadFile":"파일 다운로드","i18n.liveSync":"실시간 동기화 활성","i18n.notWatching":"감시 안 함","i18n.fileViewMode":"파일 보기 모드","i18n.compareHead":"작업 트리를 HEAD와 비교","i18n.mentionSelectedLines":"선택한 줄 멘션","i18n.disableWrap":"자동 줄바꿈 끄기","i18n.enableWrap":"자동 줄바꿈 켜기","i18n.htmlPreview":"HTML 미리보기","i18n.previewFile":"{file} 미리보기","i18n.invalidMermaid":"잘못된 Mermaid 다이어그램","i18n.renderingMermaid":"Mermaid 다이어그램 렌더링 중","i18n.previewAfterStreaming":"스트리밍 완료 후 미리보기 가능","i18n.showMermaidSource":"Mermaid 소스 보기","i18n.previewMermaid":"Mermaid 다이어그램 미리보기","i18n.openMermaidViewer":"다이어그램 뷰어 열기","i18n.mermaidViewer":"Mermaid 다이어그램 뷰어","i18n.mermaidDiagram":"Mermaid 다이어그램","i18n.zoomOut":"축소","i18n.zoomIn":"확대","toolImage.dialogLabel":"확대한 이미지","toolImage.requestEdit":"이 화면 수정 요청","toolImage.requestEditHint":"이 이미지를 입력창에 붙입니다. 고칠 내용을 적어 보내세요.","toolImage.noComposer":"붙일 입력창이 없습니다. 대화를 열고 「이 화면 수정 요청」을 누르세요.","toolImage.loadFailed":"이미지를 가져오지 못했습니다. 「이 화면 수정 요청」을 다시 누르세요.","toolImage.markHint":"고칠 곳을 드래그해 표시하세요","toolImage.markLimit":"구역은 {count}개까지 표시할 수 있습니다","toolImage.clearMarks":"표시 지우기","toolImage.regionLabel":"구역 {n}","toolImage.locatorIntro":"첨부한 화면에 고칠 곳을 빨간 상자로 표시했습니다(구역 {range}). 구역별 확대 그림이 뒤에 이어집니다.","toolImage.locatorRegion":"구역 {n}: x={x}, y={y}, 폭 {w}, 높이 {h} (원본 {width}\xd7{height} 픽셀 기준)","files.pickElement":"요소 지정","files.pickElementHint":"미리보기에서 고칠 요소를 누르세요","files.pickedElement":"지정한 요소","files.requestElementEdit":"이 요소 수정 요청","files.clearPick":"지정 해제","files.pickLocatorElement":"요소: {selector}","files.pickLocatorText":"텍스트: \\"{text}\\"","files.pickLocatorPosition":"화면 위치: x={x}, y={y}, 폭 {w}, 높이 {h} (미리보기 {vw}\xd7{vh} 기준)","i18n.fitToWidth":"너비에 맞춤","models.discoveryFetching":"모델 가져오는 중…","models.discoveryFetch":"모델 가져오기…","models.discoveryFilterPlaceholder":"{count}개 모델 필터…","models.discoveryFilter":"업스트림 모델 필터","models.discoverySelectShown":"표시된 항목 선택","models.discoveryNoMatches":"일치하는 모델이 없습니다.","models.discoveryAdded":"추가됨","models.discoveryShowing":"전체 {total}개 중 처음 {shown}개 표시","models.discoveryFetched":"{count}개 모델을 가져왔습니다","models.discoveryAddSelected":"선택 항목 추가","models.discoveryAddSelectedCount":"선택 항목 추가 ({count})","models.catalogSource":"출처: models.dev ↗","models.catalogFilling":"세부 정보 채우는 중…","models.catalogFill":"모델 세부 정보 채우기","models.catalogFilled":"{count}개 필드가 채워졌습니다","models.catalogNoEmptyFields":"채울 빈 필드가 없습니다","models.catalogNoExactMatch":"models.dev에서 정확히 일치하는 항목 없음","models.catalogPriceProvider":"Provider {provider}와 가격 일치","models.catalogPriceBaseUrl":"Base URL이 {provider}와 가격 일치","models.catalogPriceConsensus":"{total}개 중 {support}개 레코드에서 가격 일치","models.catalogPriceUnreliable":"신뢰할 수 있는 가격을 찾지 못했습니다","models.catalogUndo":"실행 취소","models.navGroupRoles":"역할 배정","models.navGroupAccounts":"연결된 계정","models.navGroupCustom":"직접 추가한 제공자","i18n.testingModel":"모델 연결 테스트 중...","i18n.connected":"연결됨","i18n.failed":"실패","i18n.test":"테스트","i18n.testConnection":"모델 연결 테스트","i18n.provider":"제공자","i18n.model":"모델","i18n.providerName":"Provider 이름","i18n.rename":"이름 변경","i18n.default":"기본값","i18n.disabled":"비활성화됨","i18n.noResources":"리소스 없음","i18n.unknown":"알 수 없음","i18n.installedVersion":"설치됨 {version}","i18n.configuredVersion":"설정됨 {version}","i18n.extensions":"확장","i18n.prompts":"프롬프트","i18n.themes":"테마","i18n.resourceCount":"{count} {label}","i18n.extensionShort":"확장","i18n.skillShort":"Skill","i18n.promptShort":"프롬프트","i18n.themeShort":"테마","i18n.custom":"사용자 지정","i18n.clearAll":"모두 지우기","i18n.connectedSuccessfully":"연결에 성공했습니다.","i18n.notConnected":"연결 안 됨","i18n.configured":"설정됨","i18n.notConfigured":"설정 안 됨","i18n.openingBrowser":"브라우저를 여는 중…","i18n.submit":"제출","i18n.login":"로그인","i18n.relogin":"다시 로그인","i18n.deviceLogin":"기기 코드로 로그인","i18n.deviceLoginGuide":"아래 주소를 열어 로그인한 뒤 이 코드를 입력하세요. 이 서버의 localhost로 돌아올 필요가 없어서 원격 서버에서도 됩니다.","i18n.disconnect":"연결 해제","i18n.networkError":"네트워크 오류","i18n.continuing":"계속 진행 중…","i18n.skills":"Skill","i18n.plugins":"Plugin","i18n.addSkill":"Skill 추가","i18n.addPlugin":"Plugin 추가","i18n.selectSkill":"Skill 선택","i18n.selectPackage":"패키지 선택","i18n.updateAvailable":"업데이트 있음","i18n.upToDate":"최신 상태","i18n.automaticChecksUnavailable":"자동 확인 불가","i18n.checkFailed":"확인 실패","i18n.installed":"설치됨","i18n.status":"상태","i18n.version":"버전","i18n.package":"패키지","i18n.resources":"리소스","i18n.installedPath":"설치 경로","i18n.cwd":"CWD","i18n.resolvedResources":"확인된 리소스","i18n.reloadSession":"세션 다시 불러오기","i18n.reloadSessionHint":"열린 세션의 설정과 스킬을 다시 불러옵니다. Plugin은 해제되지 않으니, 해제하려면 CUELO를 재시작하세요.","i18n.reloading":"다시 불러오는 중...","i18n.packageRemoved":"패키지가 제거되었습니다.","i18n.packageInstalled":"패키지가 설치되었습니다.","i18n.packageUpdated":"패키지가 업데이트되었습니다.","i18n.packageDisabled":"패키지가 비활성화되었습니다.","i18n.packageDisabledRestartRequired":"비활성화 설정을 저장했습니다. 이미 불러온 Plugin은 CUELO를 재시작해야 멈춥니다. 세션 다시 불러오기로는 해제되지 않습니다.","i18n.packageEnabled":"패키지가 활성화되었습니다.","i18n.sessionReloaded":"세션을 다시 불러왔습니다.","i18n.thinking":"사고 과정","i18n.loadingThinking":"사고 과정 불러오는 중...","i18n.copyMessage":"메시지 복사","i18n.editFromHere":"여기서부터 편집","i18n.editFromHereTitle":"여기서부터 편집 — 이 세션 내에서 분기합니다","i18n.newSession":"새 세션","i18n.newSessionTitle":"새 세션 — 여기서부터 독립된 복사본을 만듭니다","i18n.estimatedTokens":"스트리밍 중 예상 Token 수","i18n.messageUsage":"사용량","i18n.messageUsageTitle":"이 메시지의 Token\xb7비용 보기","i18n.providerAnthropicSubscription":"Anthropic 구독","i18n.providerAnthropicApi":"Anthropic API","i18n.noOutput":"(출력 없음)","i18n.noSummary":"(요약 없음)","i18n.conversationCompacted":"대화가 압축됨","i18n.compactionDescription":"이 지점 이전의 대화 기록이 다음 요약으로 압축되었습니다:","i18n.fileContext":"파일 컨텍스트: {details}","i18n.readFiles":"읽은 파일","i18n.modifiedFiles":"수정된 파일","i18n.hiddenExtensionMessage":"숨겨진 확장 메시지","i18n.noMessage":"(메시지 없음)","i18n.showOriginalReply":"영어 원문 보기","i18n.hideOriginalReply":"영어 원문 접기","i18n.showInputTranslation":"영어 통역 보기","i18n.hideInputTranslation":"영어 통역 접기","i18n.showExtensionMessage":"확장 메시지 표시","i18n.collapse":"접기","i18n.expand":"펼치기","i18n.hideDetails":"세부 정보 숨기기","i18n.showDetails":"세부 정보 표시","i18n.thinkingUnavailable":"사고 내용을 사용할 수 없음","i18n.before":"이전","i18n.after":"이후","i18n.largeMessageReveal":"메시지 내용이 매우 큽니다 ({size}). 클릭하면 일반 텍스트로 표시합니다 — 페이지 반응성을 유지하기 위해 마크다운 렌더링은 비활성화됩니다.","i18n.sessionComplete":"세션 완료","i18n.taskFinished":"작업이 완료되었습니다.","i18n.attentionNeeded":"확인이 필요합니다","i18n.extensionInputNeeded":"확장이 입력을 기다립니다.","navigator.toolbar":"탐색 보기","navigator.priority":"우선순위","navigator.view":"{label} 보기","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"이 세션은 6 Pro 연결번호 {handle}에 묶여 있습니다.","usage.none":"사용량 —","usage.open":"사용량 자세히 보기: {rows}","usage.openMore":", 그 외 {count}개","usage.showMore":"나머지 {count}개 보기","usage.showLess":"접기","usage.accountBlocked":"자동 차단","usage.accountSpent":"계정 한도 소진","usage.limitSpent":"한도 소진","usage.bai":"B.AI 누적토큰","usage.baiEmpty":"기록 없음","usage.baiRange":"집계 {from}~{to}","usage.baiUnmeasured":"미측정","usage.title":"사용량","usage.reorder":"순서 편집","usage.reorderDone":"완료","usage.reorderGroup":"계정 표시 순서","usage.moveUp":"{account} 위로","usage.moveDown":"{account} 아래로","usage.moved":"{account}: {position}번째로 이동","usage.authExpired":"인증 만료","usage.authUnavailable":"사용 불가","usage.relogin":"재로그인","usage.reloginFor":"{account} 계정 재로그인","usage.authIssues":"계정 오류 {count}","relogin.title":"재로그인 대상","relogin.guide":"「{action}」을 누른 뒤 브라우저에서 이 계정으로 로그인하세요. 다른 계정으로 로그인하면 이 계정의 오류는 그대로 남습니다.","relogin.done":"로그인을 마쳤습니다.","relogin.checking":"{account} 상태를 확인하려고 사용량을 다시 읽는 중…","relogin.recovered":"{account} 계정 인증이 복구됐습니다.","relogin.stillFailing":"로그인은 끝났지만 {account} 계정은 아직 인증 오류입니다. 다른 계정으로 로그인했을 수 있습니다.","relogin.unknown":"사용량에서 {account} 계정을 찾지 못해 복구 여부를 확인하지 못했습니다.","efficiency.title":"효율","efficiency.governor":"실행 통제","efficiency.lab":"구성 비교","efficiency.refresh":"새로고침","efficiency.refreshing":"불러오는 중…","efficiency.noSession":"세션을 선택하면 실행 기록을 볼 수 있습니다.","efficiency.loadingRuns":"실행 목록을 불러오는 중…","efficiency.runsEmpty":"이 세션에 기록된 실행이 없습니다.","efficiency.runsError":"실행 목록을 불러오지 못했습니다.","efficiency.selectRun":"실행을 고르면 역할\xb7병목\xb7미측정 공백을 볼 수 있습니다.","efficiency.loadingDetail":"실행 상세를 불러오는 중…","efficiency.detailError":"실행 상세를 불러오지 못했습니다.","efficiency.noTitle":"제목 없는 요청","efficiency.elapsed":"경과","efficiency.busyTotal":"생성시간 합","efficiency.noSumNote":"경과와 생성시간 합은 나란히만 두고 더하지 않습니다.","efficiency.summarySection":"요약","efficiency.rolesSection":"역할","efficiency.rolesEmpty":"이 실행에서 요청을 처리한 역할이 없습니다.","efficiency.bottlenecksSection":"병목","efficiency.bottlenecksEmpty":"측정된 병목이 없습니다.","efficiency.toolsSection":"도구 호출","efficiency.unmeasuredGap":"원인 미측정 공백","efficiency.elapsedValue":"경과 {value}","efficiency.estimatedCostValue":"추정 {value}","efficiency.estimatedCost":"추정 비용","efficiency.untimedLowerBound":"소요시간이 기록되지 않은 요청 {value}건 — 생성시간은 하한입니다.","efficiency.bottleneckOrderNote":"관측된 크기가 큰 순서입니다. 막대는 1위 대비 길이이며 경과시간 대비가 아닙니다.","efficiency.untimedRuns":"소요시간 미기록 run","efficiency.untimedMedianLowerBound":"소요시간이 기록되지 않은 요청이 있는 run {value}건 — 생성시간 중앙값은 하한입니다.","efficiency.unpricedLowerBound":"가격 미기록 포함 — 하한","efficiency.mixedPairingNote":"혼합 구성: 요청별 모델\xb7추론 강도 조합과 순서는 확인되지 않았습니다. 같은 조건의 실행으로 단정할 수 없습니다.","efficiency.unmeasuredShort":"미측정","efficiency.effortLabel":"effort {value}","efficiency.requestsValue":"요청 {value}회","efficiency.toolCallsValue":"도구 호출 {value}회","efficiency.busyTime":"생성시간","efficiency.tokens":"토큰","efficiency.unpricedRequests":"가격 미기록 요청","efficiency.firstTokenAvg":"첫 응답 대기(평균)","efficiency.firstTokenPartial":"첫 응답 대기는 기록된 요청 {recorded}/{total}건의 평균입니다.","efficiency.outputTokens":"대화 출력 토큰","efficiency.helpersTitle":"보조 모델 호출","efficiency.helperCallsValue":"{count}회 \xb7 출력 {output} \xb7 합계 {tokens} \xb7 {cost}","efficiency.helpersIncludedNote":"보조 호출의 토큰\xb7비용은 위 토큰\xb7추정 비용 합계에 들어 있고, 요청 수\xb7첫 응답 대기\xb7대화 출력 토큰에서는 빠집니다.","efficiency.toolFailedValue":"실패 {value}","efficiency.toolNoMatchValue":"무일치 {value}","efficiency.toolCancelledValue":"중단 {value}","efficiency.unmeasuredGapValue":"원인 미측정 공백 {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"미배정","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"완료","efficiency.outcomeError":"오류","efficiency.outcomeAborted":"중단됨","efficiency.outcomeInterrupted":"요청으로 끊김","efficiency.outcomeRunning":"실행 중","efficiency.folder":"폴더","efficiency.folderAll":"전체 폴더","efficiency.folderPlaceholder":"폴더로 걸러보기, Enter로 적용","efficiency.loadingExperiments":"구성 비교를 불러오는 중…","efficiency.experimentsEmpty":"비교할 구성이 기록되지 않았습니다.","efficiency.experimentsError":"구성 비교를 불러오지 못했습니다.","efficiency.difficultyNote":"작업 난이도는 보정되지 않음","efficiency.runsValue":"실행 {value}회","efficiency.medianElapsed":"경과 중앙값","efficiency.medianBusy":"생성시간 중앙값","efficiency.medianTokens":"토큰 중앙값","efficiency.medianEstimatedCost":"추정 비용 중앙값","efficiency.totalEstimatedCost":"추정 비용 합","efficiency.reworkRate":"재작업률","efficiency.errorRate":"오류율","efficiency.unpricedRuns":"가격 미기록 run","efficiency.scopeAttributed":"현재 역할 체계만","efficiency.scopeAll":"전체 기록","efficiency.scopeSessions":"집계 세션","efficiency.scopeRuns":"집계 run","efficiency.scopeExcludedRuns":"제외된 run","efficiency.harness":"하네스","efficiency.harnessValue":"하네스 {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"모든 하네스","efficiency.groupByHarness":"하네스별로 나누기","efficiency.harnessNote":"하네스는 run 시작 시점에 설치돼 있던 CUELO 버전입니다. 이 PC의 업데이트 기록으로만 정하며, 기록이 없거나 기록 밖에서 바뀐 구간은 unknown입니다.","efficiency.sawSection":"모델이 본 것","efficiency.sawApproxNote":"세션 기록으로 다시 맞춘 근사치입니다. 요청마다 보낸 시스템 프롬프트와 컨텍스트 훅이 바꾼 내용은 기록에 남지 않습니다.","efficiency.sawOpen":"요청별로 보기","efficiency.sawLoading":"요청 기록을 읽는 중…","efficiency.sawError":"요청 기록을 읽지 못했습니다.","efficiency.sawEmpty":"이 run에는 모델 요청 기록이 없습니다.","efficiency.sawFilterEmpty":"주입이 있는 요청이 없습니다.","efficiency.sawRole":"대화 기록","efficiency.sawSummary":"요청 {turns}회 \xb7 주입 {injections}건 \xb7 도구 {tools}회 \xb7 실패 {failed}건","efficiency.sawOnlyInjected":"주입 있는 요청만","efficiency.sawTurnLabel":"요청 {index}","efficiency.sawBefore":"이 요청 전에 들어온 것","efficiency.sawTrailing":"마지막 요청 뒤에 들어온 것 (이 run의 모델 요청에는 들어가지 않음)","efficiency.sawShowFull":"전체 보기","efficiency.sawShowArgs":"인자 보기","efficiency.sawShowResult":"결과 보기","efficiency.sawHideFull":"접기","efficiency.sawTruncated":"앞 {value}자만 보입니다.","efficiency.sawMore":"{value}개 더 보기","efficiency.sawShown":"{total}개 중 {shown}개 표시","efficiency.sawHiddenFromChat":"채팅에는 안 보임","efficiency.sawNotSent":"모델에 안 보냄","efficiency.sawSecretsMasked":"비밀값처럼 보이는 문자열은 [REDACTED]로 가렸습니다.","efficiency.sawKindInjection":"주입","efficiency.sawKindDeveloper":"개발자 메시지","efficiency.sawKindUser":"사용자 메시지","efficiency.sawKindCompaction":"압축","efficiency.sawKindModel":"모델 변경","efficiency.sawKindEffort":"effort 변경","efficiency.sawKindPrompt":"시스템 프롬프트 바뀜","efficiency.sawKindRules":"규칙 주입","efficiency.sawKindMemory":"기억 회상","efficiency.sawCompactionValue":"{before} → {after} 토큰","efficiency.sawMemoryIds":"기억 {value}건 회상 (본문은 기록되지 않음)","efficiency.sawToolOk":"성공","efficiency.sawToolFailed":"실패","efficiency.sawToolNoMatch":"일치 없음","efficiency.sawToolCancelled":"중단","efficiency.sawToolMissing":"결과 없음","efficiency.sawResultChars":"결과 {value}자","efficiency.sawUsage":"입력 {input} \xb7 출력 {output} \xb7 캐시 읽기 {cacheRead}","efficiency.sawStop":"종료: {value}","efficiency.sawToolsChanged":"도구 목록 변경: +{added} −{removed}","efficiency.sawPreludeTitle":"시스템 프롬프트와 도구","efficiency.sawPreludeRecorded":"기록된 것","efficiency.sawPreludeTools":"마지막 요청에 켜진 도구 {value}개 (기록됨)","efficiency.sawPreludeDigest":"시스템 프롬프트 지문: {value}","efficiency.sawPreludeDigestNone":"이 run 시점의 시스템 프롬프트 지문이 기록에 없습니다.","efficiency.sawPreludeMemory":"기억 회상 블록 (시스템 프롬프트의 일부, 기록됨)","efficiency.sawPreludeReconstruct":"지금 설정으로 다시 만들기","efficiency.sawPreludeLoading":"다시 만드는 중…","efficiency.sawPreludeApprox":"지금 설정으로 다시 만든 것이며 보낸 그대로가 아닙니다.","efficiency.sawPreludeNotLoaded":"이 세션이 지금 열려 있지 않아 다시 만들 수 없습니다. 시스템 프롬프트 본문은 기록되지 않습니다.","efficiency.sawPreludeMatch":"지금 프롬프트의 지문이 이 run의 기록과 같습니다.","efficiency.sawPreludeMismatch":"지금 프롬프트의 지문이 이 run의 기록과 다릅니다. 그사이 바뀌었을 수 있습니다.","toolRun.running":"실행 중","toolRun.failed":"실패","toolRun.exitCode":"exit {code}","toolRun.diffStats":"{added}줄 추가, {removed}줄 삭제","toolRun.askTimedOut":"시간 안에 답이 없어 입력된 값이 제출되었습니다.","panel.expand":"패널 넓게 보기","panel.restore":"원래 크기로","panel.more":"더 보기","panel.liveSync":"실시간 반영","panel.subagentsCount":"기록 {count}건","panel.refresh":"기록 새로고침","panel.close":"패널 닫기","pluginLab.counts":"플러그인 {count}개","pluginLab.refresh":"목록 새로고침","pluginLab.create":"새 플러그인 만들기","pluginLab.createHint":"요청을 입력창에 넣습니다. 다듬어서 보내세요.","pluginLab.starter":"plugin-lab 스킬로 내 프로필에 쓸 플러그인을 하나 만들어 줘.\\n- 하려는 일: \\n- 필요한 도구: \\n- 패널에 보여 줄 내용(없으면 비워 둠): \\n저장소 정식 폴더에 바로 만들고 이번 턴에 리뷰, 버전, CI, 배포까지 끝내 줘.","pluginLab.loading":"플러그인 목록을 불러오는 중…","pluginLab.loadFailed":"플러그인 목록을 불러오지 못했습니다: {error}","pluginLab.retry":"다시 불러오기","pluginLab.empty":"아직 플러그인이 없습니다. 「새 플러그인 만들기」로 요청을 입력창에 넣어 보세요.","pluginLab.listLabel":"플러그인 목록","pluginLab.on":"켜짐","pluginLab.off":"꺼짐","pluginLab.toggleLabel":"{name} 사용","pluginLab.toggleFailed":"상태를 바꾸지 못했습니다: {error}","pluginLab.tools":"도구","pluginLab.lastEnhancement":"마지막 보강","pluginLab.lastEnhancementHint":"이 플러그인의 기능이 마지막으로 보강된 날짜입니다.","pluginLab.problem":"문제","pluginLab.openPanel":"패널 열기","pluginLab.openPanelLabel":"{name} 패널 열기","pluginLab.back":"플러그인 목록으로","pluginLab.panelSubtitle":"격리 실행 \xb7 lab:{id}","pluginLab.frameTitle":"{name} 패널","pluginLab.lines":"에이전트 데이터 {count}줄","pluginLab.noLines":"이 세션에서 받은 에이전트 데이터 없음","pluginLab.draftInserted":"패널이 만든 초안을 입력창에 넣었습니다. 확인하고 보내세요.","pluginLab.applyHint":"도구 변경은 새 세션이나 /reload 뒤에 적용됩니다.","pluginLab.noComposer":"대화를 열어야 입력창에 넣을 수 있습니다.","pluginLab.draftNotRecorded":"초안은 입력창에 넣었지만 사용 기록은 남기지 못했습니다.","pluginLab.saving":"바꾸는 중…","makerDetail.region":"{title} 기록","makerDetail.noFiles":"이 Maker는 파일을 바꾸지 않았습니다","makerDetail.noChecks":"검사 실행 없음","makerDetail.archiveUnobserved":"기록에 도구 결과가 없어 확인할 수 없습니다","makerDetail.unavailable":"이 시도와 정확히 맞는 실행 기록이 없어 상세를 열 수 없습니다","makerDetail.checkPassed":"통과","makerDetail.checkUnverified":"판정 미확인","makerDetail.checkFailed":"실패","makerDetail.checkUnobserved":"결과 미관측","dispatchLane.label":"Maker 시도","dispatchLane.runPhase":"{run}({phase})","dispatchLane.checks":"검사 {passed}/{total}","dispatchLane.checksUnobserved":"검사 미관측","dispatchLane.checksLoading":"검사 읽는 중","dispatchLane.attempt":"시도 {attempt}","dispatchLane.attemptUnknown":"시도","dispatchLane.verdict.accepted":"수용","dispatchLane.verdict.rework":"재작업","dispatchLane.verdict.held":"보류","dispatchLane.open":"자세히","dispatchLane.openLabel":"{title} 자세히 보기","dispatchLane.unavailable":"상세 없음","credits.heading":"API 크레딧","credits.estimateNote":"결제 화면 잔액은 표시된 시각에 직접 확인해 적어 둔 값이라 이후 사용량은 빠져 있습니다. 추정 사용량과 추정 잔액은 이 PC의 토큰 수에 공개 단가를 곱한 어림값이며 청구서 금액이 아닙니다.","credits.loading":"API 크레딧 불러오는 중…","credits.loadFailed":"API 크레딧을 불러오지 못했습니다: {reason}","credits.wallet.hive":"Hive","credits.scope.hive":"이 PC 기록","credits.since":"{date}부터","credits.sinceDefault":"최근 30일","credits.total":"총액","credits.spent":"추정 사용","credits.remaining":"추정 잔액","credits.meterLabel":"{wallet} 크레딧 사용","credits.usedPct":"사용 {pct}%","credits.enterPrompt":"총액과 시작일을 넣으면 추정 잔액을 계산합니다.","credits.enter":"크레딧 입력","credits.edit":"수정","credits.formLabel":"{wallet} 크레딧","credits.totalUsd":"총액(USD)","credits.startDate":"시작일","credits.save":"저장","credits.saving":"저장 중…","credits.cancel":"취소","credits.clear":"지우기","credits.saveFailed":"저장하지 못했습니다: {reason}","credits.invalid.total":"총액을 숫자로 넣어 주세요.","credits.error.invalid_total":"총액은 0보다 큰 숫자여야 합니다","credits.error.invalid_start_date":"시작일을 확인하세요","credits.error.start_date_in_future":"시작일이 미래입니다","credits.error.session_scan_failed":"세션 기록을 읽지 못했습니다","credits.error.session_scan_partial":"일부 세션 기록을 읽지 못해 추정 사용이 실제보다 적을 수 있습니다","credits.error.internal":"예상하지 못한 오류가 났습니다","credits.error.settings_unreadable":"크레딧 설정 파일을 읽지 못해 덮어쓰지 않았습니다","credits.walletError":"사용량을 읽지 못했습니다: {reason}","credits.settingsError":"크레딧 설정 파일을 읽지 못했습니다. 다시 입력해 주세요.","credits.tokens":"입력 {input} \xb7 출력 {output}","credits.cacheTokens":"캐시 {cache}","credits.requests":"{count}회","credits.priceUnknown":"단가 미상","credits.purpose.session":"대화\xb7에이전트","credits.purpose.memory":"기억","credits.purpose.korean-reply-translation":"답변 번역","credits.wallet.anthropic":"Anthropic API","credits.billingLink":"실제 잔액 보기","credits.billingLinkLabel":"{wallet} 결제 화면에서 실제 잔액 보기(새 탭)","credits.scope.anthropic":"이 PC 기록","credits.anthropic.note":"토큰이 기록된 API 키 요청만 집계하며 구독(OAuth) 요청과 토큰 없는 실패는 제외합니다. 금액은 공개 단가 기준 추정치이며 청구서나 잔액이 아닙니다.","credits.anthropic.noCoverage":"이 기간에 인증 방식이 기록된 요청이 없어 API 키 사용량을 알 수 없습니다.","credits.anthropic.coverageSince":"인증 방식 최초 기록: {date} (이후 모든 요청의 기록을 보장하지는 않습니다)","credits.anthropic.none":"이 기간에 기록된 API 키 요청이 없습니다.","credits.anthropic.oauthExcluded":"구독(OAuth) 제외","credits.anthropic.unattributedExcluded":"인증 미기록 제외","credits.category.input":"입력","credits.category.output":"출력","credits.category.cacheRead":"캐시 읽기","credits.category.cacheWrite":"캐시 쓰기","credits.balance.label":"결제 화면 잔액","credits.balance.source":"직접 기록","credits.balance.observed":"{time} 확인","credits.balance.age.now":"방금","credits.balance.age.minutes":"{count}분 전","credits.balance.age.hours":"{count}시간 전","credits.balance.age.days":"{count}일 전","credits.balance.none":"기록된 잔액 없음","credits.balance.record":"잔액 기록","credits.balance.edit":"잔액 변경","credits.balance.formLabel":"{wallet} 결제 화면 잔액","credits.balance.amount":"잔액(USD)","credits.balance.observedAt":"확인 시각","credits.balance.observedAtHint":"제공자 결제 화면에서 잔액을 확인한 시각입니다.","credits.invalid.amount":"잔액을 숫자로 넣어 주세요.","credits.invalid.observedAt":"확인 시각을 넣어 주세요.","credits.error.invalid_balance":"잔액은 0 이상의 숫자여야 합니다","credits.error.invalid_observed_at":"확인 시각을 확인하세요","credits.error.observed_at_in_future":"확인 시각이 지금보다 늦습니다","credits.error.routes_unreadable":"설정 파일을 읽지 못해 사용 중인 API를 확인할 수 없습니다","credits.wallet.exa":"Exa","credits.wallet.typesafe":"TypeSafe Jev","credits.route.hive":"모델 역할(기억\xb7skim 등)에 배정됨","credits.route.exa":"기본 웹 검색 경로","credits.route.typesafe":"기본 빠른 판정(Jev) 경로","credits.route.anthropic":"구독 주간 한도를 다 쓰면 쓰는 API 키 대체 경로","credits.evidence.lastPaidUse":"이 PC 마지막 유료 사용: {time}","credits.evidence.unverified":"일부 세션 기록을 읽지 못해 최근 유료 사용을 확인하지 못했습니다."}'),s=["en","zh-CN","ko"],o=new Map;function l(e){if(!e.id.trim())throw Error("Locale id must not be empty");if(o.has(e.id))throw Error(`Locale already registered: ${e.id}`);o.set(e.id,e)}function c(){return[...o.keys()]}l({id:"en",label:"English",messages:{"cloudProjects.launch":"Open GitHub repository","cloudProjects.title":"Cloud project","cloudProjects.description":"Bring a GitHub repository to this server and keep working.","cloudProjects.github":"GitHub repositories","cloudProjects.serverFolder":"Open server folder","cloudProjects.account":"GitHub connection","cloudProjects.connectTitle":"Connect your GitHub repositories","cloudProjects.connectHelp":"Sign in to select private repositories from your list.","cloudProjects.connected":"Connected to GitHub","cloudProjects.refresh":"Check again","cloudProjects.waiting":"Waiting for sign-in","cloudProjects.connect":"Connect GitHub","cloudProjects.deviceHelp":"Enter this code on the GitHub sign-in page.","cloudProjects.copyCode":"Copy code","cloudProjects.copied":"Copied","cloudProjects.copyFailure":"Could not copy the code. Select and copy it manually.","cloudProjects.openLogin":"Sign in on GitHub","cloudProjects.permissionHelp":"Check the account and requested permissions on GitHub before approving. Tokens stay on the server.","cloudProjects.preparingCode":"Preparing your sign-in code.","cloudProjects.repositories":"Your repositories","cloudProjects.search":"Find a repository","cloudProjects.searchPlaceholder":"Search by name or description","cloudProjects.loading":"Loading repositories.","cloudProjects.private":"Private","cloudProjects.public":"Public","cloudProjects.empty":"No matching repositories. Try another name or enter a URL.","cloudProjects.more":"Show more","cloudProjects.urlLabel":"Selected repository or GitHub URL","cloudProjects.publicHelp":"Public repositories do not require sign-in. Existing workspaces are reopened without changing your files.","cloudProjects.error":"Could not complete the operation.","cloudProjects.openingHelp":"Importing the repository to this server. Large repositories may take a while.","cloudProjects.opening":"Opening project","cloudProjects.open":"Open project","common.ok":"OK","common.language":"Language","common.models":"Models","common.skills":"Skills","common.plugins":"Plugins","common.settings":"Settings","updates.available":"CUELO update available","updates.availableTitle":"CUELO {version} is available","updates.dialogEyebrow":"CUELO release","updates.dialogTitle":"New CUELO version","updates.current":"Running CUELO {version}","updates.changelog":"Changelog","updates.viewRelease":"View release","updates.manual":"Running from source? Stop the server first, run this update command, then start it again. If you use a custom --home path, pass the same --home option to setup.","updates.copyCommand":"Copy command","updates.commandCopied":"Command copied","updates.copyFailed":"Unable to copy the command","updates.apply":"Update now","updates.applyBusy":"Updating…","updates.applyConfirm":"Update CUELO to {version} and restart?\n\nThe server stops for a moment while it updates, and this panel shows the progress. The page reloads by itself when the new version answers.","updates.applyConfirmBusy":"Update CUELO to {version} and restart?\n\n{count} running session(s) will be interrupted and the server stops for a moment. This panel shows the progress, and the page reloads by itself when the new version answers.","updates.unsupported":"This installation cannot be updated from the app. Use the command below.","updates.unsupportedReason":"Detected: {reason}","updates.phase.starting":"Preparing the update","updates.phase.fetching":"Fetching the new version","updates.phase.installing":"Installing the package","updates.phase.building":"Building","updates.phase.restarting":"Restarting the server","updates.phase.done":"Update complete","updates.phase.handed-off":"Handed off to the service update","updates.phase.restart-required":"Installed. Restart CUELO yourself.","updates.phase.failed":"Update failed","updates.waitingForRestart":"Waiting for the server to come back. The page reloads when the new version answers.","updates.handedOff":"The WSL service update runs in its own wait screen. This page reloads when it finishes.","updates.logPath":"Log: {path}","updates.applyStartFailed":"Could not start the update: {reason}","sidebar.hide":"Hide sidebar","sidebar.show":"Show sidebar","theme.light":"Light mode (click for dark)","theme.dark":"Dark mode (click for system)","theme.auto":"System theme (click for light)","theme.graphite":"Graphite theme (wallpaper)","theme.graphiteHint":"Graphite surfaces with a wallpaper for the current character mode. Dark mode only, saved in this browser.","history.full":"Full history","history.unsaved":"Full history is available after the session is saved","history.label":"Full history","title.generating":"Generating...","title.updated":"Title updated","title.failed":"Generation failed","title.generate":"Generate title","title.unsaved":"Title generation is available after the session is saved","title.noMessages":"Send a message before naming this session","title.generateSession":"Generate a session title","system.prompt":"System prompt","system.empty":"System prompt is empty (tools are disabled)","system.load":"Send a message to load the system prompt","system.label":"System","session.info":"Session info","session.name":"Name","session.file":"File","session.inMemory":"In-memory","session.id":"ID","session.user":"User","session.assistant":"Assistant","session.toolCalls":"Tool Calls","session.toolResults":"Tool Results","session.total":"Total","session.input":"Input","session.output":"Output","session.cacheRead":"Cache Read","session.cacheWrite":"Cache Write","session.cost":"Cost","session.context":"Context","session.cacheHitRate":"Avg cache hit rate","session.copy":"Copy {value}","session.copied":"Copied","session.title":"Session info","session.load":"Send a message or run /session to load session info","session.infoSection":"Session Info","session.messages":"Messages","session.tokens":"Tokens","session.totalActive":"Active Time","session.copyFile":"Copy file path","session.copyId":"Copy session ID","workspace.opening":"Opening workspace...","workspace.unable":"Unable to open workspace","workspace.selectSession":"Select a session from the sidebar","workspace.getStarted":"Get Started","workspace.selectProject":"Select a project directory from the sidebar","workspace.addModels":"Add models via the Models button at the bottom","workspace.stepProject":"Select a project directory from the sidebar","workspace.stepModels":"Add models via the Models button at the bottom","workspace.mainWorking":"Working","workspace.mainWaiting":"Waiting","workspace.mainIdle":"Idle","workspace.mainAttention":"Input needed","files.hidePanel":"Hide file panel","files.showPanel":"Show file panel","files.noneOpen":"No file open","files.docs.noProject":"Select a project to see its documents.","files.docs.loading":"Looking for project documents…","files.docs.projectDenied":"This project folder is outside the folders CUELO may read.","files.docs.loadFailed":"Could not load project documents: {error}","files.docs.projectDir":"Project folder: {path}","files.docs.noneFound":"No HANDOFF.md up to the repository root, and no doc/README.md or doc/history in this folder.","files.docs.current":"Current state","files.docs.map":"Document map","files.docs.records":"Recent records","files.docs.missing":"{file} not found","files.docs.denied":"{file} is outside the readable folders","layout.resizeSidebar":"Resize sidebar","layout.resizeFilePanel":"Resize file panel","layout.resizeHint":"Drag to resize. Double-click or press Enter to reset.","sidebar.new":"New","sidebar.newSessionTitle":"New session in {path}","sidebar.refresh":"Refresh","sidebar.projects":"Projects","subagents.title":"Subagents","subagents.running":"Running","subagents.finished":"Finished","subagents.history":"History","subagents.runningCount":"{count} running","subagents.finishedCount":"{count} finished","subagents.failed":"Failed","subagents.aborted":"Aborted","subagents.back":"Back to subagents","subagents.retrying":"Retrying {attempt}/{max}","subagents.usingTool":"Using {tool}","subagents.details":"Subagent execution details","subagents.closeDetails":"Close subagent details","subagents.noTask":"No task description","subagents.tools":"{count} tools","subagents.tokens":"{count} tokens","subagents.loadingTranscript":"Loading live transcript…","subagents.noTranscript":"The subagent has not written any transcript messages yet.","subagents.transcriptUnavailable":"Live transcript is not available yet. Retrying while the subagent runs.","sidebar.searchProjectsAndSessions":"Search projects and session titles…","sidebar.addProject":"Add custom project path","sidebar.projectActions":"Project actions","sidebar.projectAlias":"Alias","sidebar.projectAliasEdit":"Edit alias","sidebar.projectHide":"Hide","sidebar.projectUnhide":"Unhide","sidebar.projectShowHidden":"Show hidden projects","sidebar.temporaryProjects":"Temporary / system paths","sidebar.projectMoveUp":"Move up","sidebar.projectMoveDown":"Move down","sidebar.projectMoveDisabledWhileFiltering":"Clear the search filter to reorder projects","sidebar.projectUpdateFailed":"Unable to save project changes. Try again.","sidebar.expandProject":"Expand project","sidebar.collapseProject":"Collapse project","sidebar.showMore":"Show more","sidebar.showLess":"Show less","sidebar.selectProject":"Select project…","sidebar.filterProjects":"Filter projects…","sidebar.noMatchingProjects":"No matching projects","sidebar.useDefaultDirectory":"Use default directory","sidebar.customPath":"Custom path…","directoryPicker.selectDirectory":"Select directory","directoryPicker.goToParent":"Go to parent directory","directoryPicker.directoryPath":"Directory path","directoryPicker.goToDirectory":"Go to directory","directoryPicker.go":"Go","directoryPicker.loadingDirectories":"Loading directories…","directoryPicker.noSubdirectories":"No subdirectories","directoryPicker.openBeforeSelecting":"Open this path before selecting it","directoryPicker.selectCurrentDirectory":"Select current directory","directoryPicker.selectThisFolder":"Select this folder","directoryPicker.noDrives":"No drives found","sidebar.checking":"Checking…","sidebar.open":"Open","sidebar.cancel":"Cancel","sidebar.openRepoRoot":"Open repo root","sidebar.openRepoRootTitle":"Open the repository root to manage worktrees.","sidebar.gitRepoRootOnly":"Git repo root only","sidebar.gitRepoRootOnlyTitle":"Worktrees are available in Git repository roots.","sidebar.worktrees":"Worktrees...","sidebar.checkingWorktrees":"Checking worktrees for this directory.","sidebar.filterWorktrees":"Filter worktrees…","sidebar.noMatchingWorktrees":"No matching worktrees","sidebar.switchWorktree":"Switch worktree","sidebar.switchWorktreeTitle":"Switch worktree: {path}","sidebar.main":"main","sidebar.forceRemoveCheckout":"Uncommitted changes. Force remove checkout?","sidebar.force":"Force","sidebar.createWorktreeTitle":"Create a worktree checkout for a branch","sidebar.newWorktree":"New worktree…","sidebar.branchName":"branch name","sidebar.creating":"Creating…","sidebar.create":"Create","sidebar.loading":"Loading...","sidebar.noSessions":"No sessions found","sidebar.agentRunning":"Agent running…","sidebar.newActivity":"New activity","sidebar.newSessionActivity":"New session activity","sidebar.deleteSession":"Delete {title}?","sidebar.rename":"Rename","sidebar.pin":"Pin to top","sidebar.unpin":"Unpin","sidebar.pinned":"Pinned","sidebar.delete":"Delete","sidebar.deleteWithShiftClick":"Delete (Shift+click to delete without confirmation)","sidebar.clearProjectSessions":"Clear sessions","sidebar.clearPriorityList":"Clear list","navigator.resultsToCheck":"To review","navigator.resultsToCheckCount":"To review {count}","navigator.resultsToCheckHint":"Finished conversations with new activity since you last opened them in this browser, and conversations waiting for your answer","navigator.resultsToCheckEmpty":"Nothing to review.","navigator.acknowledgeResults":"Mark all reviewed","navigator.acknowledgeResultsHint":"Marks every conversation now listed to review as seen. Conversations waiting for your answer stay.","sidebar.waitingForAnswer":"Needs answer","sidebar.waitingForAnswerHint":"Paused until you answer its question or approval request","sidebar.newScratchSession":"New session","sidebar.newScratchSessionTitle":"Start a session without a project (in a dated scratch folder under your home)","sidebar.newScratchSessionFailed":"Could not create the scratch folder: {error}","sidebar.clearSessionsTitle":"Confirm session deletion","sidebar.clearSessionsProjectBody":"Permanently delete {count} session(s) in {project}. This cannot be undone.","sidebar.clearSessionsPriorityBody":"Permanently delete {count} session(s) in the priority list. This cannot be undone.","sidebar.clearSessionsRunningExcluded":"{count} running session(s) will be kept.","sidebar.clearSessionsNone":"No session can be deleted right now.","sidebar.clearSessionsConfirm":"Delete","sidebar.clearSessionsCancel":"Cancel","sidebar.clearSessionsBusy":"Deleting…","sidebar.clearSessionsFailed":"Could not delete {count} session(s): {names}","sidebar.archive":"Archive (hide from list, restorable)","sidebar.archived":"Archived","sidebar.restore":"Restore","sidebar.noArchivedSessions":"No archived sessions","sidebar.expandForks":"Expand forks","sidebar.collapseForks":"Collapse forks","sidebar.messagesCount":"{count} msgs","sidebar.worktreePath":"Worktree: {path}","sidebar.removeWorktreeTitle":"Remove worktree checkout {path}; the branch is kept","files.deleted":"Deleted","files.insertPath":"Insert path into chat","files.mention":"mention","chat.loadingSession":"Loading session...","chat.runningTool":"Running tool...","chat.runningNamedTool":"Running {name}...","chat.runningTools":"Running {names}...","chat.runningToolsMore":"Running {names} (+{count})...","chat.waitingModel":"Waiting for model...","todo.progress":"{percent}% \xb7 {completed} of {total} done \xb7 {remaining} remaining","todo.progressDone":"{percent}% \xb7 {completed} of {total} done","todo.allDone":"All {count} done","todo.showCompleted":"Show {count} completed","todo.hideCompleted":"Hide {count} completed","todo.ready":"Ready","todo.waiting":"Waiting for: {tasks}","chat.runningCommand":"Running command...","chat.thinking":"Thinking...","chat.contextUsageTitle":"Context window: {used} of {limit} tokens ({percent})","chat.contextUsageWarning":"Context window is getting full","chat.contextUsageCritical":"Context window is nearly full","chat.processDetails":"Process details","chat.message":"message","chat.messages":"messages","chat.toolCall":"tool call","chat.toolCalls":"tool calls","chat.collapseProcess":"Collapse process details","chat.expandProcess":"Expand process details","process.empty":"No process activity in this session yet","process.turn":"turn","process.turns":"turns","chat.filesWritten":"Files changed","chat.openWrittenFile":"Open {name}","chat.lessonsSaved":"[Lessons saved] The agent stored these itself during this turn.","chat.savedLesson":"Lesson: {memory}","chat.savedSkill":"Skill {action}: {name}","chat.loadEarlier":"Scroll up to load earlier messages ({count} hidden)","chat.extensionRequest":"extension request","chat.responseSending":"Sending your answer...","chat.responseFailed":"Your answer did not reach the agent. It is still waiting - try again.","chat.cancel":"Cancel","chat.confirm":"Confirm","chat.submit":"Submit","chat.agentQuestion":"Agent needs your input","chat.agentQuestionHint":"Choose an option or provide a custom response.","chat.askAutoSelectHint":"If there is no response for {seconds}s, the recommended option is selected automatically. Choosing or typing restarts the wait.","chat.recommended":"Recommended","chat.customAnswer":"Other response (optional)","chat.chatAboutThis":"Chat about this","chat.submitAnswer":"Submit answer","chat.agentFormHint":"Fill in the form and submit it.","chat.askFormAutoSubmitHint":"If you do not respond in {seconds}s, the values currently in the form are submitted. Editing restarts the wait.","chat.formOther":"Other","chat.formOtherPlaceholder":"Type your own answer","chat.formRequired":"Required","chat.formInvalid":"Check the marked fields before you submit.","chat.formImageUnavailable":"Image could not be loaded","chat.formError.required":"Required","chat.formError.selectAtLeastOne":"Select at least one","chat.formError.enterNumber":"Enter a number","chat.formError.min":"Must be at least {value}","chat.formError.max":"Must be at most {value}","chat.formError.minLength":"Needs at least {value} characters","chat.formError.maxLength":"At most {value} characters","chat.formError.email":"Enter an email address","chat.formError.url":"Enter a full URL","chat.formError.pattern":"Must match {pattern}","chat.planApproval":"Plan approval","chat.planFeedback":"Feedback for another planning pass (optional)","chat.refinePlan":"Continue planning","chat.approvePlan":"Approve and implement","chat.extensionInput":"Extension terminal input","chat.extensionPanel":"Extension panel","chat.close":"Close","chat.queued":"Queued \xb7 {count}","chat.recall":"Recall to input","chat.recallTitle":"Remove all queued messages and put them back into the input box for editing","chat.queueRemove":"Cancel this queued message only","chat.retrying":"Retrying ({attempt}/{max})…","chat.loadingCommands":"Loading commands...","chat.slashCommands":"Slash commands \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"No commands found","chat.match":"1 match","chat.matches":"{count} matches","chat.command":"1 command","chat.commands":"{count} commands","chat.loadingFiles":"Loading files...","chat.files":"Files \xb7 {label}{hint}","chat.searching":"Searching…","chat.noMatchingFiles":"No matching files","chat.searchingAll":" \xb7 searching all files…","chat.indexTruncated":" \xb7 index truncated","chat.steerPlaceholder":"Steer now / queue follow-up...","chat.agentPlaceholder":"Agent is running…","chat.messagePlaceholder":"Message… / commands \xb7 @ files","chat.steer":"Steer","chat.followUp":"Follow-up","chat.send":"Send","chat.attachImageLimit":"A message can include at most {count} images.","chat.attachImageTooLarge":"{name} exceeds the {limit} per-image limit.","chat.attachFile":"Attach files","chat.emptyProjectLabel":"Project folder","chat.emptyProjectHint":"Your first message starts a new session in this folder.","chat.openSessionList":"Open session list","chat.attachments":"Attachments","chat.removeImage":"Remove image {index}","chat.removeAttachment":"Remove {name}","chat.attachExtracting":"Extracting text","chat.attachExtractingWait":"Wait for the attachments to finish processing","chat.attachLimit":"A message can include at most {count} non-image attachments.","chat.attachTooLarge":"{name} exceeds the {limit} per-document limit.","chat.attachTotalTooLarge":"Attached documents exceed the {limit} combined size limit.","chat.attachTextTooLarge":"{name} exceeds the {limit}-character extracted text limit.","chat.attachTooManyPages":"{name} exceeds the {limit}-page PDF limit.","chat.attachNoPdfText":"{name} has no extractable text. Scanned or image-only PDFs require OCR, which is not supported.","chat.attachPasswordProtected":"{name} is password-protected and cannot be extracted.","chat.attachExtractFailed":"Could not extract text from {name}.","chat.attachKindAudio":"Audio","chat.attachKindFile":"File","chat.attachUploading":"Saving","chat.attachTranscribing":"Transcribing","chat.attachTranscribeFailed":"Transcription failed","chat.attachStoredTooLarge":"{name} exceeds the {limit} per-file limit.","chat.attachUploadFailed":"Could not save {name}: {error}","chat.attachTranscribePending":"Needs your choice","chat.transcribeGroup":"Audio transcription","chat.transcribeChecking":"Checking length","chat.transcribeConfirmTitle":"Transcribe {name}?","chat.transcribePlanSummary":"{duration} \xb7 transcription calls: about {calls}","chat.transcribeDurationUnknown":"Length unknown","chat.transcribeUsageNotice":"Transcription counts toward the connected account's usage. Nothing is sent until you start.","chat.transcribeStart":"Start transcription","chat.transcribeSkip":"Don't transcribe","chat.transcribeCancel":"Cancel transcription","chat.transcribeRunning":"Transcribing {name}","chat.transcribeRetry":"Try again","chat.transcribeAction":"Transcribe","chat.transcribeSkipped":"{name} has no transcript; only the saved file path is sent.","chat.transcribeFailedRow":"{name}: transcription failed. {error}","chat.transcribeToolMissing":"The audio tool (ffmpeg) is not available, so this audio cannot be prepared for transcription.","chat.transcribePartialFailed":"Stopped after {done} of {total} parts; no partial transcript is attached.","chat.transcribeTooLong":"The transcript does not fit beside the other attachments.","chat.transcribeFallbackTitle":"Primary transcription failed for {name}. Continue with ChatGPT/Codex?","chat.transcribeFallbackProgress":"{done} of {total} parts already have a transcript, which stays; continuing sends only the failed part and the rest.","chat.transcribeFallbackUsageNotice":"ChatGPT/Codex is a separate provider; its transcription counts toward the signed-in account's usage. CUELO sends nothing until you continue.","chat.transcribeFallbackStart":"Continue with ChatGPT/Codex","chat.transcribeFallbackExpired":"This fallback choice expired or you already used it. CUELO sent nothing; try again to start over.","chat.attachmentSettingsNav":"Attachments","chat.attachmentSettingsTitle":"Attachments","chat.attachmentSettingsDescription":"Files you attach in chat are saved on this computer so the agent can open them.","chat.attachmentSettingsLoadFailed":"Could not load attachment settings","chat.attachmentUploadLimit":"Upload limit per file (MB)","chat.attachmentUploadLimitHelp":"Larger files are refused before they are sent. Text read straight into the message keeps its own limits: 8 MB per document and 240,000 characters in total.","chat.attachmentUploadLimitInvalid":"Enter a whole number of MB, 1 or more.","chat.attachmentAutoCleanup":"Delete unused attachments automatically","chat.attachmentAutoCleanupHelp":"Attachments used by a conversation, a branch, or an unsent draft are kept. A file is deleted {days} days after it is confirmed unused everywhere; a file whose use cannot be confirmed is kept.","chat.attachmentSettingsSaved":"Saved","characterMode.nav":"Characters","characterMode.title":"Characters","characterMode.description":"Choose the faces, names, stickers and completion voices you see on screen.","characterMode.label":"Character set","characterMode.default":"Default","characterMode.office":"Office mode","characterMode.help":"Applies to this whole PC server. In office mode, the characters registered in this PC's profile replace the face, name, voice, stickers and sounds of their seats. Seats without an entry stay as they are.","characterMode.noRoster":"This PC has no office character set, so the default characters stay in use.","characterMode.saved":"Saved","chat.steerTitle":"Interrupt the current run and inject this message now","chat.followUpTitle":"Queue this message after the agent finishes","chat.filterModels":"Filter models…","chat.noMatchingModels":"No matching models","chat.modelRoles":"Roles","chat.allModels":"All models","chat.mainPreset":"Main preset","roles.title":"Model roles","roles.description":"omp routes work by role, not by one current model. Assign a model to each role and both CUELO and the omp CLI use it.","roles.scope":"Save to","roles.scopeGlobal":"Global","roles.scopeProject":"This project","roles.unset":"— not set —","roles.needsProject":"Open a project to edit its model roles.","roles.source.global":"from global config","roles.source.project":"from project config","roles.source.default":"omp default","roles.thinking":"Thinking","roles.thinkingInherit":"Use the configured default thinking level","roles.harnessNote":"CUELO Maker and tool slots are listed even before you assign them. Pick your own model only for the slots you use; saving does not sign in or test the model.","roles.harnessUnset":"not set","roles.harness.implSol":"Maker \xb7 settled-direction code (NORMAL/HARD first choice)","roles.harness.implSonnet":"Maker \xb7 NORMAL non-UI fallback","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL background work / fallback","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD code (open design / rework)","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD code fallback","roles.harness.crossReviewOpenAI":"Cross-review \xb7 required OpenAI reviewer (openai / openai-codex)","roles.harness.crossReviewAnthropic":"Cross-review \xb7 required Anthropic reviewer (anthropic)","roles.harness.crossReviewAdvisory":"Cross-review \xb7 advisory reviewer, non-blocking (any provider)","roles.harness.skim":"Tool \xb7 multi-file source reading (skim)","roles.harness.draft":"Tool \xb7 document drafting (draft)","roles.harness.ocr":"Tool \xb7 image text transcription (ocr)","roles.harness.interpreter":"Tool \xb7 Korean–English interpreter (interpreter)","chat.moreControls":"Run options","chat.collapseControls":"Close run options","chat.shell":"Shell","chat.outputLocal":"output stays local","chat.outputModel":"output sent to model","chat.noTools":"No tools, read-only","chat.builtInTools":"Core: {tools} \xb7 other registered tools stay enabled","chat.allBuiltInTools":"Core: {tools} \xb7 other registered tools stay enabled","chat.changeReasoning":"Change reasoning level: {level}","chat.changeReasoningLabel":"Change reasoning level","chat.currentReasoning":"Current reasoning level: {level}","chat.outputSpeed":"{rate} tok/s","chat.outputSpeedTitle":"Output speed of the last answer (output tokens per second, from request start to the end of generation)","chat.outputSpeedLive":"~{rate} tok/s","chat.outputSpeedLiveTitle":"Estimated output speed of the answer in progress (received text approximated as tokens, from request start until now). Switches to the real token count when the answer ends","chat.fastModeActive":"Fast on \xb7 applied to this model. Priority service may cost more or use more quota. Click to turn off","chat.fastModeInactive":"Fast requested \xb7 not applied for this model or account. Click to turn off","chat.fastModeOff":"Fast off \xb7 click to request priority service (may cost more or use more quota, depending on the provider)","chat.fastModeUnknown":"Fast state not checked yet \xb7 click to read this session's actual state and change it","chat.fastModeBusy":"Changing Fast","chat.changeToolPreset":"Change tool preset","chat.stopCompaction":"Stop compaction","chat.compactContext":"Compact context","chat.compacting":"Compacting…","chat.compact":"Compact","chat.stopAgent":"Stop agent","chat.stop":"Stop","chat.liveVoice":"Live voice","chat.liveStart":"Start live voice","chat.liveStop":"End live voice","chat.liveConnecting":"Connecting","chat.liveOn":"Live","chat.liveWorking":"Working","chat.liveUnsupported":"This browser cannot make live calls","chat.liveMicDenied":"Microphone access was denied","chat.liveMicUnavailable":"No microphone is available","chat.liveAuthRequired":"Sign in to Codex to use live voice","chat.liveUpstreamFailed":"Codex refused the live call","chat.liveFailed":"The live call could not start","chat.liveNeedsSession":"Choose a folder first — a live call speaks as this conversation's agent","chat.liveVoiceSettingsNav":"Call voice","chat.liveVoiceSettingsTitle":"Call voice","chat.liveVoiceSettingsDescription":"Choose the Codex voice that speaks in live and interpreter calls and how fast it speaks. The choice applies from the next call.","chat.liveVoiceSpeakerGroup":"Voice","chat.liveVoiceCodexLabel":"Codex voice","chat.liveVoiceCodexHelp":"Speaks in live calls and interpreter calls.","chat.livePaceLabel":"Speaking pace","chat.livePaceHelp":"Slow makes the voice speak slowly and clearly.","chat.livePaceNormal":"Normal","chat.livePaceSlow":"Slow","chat.liveVoiceLoadFailed":"Could not load voice settings","chat.disableSound":"Disable completion sound","chat.enableSound":"Enable completion sound","chat.thinkingAuto":"Automatically select reasoning effort","chat.thinkingAutoCapped":"Automatic, at most {level}","chat.thinkingOff":"Reasoning off","chat.thinkingMinimal":"Minimal reasoning","chat.thinkingLow":"Low reasoning","chat.thinkingMedium":"Medium reasoning","chat.thinkingHigh":"High reasoning","chat.thinkingXhigh":"Extra-high reasoning","chat.thinkingMax":"Max reasoning","chat.builtIn":"Built-in","chat.extensions":"Extensions","chat.customCommands":"Custom commands","chat.mcpPrompts":"MCP prompts","chat.prompts":"Prompts","chat.fileCommands":"Command files","chat.skills":"Skills","chat.dormant":"dormant","chat.commandCompact":"Compress context, optionally with instructions","chat.commandReload":"Reload extensions, skills, prompts, and tools","chat.commandName":"Set the session display name","chat.commandSession":"Show session message, token, and cost stats","chat.commandCopy":"Copy the last assistant message","chat.goalLabel":"Goal","chat.goalPaused":"paused","chat.goalBudgetLeft":"{left} left","chat.goalTokensUsed":"{used} used","chat.jumpToBottom":"Jump to bottom","chat.loadLater":"Scroll down to load later messages ({count} below)","chat.jumpMissing":"That message is not in this conversation view (another branch or compacted history).","chat.questionRail":"Your questions","chat.searchPlaceholder":"Find in conversation","chat.searchNoResults":"No results","chat.searchCount":"{index}/{total}","chat.searchPrevious":"Previous match","chat.searchNext":"Next match","chat.searchClose":"Close find","chat.compactionLabel":"Compacting","chat.compactionProgress":"Compacting context \xb7 {seconds}s","chat.compactionReason.manual":"manual","chat.compactionReason.threshold":"threshold","chat.compactionReason.overflow":"overflow","chat.compactionReason.idle":"idle","chat.compactionReason.incomplete":"incomplete","chat.compactedFrom":"Compacted from {tokens} tokens","chat.interruptedTitle":"The last run was interrupted","chat.interruptedDetail":"The run stopped before it finished, for example when the server or PC went down. If it does not resume automatically, send a message to continue.","chat.interruptedDismiss":"Dismiss","chat.frequentModels":"Frequently used","chat.modelPickCount":"{count}\xd7","palette.searchPlaceholder":"Search conversations","palette.searchResults":"Conversation search results","palette.searching":"Searching…","palette.searchFailed":"Search failed","palette.searchEmpty":"No matching messages","palette.searchHits":"{count} messages","palette.searchTruncated.time":"stopped at the time limit after {scanned} of {total} sessions","palette.searchTruncated.bytes":"stopped at the size limit after {scanned} of {total} sessions","palette.searchTruncated.results":"showing the first results; refine the query for more","palette.searchCompacted":"{count} in compacted history not shown","palette.searchRoleUser":"You","palette.searchRoleAssistant":"Answer","palette.wideChatOn":"Use wide chat","palette.wideChatOff":"Use standard chat width","chat.compacted":"Compacted","chat.tokensSaved":"{saved} saved","i18n.close":"Close","i18n.copy":"Copy","i18n.copied":"Copied","i18n.cancel":"Cancel","i18n.save":"Save","i18n.saving":"Saving…","i18n.saved":"Saved","i18n.remove":"Remove","i18n.removing":"Removing…","i18n.delete":"Delete","i18n.loading":"Loading...","i18n.search":"Search","i18n.refresh":"Refresh","i18n.update":"Update","i18n.updating":"Updating...","restart.title":"CUELO is restarting","restart.body":"This page reloads automatically when the server is back.","restart.slow":"The restart is taking longer than two minutes. Check READY or FAILED in %USERPROFILE%\\.omp\\restart-ompweb.log on the server PC. This page still reloads when the server is back.","restart.returnedTitle":"CUELO restarted","restart.returnedBody":"The server is back and this tab reconnected to the same conversation.","restart.returnedDismiss":"Dismiss restart notice","i18n.check":"Check","i18n.checking":"Checking...","i18n.install":"Install","i18n.installing":"Installing...","i18n.noResults":"No results","i18n.searchProviders":"Search providers…","i18n.noProviders":"No providers match","i18n.newModel":"new model","i18n.addProvider":"Add provider","i18n.selectProviderModel":"Select a provider or model","i18n.visibleInPrompt":"Visible in model prompt — click to disable","i18n.hiddenFromPrompt":"Hidden from model prompt — click to enable","i18n.dormant":"Dormant","i18n.hiddenButInvocable":"Hidden from model, still manually invocable","i18n.skillSearchPlaceholder":"e.g. react, testing, deploy","i18n.searching":"Searching…","i18n.noSkills":"No skills found","i18n.checkUpdates":"Check updates","i18n.updates":"updates","i18n.noResolvedResources":"No resolved resources","i18n.enablePackage":"Enable package","i18n.disablePackage":"Disable package","i18n.filtered":"filtered","i18n.openSessionToReload":"Open a session to reload","i18n.notFound":"Not found","i18n.noPlugins":"No plugins configured","trust.resourcesNotLoaded":"Restricted mode","trust.trustProject":"Trust project","computerTakeover.allow":"Allow takeover","computerTakeover.active":"Takeover allowed","computerTakeover.allowHint":"Allow screen takeover for this session only. It goes back to refused when you turn it off or the session closes.","computerTakeover.activeHint":"Screen takeover is allowed in this session. Click to turn it off.","computerTakeover.shared":"A session opened in the server's own folder cannot be allowed separately.","computerTakeover.failed":"Could not change takeover: {error}","trust.trusting":"Trusting...","trust.cancel":"Cancel","trust.dialogTitle":"Trust this project?","trust.dialogBody":"Project resources can run local code. Trust only projects whose contents you know.","trust.skillsNotLoaded":"Project skills are not loaded because this project is not trusted.","trust.pluginsNotLoaded":"Project plugins are not loaded because this project is not trusted.","trust.projectScopeUnavailable":"Project installs are unavailable while project resources are not loaded.","trust.pendingBadge":"Restricted mode \xb7 trust scheduled","trust.scheduledTitle":"Trust scheduled","trust.scheduledBody":"This project is still in restricted mode. Trust applies once every session in this project has finished its current work; nothing that is running gets interrupted.","trust.cancelSchedule":"Cancel scheduled trust","trust.close":"Close","trust.applyFailed":"The scheduled trust was not applied, so the project is still restricted: {error}. Trust it again to retry.","trust.settingsNav":"Project trust","trust.settingsDescription":"A project that ships its own extensions, hooks, tools, or MCP servers loads that code only after you trust it. A change made while a session is working applies when every session in that project is idle — running work is never interrupted.","trust.settingsEmpty":"No project needs a trust decision yet.","trust.loadFailed":"Could not load project trust: {error}","trust.stateTrusted":"Trusted","trust.stateRestricted":"Restricted","trust.stateNotRequired":"No project code needs trust","trust.pendingGrant":"Trust approved but not applied yet. The project stays restricted until its sessions finish their work.","trust.pendingRevoke":"Trust is already revoked. {count} running session(s) still use the project code and restart restricted when their current work ends.","trust.runtime":"Live sessions {sessions} \xb7 running {running} \xb7 project code loaded {loaded}","trust.revoke":"Revoke trust","trust.trustAgain":"Trust again","trust.confirm":"Confirm","trust.working":"Saving…","trust.confirmGrant":"Trust this project? Its extensions, hooks, tools, and MCP servers can run on this machine.","trust.confirmTrustAgain":"Undoing a revoke is a new trust approval. Its extensions, hooks, tools, and MCP servers can run on this machine.","trust.confirmRevoke":"Revoke trust? New sessions start restricted right away; running sessions finish their current work first.","trust.doneApplied":"Applied. Sessions in this project now start with this setting.","trust.doneCancelled":"Scheduled trust cancelled. The project stays restricted.","trust.refresh":"Refresh","i18n.creatingSession":"Creating new session…","i18n.creating":"Creating…","i18n.subscription":"Subscription","i18n.subscriptions":"Subscriptions","i18n.customEndpoint":"Custom endpoint format","i18n.noChanges":"No changes","i18n.branches":"Branches","i18n.noActiveSession":"No active session","i18n.noBranches":"This session has no branches","i18n.source":"Source","i18n.preview":"Preview","i18n.diff":"Diff","i18n.downloadFile":"Download file","i18n.liveSync":"Live sync active","i18n.notWatching":"Not watching","i18n.fileViewMode":"File view mode","i18n.compareHead":"Compare working tree with HEAD","i18n.mentionSelectedLines":"Mention selected lines","i18n.disableWrap":"Disable word wrap","i18n.enableWrap":"Enable word wrap","i18n.htmlPreview":"HTML preview","i18n.previewFile":"Preview {file}","i18n.invalidMermaid":"Invalid Mermaid diagram","i18n.renderingMermaid":"Rendering Mermaid diagram","i18n.previewAfterStreaming":"Preview available after streaming","i18n.showMermaidSource":"Show Mermaid source","i18n.previewMermaid":"Preview Mermaid diagram","i18n.openMermaidViewer":"Open diagram viewer","i18n.mermaidViewer":"Mermaid diagram viewer","i18n.mermaidDiagram":"Mermaid diagram","i18n.zoomOut":"Zoom out","i18n.zoomIn":"Zoom in","toolImage.dialogLabel":"Enlarged image","toolImage.requestEdit":"Request changes to this screen","toolImage.requestEditHint":"Attach this image to the message box. Describe the change, then send.","toolImage.noComposer":"There is no message box to attach to. Open a conversation, then press Request changes to this screen.","toolImage.loadFailed":"Couldn't load the image. Press Request changes to this screen again.","toolImage.markHint":"Drag over the part to change","toolImage.markLimit":"You can mark up to {count} areas","toolImage.clearMarks":"Clear marks","toolImage.regionLabel":"Area {n}","toolImage.locatorIntro":"The parts to change are marked with red boxes on the attached screen (areas {range}). A close-up of each area follows.","toolImage.locatorRegion":"Area {n}: x={x}, y={y}, width {w}, height {h} (original {width}\xd7{height} pixels)","files.pickElement":"Pick element","files.pickElementHint":"Click the element to change in the preview","files.pickedElement":"Picked element","files.requestElementEdit":"Request changes to this element","files.clearPick":"Clear selection","files.pickLocatorElement":"Element: {selector}","files.pickLocatorText":'Text: "{text}"',"files.pickLocatorPosition":"Position: x={x}, y={y}, width {w}, height {h} ({vw}\xd7{vh} preview)","i18n.fitToWidth":"Fit to width","models.discoveryFetching":"Importing models…","models.discoveryFetch":"Import models…","models.discoveryFilterPlaceholder":"Filter {count} models…","models.discoveryFilter":"Filter upstream models","models.discoverySelectShown":"Select shown","models.discoveryNoMatches":"No matching models.","models.discoveryAdded":"added","models.discoveryShowing":"Showing first {shown} of {total}","models.discoveryFetched":"{count} models fetched","models.discoveryAddSelected":"Add selected","models.discoveryAddSelectedCount":"Add selected ({count})","models.catalogSource":"source: models.dev ↗","models.catalogFilling":"Filling details…","models.catalogFill":"Fill model details","models.catalogFilled":"{count} fields filled","models.catalogNoEmptyFields":"No empty fields to fill","models.catalogNoExactMatch":"No exact models.dev match","models.catalogPriceProvider":"Price matched Provider {provider}","models.catalogPriceBaseUrl":"Price matched Base URL to {provider}","models.catalogPriceConsensus":"Price agreed by {support}/{total} records","models.catalogPriceUnreliable":"No reliable price found","models.catalogUndo":"Undo","models.navGroupRoles":"Role assignments","models.navGroupAccounts":"Connected accounts","models.navGroupCustom":"Custom providers","i18n.testingModel":"Testing model connection...","i18n.connected":"Connected","i18n.failed":"Failed","i18n.test":"Test","i18n.testConnection":"Test model connection","i18n.provider":"Provider","i18n.model":"Model","i18n.providerName":"Provider name","i18n.rename":"Rename","i18n.default":"Default","i18n.disabled":"Disabled","i18n.noResources":"No resources","i18n.unknown":"Unknown","i18n.installedVersion":"installed {version}","i18n.configuredVersion":"configured {version}","i18n.extensions":"Extensions","i18n.prompts":"Prompts","i18n.themes":"Themes","i18n.resourceCount":"{count} {label}","i18n.extensionShort":"ext","i18n.skillShort":"skills","i18n.promptShort":"prompts","i18n.themeShort":"themes","i18n.custom":"Custom","i18n.clearAll":"clear all","i18n.connectedSuccessfully":"Connected successfully.","i18n.notConnected":"not connected","i18n.configured":"configured","i18n.notConfigured":"not configured","i18n.openingBrowser":"Opening browser…","i18n.submit":"Submit","i18n.login":"Login","i18n.relogin":"Re-login","i18n.deviceLogin":"Log in with device code","i18n.deviceLoginGuide":"Open the page below, sign in, and enter this code. Nothing has to reach this server's localhost, so it also works on a remote server.","i18n.disconnect":"Disconnect","i18n.networkError":"Network error","i18n.continuing":"Continuing…","i18n.skills":"Skills","i18n.plugins":"Plugins","i18n.addSkill":"Add skill","i18n.addPlugin":"Add plugin","i18n.selectSkill":"Select a skill","i18n.selectPackage":"Select a package","i18n.updateAvailable":"Update available","i18n.upToDate":"Up to date","i18n.automaticChecksUnavailable":"Automatic checks unavailable","i18n.checkFailed":"Check failed","i18n.installed":"Installed","i18n.status":"Status","i18n.version":"Version","i18n.package":"Package","i18n.resources":"Resources","i18n.installedPath":"Installed path","i18n.cwd":"CWD","i18n.resolvedResources":"Resolved Resources","i18n.reloadSession":"Reload session","i18n.reloadSessionHint":"Reloads settings and skills for the open session. It does not unload plugins; restart CUELO for that.","i18n.reloading":"Reloading...","i18n.packageRemoved":"Package removed.","i18n.packageInstalled":"Package installed.","i18n.packageUpdated":"Package updated.","i18n.packageDisabled":"Package disabled.","i18n.packageDisabledRestartRequired":"Disabled setting saved. The plugin already loaded keeps running until CUELO restarts; reloading the session does not unload it.","i18n.packageEnabled":"Package enabled.","i18n.sessionReloaded":"Session reloaded.","i18n.thinking":"Thinking","i18n.largeMessageReveal":"Message content is very large ({size}). Click to view as plain text — markdown rendering is disabled to keep the page responsive.","i18n.loadingThinking":"Loading thinking...","i18n.copyMessage":"Copy message","i18n.editFromHere":"Edit from here","i18n.editFromHereTitle":"Edit from here — branches within this session","i18n.newSession":"New session","i18n.newSessionTitle":"New session — creates an independent copy from here","i18n.estimatedTokens":"Estimated token count while streaming","i18n.messageUsage":"Usage","i18n.messageUsageTitle":"Show this message's tokens and cost","i18n.providerAnthropicSubscription":"Anthropic subscription","i18n.providerAnthropicApi":"Anthropic API","i18n.noOutput":"(no output)","i18n.noSummary":"(no summary)","i18n.conversationCompacted":"Conversation compacted","i18n.compactionDescription":"The conversation history before this point was compacted into the following summary:","i18n.fileContext":"File context: {details}","i18n.readFiles":"Read files","i18n.modifiedFiles":"Modified files","i18n.hiddenExtensionMessage":"hidden extension message","i18n.noMessage":"(no message)","i18n.showOriginalReply":"Show English original","i18n.hideOriginalReply":"Hide English original","i18n.showInputTranslation":"Show English translation","i18n.hideInputTranslation":"Hide English translation","i18n.showExtensionMessage":"Show extension message","i18n.collapse":"Collapse","i18n.expand":"Expand","i18n.hideDetails":"Hide details","i18n.showDetails":"Show details","i18n.thinkingUnavailable":"Thinking content unavailable","i18n.before":"Before","i18n.after":"After","i18n.sessionComplete":"Session complete","i18n.taskFinished":"Task finished.","i18n.attentionNeeded":"Pi needs your attention","i18n.extensionInputNeeded":"An extension is waiting for your input.","navigator.toolbar":"Navigator views","navigator.priority":"Priority","navigator.view":"{label} navigator","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"This session is bound to 6 Pro connection number {handle}.","usage.none":"Usage —","usage.open":"Open usage details: {rows}","usage.openMore":", and {count} more","usage.showMore":"Show {count} more","usage.showLess":"Show less","usage.accountBlocked":"auto-blocked","usage.accountSpent":"account limit used up","usage.limitSpent":"limit used up","usage.bai":"B.AI tokens","usage.baiEmpty":"none recorded","usage.baiRange":"aggregated {from}–{to}","usage.baiUnmeasured":"not measured","usage.title":"Usage","usage.reorder":"Reorder","usage.reorderDone":"Done","usage.reorderGroup":"Account display order","usage.moveUp":"Move {account} up","usage.moveDown":"Move {account} down","usage.moved":"{account} moved to position {position}","usage.authExpired":"sign-in expired","usage.authUnavailable":"unavailable","usage.relogin":"Sign in again","usage.reloginFor":"Sign in again as {account}","usage.authIssues":"Account issues: {count}","relogin.title":"Account to sign in again","relogin.guide":"Press {action} and finish in the browser with this account. Signing in with a different account leaves this one failing.","relogin.done":"Sign-in finished.","relogin.checking":"Re-reading usage to check {account}…","relogin.recovered":"{account} is signed in again.","relogin.stillFailing":"Sign-in finished, but {account} still reports an auth error. You may have signed in with a different account.","relogin.unknown":"Could not find {account} in usage, so recovery is not confirmed.","efficiency.title":"Efficiency","efficiency.governor":"Run control","efficiency.lab":"Experiment Lab","efficiency.refresh":"Refresh","efficiency.refreshing":"Loading…","efficiency.noSession":"Select a session to see its runs.","efficiency.loadingRuns":"Loading runs…","efficiency.runsEmpty":"No runs recorded in this session.","efficiency.runsError":"Could not load runs.","efficiency.selectRun":"Select a run to see roles, bottlenecks, and unmeasured gaps.","efficiency.loadingDetail":"Loading run detail…","efficiency.detailError":"Could not load the run detail.","efficiency.noTitle":"Untitled request","efficiency.elapsed":"Elapsed","efficiency.busyTotal":"Generation time total","efficiency.noSumNote":"Elapsed and generation total are shown side by side, never added.","efficiency.summarySection":"Summary","efficiency.rolesSection":"Roles","efficiency.rolesEmpty":"No role recorded a request in this run.","efficiency.bottlenecksSection":"Bottlenecks","efficiency.bottlenecksEmpty":"No bottleneck measured.","efficiency.toolsSection":"Tool calls","efficiency.unmeasuredGap":"Unmeasured gap","efficiency.elapsedValue":"Elapsed {value}","efficiency.estimatedCostValue":"Est. {value}","efficiency.estimatedCost":"Est. cost","efficiency.untimedLowerBound":"{value} request(s) have no recorded duration — generation time is a lower bound.","efficiency.bottleneckOrderNote":"Largest observed items, longest first. Bar length is relative to the top item, not to elapsed time.","efficiency.untimedRuns":"Runs missing duration","efficiency.untimedMedianLowerBound":"{value} run(s) contain requests with no recorded duration — the median generation time is a lower bound.","efficiency.unpricedLowerBound":"Includes unpriced records — lower bound","efficiency.mixedPairingNote":"Mixed configuration: which model and reasoning effort each request used, and in what order, could not be determined. These runs cannot be assumed to share the same conditions.","efficiency.unmeasuredShort":"Unmeasured","efficiency.effortLabel":"Effort {value}","efficiency.requestsValue":"{value} requests","efficiency.toolCallsValue":"{value} tool calls","efficiency.busyTime":"Generation time","efficiency.tokens":"Tokens","efficiency.unpricedRequests":"Unpriced requests","efficiency.firstTokenAvg":"Wait for first token (avg)","efficiency.firstTokenPartial":"First-token wait is averaged over {recorded}/{total} requests that recorded it.","efficiency.outputTokens":"Conversation output tokens","efficiency.helpersTitle":"Auxiliary model calls","efficiency.helperCallsValue":"{count} calls \xb7 output {output} \xb7 total {tokens} \xb7 {cost}","efficiency.helpersIncludedNote":"Auxiliary call tokens and cost are included in the token and estimated cost totals above, and excluded from request count, first-token wait, and conversation output tokens.","efficiency.toolFailedValue":"failed {value}","efficiency.toolNoMatchValue":"no match {value}","efficiency.toolCancelledValue":"cancelled {value}","efficiency.unmeasuredGapValue":"Unmeasured gap {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"Unattributed","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"Completed","efficiency.outcomeError":"Error","efficiency.outcomeAborted":"Aborted","efficiency.outcomeInterrupted":"Interrupted","efficiency.outcomeRunning":"Running","efficiency.folder":"Folder","efficiency.folderAll":"All folders","efficiency.folderPlaceholder":"Filter by folder, Enter to apply","efficiency.loadingExperiments":"Loading config comparison…","efficiency.experimentsEmpty":"No config recorded for comparison.","efficiency.experimentsError":"Could not load the config comparison.","efficiency.difficultyNote":"Task difficulty is not normalized.","efficiency.runsValue":"{value} runs","efficiency.medianElapsed":"Median elapsed","efficiency.medianBusy":"Median generation","efficiency.medianTokens":"Median tokens","efficiency.medianEstimatedCost":"Median est. cost","efficiency.totalEstimatedCost":"Total est. cost","efficiency.reworkRate":"Rework rate","efficiency.errorRate":"Error rate","efficiency.unpricedRuns":"Unpriced runs","efficiency.scopeAttributed":"Current roles only","efficiency.scopeAll":"All runs","efficiency.scopeSessions":"Sessions counted","efficiency.scopeRuns":"Runs counted","efficiency.scopeExcludedRuns":"Runs excluded","efficiency.harness":"Harness","efficiency.harnessValue":"Harness {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"All harnesses","efficiency.groupByHarness":"Split by harness","efficiency.harnessNote":"Harness is the CUELO version installed when the run started. It comes only from this PC's update records; runs without a record, or in a span changed outside the records, are unknown.","efficiency.sawSection":"What the model saw","efficiency.sawApproxNote":"Approximate, rebuilt from the session log. The system prompt sent with each request and context-hook rewrites are not recorded.","efficiency.sawOpen":"Show requests","efficiency.sawLoading":"Loading requests…","efficiency.sawError":"Could not load requests.","efficiency.sawEmpty":"No model requests are recorded for this run.","efficiency.sawFilterEmpty":"No requests with injections.","efficiency.sawRole":"Transcript","efficiency.sawSummary":"{turns} requests \xb7 {injections} injected \xb7 {tools} tool calls \xb7 {failed} failed","efficiency.sawOnlyInjected":"Only requests with injections","efficiency.sawTurnLabel":"Request {index}","efficiency.sawBefore":"Arrived before this request","efficiency.sawTrailing":"Arrived after the last request (not part of any model request in this run)","efficiency.sawShowFull":"Show full text","efficiency.sawShowArgs":"Show arguments","efficiency.sawShowResult":"Show result","efficiency.sawHideFull":"Collapse","efficiency.sawTruncated":"Showing the first {value} characters.","efficiency.sawMore":"Load {value} more","efficiency.sawShown":"Showing {shown} of {total}","efficiency.sawHiddenFromChat":"Hidden in chat","efficiency.sawNotSent":"Not sent to the model","efficiency.sawSecretsMasked":"Strings that look like secrets are replaced with [REDACTED].","efficiency.sawKindInjection":"Injected","efficiency.sawKindDeveloper":"Developer message","efficiency.sawKindUser":"User message","efficiency.sawKindCompaction":"Compaction","efficiency.sawKindModel":"Model change","efficiency.sawKindEffort":"Effort change","efficiency.sawKindPrompt":"System prompt changed","efficiency.sawKindRules":"Rules injected","efficiency.sawKindMemory":"Memory recall","efficiency.sawCompactionValue":"{before} → {after} tokens","efficiency.sawMemoryIds":"{value} memories recalled (text not recorded)","efficiency.sawToolOk":"OK","efficiency.sawToolFailed":"Failed","efficiency.sawToolNoMatch":"No match","efficiency.sawToolCancelled":"Cancelled","efficiency.sawToolMissing":"No result","efficiency.sawResultChars":"result {value} chars","efficiency.sawUsage":"in {input} \xb7 out {output} \xb7 cache read {cacheRead}","efficiency.sawStop":"stop: {value}","efficiency.sawToolsChanged":"Tool list changed: +{added} −{removed}","efficiency.sawPreludeTitle":"System prompt and tools","efficiency.sawPreludeRecorded":"Recorded","efficiency.sawPreludeTools":"{value} tools active in the last request (recorded)","efficiency.sawPreludeDigest":"System prompt fingerprint: {value}","efficiency.sawPreludeDigestNone":"No system prompt fingerprint is recorded for this run.","efficiency.sawPreludeMemory":"Memory recall block (part of the system prompt, recorded)","efficiency.sawPreludeReconstruct":"Rebuild from current settings","efficiency.sawPreludeLoading":"Rebuilding…","efficiency.sawPreludeApprox":"Rebuilt now from the current configuration, not as sent.","efficiency.sawPreludeNotLoaded":"This session is not loaded right now, so it cannot be rebuilt. The system prompt text is not recorded.","efficiency.sawPreludeMatch":"The current prompt's fingerprint matches this run's record.","efficiency.sawPreludeMismatch":"The current prompt's fingerprint differs from this run's record; it may have changed since.","toolRun.running":"Running","toolRun.failed":"Failed","toolRun.exitCode":"exit {code}","toolRun.diffStats":"{added} lines added, {removed} lines removed","toolRun.askTimedOut":"No answer before the timeout. The form's current values were submitted.","panel.expand":"Widen panel","panel.restore":"Restore size","panel.more":"More","panel.liveSync":"Live updates","panel.subagentsCount":"{count} records","panel.refresh":"Refresh records","panel.close":"Close panel","pluginLab.counts":"{count} plugins","pluginLab.refresh":"Refresh list","pluginLab.create":"New plugin","pluginLab.createHint":"Puts a request into the message box. Edit it, then send.","pluginLab.starter":"Use the plugin-lab skill to build a plugin for my profile.\n- What it should do: \n- Tools it needs: \n- What its panel shows (leave empty for none): \nWrite it straight into the repository's formal plugin folder and ship it through review, version, CI and deploy in this turn.","pluginLab.loading":"Loading plugins…","pluginLab.loadFailed":"Could not load plugins: {error}","pluginLab.retry":"Load again","pluginLab.empty":"No plugins yet. Use “New plugin” to put a request into the message box.","pluginLab.listLabel":"Plugins","pluginLab.on":"On","pluginLab.off":"Off","pluginLab.toggleLabel":"Use {name}","pluginLab.toggleFailed":"Could not change the state: {error}","pluginLab.tools":"Tools","pluginLab.lastEnhancement":"Last enhancement","pluginLab.lastEnhancementHint":"Shows the date this plugin was last improved.","pluginLab.problem":"Problem","pluginLab.openPanel":"Open panel","pluginLab.openPanelLabel":"Open the {name} panel","pluginLab.back":"Back to plugins","pluginLab.panelSubtitle":"Sandboxed \xb7 lab:{id}","pluginLab.frameTitle":"{name} panel","pluginLab.lines":"{count} lines of agent data","pluginLab.noLines":"No agent data in this session","pluginLab.draftInserted":"The panel's draft is in the message box. Check it, then send.","pluginLab.applyHint":"Tool changes apply in a new session or after /reload.","pluginLab.noComposer":"Open a conversation to use the message box.","pluginLab.draftNotRecorded":"The draft is in the message box, but its use was not recorded.","pluginLab.saving":"Changing…","makerDetail.region":"{title} record","makerDetail.noFiles":"This Maker changed no files","makerDetail.noChecks":"No checks were run","makerDetail.archiveUnobserved":"The record holds no tool results, so this cannot be confirmed","makerDetail.unavailable":"No run record matches this attempt exactly, so its detail cannot be opened","makerDetail.checkPassed":"passed","makerDetail.checkUnverified":"verdict not confirmed","makerDetail.checkFailed":"failed","makerDetail.checkUnobserved":"result not observed","dispatchLane.label":"Maker attempts","dispatchLane.runPhase":"{run} ({phase})","dispatchLane.checks":"checks {passed}/{total}","dispatchLane.checksUnobserved":"checks not observed","dispatchLane.checksLoading":"reading checks","dispatchLane.attempt":"attempt {attempt}","dispatchLane.attemptUnknown":"attempt","dispatchLane.verdict.accepted":"accepted","dispatchLane.verdict.rework":"rework","dispatchLane.verdict.held":"held","dispatchLane.open":"Details","dispatchLane.openLabel":"Open details for {title}","dispatchLane.unavailable":"No detail","credits.heading":"API credits","credits.estimateNote":"The billing-page balance is what you read on the provider's billing page at the shown time. Later usage is not included. Estimated spend and balance multiply this PC's token counts by published prices and are not a bill.","credits.loading":"Loading API credits…","credits.loadFailed":"Could not load API credits: {reason}","credits.wallet.hive":"Hive","credits.scope.hive":"This PC's records","credits.since":"since {date}","credits.sinceDefault":"last 30 days","credits.total":"Total","credits.spent":"Est. spent","credits.remaining":"Est. left","credits.meterLabel":"{wallet} credit used","credits.usedPct":"{pct}% used","credits.enterPrompt":"Enter the total and start date to see an estimated balance.","credits.enter":"Enter credit","credits.edit":"Edit","credits.formLabel":"{wallet} credit","credits.totalUsd":"Total (USD)","credits.startDate":"Start date","credits.save":"Save","credits.saving":"Saving…","credits.cancel":"Cancel","credits.clear":"Remove","credits.saveFailed":"Not saved: {reason}","credits.invalid.total":"Enter the total as a number.","credits.error.invalid_total":"the total must be a number above 0","credits.error.invalid_start_date":"check the start date","credits.error.start_date_in_future":"the start date is in the future","credits.error.session_scan_failed":"session records could not be read","credits.error.session_scan_partial":"some session records could not be read, so the spent amount is a minimum","credits.error.internal":"an unexpected error occurred","credits.error.settings_unreadable":"the credit settings file could not be read, so it was not overwritten","credits.walletError":"Usage not read: {reason}","credits.settingsError":"The credit settings file could not be read. Enter the credits again.","credits.tokens":"in {input} \xb7 out {output}","credits.cacheTokens":"cache {cache}","credits.requests":"{count} calls","credits.priceUnknown":"price unknown","credits.purpose.session":"Chat \xb7 agents","credits.purpose.memory":"Memory","credits.purpose.korean-reply-translation":"Reply translation","credits.wallet.anthropic":"Anthropic API","credits.billingLink":"Actual balance","credits.billingLinkLabel":"See the actual {wallet} balance on its billing page (opens in a new tab)","credits.scope.anthropic":"This PC's records","credits.anthropic.note":"Counts only API-key responses with recorded tokens; excludes subscription (OAuth) requests and failed attempts without tokens. Amounts are estimates at published prices, not a bill or balance.","credits.anthropic.noCoverage":"No requests in this window have a recorded credential kind, so API-key usage is unknown.","credits.anthropic.coverageSince":"First recorded credential in window: {date} (this PC may not have recorded every later request)","credits.anthropic.none":"No recorded API-key requests in this window.","credits.anthropic.oauthExcluded":"Subscription (OAuth) excluded","credits.anthropic.unattributedExcluded":"Unrecorded credential excluded","credits.category.input":"Input","credits.category.output":"Output","credits.category.cacheRead":"Cache read","credits.category.cacheWrite":"Cache write","credits.balance.label":"Billing-page balance","credits.balance.source":"Manual record","credits.balance.observed":"Checked {time}","credits.balance.age.now":"Just now","credits.balance.age.minutes":"{count}m ago","credits.balance.age.hours":"{count}h ago","credits.balance.age.days":"{count}d ago","credits.balance.none":"No recorded balance","credits.balance.record":"Record balance","credits.balance.edit":"Edit balance","credits.balance.formLabel":"{wallet} billing-page balance","credits.balance.amount":"Balance (USD)","credits.balance.observedAt":"Checked at","credits.balance.observedAtHint":"When you saw the balance on the billing page.","credits.invalid.amount":"Enter a valid balance number.","credits.invalid.observedAt":"Enter a valid time.","credits.error.invalid_balance":"the balance must be 0 or more","credits.error.invalid_observed_at":"check the time","credits.error.observed_at_in_future":"the time is later than now","credits.error.routes_unreadable":"the settings file could not be read, so the APIs in use are unknown","credits.wallet.exa":"Exa","credits.wallet.typesafe":"TypeSafe Jev","credits.route.hive":"Assigned to model roles (memory, skim, etc.)","credits.route.exa":"Default web search path","credits.route.typesafe":"Default quick judgement (Jev) path","credits.route.anthropic":"API key fallback when the subscription's weekly allowance runs out","credits.evidence.lastPaidUse":"Last paid use on this PC: {time}","credits.evidence.unverified":"Some session logs could not be read, so recent paid use is unconfirmed.","memoryTrace.refresh":"Refresh","memoryTrace.noSession":"Select a session to see how it looked up memories.","memoryTrace.loading":"Reading the session log…","memoryTrace.error":"Could not load the memory trace. {error}","memoryTrace.retry":"Load again","memoryTrace.empty":"This session has no memory or doc-map records.","memoryTrace.requests":"{count} requests with records","memoryTrace.requestsLabel":"Requests","memoryTrace.requestHeading":"Request #{index}","memoryTrace.noPreview":"(no text)","memoryTrace.flowLabel":"Request flow","memoryTrace.stageRecall":"Recalled","memoryTrace.stageJev":"JEV check","memoryTrace.stageDocmap":"Map candidates","memoryTrace.stageDocs":"Docs opened","memoryTrace.stageLessons":"Pre-edit lessons","memoryTrace.stageSaved":"Saved","memoryTrace.stageEmpty":"This step did not happen in this request.","memoryTrace.openedSummary":"{opened} opened \xb7 {skipped} not opened","memoryTrace.opened":"Opened","memoryTrace.candidateOnly":"Candidate only","memoryTrace.fromMap":"Map candidate","memoryTrace.lines":"Lines {lines}","memoryTrace.autoRecall":"Recalled before the request","memoryTrace.explicitRecall":"Looked up during the work","memoryTrace.query":"Query","memoryTrace.noResults":"No memories came back.","memoryTrace.noMemoryText":"This log keeps no text for this memory.","memoryTrace.jevUnknown":"{count} undecided","memoryTrace.jevUnrelated":"{count} unrelated","memoryTrace.lessonFor":"Memories shown before editing","memoryTrace.savedAuto":"Auto-saved","memoryTrace.graphLabel":"Link graph","memoryTrace.graphScope":"Graph scope","memoryTrace.scopeRequest":"This request","memoryTrace.scopeSession":"Whole session","memoryTrace.legendRequest":"Request","memoryTrace.legendMemory":"Memory","memoryTrace.legendDoc":"Map doc","memoryTrace.legendFile":"Edited file","memoryTrace.graphEmpty":"Nothing is linked in this scope.","memoryTrace.nodeLabel":"{kind}: {label}, {count} links","memoryTrace.edgeRecalled":"Recalled","memoryTrace.edgeLesson":"Pre-edit lesson","memoryTrace.verdictLegend":"JEV verdict","memoryTrace.verdictApply":"Applies","memoryTrace.verdictExcepted":"Condition not met or exception","memoryTrace.verdictConflict":"Conflicts with the request","memoryTrace.verdictUnconfirmed":"Condition unconfirmed","memoryTrace.verdictUnlisted":"Unrelated or undecided","memoryTrace.graphHint":"Point at or focus a node to read its full text here.","memoryTrace.legendDocEdited":"Opened and edited","memoryTrace.noticeHarness":"Harness","memoryTrace.noticeResume":"Auto-resume"}}),l({id:"zh-CN",label:"简体中文",messages:{"cloudProjects.launch":"打开 GitHub 仓库","cloudProjects.title":"云端项目","cloudProjects.description":"将 GitHub 仓库导入此服务器并继续工作。","cloudProjects.github":"GitHub 仓库","cloudProjects.serverFolder":"打开服务器文件夹","cloudProjects.account":"GitHub 连接","cloudProjects.connectTitle":"连接你的 GitHub 仓库","cloudProjects.connectHelp":"登录后也可以从列表中选择私有仓库。","cloudProjects.connected":"已连接 GitHub","cloudProjects.refresh":"重新检查","cloudProjects.waiting":"等待登录","cloudProjects.connect":"连接 GitHub","cloudProjects.deviceHelp":"在 GitHub 登录页面输入以下代码。","cloudProjects.copyCode":"复制代码","cloudProjects.copied":"已复制","cloudProjects.copyFailure":"无法复制代码。请选择并手动复制。","cloudProjects.openLogin":"在 GitHub 上登录","cloudProjects.permissionHelp":"请在 GitHub 上确认账号和请求的权限后再授权。令牌仅保存在服务器上。","cloudProjects.preparingCode":"正在准备登录代码。","cloudProjects.repositories":"你的仓库","cloudProjects.search":"搜索仓库","cloudProjects.searchPlaceholder":"按名称或描述搜索","cloudProjects.loading":"正在加载仓库。","cloudProjects.private":"私有","cloudProjects.public":"公开","cloudProjects.empty":"没有匹配的仓库。请尝试其他名称或输入 URL。","cloudProjects.more":"显示更多","cloudProjects.urlLabel":"选中的仓库或 GitHub URL","cloudProjects.publicHelp":"公开仓库无需登录即可导入。已存在的工作区会直接打开,不修改文件。","cloudProjects.error":"操作未能完成。","cloudProjects.openingHelp":"正在将仓库导入服务器。大型仓库可能需要一些时间。","cloudProjects.opening":"正在打开项目","cloudProjects.open":"打开项目","common.ok":"确定","common.language":"语言","common.models":"模型","common.skills":"技能","common.plugins":"插件","common.settings":"设置","updates.available":"有可用的 CUELO 更新","updates.availableTitle":"CUELO {version} 可用","updates.dialogEyebrow":"CUELO 发布","updates.dialogTitle":"新的 CUELO 版本","updates.current":"当前 CUELO {version}","updates.changelog":"更新日志","updates.viewRelease":"查看发布","updates.manual":"从源码运行时,请先停止服务器,运行以下命令更新,然后重新启动。如果使用自定义 --home 路径,请为 setup 添加相同的 --home 选项。","updates.copyCommand":"复制命令","updates.commandCopied":"命令已复制","updates.copyFailed":"无法复制命令","updates.apply":"立即更新","updates.applyBusy":"正在更新…","updates.applyConfirm":"将 CUELO 更新到 {version} 并重新启动?\n\n更新期间服务器会短暂停止,此面板会显示进度。新版本响应后页面会自动刷新。","updates.applyConfirmBusy":"将 CUELO 更新到 {version} 并重新启动?\n\n{count} 个运行中的会话会被中断,服务器会短暂停止。此面板显示进度,新版本响应后页面会自动刷新。","updates.unsupported":"此安装方式无法在应用内更新,请使用下面的命令。","updates.unsupportedReason":"检测结果:{reason}","updates.phase.starting":"正在准备更新","updates.phase.fetching":"正在获取新版本","updates.phase.installing":"正在安装包","updates.phase.building":"正在构建","updates.phase.restarting":"正在重新启动服务器","updates.phase.done":"更新完成","updates.phase.handed-off":"已交给服务更新","updates.phase.restart-required":"安装完成,请手动重启 CUELO","updates.phase.failed":"更新失败","updates.waitingForRestart":"正在等待服务器恢复。新版本响应后页面会刷新。","updates.handedOff":"WSL 服务更新会在其等待页面中继续进行,完成后此页面会刷新。","updates.logPath":"日志:{path}","updates.applyStartFailed":"无法启动更新:{reason}","sidebar.hide":"隐藏侧边栏","sidebar.show":"显示侧边栏","theme.light":"浅色模式(点击切换到深色)","theme.dark":"深色模式(点击切换到跟随系统)","theme.auto":"跟随系统(点击切换到浅色)","theme.graphite":"石墨主题(壁纸)","theme.graphiteHint":"石墨色界面,壁纸随当前角色模式变化。仅在深色模式下生效,只保存在此浏览器中。","history.full":"完整历史","history.unsaved":"会话保存后才能查看完整历史","history.label":"完整历史","title.generating":"正在生成...","title.updated":"标题已更新","title.failed":"生成失败","title.generate":"生成标题","title.unsaved":"会话保存后才能生成标题","title.noMessages":"请先发送消息,再为会话命名","title.generateSession":"生成会话标题","system.prompt":"系统提示词","system.empty":"系统提示词为空(工具已禁用)","system.load":"发送消息以加载系统提示词","system.label":"系统","session.info":"会话信息","session.name":"名称","session.file":"文件","session.inMemory":"内存中","session.id":"ID","session.user":"用户","session.assistant":"助手","session.toolCalls":"工具调用","session.toolResults":"工具结果","session.total":"总计","session.input":"输入","session.output":"输出","session.cacheRead":"缓存读取","session.cacheWrite":"缓存写入","session.cost":"费用","session.context":"上下文","session.cacheHitRate":"平均缓存命中率","session.copy":"复制{value}","session.copied":"已复制","session.title":"会话信息","session.load":"发送消息或运行 /session 以加载会话信息","session.infoSection":"会话信息","session.messages":"消息","session.tokens":"Token","session.totalActive":"活跃时长","session.copyFile":"复制文件路径","session.copyId":"复制会话 ID","workspace.opening":"正在打开工作区...","workspace.unable":"无法打开工作区","workspace.selectSession":"从侧边栏选择一个会话","workspace.getStarted":"开始使用","workspace.selectProject":"从侧边栏选择项目目录","workspace.addModels":"点击底部的“模型”按钮添加模型","workspace.stepProject":"从侧边栏选择项目目录","workspace.stepModels":"点击底部的“模型”按钮添加模型","workspace.mainWorking":"工作中","workspace.mainWaiting":"等待中","workspace.mainIdle":"空闲","workspace.mainAttention":"需要输入","files.hidePanel":"隐藏文件面板","files.showPanel":"显示文件面板","files.noneOpen":"没有打开的文件","files.docs.noProject":"选择项目后可查看其文档。","files.docs.loading":"正在查找项目文档…","files.docs.projectDenied":"此项目文件夹不在 CUELO 可读取的文件夹范围内。","files.docs.loadFailed":"无法加载项目文档:{error}","files.docs.projectDir":"项目文件夹:{path}","files.docs.noneFound":"直到仓库根目录都没有 HANDOFF.md,此文件夹中也没有 doc/README.md 或 doc/history。","files.docs.current":"当前状态","files.docs.map":"文档地图","files.docs.records":"最近记录","files.docs.missing":"未找到 {file}","files.docs.denied":"{file} 不在可读取的文件夹范围内","layout.resizeSidebar":"调整侧边栏宽度","layout.resizeFilePanel":"调整文件面板宽度","layout.resizeHint":"拖动调整宽度。双击或按 Enter 恢复默认值。","sidebar.new":"新建","sidebar.newSessionTitle":"在 {path} 中新建会话","sidebar.refresh":"刷新","sidebar.projects":"项目","subagents.title":"子代理","subagents.running":"运行中","subagents.finished":"已完成","subagents.history":"历史","subagents.runningCount":"运行中 {count}","subagents.finishedCount":"已完成 {count}","subagents.failed":"失败","subagents.aborted":"已中止","subagents.back":"返回子代理列表","subagents.retrying":"正在重试 {attempt}/{max}","subagents.usingTool":"正在使用 {tool}","subagents.details":"子代理执行详情","subagents.closeDetails":"关闭子代理详情","subagents.noTask":"无任务描述","subagents.tools":"{count} 个工具","subagents.tokens":"{count} 个 Token","subagents.loadingTranscript":"正在加载实时记录…","subagents.noTranscript":"子代理尚未写入任何会话记录。","subagents.transcriptUnavailable":"实时记录暂不可用。子代理运行期间将继续重试。","sidebar.searchProjectsAndSessions":"搜索项目和会话标题…","sidebar.addProject":"添加自定义项目路径","sidebar.projectActions":"项目操作","sidebar.projectAlias":"别名","sidebar.projectAliasEdit":"编辑别名","sidebar.projectHide":"隐藏","sidebar.projectUnhide":"取消隐藏","sidebar.projectShowHidden":"显示隐藏的项目","sidebar.temporaryProjects":"临时/系统路径","sidebar.projectMoveUp":"上移","sidebar.projectMoveDown":"下移","sidebar.projectMoveDisabledWhileFiltering":"清除搜索筛选后才能重新排序项目","sidebar.projectUpdateFailed":"无法保存项目更改,请重试。","sidebar.expandProject":"展开项目","sidebar.collapseProject":"收起项目","sidebar.showMore":"显示更多","sidebar.showLess":"收起","sidebar.selectProject":"选择项目…","sidebar.filterProjects":"筛选项目…","sidebar.noMatchingProjects":"没有匹配的项目","sidebar.useDefaultDirectory":"使用默认目录","sidebar.customPath":"自定义路径…","directoryPicker.selectDirectory":"选择目录","directoryPicker.goToParent":"转到上级目录","directoryPicker.directoryPath":"目录路径","directoryPicker.goToDirectory":"转到目录","directoryPicker.go":"转到","directoryPicker.loadingDirectories":"正在加载目录…","directoryPicker.noSubdirectories":"没有子目录","directoryPicker.openBeforeSelecting":"选择前请先打开此路径","directoryPicker.selectCurrentDirectory":"选择当前目录","directoryPicker.selectThisFolder":"选择此文件夹","directoryPicker.noDrives":"未找到盘符","sidebar.checking":"检查中…","sidebar.open":"打开","sidebar.cancel":"取消","sidebar.openRepoRoot":"打开仓库根目录","sidebar.openRepoRootTitle":"打开仓库根目录以管理 worktree。","sidebar.gitRepoRootOnly":"仅 Git 仓库根目录","sidebar.gitRepoRootOnlyTitle":"只能在 Git 仓库根目录使用 worktree。","sidebar.worktrees":"Worktrees...","sidebar.checkingWorktrees":"正在检查此目录的 worktree。","sidebar.filterWorktrees":"筛选 worktree…","sidebar.noMatchingWorktrees":"没有匹配的 worktree","sidebar.switchWorktree":"切换 worktree","sidebar.switchWorktreeTitle":"切换 worktree:{path}","sidebar.main":"主分支","sidebar.forceRemoveCheckout":"存在未提交的更改。强制移除 checkout?","sidebar.force":"强制移除","sidebar.createWorktreeTitle":"为分支创建 worktree checkout","sidebar.newWorktree":"新建 worktree…","sidebar.branchName":"分支名称","sidebar.creating":"创建中…","sidebar.create":"创建","sidebar.loading":"加载中...","sidebar.noSessions":"未找到会话","sidebar.agentRunning":"Agent 运行中…","sidebar.newActivity":"有新活动","sidebar.newSessionActivity":"会话有新活动","sidebar.deleteSession":"删除 {title}?","sidebar.rename":"重命名","sidebar.pin":"固定到顶部","sidebar.unpin":"取消固定","sidebar.pinned":"已固定","sidebar.delete":"删除","sidebar.deleteWithShiftClick":"删除(按住 Shift 点击可跳过确认)","sidebar.clearProjectSessions":"清空会话","sidebar.clearPriorityList":"清空列表","navigator.resultsToCheck":"待查看","navigator.resultsToCheckCount":"待查看 {count}","navigator.resultsToCheckHint":"自你在此浏览器上次打开后又有新进展且已结束的对话,以及等待你回答的对话","navigator.resultsToCheckEmpty":"没有待查看的结果。","navigator.acknowledgeResults":"全部标为已看","navigator.acknowledgeResultsHint":"将当前待查看的所有对话标为已看。等待你回答的对话会保留。","sidebar.waitingForAnswer":"等待回答","sidebar.waitingForAnswerHint":"在你回答其提问或批准请求之前已暂停","sidebar.newScratchSession":"新建会话","sidebar.newScratchSessionTitle":"不选择项目直接开始会话(使用主目录下按日期命名的临时文件夹)","sidebar.newScratchSessionFailed":"无法创建临时文件夹:{error}","sidebar.clearSessionsTitle":"确认删除会话","sidebar.clearSessionsProjectBody":"将永久删除 {project} 中的 {count} 个会话,且无法恢复。","sidebar.clearSessionsPriorityBody":"将永久删除优先级列表中的 {count} 个会话,且无法恢复。","sidebar.clearSessionsRunningExcluded":"保留 {count} 个正在运行的会话。","sidebar.clearSessionsNone":"当前没有可删除的会话。","sidebar.clearSessionsConfirm":"删除","sidebar.clearSessionsCancel":"取消","sidebar.clearSessionsBusy":"删除中…","sidebar.clearSessionsFailed":"有 {count} 个会话删除失败:{names}","sidebar.archive":"归档(从列表隐藏,可恢复)","sidebar.archived":"已归档","sidebar.restore":"恢复","sidebar.noArchivedSessions":"没有已归档的会话","sidebar.expandForks":"展开分叉","sidebar.collapseForks":"折叠分叉","sidebar.messagesCount":"{count} 条消息","sidebar.worktreePath":"Worktree:{path}","sidebar.removeWorktreeTitle":"移除 worktree checkout {path};保留分支","files.deleted":"已删除","files.insertPath":"将路径插入聊天","files.mention":"提及","chat.loadingSession":"正在加载会话...","chat.runningTool":"正在运行工具...","chat.runningNamedTool":"正在运行 {name}...","chat.runningTools":"正在运行 {names}...","chat.runningToolsMore":"正在运行 {names}(另有 {count} 个)...","chat.waitingModel":"正在等待模型...","todo.progress":"{percent}% \xb7 {total} 项中完成 {completed} 项 \xb7 剩余 {remaining} 项","todo.progressDone":"{percent}% \xb7 {total} 项中完成 {completed} 项","todo.allDone":"{count} 项全部完成","todo.showCompleted":"查看已完成 {count} 项","todo.hideCompleted":"收起已完成 {count} 项","todo.ready":"可开始","todo.waiting":"等待:{tasks}","chat.runningCommand":"正在运行命令...","chat.thinking":"正在思考...","chat.contextUsageTitle":"上下文窗口:已用 {used} / {limit} Token({percent})","chat.contextUsageWarning":"上下文窗口正在接近上限","chat.contextUsageCritical":"上下文窗口几乎已满","chat.processDetails":"处理详情","chat.message":"条消息","chat.messages":"条消息","chat.toolCall":"次工具调用","chat.toolCalls":"次工具调用","chat.collapseProcess":"收起处理详情","chat.expandProcess":"展开处理详情","process.empty":"此会话还没有处理记录","process.turn":"轮","process.turns":"轮","chat.filesWritten":"改动的文件","chat.openWrittenFile":"打开 {name}","chat.lessonsSaved":"[已保存经验] 代理在本轮中自行保存了以下内容。","chat.savedLesson":"经验:{memory}","chat.savedSkill":"技能 {action}:{name}","chat.loadEarlier":"向上滚动以加载更早的消息(隐藏 {count} 条)","chat.extensionRequest":"扩展请求","chat.responseSending":"正在发送你的回复...","chat.responseFailed":"回复未送达代理。它仍在等待 - 请重试。","chat.cancel":"取消","chat.confirm":"确认","chat.submit":"提交","chat.agentQuestion":"代理需要你的输入","chat.agentQuestionHint":"选择一个选项,或提供自定义回复。","chat.askAutoSelectHint":"{seconds} 秒内无响应将自动选择推荐选项。选择或输入会重新开始计时。","chat.recommended":"推荐","chat.customAnswer":"其他回复(可选)","chat.chatAboutThis":"对此进行讨论","chat.submitAnswer":"提交回答","chat.agentFormHint":"填写表单后提交。","chat.askFormAutoSubmitHint":"{seconds} 秒内无响应,将提交表单中当前的值。编辑会重新开始计时。","chat.formOther":"其他","chat.formOtherPlaceholder":"输入你自己的回答","chat.formRequired":"必填","chat.formInvalid":"请先检查标记的字段再提交。","chat.formImageUnavailable":"无法加载图片","chat.formError.required":"必填项","chat.formError.selectAtLeastOne":"至少选择一项","chat.formError.enterNumber":"请输入数字","chat.formError.min":"不能小于 {value}","chat.formError.max":"不能大于 {value}","chat.formError.minLength":"至少需要 {value} 个字符","chat.formError.maxLength":"最多 {value} 个字符","chat.formError.email":"请输入电子邮件地址","chat.formError.url":"请输入完整的 URL","chat.formError.pattern":"格式不符({pattern})","chat.planApproval":"计划审批","chat.planFeedback":"下一轮计划的反馈(可选)","chat.refinePlan":"继续规划","chat.approvePlan":"批准并实施","chat.extensionInput":"扩展终端输入","chat.extensionPanel":"扩展面板","chat.close":"关闭","chat.queued":"已排队 \xb7 {count}","chat.recall":"移回输入框","chat.recallTitle":"移除所有排队消息并将其放回输入框编辑","chat.queueRemove":"仅取消这条排队消息","chat.retrying":"正在重试({attempt}/{max})…","chat.loadingCommands":"正在加载命令...","chat.slashCommands":"斜杠命令 \xb7 {label}","chat.tabEnter":"Tab / Enter","chat.noCommands":"未找到命令","chat.match":"1 个匹配项","chat.matches":"{count} 个匹配项","chat.command":"1 个命令","chat.commands":"{count} 个命令","chat.loadingFiles":"正在加载文件...","chat.files":"文件 \xb7 {label}{hint}","chat.searching":"搜索中…","chat.noMatchingFiles":"未找到匹配的文件","chat.searchingAll":" \xb7 正在搜索所有文件…","chat.indexTruncated":" \xb7 索引不完整","chat.steerPlaceholder":"立即引导 / 排队后续消息...","chat.agentPlaceholder":"Agent 运行中…","chat.messagePlaceholder":"消息… / 命令 \xb7 @ 文件","chat.steer":"引导","chat.followUp":"后续消息","chat.send":"发送","chat.attachImageLimit":"每条消息最多可附加 {count} 张图片。","chat.attachImageTooLarge":"{name} 超出每张图片 {limit} 的限制。","chat.attachFile":"附加文件","chat.emptyProjectLabel":"工作文件夹","chat.emptyProjectHint":"发送第一条消息后,将在此文件夹中开始新会话。","chat.openSessionList":"打开会话列表","chat.attachments":"附件","chat.removeImage":"移除图片 {index}","chat.removeAttachment":"移除 {name}","chat.attachExtracting":"正在提取文本","chat.attachExtractingWait":"请等待附件处理完成","chat.attachLimit":"每条消息最多可附加 {count} 个非图片附件。","chat.attachTooLarge":"{name} 超出每个文档 {limit} 的限制。","chat.attachTotalTooLarge":"附加文档总大小超出 {limit} 的限制。","chat.attachTextTooLarge":"从 {name} 提取的文本超出 {limit} 个字符的限制。","chat.attachTooManyPages":"{name} 超出 PDF {limit} 页的限制。","chat.attachNoPdfText":"无法从 {name} 提取文本。扫描版或纯图片 PDF 需要 OCR,目前不支持。","chat.attachPasswordProtected":"{name} 受密码保护,无法提取文本。","chat.attachExtractFailed":"无法从 {name} 提取文本。","chat.attachKindAudio":"音频","chat.attachKindFile":"文件","chat.attachUploading":"正在保存","chat.attachTranscribing":"正在转写","chat.attachTranscribeFailed":"转写失败","chat.attachStoredTooLarge":"{name} 超出每个文件 {limit} 的限制。","chat.attachUploadFailed":"无法保存 {name}:{error}","chat.attachTranscribePending":"需要选择","chat.transcribeGroup":"音频转写","chat.transcribeChecking":"正在检查时长","chat.transcribeConfirmTitle":"要转写 {name} 吗?","chat.transcribePlanSummary":"{duration} \xb7 约 {calls} 次转写调用","chat.transcribeDurationUnknown":"时长未知","chat.transcribeUsageNotice":"转写会计入已连接账户的用量。点击开始之前不会发送任何内容。","chat.transcribeStart":"开始转写","chat.transcribeSkip":"不转写","chat.transcribeCancel":"取消转写","chat.transcribeRunning":"正在转写 {name}","chat.transcribeRetry":"重试","chat.transcribeAction":"转写","chat.transcribeSkipped":"{name} 没有转写,只发送已保存的文件路径。","chat.transcribeFailedRow":"{name} 转写失败:{error}","chat.transcribeToolMissing":"音频工具(ffmpeg)不可用,无法为转写准备此音频。","chat.transcribePartialFailed":"在 {total} 段中的第 {done} 段后停止;未附加部分转写。","chat.transcribeTooLong":"转写内容与其他附件合计超出字数限制。","chat.transcribeFallbackTitle":"{name} 的默认转写失败。要用 ChatGPT/Codex 继续吗?","chat.transcribeFallbackProgress":"{total} 段中的 {done} 段已转写并保留;仅发送失败段及其后的剩余段。","chat.transcribeFallbackUsageNotice":"ChatGPT/Codex 是独立的提供商,其转写会计入已登录账户的用量。点击继续之前不会发送任何内容。","chat.transcribeFallbackStart":"用 ChatGPT/Codex 继续","chat.transcribeFallbackExpired":"此备用选项已过期,或你已使用过。未发送任何内容;点击重试可从头开始。","chat.attachmentSettingsNav":"附件","chat.attachmentSettingsTitle":"附件","chat.attachmentSettingsDescription":"在聊天中附加的文件会保存在这台电脑上,供代理打开。","chat.attachmentSettingsLoadFailed":"无法加载附件设置","chat.attachmentUploadLimit":"每个文件的上传上限(MB)","chat.attachmentUploadLimitHelp":"超过上限的文件会在发送前被拒绝。直接读入消息的文本仍有单独限制:每个文档 8 MB,总计 240,000 个字符。","chat.attachmentUploadLimitInvalid":"请输入不小于 1 的整数(MB)。","chat.attachmentAutoCleanup":"自动删除未使用的附件","chat.attachmentAutoCleanupHelp":"对话、分支或未发送草稿中使用的附件会保留。确认在任何地方都不再使用后,{days} 天后删除;无法确认是否使用的文件会保留。","chat.attachmentSettingsSaved":"已保存","characterMode.nav":"角色","characterMode.title":"角色","characterMode.description":"选择屏幕上显示的头像、名称、贴纸和完成语音。","characterMode.label":"角色集","characterMode.default":"默认","characterMode.office":"办公室模式","characterMode.help":"适用于这台电脑的整个服务器。办公室模式下,这台电脑配置中登记的角色会替换对应席位的头像、名称、语气、贴纸和语音,未登记的席位保持不变。","characterMode.noRoster":"这台电脑没有办公室角色集,因此继续使用默认角色。","characterMode.saved":"已保存","chat.steerTitle":"中断当前运行并立即注入此消息","chat.followUpTitle":"在 Agent 完成后将此消息加入队列","chat.filterModels":"筛选模型…","chat.noMatchingModels":"没有匹配的模型","chat.modelRoles":"角色","chat.allModels":"全部模型","chat.mainPreset":"Main 预设","roles.title":"模型角色","roles.description":"omp 按角色分派任务,而非只用一个当前模型。为每个角色分配模型后,CUELO 与 omp 命令行都会使用该配置。","roles.scope":"保存到","roles.scopeGlobal":"全局","roles.scopeProject":"当前项目","roles.unset":"— 未设置 —","roles.needsProject":"打开一个项目后即可编辑其模型角色。","roles.source.global":"来自全局配置","roles.source.project":"来自项目配置","roles.source.default":"omp 默认值","roles.thinking":"推理","roles.thinkingInherit":"使用配置的默认推理级别","roles.harnessNote":"CUELO Maker 与工具角色在分配之前也会列出。只为要用的角色自行选择模型;保存不会登录或试调用模型。","roles.harnessUnset":"未设置","roles.harness.implSol":"Maker \xb7 方向已定的代码(NORMAL\xb7HARD 优先)","roles.harness.implSonnet":"Maker \xb7 NORMAL 非 UI 备选","roles.harness.implOpus":"Maker \xb7 NORMAL UI/UX","roles.harness.implDeepSeek":"Maker \xb7 NORMAL 后台任务\xb7备选","roles.harness.makerHardUiOpus":"Maker \xb7 HARD UI/UX","roles.harness.makerHardCodeOpus":"Maker \xb7 HARD 代码(开放设计\xb7返工)","roles.harness.makerHardCodeSonnet":"Maker \xb7 HARD 代码备选","roles.harness.crossReviewOpenAI":"交叉审查 \xb7 OpenAI 必需审查(openai / openai-codex)","roles.harness.crossReviewAnthropic":"交叉审查 \xb7 Anthropic 必需审查(anthropic)","roles.harness.crossReviewAdvisory":"交叉审查 \xb7 辅助审查,非阻塞(任意提供商)","roles.harness.skim":"工具 \xb7 多文件源码阅读(skim)","roles.harness.draft":"工具 \xb7 文档草稿撰写(draft)","roles.harness.ocr":"工具 \xb7 图像文字转写(ocr)","roles.harness.interpreter":"工具 \xb7 韩英互译(interpreter)","chat.moreControls":"运行选项","chat.collapseControls":"关闭运行选项","chat.shell":"Shell","chat.outputLocal":"输出保留在本地","chat.outputModel":"输出发送给模型","chat.noTools":"不使用工具,仅只读","chat.builtInTools":"核心:{tools} \xb7 其他已注册工具仍保持启用","chat.allBuiltInTools":"核心:{tools} \xb7 其他已注册工具仍保持启用","chat.changeReasoning":"更改推理级别:{level}","chat.changeReasoningLabel":"更改推理级别","chat.currentReasoning":"当前推理级别:{level}","chat.outputSpeed":"{rate} tok/s","chat.outputSpeedTitle":"上一条回答的输出速度(每秒输出 token,从请求开始到生成结束)","chat.outputSpeedLive":"~{rate} tok/s","chat.outputSpeedLiveTitle":"当前回答的输出速度估算(按收到的文字估算 token,从请求开始到现在)。回答结束后改用实际 token 数","chat.fastModeActive":"Fast 已开启 \xb7 正在应用于此模型。优先处理可能产生更多费用或用量。点击关闭","chat.fastModeInactive":"已请求 Fast \xb7 此模型或账户未应用。点击关闭","chat.fastModeOff":"Fast 已关闭 \xb7 点击请求优先处理(视提供商可能产生更多费用或用量)","chat.fastModeUnknown":"尚未确认 Fast 状态 \xb7 点击读取此会话的实际状态并切换","chat.fastModeBusy":"正在切换 Fast","chat.changeToolPreset":"更改工具预设","chat.stopCompaction":"停止压缩","chat.compactContext":"压缩上下文","chat.compacting":"正在压缩…","chat.compact":"压缩","chat.stopAgent":"停止 Agent","chat.stop":"停止","chat.liveVoice":"实时语音","chat.liveStart":"开始实时语音","chat.liveStop":"结束实时语音","chat.liveConnecting":"正在连接","chat.liveOn":"通话中","chat.liveWorking":"正在执行","chat.liveUnsupported":"当前浏览器无法进行实时通话","chat.liveMicDenied":"麦克风权限被拒绝","chat.liveMicUnavailable":"没有可用的麦克风","chat.liveAuthRequired":"使用实时语音需要登录 Codex","chat.liveUpstreamFailed":"Codex 拒绝了本次实时通话","chat.liveFailed":"无法启动实时通话","chat.liveNeedsSession":"请先选择文件夹 — 实时通话以本对话的智能体身份说话","chat.liveVoiceSettingsNav":"通话语音","chat.liveVoiceSettingsTitle":"通话语音","chat.liveVoiceSettingsDescription":"选择实时通话和口译通话中使用的 Codex 语音及语速。该选择从下一次通话开始生效。","chat.liveVoiceSpeakerGroup":"语音","chat.liveVoiceCodexLabel":"Codex 语音","chat.liveVoiceCodexHelp":"实时通话和口译通话都使用这个语音。","chat.livePaceLabel":"语速","chat.livePaceHelp":"选择“慢速”时,语音会放慢并清楚地说话。","chat.livePaceNormal":"正常","chat.livePaceSlow":"慢速","chat.liveVoiceLoadFailed":"无法加载语音设置","chat.disableSound":"关闭完成提示音","chat.enableSound":"开启完成提示音","chat.thinkingAuto":"自动选择推理强度","chat.thinkingAutoCapped":"自动选择,最高 {level}","chat.thinkingOff":"关闭推理","chat.thinkingMinimal":"最低限度推理","chat.thinkingLow":"低强度推理","chat.thinkingMedium":"中等强度推理","chat.thinkingHigh":"高强度推理","chat.thinkingXhigh":"超高强度推理","chat.thinkingMax":"最高强度推理","chat.builtIn":"内置","chat.extensions":"扩展","chat.customCommands":"自定义命令","chat.mcpPrompts":"MCP 提示词","chat.prompts":"提示词","chat.fileCommands":"命令文件","chat.skills":"技能","chat.dormant":"休眠","chat.commandCompact":"压缩上下文,可选附加说明","chat.commandReload":"重新加载扩展、技能、提示词和工具","chat.commandName":"设置会话显示名称","chat.commandSession":"显示会话消息、Token 和费用统计","chat.commandCopy":"复制最后一条助手消息","chat.goalLabel":"目标","chat.goalPaused":"已暂停","chat.goalBudgetLeft":"剩余 {left}","chat.goalTokensUsed":"已用 {used}","chat.jumpToBottom":"回到底部","chat.loadLater":"向下滚动以加载之后的消息(下方 {count} 条)","chat.jumpMissing":"该消息不在当前会话视图中(其他分支或已压缩的记录)。","chat.questionRail":"我的提问","chat.searchPlaceholder":"在会话中查找","chat.searchNoResults":"无结果","chat.searchCount":"{index}/{total}","chat.searchPrevious":"上一个结果","chat.searchNext":"下一个结果","chat.searchClose":"关闭查找","chat.compactionLabel":"压缩","chat.compactionProgress":"正在压缩上下文 \xb7 {seconds} 秒","chat.compactionReason.manual":"手动","chat.compactionReason.threshold":"阈值","chat.compactionReason.overflow":"溢出","chat.compactionReason.idle":"空闲","chat.compactionReason.incomplete":"未完成","chat.compactedFrom":"从 {tokens} 个 token 压缩","chat.interruptedTitle":"上次运行已中断","chat.interruptedDetail":"运行在完成前停止,例如服务器或电脑关机。如果没有自动恢复,可以发送消息继续。","chat.interruptedDismiss":"关闭","chat.frequentModels":"常用模型","chat.modelPickCount":"{count} 次","palette.searchPlaceholder":"搜索会话内容","palette.searchResults":"会话搜索结果","palette.searching":"搜索中…","palette.searchFailed":"搜索失败","palette.searchEmpty":"没有匹配的消息","palette.searchHits":"{count} 条消息","palette.searchTruncated.time":"因时间限制,仅搜索了 {total} 个会话中的 {scanned} 个","palette.searchTruncated.bytes":"因大小限制,仅搜索了 {total} 个会话中的 {scanned} 个","palette.searchTruncated.results":"仅显示前面的结果,请缩小搜索词","palette.searchCompacted":"已压缩记录中的 {count} 条未显示","palette.searchRoleUser":"我的提问","palette.searchRoleAssistant":"回答","palette.wideChatOn":"使用宽会话","palette.wideChatOff":"使用标准会话宽度","chat.compacted":"已压缩","chat.tokensSaved":"节省 {saved}","i18n.close":"关闭","i18n.copy":"复制","i18n.copied":"已复制","i18n.cancel":"取消","i18n.save":"保存","i18n.saving":"保存中…","i18n.saved":"已保存","i18n.remove":"移除","i18n.removing":"移除中…","i18n.delete":"删除","i18n.loading":"加载中...","i18n.search":"搜索","i18n.refresh":"刷新","i18n.update":"更新","i18n.updating":"更新中...","restart.title":"CUELO 正在重启","restart.body":"服务器恢复后页面会自动刷新。","restart.slow":"重启已超过两分钟。请在服务器电脑的 %USERPROFILE%\\.omp\\restart-ompweb.log 中查看 READY 或 FAILED。服务器恢复后本页仍会自动刷新。","restart.returnedTitle":"CUELO 已重启","restart.returnedBody":"服务器已恢复,此标签页已重新连接到同一对话。","restart.returnedDismiss":"关闭重启通知","i18n.check":"检查","i18n.checking":"检查中...","i18n.install":"安装","i18n.installing":"安装中...","i18n.noResults":"没有结果","i18n.searchProviders":"搜索 Provider…","i18n.noProviders":"没有匹配的 Provider","i18n.newModel":"新模型","i18n.addProvider":"添加 Provider","i18n.selectProviderModel":"选择 Provider 或模型","i18n.visibleInPrompt":"在模型提示词中可见,点击以禁用","i18n.hiddenFromPrompt":"在模型提示词中隐藏,点击以启用","i18n.dormant":"休眠","i18n.hiddenButInvocable":"对模型隐藏,仍可手动调用","i18n.skillSearchPlaceholder":"例如 react、testing、deploy","i18n.searching":"搜索中…","i18n.noSkills":"未找到技能","i18n.checkUpdates":"检查更新","i18n.updates":"项更新","i18n.noResolvedResources":"没有已解析资源","i18n.enablePackage":"启用包","i18n.disablePackage":"禁用包","i18n.filtered":"已筛选","i18n.openSessionToReload":"打开会话后才能重新加载","i18n.notFound":"未找到","i18n.noPlugins":"未配置插件","trust.resourcesNotLoaded":"受限模式","trust.trustProject":"信任项目","computerTakeover.allow":"允许接管","computerTakeover.active":"已允许接管","computerTakeover.allowHint":"仅为此会话允许接管屏幕。关闭或会话结束后恢复为拒绝。","computerTakeover.activeHint":"此会话已允许接管屏幕。点击关闭。","computerTakeover.shared":"在服务器自身目录中打开的会话无法单独允许。","computerTakeover.failed":"无法更改接管设置:{error}","trust.trusting":"正在信任...","trust.cancel":"取消","trust.dialogTitle":"信任此项目?","trust.dialogBody":"项目资源可以运行本地代码。请仅信任你了解其内容的项目。","trust.skillsNotLoaded":"此项目尚未受信任,项目技能未加载。","trust.pluginsNotLoaded":"此项目尚未受信任,项目插件未加载。","trust.projectScopeUnavailable":"项目资源未加载时,无法安装到项目范围。","trust.pendingBadge":"受限模式 \xb7 已计划信任","trust.scheduledTitle":"已计划信任","trust.scheduledBody":"此项目仍处于受限模式。项目中的所有会话完成当前工作后才会应用信任,正在运行的工作不会被中断。","trust.cancelSchedule":"取消计划的信任","trust.close":"关闭","trust.applyFailed":"计划的信任未能应用,项目仍处于受限模式:{error}。请重新信任以重试。","trust.settingsNav":"项目信任","trust.settingsDescription":"自带扩展、钩子、工具或 MCP 服务器的项目,只有在你信任后才会加载这些代码。会话工作期间所做的更改会在该项目的所有会话空闲时应用,正在运行的工作不会被中断。","trust.settingsEmpty":"目前没有需要做出信任决定的项目。","trust.loadFailed":"无法加载项目信任状态:{error}","trust.stateTrusted":"已信任","trust.stateRestricted":"受限","trust.stateNotRequired":"没有需要信任的项目代码","trust.pendingGrant":"已批准信任但尚未应用。在会话完成工作之前,项目保持受限。","trust.pendingRevoke":"信任已撤销。仍有 {count} 个运行中的会话在使用项目代码,当前工作结束后将以受限模式重新启动。","trust.runtime":"活动会话 {sessions} \xb7 运行中 {running} \xb7 已加载项目代码 {loaded}","trust.revoke":"撤销信任","trust.trustAgain":"重新信任","trust.confirm":"确认","trust.working":"正在保存…","trust.confirmGrant":"信任此项目?其扩展、钩子、工具和 MCP 服务器可以在本机运行。","trust.confirmTrustAgain":"取消撤销就是一次新的信任批准。其扩展、钩子、工具和 MCP 服务器可以在本机运行。","trust.confirmRevoke":"撤销信任?新会话会立即以受限模式启动;运行中的会话会先完成当前工作。","trust.doneApplied":"已应用。此项目的会话现在将以此设置启动。","trust.doneCancelled":"已取消计划的信任。项目仍处于受限模式。","trust.refresh":"刷新","i18n.creatingSession":"正在创建新会话…","i18n.creating":"创建中…","i18n.subscription":"订阅","i18n.subscriptions":"订阅服务","i18n.customEndpoint":"自定义端点格式","i18n.noChanges":"没有更改","i18n.branches":"分支","i18n.noActiveSession":"没有活动会话","i18n.noBranches":"此会话没有分支","i18n.source":"源代码","i18n.preview":"预览","i18n.diff":"Diff","i18n.downloadFile":"下载文件","i18n.liveSync":"实时同步已启用","i18n.notWatching":"未监视","i18n.fileViewMode":"文件视图模式","i18n.compareHead":"比较工作区与 HEAD","i18n.mentionSelectedLines":"提及所选行","i18n.disableWrap":"禁用自动换行","i18n.enableWrap":"启用自动换行","i18n.htmlPreview":"HTML 预览","i18n.previewFile":"预览 {file}","i18n.invalidMermaid":"Mermaid 图表无效","i18n.renderingMermaid":"正在渲染 Mermaid 图表","i18n.previewAfterStreaming":"流式输出完成后可预览","i18n.showMermaidSource":"显示 Mermaid 源码","i18n.previewMermaid":"预览 Mermaid 图表","i18n.openMermaidViewer":"打开图表查看器","i18n.mermaidViewer":"Mermaid 图表查看器","i18n.mermaidDiagram":"Mermaid 图表","i18n.zoomOut":"缩小","i18n.zoomIn":"放大","toolImage.dialogLabel":"放大的图片","toolImage.requestEdit":"请求修改此画面","toolImage.requestEditHint":"把这张图片附加到输入框。写下要改的地方后再发送。","toolImage.noComposer":"没有可附加的输入框。请先打开对话,再点击“请求修改此画面”。","toolImage.loadFailed":"无法获取图片。请再次点击“请求修改此画面”。","toolImage.markHint":"拖动框出要修改的地方","toolImage.markLimit":"最多可标记 {count} 个区域","toolImage.clearMarks":"清除标记","toolImage.regionLabel":"区域 {n}","toolImage.locatorIntro":"已在附加的画面上用红框标出要修改的地方(区域 {range})。后面依次附上各区域的放大图。","toolImage.locatorRegion":"区域 {n}:x={x}, y={y}, 宽 {w}, 高 {h}(以原图 {width}\xd7{height} 像素为准)","files.pickElement":"指定元素","files.pickElementHint":"在预览中点击要修改的元素","files.pickedElement":"已指定的元素","files.requestElementEdit":"请求修改此元素","files.clearPick":"取消指定","files.pickLocatorElement":"元素:{selector}","files.pickLocatorText":"文本:“{text}”","files.pickLocatorPosition":"画面位置:x={x}, y={y}, 宽 {w}, 高 {h}(以预览 {vw}\xd7{vh} 为准)","i18n.fitToWidth":"适应宽度","models.discoveryFetching":"正在导入模型…","models.discoveryFetch":"导入模型…","models.discoveryFilterPlaceholder":"筛选 {count} 个模型…","models.discoveryFilter":"筛选上游模型","models.discoverySelectShown":"选择当前结果","models.discoveryNoMatches":"没有匹配的模型。","models.discoveryAdded":"已添加","models.discoveryShowing":"显示前 {shown} 个,共 {total} 个","models.discoveryFetched":"已获取 {count} 个模型","models.discoveryAddSelected":"添加所选模型","models.discoveryAddSelectedCount":"添加所选模型({count})","models.catalogSource":"来源:models.dev ↗","models.catalogFilling":"正在填入模型信息…","models.catalogFill":"填入模型信息","models.catalogFilled":"已填入 {count} 个字段","models.catalogNoEmptyFields":"没有需要填入的空字段","models.catalogNoExactMatch":"models.dev 中没有精确匹配","models.catalogPriceProvider":"价格已匹配 Provider {provider}","models.catalogPriceBaseUrl":"价格已按 Base URL 匹配 {provider}","models.catalogPriceConsensus":"价格得到 {support}/{total} 条记录支持","models.catalogPriceUnreliable":"未找到可靠价格","models.catalogUndo":"撤销","models.navGroupRoles":"角色分配","models.navGroupAccounts":"已连接账户","models.navGroupCustom":"自定义提供商","i18n.testingModel":"正在测试模型连接...","i18n.connected":"已连接","i18n.failed":"失败","i18n.test":"测试","i18n.testConnection":"测试模型连接","i18n.provider":"Provider","i18n.model":"模型","i18n.providerName":"Provider 名称","i18n.rename":"重命名","i18n.default":"默认","i18n.disabled":"已禁用","i18n.noResources":"没有资源","i18n.unknown":"未知","i18n.installedVersion":"已安装 {version}","i18n.configuredVersion":"已配置 {version}","i18n.extensions":"扩展","i18n.prompts":"提示词","i18n.themes":"主题","i18n.resourceCount":"{count}{label}","i18n.extensionShort":"扩展","i18n.skillShort":"技能","i18n.promptShort":"提示词","i18n.themeShort":"主题","i18n.custom":"自定义","i18n.clearAll":"清除全部","i18n.connectedSuccessfully":"连接成功。","i18n.notConnected":"未连接","i18n.configured":"已配置","i18n.notConfigured":"未配置","i18n.openingBrowser":"正在打开浏览器…","i18n.submit":"提交","i18n.login":"登录","i18n.relogin":"重新登录","i18n.deviceLogin":"使用设备码登录","i18n.deviceLoginGuide":"打开下面的页面登录,然后输入此代码。无需回到此服务器的 localhost,因此远程服务器上也能使用。","i18n.disconnect":"断开连接","i18n.networkError":"网络错误","i18n.continuing":"继续中…","i18n.skills":"技能","i18n.plugins":"插件","i18n.addSkill":"添加技能","i18n.addPlugin":"添加插件","i18n.selectSkill":"选择技能","i18n.selectPackage":"选择包","i18n.updateAvailable":"有可用更新","i18n.upToDate":"已是最新","i18n.automaticChecksUnavailable":"自动检查不可用","i18n.checkFailed":"检查失败","i18n.installed":"已安装","i18n.status":"状态","i18n.version":"版本","i18n.package":"包","i18n.resources":"资源","i18n.installedPath":"安装路径","i18n.cwd":"CWD","i18n.resolvedResources":"已解析资源","i18n.reloadSession":"重新加载会话","i18n.reloadSessionHint":"重新加载当前会话的设置和技能。不会卸载插件;如需卸载,请重启 CUELO。","i18n.reloading":"重新加载中...","i18n.packageRemoved":"包已移除。","i18n.packageInstalled":"包已安装。","i18n.packageUpdated":"包已更新。","i18n.packageDisabled":"包已禁用。","i18n.packageDisabledRestartRequired":"已保存禁用设置。已加载的插件会继续运行,直到 CUELO 重启;重新加载会话无法卸载它。","i18n.packageEnabled":"包已启用。","i18n.sessionReloaded":"会话已重新加载。","i18n.thinking":"思考","i18n.largeMessageReveal":"消息内容过大({size})。点击以纯文本查看 — 已禁用 markdown 渲染以避免页面卡顿。","i18n.loadingThinking":"正在加载思考内容...","i18n.copyMessage":"复制消息","i18n.editFromHere":"从此处编辑","i18n.editFromHereTitle":"从此处编辑,此会话内创建分支","i18n.newSession":"新会话","i18n.newSessionTitle":"新会话,从此处创建独立副本","i18n.estimatedTokens":"流式输出期间的估算 Token 数","i18n.messageUsage":"用量","i18n.messageUsageTitle":"查看该消息的 Token 与费用","i18n.providerAnthropicSubscription":"Anthropic 订阅","i18n.providerAnthropicApi":"Anthropic API","i18n.noOutput":"(无输出)","i18n.noSummary":"(无摘要)","i18n.conversationCompacted":"会话已压缩","i18n.compactionDescription":"此处之前的会话历史已压缩为以下摘要:","i18n.fileContext":"文件上下文:{details}","i18n.readFiles":"读取的文件","i18n.modifiedFiles":"修改的文件","i18n.hiddenExtensionMessage":"隐藏的扩展消息","i18n.noMessage":"(无消息)","i18n.showOriginalReply":"查看英文原文","i18n.hideOriginalReply":"收起英文原文","i18n.showInputTranslation":"查看英文翻译","i18n.hideInputTranslation":"收起英文翻译","i18n.showExtensionMessage":"显示扩展消息","i18n.collapse":"收起","i18n.expand":"展开","i18n.hideDetails":"隐藏详情","i18n.showDetails":"显示详情","i18n.thinkingUnavailable":"思考内容不可用","i18n.before":"之前","i18n.after":"之后","i18n.sessionComplete":"任务完成","i18n.taskFinished":"任务已完成。","i18n.attentionNeeded":"Pi 需要你的操作","i18n.extensionInputNeeded":"扩展正在等待你的输入。","navigator.toolbar":"导航视图","navigator.priority":"优先级","navigator.view":"{label}导航","gpt6.boundBadge":"6PRO {handle}","gpt6.boundBadgeHint":"该会话已绑定到 6 Pro 连接编号 {handle}。","usage.none":"用量 —","usage.open":"查看用量详情:{rows}","usage.openMore":",另有 {count} 项","usage.showMore":"查看其余 {count} 项","usage.showLess":"收起","usage.accountBlocked":"自动拦截","usage.accountSpent":"账户额度用尽","usage.limitSpent":"额度用尽","usage.bai":"B.AI 累计 Token","usage.baiEmpty":"无记录","usage.baiRange":"统计 {from}~{to}","usage.baiUnmeasured":"未测量","usage.title":"用量","usage.reorder":"调整顺序","usage.reorderDone":"完成","usage.reorderGroup":"账户显示顺序","usage.moveUp":"上移 {account}","usage.moveDown":"下移 {account}","usage.moved":"{account} 已移到第 {position} 位","usage.authExpired":"登录已过期","usage.authUnavailable":"不可用","usage.relogin":"重新登录","usage.reloginFor":"重新登录 {account}","usage.authIssues":"账户异常 {count}","relogin.title":"需要重新登录的账户","relogin.guide":"点击「{action}」后,请在浏览器中用此账户完成登录。用其他账户登录时,此账户仍保持错误。","relogin.done":"登录已完成。","relogin.checking":"正在重新读取用量以确认 {account}…","relogin.recovered":"{account} 已重新登录。","relogin.stillFailing":"登录已完成,但 {account} 仍报告认证错误。可能登录了其他账户。","relogin.unknown":"用量中找不到 {account},无法确认是否恢复。","efficiency.title":"效率","efficiency.governor":"运行管控","efficiency.lab":"配置比较","efficiency.refresh":"刷新","efficiency.refreshing":"正在加载…","efficiency.noSession":"选择会话后查看其运行记录。","efficiency.loadingRuns":"正在加载运行记录…","efficiency.runsEmpty":"该会话暂无运行记录。","efficiency.runsError":"无法加载运行记录。","efficiency.selectRun":"选择一条运行,查看角色、瓶颈与未测量空白。","efficiency.loadingDetail":"正在加载运行详情…","efficiency.detailError":"无法加载运行详情。","efficiency.noTitle":"无标题请求","efficiency.elapsed":"耗时","efficiency.busyTotal":"生成时间合计","efficiency.noSumNote":"耗时与生成时间合计并列显示,绝不相加。","efficiency.summarySection":"摘要","efficiency.rolesSection":"角色","efficiency.rolesEmpty":"本次运行中没有角色处理请求。","efficiency.bottlenecksSection":"瓶颈","efficiency.bottlenecksEmpty":"没有测量到瓶颈。","efficiency.toolsSection":"工具调用","efficiency.unmeasuredGap":"原因未测量空白","efficiency.elapsedValue":"耗时 {value}","efficiency.estimatedCostValue":"预估 {value}","efficiency.estimatedCost":"预估费用","efficiency.untimedLowerBound":"有 {value} 个请求没有记录耗时 — 生成时间为下限。","efficiency.bottleneckOrderNote":"按观测到的时长从大到小排列。条形长度相对于第一项,而非经过时间。","efficiency.untimedRuns":"缺少耗时的 run","efficiency.untimedMedianLowerBound":"有 {value} 个 run 含未记录耗时的请求 — 生成时间中位数为下限。","efficiency.unpricedLowerBound":"包含未计价记录 — 下限","efficiency.mixedPairingNote":"混合配置:无法确认每个请求使用的模型与推理强度组合及其顺序。不能断定这些 run 处于相同条件。","efficiency.unmeasuredShort":"未测量","efficiency.effortLabel":"effort {value}","efficiency.requestsValue":"{value} 次请求","efficiency.toolCallsValue":"{value} 次工具调用","efficiency.busyTime":"生成时间","efficiency.tokens":"Token","efficiency.unpricedRequests":"未计价请求","efficiency.firstTokenAvg":"首个 Token 等待(平均)","efficiency.firstTokenPartial":"首个 Token 等待为已记录的 {recorded}/{total} 个请求的平均值。","efficiency.outputTokens":"对话输出 Token","efficiency.helpersTitle":"辅助模型调用","efficiency.helperCallsValue":"{count} 次 \xb7 输出 {output} \xb7 合计 {tokens} \xb7 {cost}","efficiency.helpersIncludedNote":"辅助调用的 Token 与费用已计入上方 Token 与预估费用合计,但不计入请求数、首个 Token 等待和对话输出 Token。","efficiency.toolFailedValue":"失败 {value}","efficiency.toolNoMatchValue":"无匹配 {value}","efficiency.toolCancelledValue":"中断 {value}","efficiency.unmeasuredGapValue":"原因未测量空白 {value}","efficiency.roleMain":"Main","efficiency.roleMaker":"Maker","efficiency.roleChecker":"Checker","efficiency.roleAdvisor":"Advisor","efficiency.roleUnattributed":"未归属","efficiency.purposePrimary":"Primary","efficiency.purposeRework":"Rework","efficiency.purposeReview":"Review","efficiency.outcomeCompleted":"已完成","efficiency.outcomeError":"错误","efficiency.outcomeAborted":"已中止","efficiency.outcomeInterrupted":"被下一请求打断","efficiency.outcomeRunning":"运行中","efficiency.folder":"文件夹","efficiency.folderAll":"全部文件夹","efficiency.folderPlaceholder":"按文件夹过滤,回车应用","efficiency.loadingExperiments":"正在加载配置比较…","efficiency.experimentsEmpty":"没有可比较的配置记录。","efficiency.experimentsError":"无法加载配置比较。","efficiency.difficultyNote":"任务难度未归一化。","efficiency.runsValue":"{value} 次运行","efficiency.medianElapsed":"耗时中位数","efficiency.medianBusy":"生成时间中位数","efficiency.medianTokens":"Token 中位数","efficiency.medianEstimatedCost":"预估费用中位数","efficiency.totalEstimatedCost":"预估费用合计","efficiency.reworkRate":"返工率","efficiency.errorRate":"错误率","efficiency.unpricedRuns":"未计价运行","efficiency.scopeAttributed":"仅当前角色体系","efficiency.scopeAll":"全部记录","efficiency.scopeSessions":"纳入会话","efficiency.scopeRuns":"纳入 run","efficiency.scopeExcludedRuns":"已排除 run","efficiency.harness":"Harness","efficiency.harnessValue":"Harness {value}","efficiency.harnessUnknown":"unknown","efficiency.harnessAll":"全部 harness","efficiency.groupByHarness":"按 harness 拆分","efficiency.harnessNote":"Harness 指 run 开始时已安装的 CUELO 版本,只根据本机的更新记录确定;没有记录或在记录之外变更的区间显示为 unknown。","efficiency.sawSection":"模型看到的内容","efficiency.sawApproxNote":"根据会话记录重建的近似视图。每次请求发送的系统提示词和上下文钩子的改写都没有记录。","efficiency.sawOpen":"按请求查看","efficiency.sawLoading":"正在读取请求…","efficiency.sawError":"无法读取请求记录。","efficiency.sawEmpty":"此运行没有模型请求记录。","efficiency.sawFilterEmpty":"没有包含注入的请求。","efficiency.sawRole":"记录","efficiency.sawSummary":"请求 {turns} 次 \xb7 注入 {injections} 条 \xb7 工具 {tools} 次 \xb7 失败 {failed} 次","efficiency.sawOnlyInjected":"仅含注入的请求","efficiency.sawTurnLabel":"请求 {index}","efficiency.sawBefore":"此请求之前到达","efficiency.sawTrailing":"最后一次请求之后到达(未进入本次运行的任何模型请求)","efficiency.sawShowFull":"查看全文","efficiency.sawShowArgs":"查看参数","efficiency.sawShowResult":"查看结果","efficiency.sawHideFull":"收起","efficiency.sawTruncated":"仅显示前 {value} 个字符。","efficiency.sawMore":"再加载 {value} 个","efficiency.sawShown":"已显示 {shown}/{total}","efficiency.sawHiddenFromChat":"聊天中不显示","efficiency.sawNotSent":"未发送给模型","efficiency.sawSecretsMasked":"疑似密钥的字符串已替换为 [REDACTED]。","efficiency.sawKindInjection":"注入","efficiency.sawKindDeveloper":"开发者消息","efficiency.sawKindUser":"用户消息","efficiency.sawKindCompaction":"压缩","efficiency.sawKindModel":"模型切换","efficiency.sawKindEffort":"推理强度变更","efficiency.sawKindPrompt":"系统提示词已变更","efficiency.sawKindRules":"注入规则","efficiency.sawKindMemory":"记忆召回","efficiency.sawCompactionValue":"{before} → {after} tokens","efficiency.sawMemoryIds":"召回 {value} 条记忆(正文未记录)","efficiency.sawToolOk":"成功","efficiency.sawToolFailed":"失败","efficiency.sawToolNoMatch":"无匹配","efficiency.sawToolCancelled":"中断","efficiency.sawToolMissing":"无结果","efficiency.sawResultChars":"结果 {value} 字符","efficiency.sawUsage":"输入 {input} \xb7 输出 {output} \xb7 缓存读取 {cacheRead}","efficiency.sawStop":"结束:{value}","efficiency.sawToolsChanged":"工具列表变化:+{added} −{removed}","efficiency.sawPreludeTitle":"系统提示词与工具","efficiency.sawPreludeRecorded":"已记录","efficiency.sawPreludeTools":"最后一次请求启用的工具 {value} 个(已记录)","efficiency.sawPreludeDigest":"系统提示词指纹:{value}","efficiency.sawPreludeDigestNone":"没有此运行时的系统提示词指纹记录。","efficiency.sawPreludeMemory":"记忆召回块(系统提示词的一部分,已记录)","efficiency.sawPreludeReconstruct":"按当前设置重建","efficiency.sawPreludeLoading":"正在重建…","efficiency.sawPreludeApprox":"依据当前配置重建,并非实际发送的内容。","efficiency.sawPreludeNotLoaded":"此会话当前未加载,无法重建。系统提示词正文没有记录。","efficiency.sawPreludeMatch":"当前提示词指纹与此运行的记录一致。","efficiency.sawPreludeMismatch":"当前提示词指纹与此运行的记录不同,之后可能已变更。","toolRun.running":"运行中","toolRun.failed":"失败","toolRun.exitCode":"exit {code}","toolRun.diffStats":"新增 {added} 行,删除 {removed} 行","toolRun.askTimedOut":"超时未回答,已提交表单当前的值。","panel.expand":"加宽面板","panel.restore":"恢复原大小","panel.more":"更多","panel.liveSync":"实时同步","panel.subagentsCount":"{count} 条记录","panel.refresh":"刷新记录","panel.close":"关闭面板","pluginLab.counts":"{count} 个插件","pluginLab.refresh":"刷新列表","pluginLab.create":"新建插件","pluginLab.createHint":"把请求放进输入框。修改后再发送。","pluginLab.starter":"用 plugin-lab 技能为我的配置做一个插件。\n- 要做的事:\n- 需要的工具:\n- 面板显示的内容(没有就留空):\n直接写进仓库的正式插件目录,并在这一轮完成评审、版本、CI 和部署。","pluginLab.loading":"正在加载插件…","pluginLab.loadFailed":"无法加载插件:{error}","pluginLab.retry":"重新加载","pluginLab.empty":"还没有插件。用“新建插件”把请求放进输入框。","pluginLab.listLabel":"插件列表","pluginLab.on":"开","pluginLab.off":"关","pluginLab.toggleLabel":"使用 {name}","pluginLab.toggleFailed":"无法更改状态:{error}","pluginLab.tools":"工具","pluginLab.lastEnhancement":"最近增强","pluginLab.lastEnhancementHint":"显示此插件最近一次获得功能优化的日期。","pluginLab.problem":"问题","pluginLab.openPanel":"打开面板","pluginLab.openPanelLabel":"打开 {name} 面板","pluginLab.back":"返回插件列表","pluginLab.panelSubtitle":"隔离运行 \xb7 lab:{id}","pluginLab.frameTitle":"{name} 面板","pluginLab.lines":"代理数据 {count} 行","pluginLab.noLines":"本会话没有代理数据","pluginLab.draftInserted":"面板的草稿已放进输入框。确认后再发送。","pluginLab.applyHint":"工具开关在新会话或 /reload 之后生效。","pluginLab.noComposer":"打开对话后才能放进输入框。","pluginLab.draftNotRecorded":"草稿已放进输入框,但未能记录这次使用。","pluginLab.saving":"正在更改…","makerDetail.region":"{title} 记录","makerDetail.noFiles":"此 Maker 未修改任何文件","makerDetail.noChecks":"未运行检查","makerDetail.archiveUnobserved":"记录中没有工具结果,无法确认","makerDetail.unavailable":"没有与此次尝试完全对应的运行记录,无法打开详情","makerDetail.checkPassed":"通过","makerDetail.checkUnverified":"判定未确认","makerDetail.checkFailed":"失败","makerDetail.checkUnobserved":"结果未观测","dispatchLane.label":"Maker 尝试","dispatchLane.runPhase":"{run}({phase})","dispatchLane.checks":"检查 {passed}/{total}","dispatchLane.checksUnobserved":"检查未观测","dispatchLane.checksLoading":"正在读取检查","dispatchLane.attempt":"尝试 {attempt}","dispatchLane.attemptUnknown":"尝试","dispatchLane.verdict.accepted":"已接受","dispatchLane.verdict.rework":"返工","dispatchLane.verdict.held":"搁置","dispatchLane.open":"详情","dispatchLane.openLabel":"查看 {title} 详情","dispatchLane.unavailable":"无详情","credits.heading":"API 额度","credits.estimateNote":"账单页余额为所显示时间手动记录的数值,不包含之后的使用量。预估花费与预估余额根据本机的 Token 数和公开单价计算,并非实际账单。","credits.loading":"正在加载 API 额度…","credits.loadFailed":"无法加载 API 额度:{reason}","credits.wallet.hive":"Hive","credits.scope.hive":"本机记录","credits.since":"自 {date} 起","credits.sinceDefault":"最近 30 天","credits.total":"总额","credits.spent":"估计已用","credits.remaining":"估计余额","credits.meterLabel":"{wallet} 额度使用","credits.usedPct":"已用 {pct}%","credits.enterPrompt":"填写总额和开始日期后显示估计余额。","credits.enter":"填写额度","credits.edit":"修改","credits.formLabel":"{wallet} 额度","credits.totalUsd":"总额(USD)","credits.startDate":"开始日期","credits.save":"保存","credits.saving":"正在保存…","credits.cancel":"取消","credits.clear":"清除","credits.saveFailed":"未保存:{reason}","credits.invalid.total":"请用数字填写总额。","credits.error.invalid_total":"总额必须是大于 0 的数字","credits.error.invalid_start_date":"请检查开始日期","credits.error.start_date_in_future":"开始日期在未来","credits.error.session_scan_failed":"无法读取会话记录","credits.error.session_scan_partial":"部分会话记录无法读取,估计已用可能偏少","credits.error.internal":"发生意外错误","credits.error.settings_unreadable":"无法读取额度设置文件,因此未覆盖","credits.walletError":"未能读取用量:{reason}","credits.settingsError":"无法读取额度设置文件,请重新填写。","credits.tokens":"输入 {input} \xb7 输出 {output}","credits.cacheTokens":"缓存 {cache}","credits.requests":"{count} 次","credits.priceUnknown":"单价未知","credits.purpose.session":"对话\xb7代理","credits.purpose.memory":"记忆","credits.purpose.korean-reply-translation":"回复翻译","credits.wallet.anthropic":"Anthropic API","credits.billingLink":"查看实际余额","credits.billingLinkLabel":"在 {wallet} 账单页面查看实际余额(新标签页)","credits.scope.anthropic":"本机记录","credits.anthropic.note":"仅统计记录了 token 的 API 密钥请求,不含订阅 (OAuth) 请求及无 token 的失败尝试。金额为按公开单价计算的估算值,并非账单或余额。","credits.anthropic.noCoverage":"此期间没有记录凭证类型的请求,无法得知 API 密钥使用量。","credits.anthropic.coverageSince":"首次记录凭证类型:{date}(本机未必记录了此后的全部请求)","credits.anthropic.none":"此期间没有记录到 API 密钥请求。","credits.anthropic.oauthExcluded":"已排除订阅 (OAuth)","credits.anthropic.unattributedExcluded":"已排除未记录凭证","credits.category.input":"输入","credits.category.output":"输出","credits.category.cacheRead":"缓存读取","credits.category.cacheWrite":"缓存写入","credits.balance.label":"账单页余额","credits.balance.source":"手动记录","credits.balance.observed":"查看于 {time}","credits.balance.age.now":"刚刚","credits.balance.age.minutes":"{count} 分钟前","credits.balance.age.hours":"{count} 小时前","credits.balance.age.days":"{count} 天前","credits.balance.none":"暂无记录的余额","credits.balance.record":"记录余额","credits.balance.edit":"修改余额","credits.balance.formLabel":"{wallet} 账单页余额","credits.balance.amount":"余额 (USD)","credits.balance.observedAt":"查看时间","credits.balance.observedAtHint":"在账单页面查看到余额的时间。","credits.invalid.amount":"请输入有效的余额数字。","credits.invalid.observedAt":"请输入有效的查看时间。","credits.error.invalid_balance":"余额必须为大于等于 0 的数字","credits.error.invalid_observed_at":"请检查查看时间","credits.error.observed_at_in_future":"查看时间不能晚于当前时间","credits.error.routes_unreadable":"无法读取设置文件,无法确认正在使用的 API","credits.wallet.exa":"Exa","credits.wallet.typesafe":"TypeSafe Jev","credits.route.hive":"已分配给模型角色(记忆、skim 等)","credits.route.exa":"默认网络搜索路径","credits.route.typesafe":"默认快速判定(Jev)路径","credits.route.anthropic":"订阅每周额度用完时的 API 密钥备用路径","credits.evidence.lastPaidUse":"本机最后一次付费使用:{time}","credits.evidence.unverified":"无法读取部分会话日志,未能确认近期付费使用。","memoryTrace.refresh":"刷新","memoryTrace.noSession":"选择会话后即可查看它如何查找记忆。","memoryTrace.loading":"正在读取会话记录…","memoryTrace.error":"无法加载记忆追踪。{error}","memoryTrace.retry":"重新加载","memoryTrace.empty":"此会话没有记忆或文档地图记录。","memoryTrace.requests":"有记录的请求 {count} 个","memoryTrace.requestsLabel":"请求","memoryTrace.requestHeading":"请求 #{index}","memoryTrace.noPreview":"(无内容)","memoryTrace.flowLabel":"请求流程","memoryTrace.stageRecall":"已召回","memoryTrace.stageJev":"JEV 比对","memoryTrace.stageDocmap":"地图候选","memoryTrace.stageDocs":"已打开文档","memoryTrace.stageLessons":"编辑前教训","memoryTrace.stageSaved":"新保存","memoryTrace.stageEmpty":"此请求中没有这一步。","memoryTrace.openedSummary":"已打开 {opened} 个 \xb7 仅候选 {skipped} 个","memoryTrace.opened":"已打开","memoryTrace.candidateOnly":"仅候选","memoryTrace.fromMap":"地图候选","memoryTrace.lines":"读取行 {lines}","memoryTrace.autoRecall":"请求前自动召回","memoryTrace.explicitRecall":"工作中主动查找","memoryTrace.query":"查询","memoryTrace.noResults":"没有找到记忆。","memoryTrace.noMemoryText":"此记录未保留该记忆的文字。","memoryTrace.jevUnknown":"不明 {count} 个","memoryTrace.jevUnrelated":"无关 {count} 个","memoryTrace.lessonFor":"编辑前显示的记忆","memoryTrace.savedAuto":"自动保存","memoryTrace.graphLabel":"关联图","memoryTrace.graphScope":"图范围","memoryTrace.scopeRequest":"此请求","memoryTrace.scopeSession":"整个会话","memoryTrace.legendRequest":"请求","memoryTrace.legendMemory":"记忆","memoryTrace.legendDoc":"地图文档","memoryTrace.legendFile":"编辑的文件","memoryTrace.graphEmpty":"此范围内没有关联项。","memoryTrace.nodeLabel":"{kind}:{label},{count} 个关联","memoryTrace.edgeRecalled":"已调取","memoryTrace.edgeLesson":"编辑前教训","memoryTrace.verdictLegend":"JEV 判定","memoryTrace.verdictApply":"符合适用条件","memoryTrace.verdictExcepted":"条件不满足\xb7例外","memoryTrace.verdictConflict":"与请求冲突","memoryTrace.verdictUnconfirmed":"条件未确认","memoryTrace.verdictUnlisted":"无关\xb7判定不明","memoryTrace.graphHint":"指向或聚焦节点即可在此查看全文。","memoryTrace.legendDocEdited":"打开并编辑的文件","memoryTrace.noticeHarness":"运行框架","memoryTrace.noticeResume":"自动恢复"}}),l({id:"ko",label:"한국어",messages:i});var d=n(2730);let u="pi-locale",p=(0,a.createContext)(null);function h({children:e}){let[t,n]=(0,a.useState)("en"),[i,l]=(0,a.useState)(!1),m=(0,a.useMemo)(()=>c().map(e=>o.get(e)).filter(e=>!!e),[]),f=(0,a.useMemo)(()=>Object.fromEntries(c().flatMap(e=>{let t=o.get(e);return t?[[e,t.messages]]:[]})),[]);(0,a.useEffect)(()=>{let e=function(){var e;let t=null;try{t=window.localStorage.getItem(u)}catch{}let n=window.navigator.languages.length?window.navigator.languages:[window.navigator.language];return"string"==typeof(e=t)&&s.includes(e)?e:function(e){for(let t of e){let e=t.toLowerCase();if("en"===e||e.startsWith("en-"))return"en";if("ko"===e||e.startsWith("ko-"))break;if("zh"===e||e.startsWith("zh-"))return"zh-CN"}return"ko"}(n)}();n(e),document.documentElement.lang=e,l(!0)},[]);let g=(0,a.useCallback)(e=>{if(o.get(e)){n(e),document.documentElement.lang=e;try{window.localStorage.setItem(u,e)}catch{}}},[]),x=(0,a.useCallback)((e,n)=>(0,d.u0)(t,e,f,n),[t,f]),v=(0,a.useMemo)(()=>({locale:i?t:"en",setLocale:g,t:x,supportedLocales:m}),[i,t,g,x,m]);return(0,r.jsx)(p.Provider,{value:v,children:e})}function m(){let e=(0,a.useContext)(p);if(!e)throw Error("useI18n must be used inside I18nProvider");return e}},98795:e=>{e.exports={root:"SearchableSelect_root__FMhaH",trigger:"SearchableSelect_trigger__eqMdt",value:"SearchableSelect_value__eJ2RU",placeholder:"SearchableSelect_placeholder__Hkg33",chevron:"SearchableSelect_chevron__DSTnM",popover:"SearchableSelect_popover__5VxMd",searchWrap:"SearchableSelect_searchWrap__IoKKk",searchIcon:"SearchableSelect_searchIcon__A6f0C",search:"SearchableSelect_search__W_1al",options:"SearchableSelect_options__tjHyi",option:"SearchableSelect_option__LRRH9",optionCopy:"SearchableSelect_optionCopy__W87H8",optionLabel:"SearchableSelect_optionLabel__G7jIg",optionDescription:"SearchableSelect_optionDescription__cE_cC",check:"SearchableSelect_check__1Likw",empty:"SearchableSelect_empty__vZzXQ"}}},e=>{e.O(0,[4697,6805,8774,7330,2545,1637,8441,3794,7358],()=>e(e.s=80455)),_N_E=e.O()}]);
|