cuelo 0.10.78 → 0.10.79
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 +20 -20
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/api/updates/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +4 -4
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/index.segments/_full.segment.rsc +4 -4
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/page.js +2 -2
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
- package/.next/server/app/recover.html +1 -1
- package/.next/server/app/recover.rsc +2 -2
- package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
- package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
- package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
- package/.next/server/app-paths-manifest.json +20 -20
- 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-d98ad797913b7436.js → layout-0148349eee570d55.js} +1 -1
- package/.next/static/chunks/app/{page-6c35bd3f88375f6e.js → page-1b85ae0118645fc9.js} +2 -2
- package/.next/trace +108 -108
- package/.next/trace-build +1 -1
- package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
- package/Tools/OMP_Global_Config/agent/extensions/lib/maker-routing.ts +2 -2
- package/Tools/OMP_Global_Config/agent/rules/harness-policy.json +6 -1
- package/Tools/OMP_Global_Config/agent/rules/subagent.md +1 -0
- package/package.json +1 -1
- /package/.next/static/{2nym4lx9Ge0zSwL5gdIKJ → 9UnuhRGMbcu571zJw_ypR}/_buildManifest.js +0 -0
- /package/.next/static/{2nym4lx9Ge0zSwL5gdIKJ → 9UnuhRGMbcu571zJw_ypR}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2730:(e,t,n)=>{"use strict";function r(e,t,n,i={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,i)}n.d(t,{u0:()=>r})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},55110:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>gq});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),o=n(81886),l=n(68890),c=n(6057);let d=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),f=Object.fromEntries(d.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===f[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let n,r=m(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=m(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,y=!1,b=-1/0;function w(e,t=Date.now()){y=e,e||(b=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function T(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let n=null;for(let[r,i]of Object.entries(t.opened))(e.opened[r]??-1/0)>=i||((n??={...e.opened})[r]=i);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function R(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function E(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function L(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=E(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function $(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(E(e.key),e.order);let r=[...e],i=new Set(e.map(E));for(let e of t){let t=E(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(E(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let P=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function A(e){let t=e.match(P);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(92176);let z=`(max-width: ${p.navigator-1}px)`;function W(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=W("(max-width: 640px)"),O=W(z);function H(){return!1}function U(){return(0,i.useSyncExternalStore)(D.subscribe,D.getSnapshot,H)}var _=n(47650);async function B(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function q(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function V(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function K({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await B(e),n=t.path??e??"/";d(n),p(t.parentPath??null),f(!0===t.upToDrives),g(n),v(t.directories??[]),b(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),C()},[C]);let N=m.trim()!==c,T=!!c&&!N&&!n,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,_.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!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:6,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:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==y?(0,r.jsx)(r.Fragment,{children:y.length>0?y.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(V,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(q,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!T,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:T?1:.6,cursor:T?"pointer":"default"},children:s(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var G=n(21443),J=n.n(G);async function Z(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function Y({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),o=(0,i.useRef)(null),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,y]=(0,i.useState)(""),[b,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,T]=(0,i.useState)(null),[I,M]=(0,i.useState)(!1),[R,E]=(0,i.useState)(50),L=p?.device?.state==="pending",$=n||S,P=(0,i.useCallback)(async()=>{w(!0),T(null);try{let e=await Z("/api/github/projects");h(e),e.connected&&m((await Z("/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 Z("/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 z(e){if(e.preventDefault(),v.trim()&&!$){C(!0),T(null);try{let{cwd:e}=await Z("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){T(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{c(!0),P()},[P]),(0,i.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,i.useEffect)(()=>{let e;if(!L||d)return;let t=!1,n=async()=>{try{let e=await Z("/api/github/projects");if(t)return;if(h(e),e.connected)return void await P();if(e.device?.state!=="pending")return}catch(e){t||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)(K,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let W=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,_.createPortal)((0,r.jsx)("dialog",{ref:o,className:J().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),$||e()},children:(0,r.jsxs)("form",{onSubmit:z,className:J().form,children:[(0,r.jsxs)("header",{className:J().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:J().sources,children:[(0,r.jsx)("span",{className:J().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:$,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:J().body,children:[(0,r.jsxs)("section",{className:J().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:b||$,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void A(),disabled:b||k||L||$,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:J().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:J().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>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:J().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:J().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:$}),b?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:J().list,children:W.slice(0,R).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:J().repo,"aria-pressed":v===e.fullName,disabled:$,onClick:()=>y(e.fullName),children:[(0,r.jsxs)("span",{className:J().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:J().repoDescription,children:e.description})]})},e.fullName))}),!W.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),W.length>R&&(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:J().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>y(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:$,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:J().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:$,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:J().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:J().footer,children:[(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:e,disabled:$,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:J().primary,disabled:$||!v.trim(),children:$?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function X({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var Q=n(2730);let ee={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 고른 엔진(ChatGPT 계정의 Codex 라이브, 또는 Google Cloud 프로젝트의 Gemini 라이브)이 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","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.setup":"언어\xb7상황 설정","translator.sizeDown":"글자 작게","translator.sizeUp":"글자 크게","translator.faceExit":"마주보기 끄기","translator.translating":"옮기는 중…","translator.errorStatus":"통역이 멈췄습니다","translator.translation":"통역","translator.unknownLanguage":"언어 모름","translator.jumpLatest":"최근 말로","translator.engine":"통역 엔진","translator.engine.codex":"Codex 라이브","translator.engine.cloud":"Gemini 라이브 (Google Cloud)","translator.cloudStatusFailed":"Google Cloud 연결 준비 상태를 읽지 못했습니다: {error}","translator.cloudNotConfigured":"서버에 Google Cloud 프로젝트와 위치가 없습니다. GOOGLE_CLOUD_PROJECT와 GOOGLE_CLOUD_LOCATION을 설정해야 쓸 수 있습니다.","translator.cloudSignedOut":"서버에 Google Cloud 로그인이 없습니다. 프로젝트 소유자 계정으로 애플리케이션 기본 사용자 인증 정보(ADC)를 설정해야 쓸 수 있습니다.","translator.cloudAuth":"Google Cloud가 연결을 받지 않았습니다. 서버의 Google Cloud 로그인과 Vertex AI API 사용 설정을 확인하세요.","translator.cloudUpstream":"Google Cloud 라이브 연결이 끊겼습니다: {error}"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and the engine you pick (Codex Live on your ChatGPT account, or Gemini Live on a Google Cloud project) 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.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.engine":"Engine","translator.engine.codex":"Codex Live","translator.engine.cloud":"Gemini Live (Google Cloud)","translator.cloudStatusFailed":"Could not read whether Google Cloud is ready: {error}","translator.cloudNotConfigured":"The server has no Google Cloud project and location. Set GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION to use it.","translator.cloudSignedOut":"The server has no Google Cloud sign-in. Set up Application Default Credentials with the project owner's account to use it.","translator.cloudAuth":"Google Cloud refused the connection. Check the server's Google Cloud sign-in and that the Vertex AI API is enabled.","translator.cloudUpstream":"The Google Cloud live connection dropped: {error}"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,所选引擎(ChatGPT 账号的 Codex 实时通话,或 Google Cloud 项目的 Gemini 实时通话)会把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","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.setup":"语言与场景设置","translator.sizeDown":"缩小文字","translator.sizeUp":"放大文字","translator.faceExit":"退出面对面","translator.translating":"正在翻译…","translator.errorStatus":"口译已停止","translator.translation":"译文","translator.unknownLanguage":"语言不明","translator.jumpLatest":"回到最新","translator.engine":"口译引擎","translator.engine.codex":"Codex Live","translator.engine.cloud":"Gemini Live(Google Cloud)","translator.cloudStatusFailed":"无法读取 Google Cloud 的连接准备状态:{error}","translator.cloudNotConfigured":"服务器没有设置 Google Cloud 项目和位置。请设置 GOOGLE_CLOUD_PROJECT 和 GOOGLE_CLOUD_LOCATION。","translator.cloudSignedOut":"服务器没有 Google Cloud 登录。请用项目所有者账号设置应用默认凭据(ADC)后再使用。","translator.cloudAuth":"Google Cloud 拒绝了连接。请检查服务器的 Google Cloud 登录并确认已启用 Vertex AI API。","translator.cloudUpstream":"Google Cloud 实时连接已断开:{error}"}};function et(){let{locale:e}=(0,F.s)();return{tt:(0,i.useCallback)((t,n)=>(0,Q.u0)(e,t,ee,n),[e]),locale:e}}let en="omp-web:unread-session-ids",er="omp-web:pinned-session-ids",ei="omp-web:removed-projects";function ea(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function es(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eo({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function el({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let ec="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ed(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ec[Math.floor(Math.random()*ec.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.78/18.12.6":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:c,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(X,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eu(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function ep({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:f,translatorActive:m=!1,onTranslatorActiveChange:g}){let x,{tt:v}=et(),{t:y,locale:b}=(0,F.s)(),w=U(),[P,A]=(0,i.useState)([]),z=(0,i.useMemo)(()=>t&&!P.some(e=>e.id===t.id)?[t,...P]:P,[P,t]),[W,D]=(0,i.useState)(!0),[O,H]=(0,i.useState)(null),[_,B]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[G,J]=(0,i.useState)(!1),[Z,X]=(0,i.useState)(""),[Q,ee]=(0,i.useState)("projects"),[ec,ef]=(0,i.useState)(()=>new Set),[ev,ey]=(0,i.useState)(()=>new Set),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)({version:1,projects:[]}),[eT,eI]=(0,i.useState)(!1),[eM,eR]=(0,i.useState)(!1),[eE,eL]=(0,i.useState)(!1),[e$,eP]=(0,i.useState)(null),[eA,eF]=(0,i.useState)(""),[ez,eW]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(""),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)(!1),[eJ,eZ]=(0,i.useState)(null),[eY,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(""),[e8,e4]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(!1),[ti,ta]=(0,i.useState)(!1),[ts,to]=(0,i.useState)(()=>new Set),[tl,tc]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(en);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[td,tu]=(0,i.useState)(()=>new Set),[tp,th]=(0,i.useState)(null),[tf,tm]=(0,i.useState)(!1),tg=(0,i.useRef)(new Set),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(null);(0,i.useEffect)(()=>{tu(function(){try{let e=window.localStorage.getItem(er);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}th(T(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=T(e.newValue,Date.now());th(e=>e?I(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let ty=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eN(await e.json())}catch{eN({version:1,projects:[]})}finally{eI(!0)}},[]);(0,i.useEffect)(()=>{ty()},[ty,c]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ei)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await eu(n.map(e=>({key:E(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ei)}catch{}await ty()})()},[ty]);let tb=(0,i.useCallback)(async e=>{if(tr.current)throw Error("Project update in progress");tr.current=!0,eW(!0);try{await eu(e),await ty()}finally{tr.current=!1,eW(!1)}},[ty]);(0,i.useEffect)(()=>{e$&&tt.current?.select()},[e$]);let tw=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();A(r.sessions),tx.current||to(new Set(r.runningSessionIds??[])),H(null),e||(ta(!0),tv.current&&clearTimeout(tv.current),tv.current=setTimeout(()=>ta(!1),2e3))}catch(e){H(String(e))}finally{e&&D(!1)}},[]),tk=(0,i.useCallback)(e=>{tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tu(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),th(t=>t&&R(t,[e])),d?.(e),tw()},[tw,d]),[tj,tS]=(0,i.useState)(null),[tC,tN]=(0,i.useState)(!1),[tT,tI]=(0,i.useState)(null),tM=(0,i.useCallback)(()=>{tC||(tS(null),tI(null))},[tC]),tR=(0,i.useCallback)(async e=>{tN(!0),tI(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(tx.current=!0,to(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(tc(n),tu(n),th(e=>e&&R(e,t)),t))d?.(e)}(await tw(),tN(!1),r.length>0)?tI(y("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tS(null)},[tw,d,y]),[tE,tL]=(0,i.useState)(0),t$=(0,i.useCallback)(()=>{tL(e=>e+1),tw()},[tw]),tP=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tP.current;tP.current=!0,tw(e,!e)},[tw,c]),(0,i.useEffect)(()=>{try{ee(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tA=(0,i.useCallback)(e=>{ee(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==Q)return;let e=()=>{"visible"===document.visibilityState&&tw(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tw,Q]),(0,i.useEffect)(()=>{try{0===tl.size?window.localStorage.removeItem(en):window.localStorage.setItem(en,JSON.stringify([...tl]))}catch{}},[tl]),(0,i.useEffect)(()=>{try{0===td.size?window.localStorage.removeItem(er):window.localStorage.setItem(er,JSON.stringify([...td]))}catch{}},[td]),(0,i.useEffect)(()=>{if(tp)try{var e,t,n;let r,i,a=window.localStorage;a.setItem(N,(e=a.getItem(N),t=Date.now(),i=(r=Object.entries((n=I(tp,T(e,t))).opened)).length>500?r.sort((e,t)=>t[1]-e[1]).slice(0,500):r,JSON.stringify({since:n.since,opened:Object.fromEntries(i)})))}catch{}},[tp]);let tF=(0,i.useCallback)(e=>{tu(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;tx.current=!0,to(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tg.current,n=[...t].filter(t=>!ts.has(t)&&t!==e),r=[...ts].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tc(e=>{let t=new Set(e);return ts.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!P.some(t=>t.id===e));(n.length>0||i)&&tw(!1,!0),n.length>0&&h?.(),tg.current=ts},[ts,e,P,tw,h]),(0,i.useEffect)(()=>{e&&tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let tz=e?z.find(t=>t.id===e)?.modified:void 0,tW=null!==tp;(0,i.useEffect)(()=>{e&&void 0!==tz&&tW&&th(t=>{var n;let r;return t&&(n={id:e,modified:tz},r=Math.max(Date.now(),M(n)??0),(t.opened[n.id]??-1/0)>=r?t:{since:t.since,opened:{...t.opened,[n.id]:r}})})},[e,tz,tW]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tD=(0,i.useRef)(!1),tO=(0,i.useCallback)(e=>{if(!e)return null;if(eJ&&eJ.forCwd===e||eJ?.worktrees.some(t=>t.path===e))return eJ.projectRoot;let t=z.find(t=>t.cwd===e);return t?.projectRoot??e},[eJ,z]),tH=(0,i.useRef)(null);(0,i.useEffect)(()=>{tH.current!==_&&(tH.current=_,p?.(_,tO(_)))},[_,p,tO]);let tU=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tU.current&&(tU.current=u,B(u))},[u]);let[t_,tB]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!_)return void eZ(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(_)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eZ(null);eZ({forCwd:_,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eZ(null)}),()=>{e=!0}},[_,t_,c]),(0,i.useEffect)(()=>{if(0!==P.length&&!o&&null===_){if(s&&!tD.current){tD.current=!0;let e=P.find(e=>e.id===s);if(e){B(e.cwd),n(e,!0);return}l?.()}if(!eT)return;let e=new Map(eC.projects.map(e=>[e.key,e])),t=$(P.length>0?L(P):[],eC.projects).filter(t=>!e.get(E(t))?.hidden);t.length>0&&B(t[0])}},[P,_,s,o,n,l,eC,eT]);let tq=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eK){eG(!0),eV(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eV(n.error??y("workspace.unable"));let r=n.cwd??t,i=E(r),a=eC.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tb([{key:i,path:r,hidden:!1}])}catch{}B(r),eB(!1)}catch{eV(y("workspace.unable"))}finally{eG(!1)}}},[tb,eK,eC.projects,y]),tV=(0,i.useCallback)(()=>{eB(!0),eV(null)},[]),tK=(0,i.useCallback)(async()=>{let e=e1.trim();if(e&&!e5&&eJ){e6(!0),e4(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e4(n.error??`HTTP ${t.status}`);e0(!1),e2(""),eX(!1),eZ(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[e1,e5,eJ]),tG=(0,i.useCallback)(async(e,t)=>{if(eJ&&!e5){e6(!0),e4(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e7(e);e4(r.error??`HTTP ${n.status}`);return}e7(null),_===e&&B(eJ.projectRoot),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[eJ,e5,_]);(0,i.useEffect)(()=>{let e=e=>{e9.current&&!e9.current.contains(e.target)&&(eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU(""),ek(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tJ=(0,i.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),tZ=(0,i.useCallback)((e=_)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;B(e),a?.(t,e)},[_,a]),[tY,tX]=(0,i.useState)(!1),[tQ,t0]=(0,i.useState)(null),t1=(0,i.useCallback)(async()=>{tX(!0),t0(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);tZ(t.cwd)}catch(e){t0(y("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tX(!1)}},[tZ,y]),t2=(0,i.useCallback)(e=>{ey(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),t8=tO(_),t4=null===t8?null:E(t8),t5=(0,i.useMemo)(()=>new Map(eC.projects.map(e=>[e.key,e])),[eC.projects]),t6=L(z);if(null!==t8){let e=E(t8);t6.some(t=>E(t)===e)||t6.unshift(t8)}let t3=$(t6,eC.projects),t7=t3.filter(e=>eM||!t5.get(E(e))?.hidden),t9=t3.some(e=>t5.get(E(e))?.hidden),ne=()=>{eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU("")},nt=async(e,t)=>{ne();try{await tb([{key:E(e),path:e,hidden:t}]),t&&t4&&t4===E(e)&&B(null),t||t3.some(t=>E(t)!==E(e)&&t5.get(E(t))?.hidden)||eR(!1)}catch{}},nn=async e=>{if(tn.current){tn.current=!1,eP(null);return}let t=eA.trim();if(t===(t5.get(E(e))?.alias??""))return void eP(null);eO(null);try{await tb([{key:E(e),path:e,alias:t||null}]),eP(null)}catch{eO(y("sidebar.projectUpdateFailed"))}},nr=async(e,t)=>{if(Z)return;let n=t7.indexOf(e),r=n+t;if(n<0||r<0||r>=t7.length)return;let i=new Set(t7),a=t3.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...t3],o=a[n],l=a[r];[s[o],s[l]]=[s[l],s[o]],ne();try{await tb(s.map((e,t)=>({key:E(e),path:e,order:t})))}catch{}},ni=new Map;for(let e of z){let t=e.projectRoot??e.cwd;if(!t)continue;let n=E(t),r=ni.get(n);r?r.push(e):ni.set(n,[e])}let na=(0,i.useMemo)(()=>{let e=new Map;for(let t of z){let n=t.projectRoot??t.cwd;if(!n)continue;let r=E(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),ts.has(t.id)&&i.running++,tl.has(t.id)&&i.unread++}return e},[z,ts,tl]),ns=Z.trim().toLowerCase(),no=Z.length>0,nl=t7.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=E(e),r=t5.get(n),i=r?.alias??t,a=(ni.get(n)??[]).slice().sort((e,t)=>{let n=Number(td.has(t.id))-Number(td.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!ns)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(ns)||t.toLowerCase().includes(ns),o=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(ns));return s||0!==o.length?[{project:e,key:n,name:i,sessions:s?a:o,hidden:r?.hidden===!0}]:[]}),nc=[],nd=[];for(let e of nl){let t=e.key===t4||(na.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?nd.push(e):nc.push(e)}let nu={running:0,unread:0};for(let e of nd){let t=na.get(e.key);t&&(nu.running+=t.running,nu.unread+=t.unread)}let np=no||eE,nh=[...nc.map(e=>({kind:"project",group:e})),...nd.length>0?[{kind:"temporary"}]:[],...np?nd.map(e=>({kind:"project",group:e})):[]],nf=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nh.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nm=(0,i.useMemo)(()=>tp?z.filter(e=>(function(e,t,n){if(e.transient||t.has(e.id))return!1;let r=M(e);return null!==r&&r>(n.opened[e.id]??n.since)})(e,ts,tp)):[],[tp,ts,z]),ng=tf&&null!==tp,[nx,nv]=(0,i.useState)(null),ny=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),c=l.filter(e=>a.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(p>=o)continue;p+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=u.get(r);i?i.push(e):u.set(r,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:i,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:u.get(e)??[]});return h})(ng?z.filter(e=>e.id===nx&&!ts.has(e.id)||nm.includes(e)):z,ts,new Date,b,y("navigator.priority"),td,y("sidebar.pinned"),ng?1/0:void 0),[nx,b,td,nm,ng,ts,z,y]),nb=(0,i.useCallback)(e=>{nv(e.id),tJ(e)},[tJ]),nw=!!(eJ?.isGit&&eJ.isTopLevel&&_&&t8===eJ.projectRoot),nk=eJ?.worktrees.find(e=>e.path===_)??eJ?.worktrees.find(e=>e.isMain),nj=(eJ?.worktrees.length??0)>=8,nS=nj&&eH.trim()?(eJ?.worktrees??[]).filter(e=>(e.branch??es(e.path,q)).toLowerCase().includes(eH.trim().toLowerCase())):eJ?.worktrees??[],nC=(()=>{if(!tj)return[];let e="project"===tj.kind?ni.get(E(tj.project))??[]:ny.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nN=nC.filter(e=>!ts.has(e.id)),nT=e=>{let t=new Set;for(let n of e)n.transient||ts.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nI=void 0!==f&&m;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[e_&&(0,r.jsx)(G?Y:K,{busy:eK,error:eq,onCancel:()=>{eB(!1),eV(null)},onSelect:e=>void tq(e)}),tj&&(0,r.jsx)(eh,{scope:tj,eligible:nN.length,runningExcluded:nC.length-nN.length,busy:tC,error:tT,onCancel:tM,onConfirm:()=>void tR(nN)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ed,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>tZ(),disabled:!_,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:_?"var(--text-muted)":"var(--text-dim)",cursor:_?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),"aria-label":_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),onMouseEnter:e=>{_&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=_?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${ti?" is-success":""}`,onClick:()=>tw(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ti?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ti?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ti?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{ti||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{ti||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:y("sidebar.refresh"),children:ti?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),G&&!nI&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tV,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:y("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":y("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?y("sidebar.projects"):y("navigator.priority"),n=!nI&&Q===e;return(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tA(e),nI&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==f&&(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:v("translator.tab")}),"aria-pressed":nI,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!nI),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:nI?"var(--bg-selected)":"transparent",color:nI?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nI?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!nI&&"projects"===Q&&(0,r.jsx)("button",{type:"button",onClick:()=>eR(e=>!e),disabled:!t9,title:y("sidebar.projectShowHidden"),"aria-label":y("sidebar.projectShowHidden"),"aria-pressed":eM,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eM?"var(--bg-selected)":"transparent",color:eM?"var(--accent)":"var(--text-dim)",cursor:t9?"pointer":"default",opacity:t9?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eM&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nI&&"projects"===Q&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tV,title:y("sidebar.addProject"),"aria-label":y("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),nI&&f,!nI&&"projects"===Q&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:Z,onChange:e=>X(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),X(""),e.currentTarget.blur())},placeholder:y("sidebar.searchProjectsAndSessions"),"aria-label":y("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!nI&&"projects"===Q&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(W||!eT)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),eD&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!W&&eT&&!O&&0===nl.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ns?y("sidebar.noMatchingProjects"):y("sidebar.noSessions")}),!W&&eT&&!O&&nh.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":np,title:y("sidebar.temporaryProjects"),onClick:()=>eL(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:np?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nd.length}),eb(nu,y)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t4,p=nf.has(l.toLowerCase())&&es((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),q)||null,h=!ev.has(s)&&!ns,f=ec.has(s),m=e$===s,g=t7.indexOf(s),x=ez||no||g<=0,v=ez||no||g>=t7.length-1,b=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(f?c:c.slice(0,5)),k=c.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ej===s?e9:void 0,onMouseEnter:()=>ek(s),onMouseLeave:()=>ek(e=>e===s&&ej!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t2(s),title:h?y("sidebar.expandProject"):y("sidebar.collapseProject"),"aria-label":h?y("sidebar.expandProject"):y("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),m?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:tt,value:eA,onChange:e=>eF(e.target.value),onBlur:()=>void nn(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tn.current=!0,eP(null))},"aria-label":y("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>B(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),eb(na.get(o),y)]}),(0,r.jsx)("button",{type:"button",onClick:()=>tZ(s),title:y("sidebar.newSessionTitle",{path:s}),"aria-label":y("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||ew===s?1:0,pointerEvents:w||ew===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ek(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eS(ej===s?null:s),eX(!1),e0(!1),e4(null),u||B(s)},title:y("sidebar.projectActions"),"aria-label":y("sidebar.projectActions"),"aria-expanded":ej===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ej===s?"var(--bg-selected)":"transparent",color:u&&nk&&!nk.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ew===s||ej===s?1:0,pointerEvents:w||ew===s||ej===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ek(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(el,{open:ej===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[nw&&eJ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eX(e=>!e),title:nk?y("sidebar.switchWorktreeTitle",{path:nk.path}):y("sidebar.switchWorktree"),"aria-label":y("sidebar.worktrees"),"aria-expanded":eY,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eY?"1px solid var(--border)":"none",background:eY?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:y("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(el,{open:eY,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nj&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eH,onChange:e=>eU(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eU(""),eX(!1))},placeholder:y("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[nS.map(e=>{let t=e.path===_||e.isMain&&!eJ.worktrees.some(e=>e.path===_);return e3===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tG(e.path,!0),disabled:e5,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:y("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>e7(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:y("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{B(e.path),eX(!1),e4(null),eU("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(eo,{text:e.branch??es(e.path,q),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:y("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tG(e.path,!1),disabled:e5,title:y("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nj&&0===nS.length&&eH.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:y("sidebar.noMatchingWorktrees")})]}),eQ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:te,value:e1,onChange:e=>{e2(e.target.value),e4(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tK()),"Escape"===e.key&&(e0(!1),e2(""),e4(null))},placeholder:y("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tK(),disabled:e5||!e1.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e5||!e1.trim()?"not-allowed":"pointer",opacity:e5||!e1.trim()?.65:1},children:e5?y("sidebar.creating"):y("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e0(!1),e2(""),e4(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:y("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e0(!0),e4(null),setTimeout(()=>te.current?.focus(),0)},title:y("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:y("sidebar.newWorktree")})]}),e8&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e8})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=t5.get(E(s))?.alias??"",void(tn.current=!1,eO(null),eF(e),eP(s),ne())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),y(t5.get(E(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),y("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),y("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>void nt(s,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),y(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nT(ni.get(o)??[])||tC,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{ne(),tI(null),tS({kind:"project",project:s,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),y("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:y("sidebar.noSessions")}),!h&&b.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:b.map(t=>(0,r.jsx)(ex,{node:t,selectedSessionId:e,runningSessionIds:ts,unreadSessionIds:tl,pinnedSessionIds:td,onSelectSession:tJ,onTogglePinnedSession:tF,onRenamed:tw,onSessionDeleted:tk,onSessionArchived:t$,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ef(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?y("sidebar.showLess"):y("sidebar.showMore")})]},s)})]}),!nI&&(0,r.jsx)(eg,{refreshKey:tE,selectedSessionId:e,onSelectSession:tJ,onRestored:t$}),!nI&&"priority"===Q&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[W&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),!W&&!O&&(x=nT(ny.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:tY,onClick:()=>void t1(),title:y("sidebar.newScratchSessionTitle"),style:ea(tY,w),children:y("sidebar.newScratchSession")}),ny.length>0&&!ng&&(0,r.jsx)("button",{type:"button",disabled:0===x||tC,onClick:()=>{tI(null),tS({kind:"priority"})},style:ea(0===x||tC,w),children:y("sidebar.clearPriorityList")})]})),!W&&!O&&tp&&(0,r.jsx)("div",{style:{display:"flex",padding:"6px 2px 4px"},children:(0,r.jsxs)("button",{type:"button","aria-pressed":ng,"aria-label":y("navigator.resultsToCheckCount",{count:nm.length}),title:y("navigator.resultsToCheckHint"),onClick:()=>{nv(null),tm(e=>!e)},style:{...ea(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ng?"var(--border-strong)":"var(--border)",background:ng?"var(--bg-selected)":"transparent",color:ng||nm.length>0?"var(--text)":"var(--text-muted)",fontWeight:ng?600:500,whiteSpace:"nowrap"},children:[y("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:9,background:nm.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nm.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nm.length})]})}),tQ&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tQ}),!W&&!O&&0===ny.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ng?y("navigator.resultsToCheckEmpty"):y("sidebar.noSessions")}),!W&&!O&&ny.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(em,{session:t,selected:t.id===e,running:ts.has(t.id),unread:tl.has(t.id),pinned:td.has(t.id),onSelect:ng?nb:tJ,onTogglePin:tF},t.id))]},t.key))]})]})}function eh({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,F.s)(),d=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let f=(0,i.useRef)(o);return f.current=o,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),f.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ef({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function em({session:e,selected:t,running:n,unread:i,pinned:a,onSelect:s,onTogglePin:o}){let{t:l}=(0,F.s)(),c=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),d=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>s(e),title:`${c}
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{2730:(e,t,n)=>{"use strict";function r(e,t,n,i={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,i)}n.d(t,{u0:()=>r})},13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>o,xG:()=>l});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function o(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function l(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},55110:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>gq});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),o=n(81886),l=n(68890),c=n(6057);let d=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),f=Object.fromEntries(d.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===f[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let n,r=m(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=m(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,y=!1,b=-1/0;function w(e,t=Date.now()){y=e,e||(b=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"],N="omp-web:session-opened-at";function T(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function I(e,t){let n=null;for(let[r,i]of Object.entries(t.opened))(e.opened[r]??-1/0)>=i||((n??={...e.opened})[r]=i);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function M(e){let t=Date.parse(e.modified);return Number.isFinite(t)?t:null}function R(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function E(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function L(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=E(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function $(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(E(e.key),e.order);let r=[...e],i=new Set(e.map(E));for(let e of t){let t=E(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(E(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let P=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function A(e){let t=e.match(P);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(92176);let z=`(max-width: ${p.navigator-1}px)`;function W(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let D=W("(max-width: 640px)"),O=W(z);function H(){return!1}function U(){return(0,i.useSyncExternalStore)(D.subscribe,D.getSnapshot,H)}var _=n(47650);async function B(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function q(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function V(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function K({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[m,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await B(e),n=t.path??e??"/";d(n),p(t.parentPath??null),f(!0===t.upToDrives),g(n),v(t.directories??[]),b(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{l(document.body),C()},[C]);let N=m.trim()!==c,T=!!c&&!N&&!n,I=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(c);return o?(0,_.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!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:6,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:m,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!m.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==y?(0,r.jsx)(r.Fragment,{children:y.length>0?y.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(V,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(q,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!T,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:T?1:.6,cursor:T?"pointer":"default"},children:s(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var G=n(21443),J=n.n(G);async function Z(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function Y({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,F.s)(),o=(0,i.useRef)(null),[l,c]=(0,i.useState)(!1),[d,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,m]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,y]=(0,i.useState)(""),[b,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,T]=(0,i.useState)(null),[I,M]=(0,i.useState)(!1),[R,E]=(0,i.useState)(50),L=p?.device?.state==="pending",$=n||S,P=(0,i.useCallback)(async()=>{w(!0),T(null);try{let e=await Z("/api/github/projects");h(e),e.connected&&m((await Z("/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 Z("/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 z(e){if(e.preventDefault(),v.trim()&&!$){C(!0),T(null);try{let{cwd:e}=await Z("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){T(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{c(!0),P()},[P]),(0,i.useEffect)(()=>{if(!l||d)return;let e=o.current;return e?.showModal(),()=>e?.close()},[l,d]),(0,i.useEffect)(()=>{let e;if(!L||d)return;let t=!1,n=async()=>{try{let e=await Z("/api/github/projects");if(t)return;if(h(e),e.connected)return void await P();if(e.device?.state!=="pending")return}catch(e){t||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)(K,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let W=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,_.createPortal)((0,r.jsx)("dialog",{ref:o,className:J().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),$||e()},children:(0,r.jsxs)("form",{onSubmit:z,className:J().form,children:[(0,r.jsxs)("header",{className:J().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:J().sources,children:[(0,r.jsx)("span",{className:J().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:$,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:J().body,children:[(0,r.jsxs)("section",{className:J().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:b||$,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void A(),disabled:b||k||L||$,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:J().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:J().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>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:J().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:J().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:$}),b?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:J().list,children:W.slice(0,R).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:J().repo,"aria-pressed":v===e.fullName,disabled:$,onClick:()=>y(e.fullName),children:[(0,r.jsxs)("span",{className:J().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:J().repoDescription,children:e.description})]})},e.fullName))}),!W.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),W.length>R&&(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:J().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>y(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:$,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:J().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:()=>void P(),disabled:$,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:J().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:J().footer,children:[(0,r.jsx)("button",{type:"button",className:J().secondary,onClick:e,disabled:$,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:J().primary,disabled:$||!v.trim(),children:$?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function X({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var Q=n(2730);let ee={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 고른 엔진(ChatGPT 계정의 Codex 라이브, 또는 Google Cloud 프로젝트의 Gemini 라이브)이 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","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.setup":"언어\xb7상황 설정","translator.sizeDown":"글자 작게","translator.sizeUp":"글자 크게","translator.faceExit":"마주보기 끄기","translator.translating":"옮기는 중…","translator.errorStatus":"통역이 멈췄습니다","translator.translation":"통역","translator.unknownLanguage":"언어 모름","translator.jumpLatest":"최근 말로","translator.engine":"통역 엔진","translator.engine.codex":"Codex 라이브","translator.engine.cloud":"Gemini 라이브 (Google Cloud)","translator.cloudStatusFailed":"Google Cloud 연결 준비 상태를 읽지 못했습니다: {error}","translator.cloudNotConfigured":"서버에 Google Cloud 프로젝트와 위치가 없습니다. GOOGLE_CLOUD_PROJECT와 GOOGLE_CLOUD_LOCATION을 설정해야 쓸 수 있습니다.","translator.cloudSignedOut":"서버에 Google Cloud 로그인이 없습니다. 프로젝트 소유자 계정으로 애플리케이션 기본 사용자 인증 정보(ADC)를 설정해야 쓸 수 있습니다.","translator.cloudAuth":"Google Cloud가 연결을 받지 않았습니다. 서버의 Google Cloud 로그인과 Vertex AI API 사용 설정을 확인하세요.","translator.cloudUpstream":"Google Cloud 라이브 연결이 끊겼습니다: {error}"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and the engine you pick (Codex Live on your ChatGPT account, or Gemini Live on a Google Cloud project) 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.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.engine":"Engine","translator.engine.codex":"Codex Live","translator.engine.cloud":"Gemini Live (Google Cloud)","translator.cloudStatusFailed":"Could not read whether Google Cloud is ready: {error}","translator.cloudNotConfigured":"The server has no Google Cloud project and location. Set GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION to use it.","translator.cloudSignedOut":"The server has no Google Cloud sign-in. Set up Application Default Credentials with the project owner's account to use it.","translator.cloudAuth":"Google Cloud refused the connection. Check the server's Google Cloud sign-in and that the Vertex AI API is enabled.","translator.cloudUpstream":"The Google Cloud live connection dropped: {error}"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,所选引擎(ChatGPT 账号的 Codex 实时通话,或 Google Cloud 项目的 Gemini 实时通话)会把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","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.setup":"语言与场景设置","translator.sizeDown":"缩小文字","translator.sizeUp":"放大文字","translator.faceExit":"退出面对面","translator.translating":"正在翻译…","translator.errorStatus":"口译已停止","translator.translation":"译文","translator.unknownLanguage":"语言不明","translator.jumpLatest":"回到最新","translator.engine":"口译引擎","translator.engine.codex":"Codex Live","translator.engine.cloud":"Gemini Live(Google Cloud)","translator.cloudStatusFailed":"无法读取 Google Cloud 的连接准备状态:{error}","translator.cloudNotConfigured":"服务器没有设置 Google Cloud 项目和位置。请设置 GOOGLE_CLOUD_PROJECT 和 GOOGLE_CLOUD_LOCATION。","translator.cloudSignedOut":"服务器没有 Google Cloud 登录。请用项目所有者账号设置应用默认凭据(ADC)后再使用。","translator.cloudAuth":"Google Cloud 拒绝了连接。请检查服务器的 Google Cloud 登录并确认已启用 Vertex AI API。","translator.cloudUpstream":"Google Cloud 实时连接已断开:{error}"}};function et(){let{locale:e}=(0,F.s)();return{tt:(0,i.useCallback)((t,n)=>(0,Q.u0)(e,t,ee,n),[e]),locale:e}}let en="omp-web:unread-session-ids",er="omp-web:pinned-session-ids",ei="omp-web:removed-projects";function ea(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function es(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eo({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function el({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[o,l]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),l(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>l(!0))})):(l(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let ec="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ed(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),o=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ec[Math.floor(Math.random()*ec.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.79/18.12.6":"CUELO",n),l=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;l(t),t&&(s.current=setTimeout(()=>l(!1),3e3))},[e,l]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:c,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(X,{label:o,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function eu(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function ep({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:o,onInitialRestoreDone:l,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:f,translatorActive:m=!1,onTranslatorActiveChange:g}){let x,{tt:v}=et(),{t:y,locale:b}=(0,F.s)(),w=U(),[P,A]=(0,i.useState)([]),z=(0,i.useMemo)(()=>t&&!P.some(e=>e.id===t.id)?[t,...P]:P,[P,t]),[W,D]=(0,i.useState)(!0),[O,H]=(0,i.useState)(null),[_,B]=(0,i.useState)(null),[q,V]=(0,i.useState)(""),[G,J]=(0,i.useState)(!1),[Z,X]=(0,i.useState)(""),[Q,ee]=(0,i.useState)("projects"),[ec,ef]=(0,i.useState)(()=>new Set),[ev,ey]=(0,i.useState)(()=>new Set),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)({version:1,projects:[]}),[eT,eI]=(0,i.useState)(!1),[eM,eR]=(0,i.useState)(!1),[eE,eL]=(0,i.useState)(!1),[e$,eP]=(0,i.useState)(null),[eA,eF]=(0,i.useState)(""),[ez,eW]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,eU]=(0,i.useState)(""),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)(!1),[eJ,eZ]=(0,i.useState)(null),[eY,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(""),[e8,e4]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(!1),[ti,ta]=(0,i.useState)(!1),[ts,to]=(0,i.useState)(()=>new Set),[tl,tc]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(en);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[td,tu]=(0,i.useState)(()=>new Set),[tp,th]=(0,i.useState)(null),[tf,tm]=(0,i.useState)(!1),tg=(0,i.useRef)(new Set),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(null);(0,i.useEffect)(()=>{tu(function(){try{let e=window.localStorage.getItem(er);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(N)}catch{}th(T(e,Date.now()));let t=e=>{if(e.key!==N||null===e.newValue)return;let t=T(e.newValue,Date.now());th(e=>e?I(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let ty=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);eN(await e.json())}catch{eN({version:1,projects:[]})}finally{eI(!0)}},[]);(0,i.useEffect)(()=>{ty()},[ty,c]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ei)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await eu(n.map(e=>({key:E(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ei)}catch{}await ty()})()},[ty]);let tb=(0,i.useCallback)(async e=>{if(tr.current)throw Error("Project update in progress");tr.current=!0,eW(!0);try{await eu(e),await ty()}finally{tr.current=!1,eW(!1)}},[ty]);(0,i.useEffect)(()=>{e$&&tt.current?.select()},[e$]);let tw=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&D(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();A(r.sessions),tx.current||to(new Set(r.runningSessionIds??[])),H(null),e||(ta(!0),tv.current&&clearTimeout(tv.current),tv.current=setTimeout(()=>ta(!1),2e3))}catch(e){H(String(e))}finally{e&&D(!1)}},[]),tk=(0,i.useCallback)(e=>{tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tu(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),th(t=>t&&R(t,[e])),d?.(e),tw()},[tw,d]),[tj,tS]=(0,i.useState)(null),[tC,tN]=(0,i.useState)(!1),[tT,tI]=(0,i.useState)(null),tM=(0,i.useCallback)(()=>{tC||(tS(null),tI(null))},[tC]),tR=(0,i.useCallback)(async e=>{tN(!0),tI(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(tx.current=!0,to(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(tc(n),tu(n),th(e=>e&&R(e,t)),t))d?.(e)}(await tw(),tN(!1),r.length>0)?tI(y("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tS(null)},[tw,d,y]),[tE,tL]=(0,i.useState)(0),t$=(0,i.useCallback)(()=>{tL(e=>e+1),tw()},[tw]),tP=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tP.current;tP.current=!0,tw(e,!e)},[tw,c]),(0,i.useEffect)(()=>{try{ee(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tA=(0,i.useCallback)(e=>{ee(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==Q)return;let e=()=>{"visible"===document.visibilityState&&tw(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tw,Q]),(0,i.useEffect)(()=>{try{0===tl.size?window.localStorage.removeItem(en):window.localStorage.setItem(en,JSON.stringify([...tl]))}catch{}},[tl]),(0,i.useEffect)(()=>{try{0===td.size?window.localStorage.removeItem(er):window.localStorage.setItem(er,JSON.stringify([...td]))}catch{}},[td]),(0,i.useEffect)(()=>{if(tp)try{var e,t,n;let r,i,a=window.localStorage;a.setItem(N,(e=a.getItem(N),t=Date.now(),i=(r=Object.entries((n=I(tp,T(e,t))).opened)).length>500?r.sort((e,t)=>t[1]-e[1]).slice(0,500):r,JSON.stringify({since:n.since,opened:Object.fromEntries(i)})))}catch{}},[tp]);let tF=(0,i.useCallback)(e=>{tu(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;tx.current=!0,to(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tg.current,n=[...t].filter(t=>!ts.has(t)&&t!==e),r=[...ts].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tc(e=>{let t=new Set(e);return ts.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!P.some(t=>t.id===e));(n.length>0||i)&&tw(!1,!0),n.length>0&&h?.(),tg.current=ts},[ts,e,P,tw,h]),(0,i.useEffect)(()=>{e&&tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let tz=e?z.find(t=>t.id===e)?.modified:void 0,tW=null!==tp;(0,i.useEffect)(()=>{e&&void 0!==tz&&tW&&th(t=>{var n;let r;return t&&(n={id:e,modified:tz},r=Math.max(Date.now(),M(n)??0),(t.opened[n.id]??-1/0)>=r?t:{since:t.since,opened:{...t.opened,[n.id]:r}})})},[e,tz,tW]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tD=(0,i.useRef)(!1),tO=(0,i.useCallback)(e=>{if(!e)return null;if(eJ&&eJ.forCwd===e||eJ?.worktrees.some(t=>t.path===e))return eJ.projectRoot;let t=z.find(t=>t.cwd===e);return t?.projectRoot??e},[eJ,z]),tH=(0,i.useRef)(null);(0,i.useEffect)(()=>{tH.current!==_&&(tH.current=_,p?.(_,tO(_)))},[_,p,tO]);let tU=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tU.current&&(tU.current=u,B(u))},[u]);let[t_,tB]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!_)return void eZ(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(_)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eZ(null);eZ({forCwd:_,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eZ(null)}),()=>{e=!0}},[_,t_,c]),(0,i.useEffect)(()=>{if(0!==P.length&&!o&&null===_){if(s&&!tD.current){tD.current=!0;let e=P.find(e=>e.id===s);if(e){B(e.cwd),n(e,!0);return}l?.()}if(!eT)return;let e=new Map(eC.projects.map(e=>[e.key,e])),t=$(P.length>0?L(P):[],eC.projects).filter(t=>!e.get(E(t))?.hidden);t.length>0&&B(t[0])}},[P,_,s,o,n,l,eC,eT]);let tq=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eK){eG(!0),eV(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eV(n.error??y("workspace.unable"));let r=n.cwd??t,i=E(r),a=eC.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tb([{key:i,path:r,hidden:!1}])}catch{}B(r),eB(!1)}catch{eV(y("workspace.unable"))}finally{eG(!1)}}},[tb,eK,eC.projects,y]),tV=(0,i.useCallback)(()=>{eB(!0),eV(null)},[]),tK=(0,i.useCallback)(async()=>{let e=e1.trim();if(e&&!e5&&eJ){e6(!0),e4(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e4(n.error??`HTTP ${t.status}`);e0(!1),e2(""),eX(!1),eZ(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[e1,e5,eJ]),tG=(0,i.useCallback)(async(e,t)=>{if(eJ&&!e5){e6(!0),e4(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eJ.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e7(e);e4(r.error??`HTTP ${n.status}`);return}e7(null),_===e&&B(eJ.projectRoot),tB(e=>e+1)}catch(e){e4(e instanceof Error?e.message:String(e))}finally{e6(!1)}}},[eJ,e5,_]);(0,i.useEffect)(()=>{let e=e=>{e9.current&&!e9.current.contains(e.target)&&(eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU(""),ek(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tJ=(0,i.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),tZ=(0,i.useCallback)((e=_)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;B(e),a?.(t,e)},[_,a]),[tY,tX]=(0,i.useState)(!1),[tQ,t0]=(0,i.useState)(null),t1=(0,i.useCallback)(async()=>{tX(!0),t0(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);tZ(t.cwd)}catch(e){t0(y("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tX(!1)}},[tZ,y]),t2=(0,i.useCallback)(e=>{ey(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),t8=tO(_),t4=null===t8?null:E(t8),t5=(0,i.useMemo)(()=>new Map(eC.projects.map(e=>[e.key,e])),[eC.projects]),t6=L(z);if(null!==t8){let e=E(t8);t6.some(t=>E(t)===e)||t6.unshift(t8)}let t3=$(t6,eC.projects),t7=t3.filter(e=>eM||!t5.get(E(e))?.hidden),t9=t3.some(e=>t5.get(E(e))?.hidden),ne=()=>{eS(null),eX(!1),e0(!1),e2(""),e4(null),e7(null),eU("")},nt=async(e,t)=>{ne();try{await tb([{key:E(e),path:e,hidden:t}]),t&&t4&&t4===E(e)&&B(null),t||t3.some(t=>E(t)!==E(e)&&t5.get(E(t))?.hidden)||eR(!1)}catch{}},nn=async e=>{if(tn.current){tn.current=!1,eP(null);return}let t=eA.trim();if(t===(t5.get(E(e))?.alias??""))return void eP(null);eO(null);try{await tb([{key:E(e),path:e,alias:t||null}]),eP(null)}catch{eO(y("sidebar.projectUpdateFailed"))}},nr=async(e,t)=>{if(Z)return;let n=t7.indexOf(e),r=n+t;if(n<0||r<0||r>=t7.length)return;let i=new Set(t7),a=t3.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...t3],o=a[n],l=a[r];[s[o],s[l]]=[s[l],s[o]],ne();try{await tb(s.map((e,t)=>({key:E(e),path:e,order:t})))}catch{}},ni=new Map;for(let e of z){let t=e.projectRoot??e.cwd;if(!t)continue;let n=E(t),r=ni.get(n);r?r.push(e):ni.set(n,[e])}let na=(0,i.useMemo)(()=>{let e=new Map;for(let t of z){let n=t.projectRoot??t.cwd;if(!n)continue;let r=E(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),ts.has(t.id)&&i.running++,tl.has(t.id)&&i.unread++}return e},[z,ts,tl]),ns=Z.trim().toLowerCase(),no=Z.length>0,nl=t7.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=E(e),r=t5.get(n),i=r?.alias??t,a=(ni.get(n)??[]).slice().sort((e,t)=>{let n=Number(td.has(t.id))-Number(td.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!ns)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(ns)||t.toLowerCase().includes(ns),o=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(ns));return s||0!==o.length?[{project:e,key:n,name:i,sessions:s?a:o,hidden:r?.hidden===!0}]:[]}),nc=[],nd=[];for(let e of nl){let t=e.key===t4||(na.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?nd.push(e):nc.push(e)}let nu={running:0,unread:0};for(let e of nd){let t=na.get(e.key);t&&(nu.running+=t.running,nu.unread+=t.unread)}let np=no||eE,nh=[...nc.map(e=>({kind:"project",group:e})),...nd.length>0?[{kind:"temporary"}]:[],...np?nd.map(e=>({kind:"project",group:e})):[]],nf=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nh.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nm=(0,i.useMemo)(()=>tp?z.filter(e=>(function(e,t,n){if(e.transient||t.has(e.id))return!1;let r=M(e);return null!==r&&r>(n.opened[e.id]??n.since)})(e,ts,tp)):[],[tp,ts,z]),ng=tf&&null!==tp,[nx,nv]=(0,i.useState)(null),ny=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned",o=10){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),c=l.filter(e=>a.has(e.id)),d=[],u=new Map,p=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(p>=o)continue;p+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=u.get(r);i?i.push(e):u.set(r,[e])}let h=[];for(let e of(c.length>0&&h.push({key:"pinned",label:s,running:!1,sessions:c}),d.length>0&&h.push({key:"priority",label:i,running:!0,sessions:d}),[...u.keys()].sort().reverse()))h.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),o=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===o||1===o?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-o,"day"):o>=0&&o<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:u.get(e)??[]});return h})(ng?z.filter(e=>e.id===nx&&!ts.has(e.id)||nm.includes(e)):z,ts,new Date,b,y("navigator.priority"),td,y("sidebar.pinned"),ng?1/0:void 0),[nx,b,td,nm,ng,ts,z,y]),nb=(0,i.useCallback)(e=>{nv(e.id),tJ(e)},[tJ]),nw=!!(eJ?.isGit&&eJ.isTopLevel&&_&&t8===eJ.projectRoot),nk=eJ?.worktrees.find(e=>e.path===_)??eJ?.worktrees.find(e=>e.isMain),nj=(eJ?.worktrees.length??0)>=8,nS=nj&&eH.trim()?(eJ?.worktrees??[]).filter(e=>(e.branch??es(e.path,q)).toLowerCase().includes(eH.trim().toLowerCase())):eJ?.worktrees??[],nC=(()=>{if(!tj)return[];let e="project"===tj.kind?ni.get(E(tj.project))??[]:ny.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nN=nC.filter(e=>!ts.has(e.id)),nT=e=>{let t=new Set;for(let n of e)n.transient||ts.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nI=void 0!==f&&m;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[e_&&(0,r.jsx)(G?Y:K,{busy:eK,error:eq,onCancel:()=>{eB(!1),eV(null)},onSelect:e=>void tq(e)}),tj&&(0,r.jsx)(eh,{scope:tj,eligible:nN.length,runningExcluded:nC.length-nN.length,busy:tC,error:tT,onCancel:tM,onConfirm:()=>void tR(nN)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ed,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>tZ(),disabled:!_,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:_?"var(--text-muted)":"var(--text-dim)",cursor:_?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),"aria-label":_?y("sidebar.newSessionTitle",{path:_}):y("sidebar.selectProject"),onMouseEnter:e=>{_&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=_?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${ti?" is-success":""}`,onClick:()=>tw(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ti?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ti?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ti?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{ti||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{ti||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:y("sidebar.refresh"),children:ti?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),G&&!nI&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tV,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:y("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":y("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?y("sidebar.projects"):y("navigator.priority"),n=!nI&&Q===e;return(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tA(e),nI&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==f&&(0,r.jsx)("button",{type:"button","aria-label":y("navigator.view",{label:v("translator.tab")}),"aria-pressed":nI,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!nI),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:nI?"var(--bg-selected)":"transparent",color:nI?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:nI?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!nI&&"projects"===Q&&(0,r.jsx)("button",{type:"button",onClick:()=>eR(e=>!e),disabled:!t9,title:y("sidebar.projectShowHidden"),"aria-label":y("sidebar.projectShowHidden"),"aria-pressed":eM,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eM?"var(--bg-selected)":"transparent",color:eM?"var(--accent)":"var(--text-dim)",cursor:t9?"pointer":"default",opacity:t9?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eM&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nI&&"projects"===Q&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tV,title:y("sidebar.addProject"),"aria-label":y("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),nI&&f,!nI&&"projects"===Q&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:Z,onChange:e=>X(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),X(""),e.currentTarget.blur())},placeholder:y("sidebar.searchProjectsAndSessions"),"aria-label":y("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!nI&&"projects"===Q&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(W||!eT)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),eD&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eD}),!W&&eT&&!O&&0===nl.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ns?y("sidebar.noMatchingProjects"):y("sidebar.noSessions")}),!W&&eT&&!O&&nh.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":np,title:y("sidebar.temporaryProjects"),onClick:()=>eL(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:np?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nd.length}),eb(nu,y)]})},"navigator-temporary-projects");let{project:s,key:o,name:l,sessions:c,hidden:d}=t.group,u=o===t4,p=nf.has(l.toLowerCase())&&es((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),q)||null,h=!ev.has(s)&&!ns,f=ec.has(s),m=e$===s,g=t7.indexOf(s),x=ez||no||g<=0,v=ez||no||g>=t7.length-1,b=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(f?c:c.slice(0,5)),k=c.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ej===s?e9:void 0,onMouseEnter:()=>ek(s),onMouseLeave:()=>ek(e=>e===s&&ej!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t2(s),title:h?y("sidebar.expandProject"):y("sidebar.collapseProject"),"aria-label":h?y("sidebar.expandProject"):y("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),m?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:tt,value:eA,onChange:e=>eF(e.target.value),onBlur:()=>void nn(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tn.current=!0,eP(null))},"aria-label":y("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>B(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),eb(na.get(o),y)]}),(0,r.jsx)("button",{type:"button",onClick:()=>tZ(s),title:y("sidebar.newSessionTitle",{path:s}),"aria-label":y("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||ew===s?1:0,pointerEvents:w||ew===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ek(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eS(ej===s?null:s),eX(!1),e0(!1),e4(null),u||B(s)},title:y("sidebar.projectActions"),"aria-label":y("sidebar.projectActions"),"aria-expanded":ej===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ej===s?"var(--bg-selected)":"transparent",color:u&&nk&&!nk.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||ew===s||ej===s?1:0,pointerEvents:w||ew===s||ej===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ek(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(el,{open:ej===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[nw&&eJ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eX(e=>!e),title:nk?y("sidebar.switchWorktreeTitle",{path:nk.path}):y("sidebar.switchWorktree"),"aria-label":y("sidebar.worktrees"),"aria-expanded":eY,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eY?"1px solid var(--border)":"none",background:eY?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:y("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(el,{open:eY,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nj&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eH,onChange:e=>eU(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eU(""),eX(!1))},placeholder:y("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[nS.map(e=>{let t=e.path===_||e.isMain&&!eJ.worktrees.some(e=>e.path===_);return e3===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tG(e.path,!0),disabled:e5,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:y("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>e7(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:y("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{B(e.path),eX(!1),e4(null),eU("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(eo,{text:e.branch??es(e.path,q),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:y("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tG(e.path,!1),disabled:e5,title:y("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nj&&0===nS.length&&eH.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:y("sidebar.noMatchingWorktrees")})]}),eQ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:te,value:e1,onChange:e=>{e2(e.target.value),e4(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tK()),"Escape"===e.key&&(e0(!1),e2(""),e4(null))},placeholder:y("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tK(),disabled:e5||!e1.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e5||!e1.trim()?"not-allowed":"pointer",opacity:e5||!e1.trim()?.65:1},children:e5?y("sidebar.creating"):y("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e0(!1),e2(""),e4(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:y("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e0(!0),e4(null),setTimeout(()=>te.current?.focus(),0)},title:y("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:y("sidebar.newWorktree")})]}),e8&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e8})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=t5.get(E(s))?.alias??"",void(tn.current=!1,eO(null),eF(e),eP(s),ne())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),y(t5.get(E(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),y("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:no?y("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nr(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),y("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>void nt(s,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),y(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nT(ni.get(o)??[])||tC,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{ne(),tI(null),tS({kind:"project",project:s,label:l})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),y("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:y("sidebar.noSessions")}),!h&&b.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:b.map(t=>(0,r.jsx)(ex,{node:t,selectedSessionId:e,runningSessionIds:ts,unreadSessionIds:tl,pinnedSessionIds:td,onSelectSession:tJ,onTogglePinnedSession:tF,onRenamed:tw,onSessionDeleted:tk,onSessionArchived:t$,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ef(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?y("sidebar.showLess"):y("sidebar.showMore")})]},s)})]}),!nI&&(0,r.jsx)(eg,{refreshKey:tE,selectedSessionId:e,onSelectSession:tJ,onRestored:t$}),!nI&&"priority"===Q&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[W&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:y("sidebar.loading")}),O&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),!W&&!O&&(x=nT(ny.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:tY,onClick:()=>void t1(),title:y("sidebar.newScratchSessionTitle"),style:ea(tY,w),children:y("sidebar.newScratchSession")}),ny.length>0&&!ng&&(0,r.jsx)("button",{type:"button",disabled:0===x||tC,onClick:()=>{tI(null),tS({kind:"priority"})},style:ea(0===x||tC,w),children:y("sidebar.clearPriorityList")})]})),!W&&!O&&tp&&(0,r.jsx)("div",{style:{display:"flex",padding:"6px 2px 4px"},children:(0,r.jsxs)("button",{type:"button","aria-pressed":ng,"aria-label":y("navigator.resultsToCheckCount",{count:nm.length}),title:y("navigator.resultsToCheckHint"),onClick:()=>{nv(null),tm(e=>!e)},style:{...ea(!1,w),display:"inline-flex",alignItems:"center",gap:6,borderColor:ng?"var(--border-strong)":"var(--border)",background:ng?"var(--bg-selected)":"transparent",color:ng||nm.length>0?"var(--text)":"var(--text-muted)",fontWeight:ng?600:500,whiteSpace:"nowrap"},children:[y("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:9,background:nm.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nm.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nm.length})]})}),tQ&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tQ}),!W&&!O&&0===ny.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ng?y("navigator.resultsToCheckEmpty"):y("sidebar.noSessions")}),!W&&!O&&ny.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(em,{session:t,selected:t.id===e,running:ts.has(t.id),unread:tl.has(t.id),pinned:td.has(t.id),onSelect:ng?nb:tJ,onTogglePin:tF},t.id))]},t.key))]})]})}function eh({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:o,onConfirm:l}){let{t:c}=(0,F.s)(),d=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let f=(0,i.useRef)(o);return f.current=o,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),f.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:c("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:o,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:d,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ef({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function em({session:e,selected:t,running:n,unread:i,pinned:a,onSelect:s,onTogglePin:o}){let{t:l}=(0,F.s)(),c=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),d=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>s(e),title:`${c}
|
|
2
2
|
${e.cwd}
|
|
3
3
|
${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:c}),n&&(0,r.jsx)(ev,{}),!n&&i&&(0,r.jsx)(ey,{})]}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:d})]}),(0,r.jsx)("button",{type:"button","aria-pressed":a,"aria-label":l(a?"sidebar.unpin":"sidebar.pin"),title:l(a?"sidebar.unpin":"sidebar.pin"),onClick:()=>o(e.id),style:{width:30,border:"none",background:"transparent",color:a?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(ef,{filled:a})})]})}function eg({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||d(n.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,i.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),a(t)}catch{}},[a]);return 0!==c.length||o?(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:o?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),s("sidebar.archived")," (",c.length,")"]}),o&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===c.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:s("sidebar.noArchivedSessions")}),c.map(e=>{let i=A(e.firstMessage)??e.firstMessage,a=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function ex({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:o,onRenamed:l,onSessionDeleted:c,onTogglePinnedSession:d,onSessionArchived:u,depth:p}){let[h,f]=(0,i.useState)(!1),m=e.children.length>0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(ew,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:a.has(e.session.id),isPinned:s.has(e.session.id),onClick:()=>o(e.session),onTogglePin:()=>d(e.session.id),onRenamed:l,onDeleted:e=>c?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:m,collapsed:h,onToggleCollapse:()=>f(e=>!e)})]}),m&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ex,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:o,onTogglePinnedSession:d,onRenamed:l,onSessionDeleted:c,onSessionArchived:u,depth:p+1},e.session.id))})]})}function ev(){let{t:e}=(0,F.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function ey(){let{t:e}=(0,F.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function eb(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,r.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function ew({session:e,isSelected:t,isRunning:n,isUnread:a,isPinned:s,onClick:o,onTogglePin:l,onRenamed:c,onDeleted:d,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:f=!1,onToggleCollapse:m}){let{t:g}=(0,F.s)(),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),T=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(y){let e=requestAnimationFrame(()=>T.current?.select());return()=>cancelAnimationFrame(e)}},[y]);let I=A(e.firstMessage)??e.firstMessage,M=e.name||I.slice(0,50)||e.id.slice(0,12),R=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||I.slice(0,50)||e.id.slice(0,12)),b(!0))},[e.name,e.transient,I,e.id]),E=(0,i.useCallback)(async()=>{let t=w.trim();if(b(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[w,e.id,e.name,c,M]),L=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),d?.(e.id)}catch{N(!1)}}},[e.id,e.transient,d]),$=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),P=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?L():S(!0)},[L]),z=(0,i.useCallback)(e=>{e.stopPropagation(),L()},[L]),W=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),D=(0,i.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}${j?" is-confirming":""}`,onClick:j||y?void 0:o,onContextMenu:j||y?void 0:D,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||y?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:z,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick:W,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):y?(0,r.jsx)("input",{ref:T,value:w,onChange:e=>k(e.target.value),onBlur:E,onKeyDown:e=>{"Enter"===e.key&&E(),"Escape"===e.key&&b(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[p>0&&(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),o()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(ev,{}),!n&&a&&(0,r.jsx)(ey,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),m?.()},title:g(f?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:f?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),l?.()},title:g(s?"sidebar.unpin":"sidebar.pin"),"aria-label":g(s?"sidebar.unpin":"sidebar.pin"),"aria-pressed":s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:s?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(ef,{filled:s})}),(0,r.jsx)("button",{onClick:R,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:$,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{onClick:P,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let ek=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,ej=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eS=/\x1B\[([0-9;]*)m/g,eC=/\x1B_pi:c\x07/g,eN=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eT=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function eI(e){return e.replace(eC,"").replace(ek,"")}function eM(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(ej);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function eR(e,t){let n=eM(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eE(e){return eM(e)[0]?.char}function eL(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(eC,""),i=eI(e).trimEnd();if(t.test(i))continue;let a=e,s=eE(a);("│"===s||"┃"===s)&&" "===eE(a=eR(a,0))&&(a=eR(a,0));let o=function(e){let t=eM(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),l=o>=0?eM(a)[o]?.char:void 0;("│"===l||"┃"===l)&&(a=eR(a,o)),n.push(function(e){let t=e;for(;;){let e=eM(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(a))}for(;n.length>0&&""===eI(n[0]).trim();)n.shift();for(;n.length>0&&""===eI(n[n.length-1]).trim();)n.pop();return n.length?n:e}function e$(e){let t,n=[],r={},i=0;for(eS.lastIndex=0;null!==(t=eS.exec(e));)t.index>i&&n.push({text:e.slice(i,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=eN[r-30];else if(r>=90&&r<=97)n.color=eT[r-90];else if(r>=40&&r<=47)n.backgroundColor=eN[r-40];else if(r>=100&&r<=107)n.backgroundColor=eT[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,a,s]=[t[e+2],t[e+3],t[e+4]];[i,a,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${a}, ${s})`:n.backgroundColor=`rgb(${i}, ${a}, ${s})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return eN[e];if(e>=8&&e<16)return eT[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(n)}, ${i(r)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===r?n.color=i:n.backgroundColor=i),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&n.push({text:e.slice(i),style:r}),n}let eP={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},eA={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eF={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},ez={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm",webm:"audio/webm"};function eW(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eD(e){return null!==(eF[eW(e)]??null)}function eO(e){let t;return null!==("pdf"===(t=eW(e))||"docx"===t?t:null)}function eH(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eU(e,t={}){return!!t.hideThinking&&"thinking"===e.type||function(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}(e,t)}function e_(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eB(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eU(e,t))}(e,t)){let e="image"===r.type||"text"===r.type&&r.text.trim().length>0?"answer":"process",t=n[n.length-1];t?.kind===e?t.blocks.push(r):n.push({kind:e,blocks:[r]})}return n}function eq(e){return e.filter(e=>"toolCall"===e.type).length}function eV(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}let eK=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function eG(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let a of i)"toolCall"===a.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===n.path;if("eval"===e.toolName){let e;return e=t.content?.at(-1),e?.type==="text"&&eK.test(e.text)}return"read"===e.toolName&&"string"==typeof n.path&&eD(n.path)}(a,t.get(a.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:a.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let eJ=new Map,eZ=new Map,eY="[한국어 번역]\n";function eX(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function eQ(e){if("custom"!==e.role||"korean-reply-translation"!==e.customType)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let n="sourceTimestamp"in t&&"number"==typeof t.sourceTimestamp?t.sourceTimestamp:void 0,r="sourceHash"in t&&"string"==typeof t.sourceHash?t.sourceHash:void 0;return void 0===n&&void 0===r?null:{sourceTimestamp:n,sourceHash:r}}let e0="command",e1="autolearn-saved";function e2(e){return"custom"===e.role&&(e.customType===e0||e.customType===e1&&!1!==e.display)}let e8="local-command:";function e4(e){return e?.startsWith(e8)===!0}function e5(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],a=[];for(let n=0;n<e.length;n++){let s=n<t.length;!(r.has(e[n])||s&&e4(t[n]))&&(i.push(e[n]),s&&a.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=a.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=a.length&&a.splice(t,0,e.entryId)}return{messages:i,entryIds:a}}function e6(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let e3={create:!0,update:!0};function e7(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function e9(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let n of e)n&&"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&"string"==typeof n.text&&t.push(n.text);return t.join("\n")}function te(e,t){if(0===e.length)return -1;if(!t)return 0;let n=-1;for(let r=0;r<e.length;r++){let i=e[r];if(i.item===t.item){if(i.k===t.k)return r;n=r}}return -1===n?0:n}function tt(e){try{return decodeURIComponent(e)}catch{return e}}function tn(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tr(e){let t=tn(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,a=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){a.length>0&&".."!==a[a.length-1]?a.pop():i||n||r||a.push(e);continue}a.push(e)}let s=a.join("/");return n?s:r?`//${s}`:i?`/${s}`:s}function ti(e,t,n=t){let r,i,a,s,o;if(!e)return null;let l=e.split("#",1)[0].split("?",1)[0].trim();if(!l)return null;let c=null,d=null,u=tt(l),p=u.startsWith("\\\\"),h=tn(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=tt(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(c=h,d="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(c=`${tn(t).replace(/\/+$/,"")}/${h}`,d="relative"),!c)return null;let m=tr(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&n&&(r=tr(m).replace(/\/+$/,""),i=tr(n).replace(/\/+$/,""),s=(a=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(s===(o=a?i.toLowerCase():i)||s.startsWith(`${o}/`)))?null:m}function ta(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,a=i(e),s=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(a),l=a.startsWith("//");if(o||l)n=a;else if(a.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${a}`:a}else{if(!s)return null;n=`${s}/${a}`}return tr(n)}function ts(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function to(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function tl(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tc(e,t){if(!e||"object"!=typeof e||"delete"===e.op&&!t)return null;let n=e.path??e.resolvedPath;return"string"==typeof n&&n.length>0?n:null}function td(e,t,n=!1){let r=t.details,i=tl(e);if(i)return!n&&r&&"object"==typeof r&&"delete"===r.op?[]:[i];if(!r||"object"!=typeof r)return[];if(Array.isArray(r.perFileResults))return r.perFileResults.map(e=>tc(e,n)).filter(e=>null!==e);let a=tc(r,n);return a?[a]:[]}function tu(e,t){let n=tl(e);return(t?td(e,t,!0):n?[n]:[]).filter(tg)}function tp(e,t,n){let r=tu(e,t);return r.length>0&&r.every(e=>tm(e,n))}let th=new Map(["skills","commands","rules","prompts","extensions","instructions","hooks","tools","agents","plugins","mcp.json",".mcp.json","SYSTEM.md","SYSTEM_TEMPLATE.md","APPEND_SYSTEM.md","AGENTS.md","settings.json","config.yml","secrets.yml"].map(e=>[e.toLowerCase(),e])),tf=[/^\/(?:private\/)?(?:var\/)?tmp(?:\/|$)/,/^\/(?:private\/)?var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/,/^(?:[a-z]:|\/mnt\/[a-z])\/(?:windows\/)?temp(?:\/|$)/i,/^(?:[a-z]:|\/mnt\/[a-z])\/users\/[^/]+\/appdata\/local\/temp(?:\/|$)/i];function tm(e,t){let n=ta(e,t),r=t?ta(t)?.replace(/\/+$/,""):void 0,i=n??e.replace(/\\/g,"/"),a=/^(?:[a-zA-Z]:\/|\/\/|\/mnt\/[a-zA-Z](?:\/|$))/.test(i)||void 0!==r&&/^(?:[a-zA-Z]:\/|\/\/)/.test(r),s=e=>a?e.toLowerCase():e,o=null===n||void 0!==r&&(s(n)===s(r)||s(n).startsWith(`${s(r)}/`));return!!function(e,t){let n=(e,n)=>void 0!==e&&(t?e.toLowerCase()===n:e===n),r=e.findIndex(e=>n(e,".omp"));if(r<0||r===e.length-1)return!1;let i=e[r+1];if(n(i,"agent")||n(i,"wt")||n(i,"profiles")&&n(e[r+3],"agent"))return!1;let a=th.get(i.toLowerCase());return!(void 0!==a&&(t||a===i))}((null!==n&&o&&void 0!==r?n.slice(r.length):i).split("/").filter(e=>""!==e&&"."!==e),a)||!o&&tf.some(e=>e.test(i))}function tg(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tx(e,t,n){let r=new Set,i=[];for(let s of e){var a;if("toolCall"!==s.type||!(ts(a=s.toolName)||to(a)))continue;let e=t?.get(s.toolCallId);if(e&&!e.isError)for(let t of td(s.input,e)){if(!tg(t))continue;let e=ta(t,n);!(!e||tm(t,n))&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}function tv(e){let t=[];for(let n of e){if(!n||"object"!=typeof n||!("name"in n)||!("tasks"in n))return{phases:t,malformed:!0};let{name:e,tasks:r}=n;if("string"!=typeof e||!Array.isArray(r))return{phases:t,malformed:!0};let i=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;return"string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n?[]:[{content:t,status:n,blocker:"blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0}]}):[];if(i.length!==r.length)return{phases:t,malformed:!0};i.length>0&&t.push({name:e,tasks:i})}return{phases:t,malformed:!1}}function ty(e){if(!Array.isArray(e))return null;let{phases:t,malformed:n}=tv(e);return n?null:t}function tb(e,t){var n;let r;if(t){let e=t.details,n=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(n))return{kind:"unknown"};let{phases:r,malformed:i}=tv(n);return i?{kind:"unknown"}:{kind:"authoritative",phases:r}}let i=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}function tw(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}function tk(e,t,n=null,r=null){return n||(function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n],i=r.trackerTodos??[];for(let e=i.length-1;e>=0;e-=1){let t=ty(i[e]);if(t)return t}if("assistant"!==r.role)continue;let a=r.content;if(Array.isArray(a))for(let e=a.length-1;e>=0;e-=1){let n=a[e];if("toolCall"!==n.type||!tw(n.toolName))continue;let r=tb(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function tj(e){let t=0,n=0,r=null,i=null,a=null;for(let s of e)for(let e of s.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:s,task:e}):"blocked"===e.status?a||(a={phase:s,task:e}):i||(i={phase:s,task:e}))}let s=r??i??a,o=t+n;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:n,completed:t,total:o,percent:o>0?Math.round(t/o*100):null}}function tS(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tC(e){return tS(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tN(e){let t=tS(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tT(e,t){if(!t)return e;let n=tS(e),r=tS(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var tI=n(65063),tM=n(7644),tR=n(32316),tE=n(88374),tL=n(63280),t$=n(94764),tP=n(63835),tA=n(54152),tF=n(84678),tz=n(98164);let tW={...t$.j,attributes:{...t$.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...t$.j.strip||[],"iframe","object","style","form"]};function tD(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,a=0,s=null,o=new Map;for(let e=0;e<n.length;e++){var l;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},a=0,r.push(t);continue}if(i){r.push(t);continue}let d=t.match(/<(code|pre|script|style)\b/i);if(d){let e=d[1].toLowerCase(),n=t.slice((d.index??0)+d[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(s=e),a=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){a=0,r.push(t);continue}if(a||t.includes("`")){a=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,a),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>tH(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let f=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(f){let t=f[1],i=f[2].trimEnd();if(i&&!i.includes("$$")){let a=tO(n,e+1,t,o);if(a){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<a.index;i++)r.push(tH(n[i],t));a.content&&r.push(`${t}${a.content}`),r.push(`${t}$$`),e=a.index;continue}}}let m=t.match(/^([ \t]{0,3})\$\$\s*$/);if(m){let t=m[1],i=tO(n,e+1,t,o);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let a=e+1;a<i.index;a++)r.push(tH(n[a],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((l=t,/^\s{0,3}\[[^\]]+\]:/.test(l)||/]\s*\(/.test(l)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(l)||/\b(?:https?|file|mailto):/i.test(l)||/\b[A-Za-z]:\\/.test(l)?l:l.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function tO(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var a,s,o,l;let t=e[i];if(a=t,""===(s=n)?/^ {0,3}\$\$\s*$/.test(a):a.startsWith(s)&&/^\$\$\s*$/.test(a.slice(s.length)))return{index:i,content:"",glued:!1};if(o=t,/^ {0,3}(`{3,}|~{3,})/.test(o)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(o)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(o)||/^ {0,3}>/.test(o)||/<(code|pre|script|style)\b/i.test(o)||(l=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(l)))return r.set(n,i),null;let c=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==c)return{index:i,content:c,glued:!0}}return r.set(n,e.length),null}function tH(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let tU={singleTilde:!1},t_=[[tA.A,["yaml"]],[tF.A,tU],tz.A],tB=[[tA.A,["yaml"]],[tF.A,tU],tz.A],tq=[tL.A,[tP.A,tW],[tE.A,{throwOnError:!1,strict:!1}]],tV=[tL.A,[tP.A,tW],[tE.A,{throwOnError:!1,strict:!1}]],tK="pi-theme",tG=["light","dark","auto"],tJ={preference:"auto",theme:"light"},tZ="omp-theme",tY=null,tX=0,tQ=new Set,t0=null,t1=!1;function t2(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function t8(e){return"auto"===e?t2():e}let t4="--omp-md-";function t5(e){let t=document.documentElement,n=tY?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let n=t.style.item(e);n.startsWith("--")&&!n.startsWith(t4)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(t4)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tZ,e)}catch{}}function t6(){if(t0)return t0;let e=function(){try{let e=localStorage.getItem(tK);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tZ);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=t8(e);return t5(t),t0={preference:e,theme:t}}function t3(e,t,n){if(t5(t),n)try{localStorage.setItem(tK,e)}catch{}t0={preference:e,theme:t},tQ.forEach(e=>e())}function t7(){let e=t6();if("auto"!==e.preference)return;let t=t2();t!==e.theme&&t3("auto",t,!1)}function t9(e){return tQ.add(e),t6(),t1||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",t7),window.addEventListener("focus",t7),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&t7()}),t1=!0),t7(),()=>{tQ.delete(e)}}function ne(){return t6()}function nt(){return tJ}async function nn(e){let t=++tX,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/theme${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Theme request failed (${r.status})`);let i=await r.json();if(t===tX){tY=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(tY))}catch{}t5(t6().theme)}}function nr(e){let t=(0,i.useSyncExternalStore)(t9,ne,nt);(0,i.useEffect)(()=>{e?.syncWithOmp&&nn(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=t8(e),r=()=>{t3(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let a=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(a,window.innerWidth-a),Math.max(s,window.innerHeight-s));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${a}px ${s}px)`,`circle(${o}px at ${a}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=t6().preference,r=tG.indexOf(t),tG[(r+1)%tG.length]),e)},[n]),a=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:a,isDark:"dark"===t.theme}}function ni(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}let na={...tM.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tM.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function ns({code:e,isStreaming:t}){let{isDark:a}=nr(),{t:s}=(0,F.s)(),[o,l]=(0,i.useState)(!0),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),h=`${a?"dark":"light"}
|
|
4
4
|
${e}`,f=o&&!t;(0,i.useEffect)(()=>{if(!f)return;let t=!1;return d({key:h,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328)),i=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${i}`,e),await document.fonts.ready,t)return;if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:a?"dark":"default",fontFamily:i}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let s="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await r.render(s,e);t||d({key:h,status:"ready",svg:o.svg})})().catch(()=>{t||d({key:h,status:"error"})}),()=>{t=!0}},[e,h,a,f]);let m=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),disabled:t,title:t?s("i18n.previewAfterStreaming"):f?s("i18n.showMermaidSource"):s("i18n.previewMermaid"),className:["markdown-code-action",f?"is-active":""].filter(Boolean).join(" "),children:f?s("i18n.source"):s("i18n.preview")}),[t,f,s]);if(!f)return(0,r.jsx)(nl,{code:e,lang:"mermaid",headerAction:m,isStreaming:t});let g=c?.key===h&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==h||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!u&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openMermaidViewer"),"aria-label":s("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),u&&(0,r.jsx)(no,{svg:c.svg,onClose:()=>p(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),m]}),g]})}function no({svg:e,onClose:t}){let{t:n}=(0,F.s)(),a=(0,i.useRef)(null),[s,o]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>Math.min(3,e+.25)),disabled:s>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>o(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let nl=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:a}){let{isDark:s}=nr(),{t:o}=(0,F.s)(),[l,c]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{ni(e).then(()=>{c(!0),setTimeout(()=>c(!1),1500)})},className:"markdown-code-action",children:o(l?"i18n.copied":"i18n.copy")})]})]}),a?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(tI.A,{language:t||"text",style:s?tM.xJ:na,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-muted)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function nc({children:e,className:t,isStreaming:n,cwd:a,onOpenFile:s}){let o=(0,i.useMemo)(()=>tD(e),[e]),l=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let a=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===a?(0,r.jsx)(ns,{code:s.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(nl,{code:s.replace(/\n$/,""),lang:a,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=s?ti(e,a):null;return i&&s?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?ti(e,a):null,s=i?`/api/files/${tC(i)}?type=read`:e;return(0,r.jsx)("img",{src:s,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[a,n,s]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(tR.oz,{remarkPlugins:t_,rehypePlugins:tq,components:l,children:o})})}function nd(e){let[t,n]=(0,i.useState)(()=>Date.now());return(0,i.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}var nu=n(54265);let np=(0,i.createContext)(null);function nh(e,t,n){return Math.min(n,Math.max(t,e))}function nf(e,t,n){let r=t.width>0?n.width/t.width:0,i=t.height>0?n.height/t.height:0;return{x:nh((e.x-t.left)*r,0,n.width),y:nh((e.y-t.top)*i,0,n.height)}}function nm(e){let t=nh(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let ng="#e5191f",nx="#ffffff";function nv(e){let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.toBlob(e=>e?n(e):r(Error("canvas encode failed")),"image/png"),t}function ny(e,t){let n=document.createElement("canvas");n.width=e,n.height=t;let r=n.getContext("2d");if(!r)throw Error("canvas 2d unavailable");return[n,r]}async function nb(e,t){let n=await createImageBitmap(e);try{let e={width:n.width,height:n.height},{inner:r,outer:i}=nm(e),a=Math.max(14,7*nm(e).inner),[s,o]=ny(e.width,e.height);o.drawImage(n,0,0),t.forEach((t,n)=>{let s=function(e,t){let{inner:n,outer:r}=nm(t),i=(n,r)=>{let i=nh(e.x-n,r,t.width-r),a=nh(e.y-n,r,t.height-r),s=nh(e.x+e.w+n,r,t.width-r);return{x:i,y:a,w:Math.max(0,s-i),h:Math.max(0,nh(e.y+e.h+n,r,t.height-r)-a)}};return{inner:i(n/2,n/2),outer:i(n+r/2,r/2)}}(t,e);o.lineJoin="miter",o.strokeStyle=nx,o.lineWidth=i,o.strokeRect(s.outer.x,s.outer.y,s.outer.w,s.outer.h),o.strokeStyle=ng,o.lineWidth=r,o.strokeRect(s.inner.x,s.inner.y,s.inner.w,s.inner.h);let l=String(n+1);o.font=`700 ${a}px sans-serif`;let c=Math.round(.35*a),d=Math.ceil(o.measureText(l).width)+2*c,u=Math.round(1.3*a),p=Math.min(Math.max(0,t.x-r),e.width-d),h=t.y-r-u,f=h>=0?h:Math.min(t.y,e.height-u);o.fillStyle=nx,o.fillRect(p-1,f-1,d+2,u+2),o.fillStyle=ng,o.fillRect(p,f,d,u),o.fillStyle=nx,o.textBaseline="middle",o.textAlign="center",o.fillText(l,p+d/2,f+u/2)});let l=await Promise.all(t.map(t=>{let r=function(e,t,n=.12){let r=Math.round(e.w*n),i=Math.round(e.h*n),a=nh(e.x-r,0,t.width),s=nh(e.y-i,0,t.height),o=nh(e.x+e.w+r,0,t.width);return{x:a,y:s,w:o-a,h:nh(e.y+e.h+i,0,t.height)-s}}(t,e),[i,a]=ny(r.w,r.h);return a.drawImage(n,r.x,r.y,r.w,r.h,0,0,r.w,r.h),nv(i)}));return{marked:await nv(s),crops:l}}finally{n.close()}}function nw({src:e,regions:t,max:n,onAdd:a,onNaturalSize:s,regionLabel:o}){let l=(0,i.useRef)(null),[c,d]=(0,i.useState)(null),u=(0,i.useRef)(null),[p,h]=(0,i.useState)(null),f=e=>{let t=l.current,n=u.current;return t&&n&&c?function(e,t,n,r){let i=nh(Math.min(e.x,t.x),n.left,n.left+n.width),a=nh(Math.max(e.x,t.x),n.left,n.left+n.width),s=nh(Math.min(e.y,t.y),n.top,n.top+n.height),o=nh(Math.max(e.y,t.y),n.top,n.top+n.height);if(a-i<6||o-s<6)return null;let l=nf({x:i,y:s},n,r),c=nf({x:a,y:o},n,r),d=Math.floor(l.x),u=Math.floor(l.y),p=Math.min(r.width,Math.ceil(c.x))-d,h=Math.min(r.height,Math.ceil(c.y))-u;return p>0&&h>0?{x:d,y:u,w:p,h}:null}(n.start,e,t.getBoundingClientRect(),c):null},m=(e,t)=>{if(u.current?.pointerId!==e.pointerId)return;let n=t?f({x:e.clientX,y:e.clientY}):null;u.current=null,h(null),n&&a(n)};return(0,r.jsxs)("div",{className:"tool-image-marker","data-drawing":c&&t.length<n?"true":void 0,onPointerDown:e=>{c&&!(t.length>=n)&&("mouse"!==e.pointerType||0===e.button)&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),u.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY}})},onPointerMove:e=>{u.current?.pointerId===e.pointerId&&h(f({x:e.clientX,y:e.clientY}))},onPointerUp:e=>m(e,!0),onPointerCancel:e=>m(e,!1),children:[(0,r.jsx)("img",{ref:l,className:"tool-image-full",src:e,alt:"",draggable:!1,onLoad:e=>{let t={width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight};d(t),s(t)}}),c&&t.map((e,t)=>(0,r.jsx)(nk,{region:e,natural:c,label:String(t+1),title:o(t+1)},`${t}-${e.x}-${e.y}`)),c&&p&&(0,r.jsx)(nk,{region:p,natural:c})]})}function nk({region:e,natural:t,label:n,title:i}){let a={left:e.x/t.width*100,top:e.y/t.height*100,width:e.w/t.width*100,height:e.h/t.height*100};return(0,r.jsx)("span",{className:"tool-image-region","data-draft":n?void 0:"true",role:n?"img":void 0,"aria-label":i,style:{left:`${a.left}%`,top:`${a.top}%`,width:`${a.width}%`,height:`${a.height}%`},children:n&&(0,r.jsx)("span",{className:"tool-image-region-number","aria-hidden":"true",children:n})})}function nj(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}function nS(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}let nC=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,nN=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function nT(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let nI={hideThinkingBlock:!1},nM=new Set,nR=nI,nE=0;function nL(e){return nM.add(e),()=>{nM.delete(e)}}function n$(){return nR}function nP(){return nI}async function nA(e){let t=++nE,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/display-settings${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Display settings request failed (${r.status})`);let i=await r.json();t!==nE||i.hideThinkingBlock!==nR.hideThinkingBlock&&(nR={hideThinkingBlock:!0===i.hideThinkingBlock},nM.forEach(e=>e()))}function nF(){return(0,i.useSyncExternalStore)(nL,n$,nP)}let nz="/api/sidecars/resource";function nW(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},n=e=>{let n=t[e];return"number"==typeof n&&Number.isFinite(n)?n:null},r=n("usedFraction");if(null!==r&&r>=1)return!0;let i=n("remainingFraction");if(null!==i&&i<=0)return!0;let a=n("used"),s=n("limit");if(null!==a&&null!==s&&a>=s)return!0;let o=n("remaining");return null!==o&&o<=0||"percent"===t.unit&&null!==a&&a>=100}let nD=[{alias:"RIN(린)",file:"rin.webp"},{alias:"MIO(미오)",file:"mio.webp"},{alias:"MITSU(미츠)",file:"mitsu.webp",provider:"hive",model:"zai-org/glm-5.3-flash"},{alias:"YUKI(유키)",file:"yuki.webp",provider:"openai-codex"},{alias:"ISANA(이사나)",file:"isana.webp",provider:"hive"},{alias:"SHION(시온)",file:"shion.webp",provider:"web6"},{alias:"HIKARI(히카리)",file:"hikari.webp",provider:"google-antigravity"}],nO=[{seed:3,alias:nD[3].alias,provider:"openai-codex",model:"gpt-6-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:nD[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:nD[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:nD[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:nD[2].alias,provider:"hive",model:"zai-org/glm-5.3-flash",voice:"부지런한 배달\xb7통통 튀는 보고\xb7끈질긴 재도전",summonExample:"미츠 불러와",switchExample:"미츠로 교체해"},{seed:6,alias:nD[6].alias,provider:"google-antigravity",model:"gemini-3.8-flash",voice:"빠른 관찰\xb7톡 쏘는 한마디\xb7장난스러운 여유",summonExample:"히카리 불러와",switchExample:"히카리로 교체해"},{seed:5,alias:nD[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],nH=nO.filter(e=>null!==e.switchExample),nU=nD.filter(e=>!("provider"in e)).length,n_=new Map(nD.flatMap((e,t)=>"provider"in e&&!("model"in e)?[[e.provider,t]]:[])),nB=new Map(nD.flatMap((e,t)=>"model"in e?[[`${e.provider}/${e.model}`,{seed:t,alias:e.alias}]]:[])),nq=new Map([...n_].map(([e,t])=>[e,{seed:t,alias:nD[t].alias}]));function nV(e){return nq.get(e)??null}function nK(e){let t=e%nD.length;return nD[t].alias}function nG(e){let t=e%nD.length;return`/avatars/${nD[t].file}`}function nJ(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function nZ(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 nY(e){let t=new Map;for(let n of e){if(!Number.isSafeInteger(n.oauthPosition)||n.oauthPosition<0)continue;let e=t.get(n.provider)??new Set;e.add(n.oauthPosition),t.set(n.provider,e)}return e.map(e=>{var n;let r=e.metadata?.email,i=e.metadata?.accountId,a="string"==typeof r&&r.length>0?r:"string"==typeof i?i:"",s=a.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return nJ(e);let n=e.slice(t+1),r=n.lastIndexOf("."),i=r<0?n:n.slice(0,r),a=r<0?"":n.slice(r);return`${nJ(e.slice(0,t))}@${0===i.length?"":`${i[0]}•••`}${a}`}(a):"",o=(n=e.provider,n_.get(n)??-1);if(o>=0)return{seed:o,alias:nK(o),masked:s,raw:a};let l=e.oauthPosition;if(!Number.isSafeInteger(l)||l<0){let n=t.get(e.provider)??new Set;for(l=0;n.has(l);)l++;n.add(l),t.set(e.provider,n)}let c=l%nU,d=l<nU?nK(c):`${nK(c)}${l+1}`;return{seed:c,alias:d,masked:s,raw:a}})}class nX 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 nQ(e,t){return`${nz}${e}${t?"?refresh=1":""}`}function n0(e,t,n=!1){return e instanceof nX?e:t?new nX("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new nX("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new nX(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function n1(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function n2(e,t){let n,r=t.fetchImpl??fetch,i=new AbortController,a=!1,s=()=>i.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0}),null!=t.timeoutMs&&(n=setTimeout(()=>{a=!0,i.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,n=await r(e,{signal:i.signal});try{t=await n.json()}catch(e){throw new nX("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",n.status,{cause:e})}let a=t&&"object"==typeof t?t:null,s="string"==typeof a?.error?a.error:null;if(!n.ok||s)throw new nX(s??`HTTP ${n.status}`,"http",n.status,{code:"string"==typeof a?.code?a.code:void 0,outcomeUnknown:a?.outcomeUnknown===!0});return t}catch(e){throw n0(e,a,i.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",s)}}let n8="google-antigravity",n4=`${n8}:google:`;function n5(e){if(e.provider!==n8||!Array.isArray(e.limits))return e;let t=e.limits.filter(e=>"string"==typeof e.id&&e.id.startsWith(n4));return t.length===e.limits.length?e:{...e,limits:t}}async function n6(e={}){try{let t=await n2(nQ("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new nX("사용량 응답 형식이 올바르지 않습니다.","invalid-response");let n=t.reports.map(n5);return{status:"fresh",data:n.every((e,n)=>e===t.reports[n])?t:{...t,reports:n},error:null}}catch(t){return n1(e.previous,n0(t,!1))}}async function n3(e,t={}){if(!e)return n1(void 0,new nX("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await n2(`/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 nX("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return n1(void 0,n0(e,!1))}}async function n7(e={}){try{let t=await n2(nQ("/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 nX("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return n1(e.previous,n0(t,!1))}}async function n9(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new nX("credential id가 올바르지 않습니다.","invalid-response");let r=await n2(`${nz}/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 nX("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function re(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new nX("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new nX("credit id가 올바르지 않습니다.","invalid-response");let r=await n2(`${nz}/credential/${e}/reset`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,r)=>{let i=new Headers(r?.headers);return i.set("Content-Type","application/json"),(n.fetchImpl??fetch)(e,{...r,method:"POST",headers:i,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!r||"boolean"!=typeof r.ok||r.credentialId!==e||r.creditId!==t||"string"!=typeof r.code||r.ok!==("reset"===r.code))throw new nX("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function rt(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let rn={faces:new Map,pins:new Map},rr=[],ri=rn,ra=null,rs=new Map,ro=new Set;function rl(e){return ro.add(e),()=>{ro.delete(e)}}function rc(e){ri=e,ro.forEach(e=>e())}function rd(e){return Number.isSafeInteger(e)&&e>0}function ru(e,t){return`${e}:${t}`}function rp(e,t,n,r){if(!t)return null;let i=void 0===r?null:nB.get(`${t}/${r}`)??null;if(i)return i;if(rd(n)){let e=ri.faces.get(ru(t,n));if(e)return e}let a=e?ri.pins.get(e):void 0;if(a&&a.provider===t){let e=ri.faces.get(ru(t,a.credentialId));if(e)return e}return nV(t)}async function rh(e,t,n,r){if(!t||rd(n)||nV(t))return rp(e,t,n,r);try{let{data:n}=await n3(e);if(n?.state==="resolved"&&n.provider===t&&rd(n.credentialId)){let r=new Map(ri.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),rc({faces:ri.faces,pins:r})}}catch{}return rp(e,t,void 0,r)}function rf(e,t,n,r){let a=!!t&&!rd(n)&&!!e;return(0,i.useEffect)(()=>{a&&e&&t&&function(e,t){let n=Date.now(),r=ri.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,a=rs.get(i);void 0!==a&&n-a<3e4||(rs.set(i,n),n3(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!rd(i))return;let a=new Map(ri.pins);a.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),rc({faces:ri.faces,pins:a})}).catch(()=>{}))}(e,t)},[a,e,t]),(0,i.useSyncExternalStore)(rl,()=>rp(e,t,n,r),()=>null)}let rm={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","run.dispatching":"발주 중","run.pending":"대기","run.running":"실행 중","run.completed":"실행 완료","run.failed":"실행 실패","run.aborted":"중단됨","run.unobserved":"실행 상태 미관측","verdict.accepted":"Main 수용","verdict.rework":"Main 재작업 요청","verdict.held":"Main 보류","verdict.none":"검수 미기록","verdict.attempt":"{attempt}차","detail.stage":"현재 단계","detail.stageNone":"기록 없음","detail.model":"모델","detail.modelNone":"미관측","detail.fallback":"대체 모델","detail.agentId":"담당 ID","detail.reason":"판정 사유","detail.source.live":"실시간 관측","detail.source.record":"세션 기록","detail.openSubagents":"서브에이전트 상세 열기","detail.openProcess":"작업 기록 열기","summary.live":"진행 중","summary.files":"변경 파일 {count}","summary.files.one":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checks.one":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.verdictUnverified":"판정 미확인 {count}","summary.verdictUnverified.one":"판정 미확인 {count}","summary.expand":"턴 요약 펼치기","summary.collapse":"턴 요약 접기","result.label":"이번 결과","result.open":"결과 보기","result.openNamed":"{name} 결과 보기","result.previewTitle":"{name} 미리보기","result.previewFailed":"미리보기를 불러오지 못했습니다. 결과 보기를 누르세요.","result.more":"다른 결과 {count}","result.previewLoading":"미리보기를 불러오는 중","result.kind.html":"화면","result.kind.pdf":"PDF","result.kind.document":"문서","result.kind.image":"이미지","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.check.exit":"exit {code}","summary.makers":"Maker {count}","summary.makers.one":"Maker {count}","summary.remaining":"남은 일 {count}","summary.heading.remaining":"남은 일","summary.time.unobserved":"시간 기록 없음","summary.time.running":"아직 실행 중","summary.todo.pending":"대기","summary.todo.in_progress":"진행 중","summary.todo.blocked":"막힘","summary.todo.blocker":"막힌 이유: {blocker}","summary.todo.none":"남은 일 없음","flow.heading":"작업 흐름","flow.aria":"이번 턴의 작업 단계","flow.toggle":"작업 흐름","flow.stage.investigate":"조사","flow.stage.edit":"수정","flow.stage.check":"검사","flow.stage.review":"교차리뷰","flow.stage.commit":"커밋\xb7푸시","flow.stage.ci":"CI","flow.stage.deploy":"배포","flow.state.waiting":"대기","flow.state.running":"진행 중","flow.state.done":"완료","flow.state.redone":"다시 고침","flow.state.passed":"통과","flow.state.unverified":"판정 미확인","flow.state.failed":"실패","flow.state.unobserved":"결과 미관측","flow.state.findings":"지적 {count}건","flow.state.findings.one":"지적 {count}건","flow.state.noFindings":"지적 없음","flow.state.open":"미해결 {count}건","flow.state.reviewUnusable":"리뷰 불가","flow.state.skipped":"건너뜀","flow.state.notNeeded":"필요 없음","flow.count.passed":"통과 {count}","flow.count.unverified":"판정 미확인 {count}","flow.count.failed":"실패 {count}","flow.count.unobserved":"결과 미관측 {count}","flow.count.running":"진행 중 {count}","flow.earlier":"이전 회차 {count}건","flow.attempt":"{attempt}회차","flow.label.typecheck":"타입 검사","flow.label.lint":"린트","flow.label.test":"테스트","flow.label.build":"빌드","flow.label.verify":"검증","flow.label.smoke":"스모크 확인","flow.label.check":"검사","flow.label.ci":"CI 확인","flow.label.deploy":"배포 실행","flow.label.review":"리뷰","flow.label.resolve":"지적 처리","flow.label.commit":"커밋\xb7푸시","flow.details":"자세히","flow.commandOmitted":"명령 본문은 압축된 요청의 요약에서 생략했어요.","flow.exit":"셸 종료 코드 {code}","flow.exit.none":"종료 코드 기록 없음","flow.exit.error":"오류로 끝남","flow.evidence":"판정에 쓴 기록","flow.why.confirmed":"확인된 것","flow.why.missing":"없는 것","flow.why.exitZero":"셸 종료 코드 0","flow.why.check":"{label} 명령의 종료 코드. 뒤에 이어 붙인 명령(파이프, ;, || 등)이 결과를 가릴 수 있어서 통과로 세지 않았어요.","flow.why.ci":"CI 결과를 종료 코드로 돌려준 기록. gh run watch --exit-status처럼 결과를 돌려주는 명령이 아니라서 통과로 세지 않았어요.","flow.why.ciOtherRun":"이 커밋의 CI 실행이라는 기록. 기다린 실행은 기록상 다른 커밋 {sha}의 실행이에요.","flow.why.ciPublishRun":"이 커밋의 CI 실행 결과. 이 명령이 기다린 실행은 게시 실행이라 CI 판정으로 세지 않았어요.","flow.why.watched.passed":"기다린 실행이 통과로 끝남","flow.why.watched.failed":"기다린 실행이 실패로 끝남","flow.why.watched.unjudged":"기다린 실행이 판정 없이 끝남({conclusion})","flow.why.ciUnjudged":"이 커밋의 CI 판정. 기다린 실행이 통과도 실패도 아닌 {conclusion} 상태로 끝나서, 명령의 실패를 CI 실패로 세지 않았어요.","flow.why.deploy":"배포가 끝났다는 기록. 배포를 띄우고 바로 돌아오는 명령이라 셸 종료 코드만으로는 끝났는지 알 수 없어요.","flow.strip.running":"{stage} 진행 중","flow.loop.badge":"↻ {attempt}회차","flow.loop.failed":"{stage} {attempt}회차 실패로 수정에 되돌아옴","flow.loop.findings":"{stage} {attempt}회차 지적으로 수정에 되돌아옴","flow.state.stale":"수정 전 통과","flow.state.staleDone":"수정 전 완료","flow.count.stale":"수정 전 통과 {count}","flow.why.stale":"이 결과 뒤에 파일을 다시 고쳐서, 마지막 수정본은 아직 확인하지 않았어요.","flow.compound.failed":"묶은 명령 실패","flow.why.compoundConfirmed":"{stages}를 한 명령으로 돌렸고, 명령 전체가 실패로 끝남","flow.why.compoundMissing":"어느 단계에서 실패했는지","flow.ci.notNeeded":"비공개 저장소에만 반영됐어요. 게시 실행 {run} 뒤에도 공개 {repo}의 {ref}는 CI를 통과한 {sha} 그대로예요.","flow.ci.nothingToPublish":"커밋 {sha}의 게시 실행 로그에 「Public tree already matches; nothing to publish」가 남았어요. 공개 저장소가 그대로라 새로 돌 CI가 없어요.","summary.stale":"수정 전 통과 {count}","summary.compoundFailed":"묶은 명령 실패 {count}","graph.branch":"수정 중 맡긴 Maker {count}","graph.branch.one":"수정 중 맡긴 Maker {count}","graph.parallel.observed":"동시 실행 관측","graph.join":"Main 판정","graph.parallel.batch":"같은 발주 묶음","graph.concurrency.overlapped":"겹쳐 실행","graph.concurrency.unknown":"겹침 여부 모름","graph.kind.feature":"기능","graph.kind.maintenance":"유지보수","graph.kind.diagnostic":"진단","graph.kind.unknown":"종류 미기록","graph.outputs":"변경 결과","graph.files":"파일 {count}","graph.docs":"문서 {count}","graph.files.one":"파일 {count}","graph.docs.one":"문서 {count}","graph.detail.aria":"선택한 노드 자세히","graph.maker.open":"Maker 기록 열기","graph.maker.unavailable":"실시간 기록이 없어 여기서 열 수 없어요.","graph.motion.pause":"움직임 멈춤","graph.replay":"재생","graph.replay.stop":"재생 멈춤","subflow.aria":"이 서브에이전트 실행의 단계","subflow.calls":"도구 {count}회","subflow.reedits":"다시 수정 {count}회","subflow.checks":"검사 {passed}/{total} 통과","subflow.reported":"보고함","subflow.unobserved":"기록 미관측","subflow.rework":"↻ Main 재작업 요청 {count}회로 구현에 되돌아옴","subflow.prior":"이전 판정","subflow.firstTitle":"첫 발주 제목","subflow.runTitle":"이번 실행 제목","delivery.title":"보낸 입력 {count}","delivery.kind.steer":"지금 지시","delivery.kind.followUp":"완료 후 요청","delivery.stage.sending":"보내는 중","delivery.stage.accepted":"접수됨 \xb7 전달 대기","delivery.stage.delivered":"전달됨 \xb7 대화에 들어감","delivery.stage.failed":"보내지 못함 \xb7 입력창에 되돌림","delivery.stage.unconfirmed":"전달 확인 못 함 \xb7 큐에서 빠짐","delivery.images":"이미지 {count}개","delivery.images.one":"이미지 {count}개","delivery.showOlder":"이전 {count}개 더 보기","delivery.showRecent":"최근 {count}개만 보기","live.nativeVoice":"기본 음성","progress.label":"진행","phase.investigate":"조사","phase.implement":"구현","phase.verify":"검증","phase.report":"보고","phase.current":"지금 단계 {phase}","phase.hint":"도구 호출로 읽은 지금 단계입니다. 고친 뒤 다시 고치면 앞 단계로 돌아갑니다.","progress.todo":"할 일 {completed}/{total} ({percent}%)","eta.label":"예상 시간","eta.elapsed":"경과 {duration}","eta.remaining":"남은 시간 보통 {range} (과거 {samples}건)","eta.percent":"약 {percent}% 추정","eta.overrun":"과거 최장 기록({longest}) 이상 경과","eta.sparseTail":"과거 {samples}건 중 {longerRuns}건만 이보다 오래 걸림","eta.hint":"같은 모델\xb7작업 등급의 과거 첫 시도 가운데 지금 경과보다 오래 걸린 실행들의 남은 시간 분포(가운데 절반)입니다.","eta.byTodo":"할 일 기준 약 {duration} 남음 ({completed}/{total} 단계)","eta.byTodoSoon":"할 일 기준 1분 이내 ({completed}/{total} 단계)","eta.byTodoHint":"todo 완료 비율로만 잰 값입니다. 단계마다 걸리는 시간이 달라 오차가 큽니다.","eta.rework":"재작업 {attempt}차 \xb7 첫 발주부터 {duration}","eta.reworkAttempt":"재작업 {attempt}차","eta.reworkHint":"재작업 시도는 과거 소요 기록이 거의 없어 남은 시간\xb7%를 추정하지 않습니다. 첫 발주부터의 시간에는 시도 사이 Main 검수\xb7대기 시간이 들어 있습니다.","eta.rangeMinutes":"{low}~{high}분","eta.range":"{low}~{high}","duration.seconds":"{seconds}초","duration.minutesSeconds":"{minutes}분 {seconds}초","duration.minutes":"{minutes}분","duration.hours":"{hours}시간","duration.hoursMinutes":"{hours}시간 {minutes}분","duration.underMinute":"1분 미만"},en:{"dispatch.title":"Subagents: {count}","dispatch.tally":"{running} running \xb7 {done} finished \xb7 {accepted} accepted by Main","dispatch.expand":"Show dispatch details","dispatch.collapse":"Hide dispatch details","run.dispatching":"Dispatching","run.pending":"Queued","run.running":"Running","run.completed":"Run finished","run.failed":"Run failed","run.aborted":"Stopped","run.unobserved":"Run state not observed","verdict.accepted":"Accepted by Main","verdict.rework":"Main asked for rework","verdict.held":"Held by Main","verdict.none":"No review recorded","verdict.attempt":"attempt {attempt}","detail.stage":"Current step","detail.stageNone":"Not recorded","detail.model":"Model","detail.modelNone":"Not observed","detail.fallback":"fallback","detail.agentId":"Agent ID","detail.reason":"Review note","detail.source.live":"live","detail.source.record":"session record","detail.openSubagents":"Open subagent details","detail.openProcess":"Open work log","summary.live":"In progress","summary.files":"{count} files changed","summary.files.one":"{count} file changed","summary.checks":"{count} checks","summary.checks.one":"{count} check","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.verdictUnverified":"{count} verdicts not confirmed","summary.verdictUnverified.one":"{count} verdict not confirmed","summary.expand":"Show turn summary","summary.collapse":"Hide turn summary","result.label":"Result","result.open":"View result","result.openNamed":"View result: {name}","result.previewTitle":"Preview of {name}","result.previewFailed":"Couldn't load the preview. Use View result to open it.","result.more":"{count} more","result.previewLoading":"Loading preview","result.kind.html":"Page","result.kind.pdf":"PDF","result.kind.document":"Document","result.kind.image":"Image","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.check.exit":"exit {code}","summary.makers":"{count} Makers","summary.makers.one":"{count} Maker","summary.remaining":"{count} left","summary.heading.remaining":"Still to do","summary.time.unobserved":"time not recorded","summary.time.running":"still running","summary.todo.pending":"pending","summary.todo.in_progress":"in progress","summary.todo.blocked":"blocked","summary.todo.blocker":"blocked by: {blocker}","summary.todo.none":"nothing left","flow.heading":"Work flow","flow.aria":"Work stages of this turn","flow.toggle":"Work flow","flow.stage.investigate":"Investigate","flow.stage.edit":"Edit","flow.stage.check":"Check","flow.stage.review":"Cross review","flow.stage.commit":"Commit & push","flow.stage.ci":"CI","flow.stage.deploy":"Deploy","flow.state.waiting":"waiting","flow.state.running":"in progress","flow.state.done":"done","flow.state.redone":"fixed again","flow.state.passed":"passed","flow.state.unverified":"verdict not confirmed","flow.state.failed":"failed","flow.state.unobserved":"result not observed","flow.state.findings":"{count} findings","flow.state.findings.one":"{count} finding","flow.state.noFindings":"no findings","flow.state.open":"{count} open","flow.state.reviewUnusable":"review unusable","flow.state.skipped":"skipped","flow.state.notNeeded":"not needed","flow.count.passed":"{count} passed","flow.count.unverified":"{count} not confirmed","flow.count.failed":"{count} failed","flow.count.unobserved":"{count} not observed","flow.count.running":"{count} running","flow.earlier":"{count} from earlier attempts","flow.attempt":"Attempt {attempt}","flow.label.typecheck":"Type check","flow.label.lint":"Lint","flow.label.test":"Tests","flow.label.build":"Build","flow.label.verify":"Verification","flow.label.smoke":"Smoke check","flow.label.check":"Check","flow.label.ci":"CI check","flow.label.deploy":"Deploy run","flow.label.review":"Review","flow.label.resolve":"Resolve","flow.label.commit":"Commit & push","flow.details":"Details","flow.commandOmitted":"The command body is omitted from this compacted request summary.","flow.exit":"shell exit code {code}","flow.exit.none":"no exit code recorded","flow.exit.error":"ended with an error","flow.evidence":"Judged from","flow.why.confirmed":"Confirmed","flow.why.missing":"Missing","flow.why.exitZero":"shell exit code 0","flow.why.check":"The exit code of the {label} command itself. Commands chained after it (a pipe, ;, || and so on) can hide its result, so it was not counted as passed.","flow.why.ci":"A CI result returned as an exit code. The command does not return one the way gh run watch --exit-status does, so it was not counted as passed.","flow.why.ciOtherRun":"A record that the run belongs to this commit. The watched run is recorded for another commit, {sha}.","flow.why.ciPublishRun":"The result of this commit's CI run. The run this command waited on is the publish run, so its result was not counted as CI.","flow.why.watched.passed":"The watched run ended as passed","flow.why.watched.failed":"The watched run ended as failed","flow.why.watched.unjudged":"The watched run ended without a verdict ({conclusion})","flow.why.ciUnjudged":"This commit's CI verdict. The watched run ended as {conclusion}, neither passed nor failed, so the command's failure was not counted as a CI failure.","flow.why.deploy":"A record that the deploy finished. The command starts the deploy and returns at once, so its exit code cannot tell whether the deploy finished.","flow.strip.running":"{stage} in progress","flow.loop.badge":"↻ attempt {attempt}","flow.loop.failed":"{stage} failed in attempt {attempt}, so the flow went back to edit","flow.loop.findings":"{stage} raised findings in attempt {attempt}, so the flow went back to edit","flow.state.stale":"Passed before edit","flow.state.staleDone":"Done before edit","flow.count.stale":"{count} passed before edit","flow.why.stale":"Files were edited after this result, so the latest revision has not been checked.","flow.compound.failed":"Combined command failed","flow.why.compoundConfirmed":"{stages} ran as one command, and the whole command failed","flow.why.compoundMissing":"Which stage failed","flow.ci.notNeeded":"Only the private repository changed. After publish run {run}, public {repo} {ref} still points at {sha}, which already passed CI.","flow.ci.nothingToPublish":"The publish run log for commit {sha} says “Public tree already matches; nothing to publish”. The public repository did not change, so there is no new CI run.","summary.stale":"{count} passed before edit","summary.compoundFailed":"{count} combined failed","graph.branch":"{count} Makers dispatched during edit","graph.branch.one":"{count} Maker dispatched during edit","graph.parallel.observed":"Seen running together","graph.join":"Main verdict","graph.parallel.batch":"Same dispatch batch","graph.concurrency.overlapped":"Overlapped","graph.concurrency.unknown":"Overlap unknown","graph.kind.feature":"Feature","graph.kind.maintenance":"Maintenance","graph.kind.diagnostic":"Diagnostic","graph.kind.unknown":"Kind not recorded","graph.outputs":"Changed","graph.files":"{count} files","graph.docs":"{count} docs","graph.files.one":"{count} file","graph.docs.one":"{count} doc","graph.detail.aria":"Selected node details","graph.maker.open":"Open Maker record","graph.maker.unavailable":"No live record, so it can't be opened here.","graph.motion.pause":"Pause motion","graph.replay":"Replay","graph.replay.stop":"Stop replay","subflow.aria":"Stages of this subagent run","subflow.calls":"tool calls: {count}","subflow.reedits":"re-edited {count}\xd7","subflow.checks":"{passed}/{total} checks passed","subflow.reported":"Reported","subflow.unobserved":"Not observed","subflow.rework":"↻ Back to implement \xb7 Main rework requests: {count}","subflow.prior":"Previous verdict","subflow.firstTitle":"First dispatch title","subflow.runTitle":"Current run title","delivery.title":"{count} sent","delivery.kind.steer":"Now","delivery.kind.followUp":"After this run","delivery.stage.sending":"Sending","delivery.stage.accepted":"Received \xb7 waiting to deliver","delivery.stage.delivered":"Delivered \xb7 in the conversation","delivery.stage.failed":"Not sent \xb7 back in the composer","delivery.stage.unconfirmed":"Delivery not confirmed \xb7 left the queue","delivery.images":"{count} images","delivery.images.one":"{count} image","delivery.showOlder":"Show {count} earlier","delivery.showRecent":"Show only the latest {count}","live.nativeVoice":"default voice","progress.label":"Progress","phase.investigate":"Investigate","phase.implement":"Implement","phase.verify":"Verify","phase.report":"Report","phase.current":"current phase {phase}","phase.hint":"Current phase read from tool calls. It goes back when the child edits again after checking.","progress.todo":"todo {completed}/{total} ({percent}%)","eta.label":"Estimate","eta.elapsed":"{duration} elapsed","eta.remaining":"usually {range} left ({samples} past runs)","eta.percent":"about {percent}% (estimate)","eta.overrun":"At or beyond the longest past run ({longest})","eta.sparseTail":"Only {longerRuns} of {samples} past runs took longer","eta.hint":"Middle half of the remaining time among past first attempts of the same model and class that ran longer than this one has so far.","eta.byTodo":"about {duration} left by todo ({completed}/{total} steps)","eta.byTodoSoon":"under a minute left by todo ({completed}/{total} steps)","eta.byTodoHint":"Measured from the todo completion ratio only. Steps take different amounts of time, so this can be far off.","eta.rework":"rework attempt {attempt} \xb7 {duration} since first dispatch","eta.reworkAttempt":"rework attempt {attempt}","eta.reworkHint":"Rework attempts have almost no recorded durations, so no remaining time or % is estimated. Time since the first dispatch includes Main review and waiting between attempts.","eta.rangeMinutes":"{low}–{high} min","eta.range":"{low}–{high}","duration.seconds":"{seconds} s","duration.minutesSeconds":"{minutes} min {seconds} s","duration.minutes":"{minutes} min","duration.hours":"{hours} h","duration.hoursMinutes":"{hours} h {minutes} min","duration.underMinute":"under 1 min"},"zh-CN":{"dispatch.title":"{count} 个子代理","dispatch.tally":"运行中 {running} \xb7 运行完成 {done} \xb7 Main 已接受 {accepted}","dispatch.expand":"展开派发详情","dispatch.collapse":"收起派发详情","run.dispatching":"派发中","run.pending":"等待中","run.running":"运行中","run.completed":"运行完成","run.failed":"运行失败","run.aborted":"已中止","run.unobserved":"未观测到运行状态","verdict.accepted":"Main 已接受","verdict.rework":"Main 要求返工","verdict.held":"Main 暂缓","verdict.none":"未记录审查","verdict.attempt":"第 {attempt} 次","detail.stage":"当前步骤","detail.stageNone":"无记录","detail.model":"模型","detail.modelNone":"未观测","detail.fallback":"备用模型","detail.agentId":"代理 ID","detail.reason":"审查说明","detail.source.live":"实时观测","detail.source.record":"会话记录","detail.openSubagents":"打开子代理详情","detail.openProcess":"打开工作记录","summary.live":"进行中","summary.files":"变更文件 {count}","summary.checks":"检查 {count}","summary.files.one":"变更文件 {count}","summary.checks.one":"检查 {count}","summary.checksFailed":"失败 {count}","summary.unverified":"未确认 {count}","summary.verdictUnverified":"判定未确认 {count}","summary.verdictUnverified.one":"判定未确认 {count}","summary.expand":"展开本轮摘要","summary.collapse":"收起本轮摘要","result.label":"本次结果","result.open":"查看结果","result.openNamed":"查看结果:{name}","result.previewTitle":"{name} 预览","result.previewFailed":"无法加载预览。请点击“查看结果”打开。","result.more":"其他结果 {count}","result.previewLoading":"正在加载预览","result.kind.html":"页面","result.kind.pdf":"PDF","result.kind.document":"文档","result.kind.image":"图片","summary.heading.files":"变更文件","summary.heading.checks":"已运行的检查","summary.check.exit":"exit {code}","summary.makers":"Maker {count}","summary.makers.one":"Maker {count}","summary.remaining":"剩余 {count}","summary.heading.remaining":"剩余事项","summary.time.unobserved":"无时间记录","summary.time.running":"仍在运行","summary.todo.pending":"待办","summary.todo.in_progress":"进行中","summary.todo.blocked":"受阻","summary.todo.blocker":"受阻原因:{blocker}","summary.todo.none":"没有剩余事项","flow.heading":"工作流程","flow.aria":"本轮的工作阶段","flow.toggle":"工作流程","flow.stage.investigate":"调查","flow.stage.edit":"修改","flow.stage.check":"检查","flow.stage.review":"交叉评审","flow.stage.commit":"提交\xb7推送","flow.stage.ci":"CI","flow.stage.deploy":"部署","flow.state.waiting":"等待","flow.state.running":"进行中","flow.state.done":"完成","flow.state.redone":"再次修改","flow.state.passed":"通过","flow.state.unverified":"判定未确认","flow.state.failed":"失败","flow.state.unobserved":"结果未观测","flow.state.findings":"意见 {count} 条","flow.state.findings.one":"意见 {count} 条","flow.state.noFindings":"无意见","flow.state.open":"未解决 {count} 条","flow.state.reviewUnusable":"评审无效","flow.state.skipped":"已跳过","flow.state.notNeeded":"无需","flow.count.passed":"通过 {count}","flow.count.unverified":"判定未确认 {count}","flow.count.failed":"失败 {count}","flow.count.unobserved":"结果未观测 {count}","flow.count.running":"进行中 {count}","flow.earlier":"之前轮次 {count} 条","flow.attempt":"第 {attempt} 轮","flow.label.typecheck":"类型检查","flow.label.lint":"Lint","flow.label.test":"测试","flow.label.build":"构建","flow.label.verify":"验证","flow.label.smoke":"冒烟检查","flow.label.check":"检查","flow.label.ci":"CI 确认","flow.label.deploy":"部署执行","flow.label.review":"评审","flow.label.resolve":"处理意见","flow.label.commit":"提交\xb7推送","flow.details":"详情","flow.commandOmitted":"压缩请求的摘要中省略了命令正文。","flow.exit":"Shell 退出码 {code}","flow.exit.none":"没有退出码记录","flow.exit.error":"以错误结束","flow.evidence":"判定依据","flow.why.confirmed":"已确认","flow.why.missing":"缺少","flow.why.exitZero":"Shell 退出码 0","flow.why.check":"{label} 命令本身的退出码。后面接的命令(管道、;、|| 等)可能掩盖其结果,因此未计为通过。","flow.why.ci":"以退出码返回的 CI 结果。该命令不像 gh run watch --exit-status 那样返回结果,因此未计为通过。","flow.why.ciOtherRun":"这次运行属于此提交的记录。所等待的运行在记录中属于另一个提交 {sha}。","flow.why.ciPublishRun":"此提交 CI 运行的结果。该命令等待的是发布运行,因此未计为 CI 判定。","flow.why.watched.passed":"所等待的运行以通过结束","flow.why.watched.failed":"所等待的运行以失败结束","flow.why.watched.unjudged":"所等待的运行未产生判定即结束({conclusion})","flow.why.ciUnjudged":"此提交的 CI 判定。所等待的运行以 {conclusion} 结束,既非通过也非失败,因此该命令的失败未计为 CI 失败。","flow.why.deploy":"部署已完成的记录。该命令启动部署后立即返回,仅凭 Shell 退出码无法判断部署是否完成。","flow.strip.running":"{stage} 进行中","flow.loop.badge":"↻ 第 {attempt} 轮","flow.loop.failed":"{stage} 第 {attempt} 轮失败,回到修改","flow.loop.findings":"{stage} 第 {attempt} 轮有意见,回到修改","flow.state.stale":"修改前通过","flow.state.staleDone":"修改前完成","flow.count.stale":"修改前通过 {count}","flow.why.stale":"此结果之后又修改了文件,最新版本尚未检查。","flow.compound.failed":"组合命令失败","flow.why.compoundConfirmed":"{stages} 在一条命令中运行,整条命令失败","flow.why.compoundMissing":"具体哪个阶段失败","flow.ci.notNeeded":"仅私有仓库有变更。发布运行 {run} 之后,公开 {repo} 的 {ref} 仍是已通过 CI 的 {sha}。","flow.ci.nothingToPublish":"提交 {sha} 的发布运行日志中记录了“Public tree already matches; nothing to publish”。公开仓库没有变化,因此没有新的 CI 运行。","summary.stale":"修改前通过 {count}","summary.compoundFailed":"组合命令失败 {count}","graph.branch":"修改阶段派发的 Maker {count}","graph.branch.one":"修改阶段派发的 Maker {count}","graph.parallel.observed":"观测到同时运行","graph.join":"Main 判定","graph.parallel.batch":"同一派发批次","graph.concurrency.overlapped":"重叠运行","graph.concurrency.unknown":"是否重叠未知","graph.kind.feature":"功能","graph.kind.maintenance":"维护","graph.kind.diagnostic":"诊断","graph.kind.unknown":"类型未记录","graph.outputs":"变更结果","graph.files":"文件 {count}","graph.docs":"文档 {count}","graph.files.one":"文件 {count}","graph.docs.one":"文档 {count}","graph.detail.aria":"所选节点详情","graph.maker.open":"打开 Maker 记录","graph.maker.unavailable":"没有实时记录,无法在此打开。","graph.motion.pause":"暂停动画","graph.replay":"回放","graph.replay.stop":"停止回放","subflow.aria":"此子代理运行的阶段","subflow.calls":"工具调用 {count} 次","subflow.reedits":"重新修改 {count} 次","subflow.checks":"检查通过 {passed}/{total}","subflow.reported":"已报告","subflow.unobserved":"未观测","subflow.rework":"↻ 因 Main 返工请求 {count} 次回到实现","subflow.prior":"上次判定","subflow.firstTitle":"首次派发标题","subflow.runTitle":"本次运行标题","delivery.title":"已发送 {count}","delivery.kind.steer":"立即指示","delivery.kind.followUp":"完成后请求","delivery.stage.sending":"发送中","delivery.stage.accepted":"已接收 \xb7 等待送达","delivery.stage.delivered":"已送达 \xb7 已进入对话","delivery.stage.failed":"未发送 \xb7 已退回输入框","delivery.stage.unconfirmed":"未能确认送达 \xb7 已离开队列","delivery.images":"图片 {count} 张","delivery.images.one":"图片 {count} 张","delivery.showOlder":"显示更早的 {count} 条","delivery.showRecent":"仅显示最近 {count} 条","live.nativeVoice":"默认语音","progress.label":"进度","phase.investigate":"调查","phase.implement":"实现","phase.verify":"验证","phase.report":"报告","phase.current":"当前阶段 {phase}","phase.hint":"根据工具调用判断的当前阶段。验证后再次修改时会回到前一阶段。","progress.todo":"待办 {completed}/{total}({percent}%)","eta.label":"预计时间","eta.elapsed":"已用 {duration}","eta.remaining":"通常还需 {range}(过去 {samples} 次)","eta.percent":"约 {percent}%(估计)","eta.overrun":"已达到或超过过去最长记录({longest})","eta.sparseTail":"过去 {samples} 次中仅 {longerRuns} 次用时更长","eta.hint":"同模型、同等级的过去首次尝试中,运行时间超过当前已用时间的那些实行的剩余时间分布(中间一半)。","eta.byTodo":"按待办约还需 {duration}({completed}/{total} 步)","eta.byTodoSoon":"按待办 1 分钟内({completed}/{total} 步)","eta.byTodoHint":"仅按 todo 完成比例估算。各步骤耗时不同,误差可能很大。","eta.rework":"返工第 {attempt} 次 \xb7 自首次派发 {duration}","eta.reworkAttempt":"返工第 {attempt} 次","eta.reworkHint":"返工尝试几乎没有耗时记录,因此不估算剩余时间和百分比。自首次派发起的时间包含各次尝试之间 Main 审查和等待的时间。","eta.rangeMinutes":"{low}~{high} 分钟","eta.range":"{low}~{high}","duration.seconds":"{seconds} 秒","duration.minutesSeconds":"{minutes} 分 {seconds} 秒","duration.minutes":"{minutes} 分钟","duration.hours":"{hours} 小时","duration.hoursMinutes":"{hours} 小时 {minutes} 分钟","duration.underMinute":"不到 1 分钟"}};function rg(){let{locale:e}=(0,F.s)();return{st:(0,i.useCallback)((t,n)=>(0,Q.u0)(e,t,rm,n),[e]),locale:e}}function rx({seed:e,size:t,provider:n}){let a=nG(e),[s,o]=(0,i.useState)(null),l=s===a,[c,d]=(0,i.useState)(!1);return l?(0,r.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:nK(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":nK(e),children:(0,r.jsx)("img",{className:"account-avatar",src:a,width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>o(a)})}),c&&(0,r.jsx)(rv,{seed:e,provider:n,onClose:()=>d(!1)})]})}function rv({seed:e,provider:t,onClose:n}){let{t:a}=(0,F.s)(),s=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let o=nK(e);return(0,_.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"account-avatar-dialog","aria-label":o,onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&n()},children:[(0,r.jsx)("img",{className:"account-avatar-full",src:nG(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:nZ(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:a("i18n.close")})]}),document.body)}function ry(e){let t,n=[],r=null,i=0,a=0,s=0,o=0,l=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){l=[],c=[];return}let e=Math.max(l.length,c.length);for(let t=0;t<e;t++){let e=l[t]?{lineNo:l[t].lineNo,text:l[t].text,type:"removed"}:d(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();r.rows.push({type:"line",left:e,right:n})}l=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(s>0||o>0)){if(d.startsWith("--- ")){u(),t=rb(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:rb(d.slice(4)),rows:[]},n.push(r);continue}}let e=d.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),a=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),o=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:d});continue}if(!r)continue;if(d.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:d});continue}let p=d[0],h=d.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:a++,text:h,type:"context"}}),s>0&&s--,o>0&&o--):"-"===p?(l.push({lineNo:i++,text:h}),s>0&&s--):"+"===p?(c.push({lineNo:a++,text:h}),o>0&&o--):""!==d&&(u(),r.rows.push({type:"hunk",text:d}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function rb(e){return e.split(" ")[0].trim()}function rw({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,a="blocked"===e.status;return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":n?"is-abandoned":a?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":a?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,a&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let rk="/icons/catppuccin";function rj({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${rk}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${rk}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function rS({size:e=14,open:t=!1}){return(0,r.jsx)(rj,{name:t?"_folder_open":"_folder",size:e})}function rC({size:e=14}){return(0,r.jsx)(rj,{name:"_file",size:e})}let rN={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 rT(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(rj,{name:i,size:t});let a=rN[n.split(".").pop()??""];return a?(0,r.jsx)(rj,{name:a,size:t}):(0,r.jsx)(rC,{size:t})}function rI({files:e,onOpenFile:t}){let{t:n}=(0,F.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=tN(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[rT(i,12),(0,r.jsx)("span",{children:i})]},e)})})}let rM=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function rR(e){if(!e)return null;let t=/^\s*TASK_GUARD\s*:\s*$/im.exec(e),n=e;if(t){let r=t.index+t[0].length;"\r"===e[r]&&(r+=1),"\n"===e[r]&&(r+=1);let i=r;for(;r<e.length;){let t=e.indexOf("\n",r),n=-1===t?e.length:t,a=n>r&&"\r"===e[n-1]?n-1:n;if(!rM.test(e.slice(r,a)))break;i=a,r=-1===t?e.length:t+1}let a=t[0].length-t[0].trimStart().length;n=`${e.slice(0,t.index+a)}${e.slice(i)}`}let r=[...n.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===r.length&&r[0]&&r[0]===r[0].trim()&&/[가-힣]/u.test(r[0])?r[0]:null}function rE(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(rR).find(e=>null!==e)??(n?.taskTitle?.trim()||null),i=t?.progress?.lastIntent?.trim()||"",a=t?.progress?.currentTool?.trim()||"";return{title:r??"담당 업무 미확인",stage:i&&a?`${i} \xb7 ${a}`:i||(a?`${a} 실행 중`:null),explicitTitle:null!==r}}function rL(e){let t=e.live?.progress,n="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,i="string"==typeof t?.resolvedThinkingLevel?t.resolvedThinkingLevel.trim():"",a="string"==typeof r?.thinkingLevel?r.thinkingLevel.trim():"";if(n){let e=n.split("/").pop()||n;return{model:n,modelShort:i&&e.endsWith(`:${i}`)?e.slice(0,-(i.length+1)):e,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:i||a||null}}let s="string"==typeof r?.model?r.model.trim():"";return{model:s||null,modelShort:s?s.split("/").pop()||s:null,modelIsFallback:!!s&&r?.modelIsFallback===!0,effort:a||null}}class r$ extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function rP(e){try{return await e.json()}catch{throw new r$("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function rA(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 rF(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 rz(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 rW(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 rD(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let n=async(t,n,r)=>{let i;try{i=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new r$(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let a=await rP(i);if(!i.ok)throw new r$("http",function(e,t){if(e&&"object"==typeof e&&"error"in e){let t=e.error;if("string"==typeof t&&t)return t}return t}(a,`HTTP ${i.status}`),i.status);return{response:i,body:a}};return{async getLiveSnapshots(e,t){let{body:r}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!r||"object"!=typeof r)throw new r$("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new r$("http",r.error);if(!0!==r.running)return{runtime:"detached",subagents:[]};let i=r.state?.subagents;if(void 0!==i&&(!Array.isArray(i)||!i.every(rz)))throw new r$("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:i??[]}},async getLiveTranscript(e,t,r,i){let{body:a}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:r}),signal:i},"live-unreachable");if(!a||"object"!=typeof a)throw new r$("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof a.error&&a.error)throw new r$("http",a.error);if(!0!==a.success||!a.data||"object"!=typeof a.data)throw new r$("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let s=a.data;if(!Array.isArray(s.entries)||!s.entries.every(rW)||"number"!=typeof s.fromByte||"number"!=typeof s.nextByte||"boolean"!=typeof s.reset)throw new r$("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:s.fromByte,nextByte:s.nextByte,reset:s.reset,entries:s.entries}},async getArchive(e,r){let i=`${t}/archive?session=${encodeURIComponent(e)}`,{body:a}=await n(i,{method:"GET",signal:r},"sidecar-unreachable");if(!a||"object"!=typeof a||"string"!=typeof a.sessionId||"string"!=typeof a.dir||"boolean"!=typeof a.found||!Array.isArray(a.subagents)||!a.subagents.every(rA))throw new r$("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:a.sessionId,dir:a.dir,found:a.found,subagents:a.subagents,...!0===a.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,r,i=400,a){let s=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(r)}&limit=${encodeURIComponent(String(i))}`,{body:o}=await n(s,{method:"GET",signal:a},"sidecar-unreachable");if(!o||"object"!=typeof o||"string"!=typeof o.sessionId||"string"!=typeof o.name||"number"!=typeof o.bytes||"boolean"!=typeof o.truncated||!Array.isArray(o.entries)||!o.entries.every(rF))throw new r$("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:o.sessionId,name:o.name,bytes:o.bytes,truncated:o.truncated,entries:o.entries}}}}let rO=["feature","maintenance","diagnostic"],rH=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function rU(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=rH.exec(t[e]);if(!n)break;if("WORK_CLASS"!==n[1])continue;let r=n[2].toLowerCase();return rO.includes(r)?r:null}return null}let r_={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function rB(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function rq(e){return"string"==typeof e&&e.trim()?e:null}function rV(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function rK(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 rG(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function rJ(e,t){if(t?.isError)return null;let n=rB(e.input.tasks),r=rB(t?.details?.progress),i=Math.max(n.length,r.length),a=[];for(let s=0;s<i;s++){let i=r.find(e=>e.index===s)??r[s],o=n[s],l=rq(i?.id)??rq(o?.name);l&&a.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:l,agent:rq(i?.agent)??rq(o?.agent),task:rq(i?.task)??rq(o?.task)??"",workClass:rU(o?.task)??rU(i?.task),spawned:!!t})}return a}let rZ=/<task-result\b([^>]*)>/g,rY=/(\w+)="([^"]*)"/g;function rX(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 rQ(e,t,n){var r;let i,a,s,o,l=rX(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=rE(c),u=n.runs.get(e.key),p=null;l&&"unknown"!==l.status?(i=l.status,p="live"):u&&"unknown"!==u.status?(i=u.status,p="record"):i=e.spawned?"unobserved":"dispatching";let h=n.verdicts.get(e.key),f=h&&h.length>0?h[h.length-1]:null,m=f?.at??null,g=null===m?null:(r=e.key,a=n.runStartedAt.get(r)??null,s=l?.progress?.durationMs,o=l&&("pending"===l.status||"running"===l.status)&&"number"==typeof s&&l.lastUpdate>0?l.lastUpdate-s:null,null===a?o:null===o?a:Math.max(a,o)),x=null!==m&&null!==g&&g>m;return{member:e,title:d.title,explicitTitle:d.explicitTitle,stage:l?d.stage:null,model:l?rL(c):null,run:i,runSource:p,verdict:x?null:f,priorVerdict:x?f:null,runTitle:x?rR(l?.progress?.task):null,observedParallelWith:n.parallelWith.get(e.key)}}function r0(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function r1(e,t){let n=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),r=new Map,i=[];for(let e of n){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?i.push(t):r.set(e.attempt,t)}return[...i,...[...r.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}function r2(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function r8(e,t,n){let r=-1;n.forEach((e,t)=>{"user"===e.role&&(r=t)});let i=n.slice(0,r+1).flatMap(r2),a=n.slice(r+1).flatMap(r2),s=t.findIndex(e=>"user"===e.role),o=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===o?{continuing:null,atCompaction:[...i,...a]}:{continuing:{position:o,calls:a},atCompaction:i}}let r4={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function r5(e){return e.trim()}function r6(e){return r5(e.text)||(e.images>0?"[Image]":"")}function r3(e){let t=e.filter(e=>!r4[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 r7(e,t){switch(t.type){case"submit":return r3([...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 r3(e.map(e=>e.id===t.id&&r4[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,i=(e,t)=>{let n=`${e}\u0000${r5(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)i("steer",e);for(let e of n)i("followUp",e);let a=!1,s=e.map(e=>{if(!r4[e.stage])return e;let t=`${e.kind}\u0000${r6(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-1),e.inQueue&&"accepted"===e.stage)?e:(a=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(a=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return a?s:e}(e,t.steering,t.followUp);case"user-message":{let n=r5(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(r4[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&r5(e.text)===n&&e.images===t.images);if(!r)return e;return r3(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>r4[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=r5(t.text),i=e.find(e=>n(e)&&e.kind===t.kind&&(r5(e.text)===r||r6(e)===r));return i?e.filter(e=>e!==i):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}function r9(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 ie(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}let it=["investigate","edit","check","review","commit","ci","deploy"];function ir(e,t){let n="",r=t;for(;r<e.length&&'"'!==e[r];){let t=e[r];if("\\"===t&&r+1<e.length){let i=e[r+1];"\n"!==i&&(n+='$`"\\'.includes(i)?i:t+i),r+=2}else if("$"===t&&"("===e[r+1]){let t=ii(e,r+1);n+=e.slice(r,t),r=t}else if("`"===t){let t=ia(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 ii(e,t){let n=e[t],r="{"===n?"}":")",i=0,a=t;for(;a<e.length;){let t=e[a];if("\\"===t)a+=2;else if("'"===t){let t=e.indexOf("'",a+1);a=t<0?e.length:t+1}else if('"'===t)a=ir(e,a+1).end;else if("`"===t)a=ia(e,a+1);else{if(t===n)i+=1;else if(t===r&&0==--i)return a+1;a+=1}}return e.length}function ia(e,t){let n=t;for(;n<e.length&&"`"!==e[n];)n+="\\"===e[n]?2:1;return Math.min(n+1,e.length)}function is(e){let t=[],n=[],r={pipelines:[],operators:[],background:!1},i={commands:[],negated:!1},a=[],s=()=>{let t=a.map(e=>e.value).filter(e=>"{"!==e&&"}"!==e);if(0===i.commands.length&&"!"===t[0]&&(i.negated=!0,t.shift()),t.length>0){let r={words:t,text:e.slice(a[0].start,a[a.length-1].end)};i.commands.push(r),n.push(r)}a=[]},o=()=>{s(),i.commands.length>0&&r.pipelines.push(i),i={commands:[],negated:!1}},l=e=>{o(),r.pipelines.length>0&&t.push({...r,background:e}),r={pipelines:[],operators:[],background:!1}};for(let t of function(e){let t=[],n=[],r="",i=-1,a=e=>{i<0||(t.push({value:r,start:i,end:e}),r="",i=-1)},s=0;for(;s<e.length;){let o=e[s];if("\\"===o)"\n"!==e[s+1]&&(i<0&&(i=s),r+=e[s+1]??""),s+=2;else if("'"===o){i<0&&(i=s);let t=e.indexOf("'",s+1),n=t<0?e.length:t;r+=e.slice(s+1,n),s=n+1}else if('"'===o){i<0&&(i=s);let t=ir(e,s+1);r+=t.text,s=t.end}else if("$"===o&&("("===e[s+1]||"{"===e[s+1])){i<0&&(i=s);let t=ii(e,s+1);r+=e.slice(s,t),s=t}else if("`"===o){i<0&&(i=s);let t=ia(e,s+1);r+=e.slice(s,t),s=t}else if("#"===o&&i<0){let t=e.indexOf("\n",s);s=t<0?e.length:t}else if(" "===o||" "===o||"\r"===o)a(s),s+=1;else if("\n"===o){a(s);let r=t[t.length-1];for(let{delimiter:i,stripTabs:a}of("&&"!==r&&"||"!==r&&"|"!==r&&t.push(";"),s+=1,n.splice(0)))for(;s<e.length;){let t=e.indexOf("\n",s),n=t<0?e.length:t,r=e.slice(s,n);if(s=n+1,(a?r.replace(/^\t+/,""):r)===i)break}}else if("<"===o&&"<"===e[s+1]&&"<"!==e[s+2]){a(s);let t=s+2,r="-"===e[t];for(r&&(t+=1);" "===e[t]||" "===e[t];)t+=1;let i="";for(;t<e.length&&!/[\s;&|<>()]/.test(e[t]);){let n=e[t];if("'"===n||'"'===n){let r=e.indexOf(n,t+1),a=r<0?e.length:r;i+=e.slice(t+1,a),t=a+1}else i+="\\"===n?e[t+1]??"":n,t+="\\"===n?2:1}i&&n.push({delimiter:i,stripTabs:r}),s=t}else";"===o?(a(s),t.push(";"),s+=";"===e[s+1]?2:1):"&"===o?"&"===e[s+1]?(a(s),t.push("&&"),s+=2):(">"===e[s+1]||/[<>]$/.test(r)?(i<0&&(i=s),r+=o):(a(s),t.push("&")),s+=1):"|"===o?"|"===e[s+1]?(a(s),t.push("||"),s+=2):r.endsWith(">")?(r+=o,s+=1):(a(s),t.push("|"),s+="&"===e[s+1]?2:1):("("===o||")"===o?a(s):(i<0&&(i=s),r+=o),s+=1)}return a(e.length),t}(e))"string"!=typeof t?a.push(t):"|"===t?s():"&&"===t||"||"===t?(o(),r.operators.push(t)):l("&"===t);return l(!1),{lists:t,commands:n,uncertain:/[(){}!`]/.test(e)}}function io(e){return e.slice(e.lastIndexOf("/")+1)}let il={bash:!0,sh:!0,zsh:!0,dash:!0},ic={sudo:!0,env:!0,command:!0,exec:!0,nice:!0,nohup:!0,time:!0,timeout:!0,setsid:!0,"systemd-run":!0},id={"-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},iu={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},ip={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function ih(e){let t=ix(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(il,io(e[t]))||im(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 im(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 ig={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function ix(e){let t=!1,n="";for(let r=0;r<e.length;r+=1){let i=e[r];if(!(/^[A-Za-z_]\w*=/.test(i)||!t&&Object.hasOwn(ip,i))){if(t&&(i.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(i))){if(Object.hasOwn(ig,n)&&ig[n].test(i))return -1;"command"!==n&&Object.hasOwn(id,i)&&(r+=1);continue}if(!Object.hasOwn(ic,io(i)))return r;t=!0,n=io(i)}}return -1}let iv=/(?:^|\/)wsl\/update\.sh$/;function iy(e,t=0){let n=ih(e);if(null!==n)return t<3&&is(n).commands.some(e=>iy(e.words,t+1));let r=ix(e);if(r<0)return!1;if(iv.test(e[r]))return!0;if(!Object.hasOwn(il,io(e[r]))||im(e,r))return!1;let i=e.slice(r+1).find(e=>!e.startsWith("-"));return void 0!==i&&iv.test(i)}function ib(e){let t=ix(e),n=t<0?e:e.slice(0,t),r=n.map(io);return r.includes("systemd-run")?!n.some(e=>Object.hasOwn(iu,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 iw(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function ik(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 ij={tail:!0,head:!0,cat:!0,tee:!0},iS=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,iC={bun:!0,bunx:!0,npm:!0,npx:!0,pnpm:!0,yarn:!0,node:!0,python:!0,python3:!0,deno:!0},iN={"--help":!0,"-h":!0,"--version":!0},iT=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 iI(e){let t=ix(e);if(t<0)return!1;let n=io(e[t]);if("test"===n||"["===n||e.slice(t+1).some(e=>Object.hasOwn(iN,e)))return!1;if(iS.test(n))return!0;if(!Object.hasOwn(iC,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(iT,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&&iS.test(r)}let iM={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},iR={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function iE(e){let t=ix(e);if(t<0||"git"!==io(e[t]))return null;for(let n=t+1;n<e.length;n+=1)if(Object.hasOwn(iM,e[n]))n+=1;else if(!e[n].startsWith("-"))return{name:e[n],at:n};return null}function iL(e,t=0,n){let r=ih(e);if(null!==r)return t<3&&is(r).commands.some(e=>iL(e.words,t+1,n));let i=iE(e);if(!i||"commit"!==i.name&&"push"!==i.name||void 0!==n&&i.name!==n)return!1;let a=iR[i.name];return!e.slice(i.at+1).some(e=>Object.hasOwn(a,e)||"push"===i.name&&/[nd]/.test(function(e){if(!/^-[a-zA-Z0-9]/.test(e))return"";let t="";for(let n of e.slice(1)){if("o".includes(n)||!/[a-zA-Z0-9]/.test(n))break;t+=n}return t}(e)))}function i$(e){return ik(e)||null!==iE(e)}let iP={check:({words:e})=>iI(e),commit:({words:e})=>iL(e),ci:({words:e})=>{let t=ix(e);return t>=0&&"gh"===io(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>iy(e.words)},iA={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 iF(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 iz={"$?":!1,"${PIPESTATUS[0]}":!0};function iW(e,t){let n=iJ(t);if("notRun"===n)return[];let r=n?void 0:t,i=is(e),a=[];if(i.commands.some(({words:e})=>(function e(t,n=0){let r=ih(t);return null!==r?n<3&&is(r).commands.some(t=>e(t.words,n+1)):iI(t)})(e))&&a.push("check"),i.commands.some(({words:e})=>iL(e))&&a.push("commit"),i.commands.some(({words:e})=>(function e(t,n=0){let r=ih(t);if(null!==r)return n<3&&is(r).commands.some(t=>e(t.words,n+1));let i=ix(t);return i>=0&&"gh"===io(t[i])&&"run"===t[i+1]&&["watch","view","list"].includes(t[i+2])})(e))&&a.push("ci"),i.commands.some(iP.deploy)&&a.push("deploy"),0===a.length)return[];let s=r?nS(r):null,o=null===s?!!r?.isError:0!==s,l=a.length>1?{stages:a,failed:o}:void 0,c=r?an(r):"";return a.map(e=>{var t;let n,a,d,u="commit"===e?i$:ik,p=function e(t,n,r=ik,i=0){let{lists:a}=t,s=[],o=t.uncertain,l=!1;return a.forEach((t,c)=>{for(let d of(t.pipelines.some(e=>e.commands.some(({words:e})=>e.some(e=>e.includes("pipefail"))))&&(l=!1),t.pipelines)){let u=!1;for(let p of d.commands){let h=i<3?ih(p.words):null,f=null===h?null:e(is(h),n,r,i+1);if(f&&f.decisive.length>0)s.push(...f.decisive);else if(n(p))s.push(p);else{let e=ix(p.words);u&&l&&e>=0&&Object.hasOwn(ij,io(p.words[e]))||r(p.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let n=iw(e[t])?.words;return n?.[0]==="exit"&&(1===n.length||2===n.length&&"$?"===n[1])}(a,c)||(o=!0);continue}u=!0,(f?.reach==="masked"||d.negated||d.commands.length>1&&!l||t.operators.includes("||")||t.background||ib(p.words)||!function(e,t){if(t===e.length-1)return!0;let n=e[e.length-1],r=iw(n)?.words;return!!r&&"exit"===r[0]&&!n.background&&t===e.length-2&&(1===r.length||2===r.length&&"$?"===r[1])}(a,c))&&(o=!0)}}let d=iw(t)?.words;!t.background&&d?.[0]==="set"&&3===d.length&&"pipefail"===d[2]&&(/^-[a-zA-Z]*o$/.test(d[1])?l=!0:/^\+[a-zA-Z]*o$/.test(d[1])&&(l=!1))}),{reach:0===s.length?"absent":o?"masked":"carried",decisive:s}}(i,iP[e],u),h="check"===e&&p.decisive.some(({words:e})=>e.includes("--if-present")),f=r?(t=iP[e],n=new Map,a=i.lists.map(e=>(function(e){let t=e&&!e.background?iw(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(iz)){let n=r.indexOf(e);if(n<0||r.indexOf(e,n+1)>=0)continue;let i=r.slice(0,n),a=r.slice(n+e.length);if(/[$`\\]/.test(i+a)||!/[^\s\d]/.test(i))break;return{prefix:i,suffix:a,first:t}}return null})(e)),d=c.split("\n").map(e=>e.trimEnd()),i.lists.forEach((e,r)=>{let i=a[r+1];if(!i||e.background||e.operators.includes("||"))return;let s=e.pipelines[e.pipelines.length-1],o=e.pipelines.slice(0,-1);if(s.negated||o.some(e=>e.negated||1!==e.commands.length||!u(e.commands[0].words)))return;let l=i.first||1===s.commands.length?s.commands[0]:void 0;if(!l||!t(l)||ib(l.words)||/[(){}!`]/.test(l.text))return;let c=a.filter(e=>e?.prefix===i.prefix&&e.suffix===i.suffix),p=RegExp(`^${i.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(-?\\d+)${i.suffix.trimEnd().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`),h=d.flatMap(e=>{let t=p.exec(e);return t?[{code:Number(t[1]),line:e}]:[]});if(h.length!==c.length)return;let f=a.slice(0,r+2).filter(e=>c.includes(e)).length-1;n.set(l,h[f])}),n):new Map,m=p.decisive.flatMap(e=>f.get(e)??[]),g=m.length>0&&m.length===p.decisive.length?m.find(({code:e})=>0!==e)??m[0]:null;return{stage:e,state:g?0!==g.code?"failed":h?"unverified":"passed":o?l?"unverified":"failed":null===s?"unobserved":"carried"!==p.reach||h?"unverified":"passed",exitCode:s,labels:"check"===e?function(e){let t=[];for(let{words:n}of e){let e=ix(n);n.forEach((n,r)=>{if(r!==e||"test"!==n)for(let e of n.replace(/^-+/,"").toLowerCase().split(":")){let n=Object.hasOwn(iA,e)?iA[e]:void 0;n&&!t.includes(n)&&t.push(n)}})}return t}(p.decisive):[],...l?{compound:l}:{},...g?{evidence:g.line}:{}}})}function iD(e,t){let n=iF(e),r=null===n?void 0:iW(n,t).find(e=>"check"===e.stage);return null!==n&&r?{toolCallId:e.toolCallId,command:n,state:r.state,exitCode:r.exitCode,labels:r.labels,...r.compound?{compound:r.compound}:{}}:null}let iO=/\.(?:md|mdx|markdown|txt)$/i,iH=/^docs?$/i,iU={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},i_={multiedit:!0,notebookedit:!0,draft:!0},iB={rename:!0,rename_file:!0},iq={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function iV(e){return e.split("\n")[0].trim()||void 0}let iK=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,iG=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function iJ(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 iZ=/\btool\.git_finalize\s*\(/,iY=/\bCommitted and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,iX=/\bgit_finalize failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,iQ=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/,i0=/^bg_\d+$/;function i1(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 i2(e){return"passed"===e||"failed"===e||"done"===e}function i8(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 i4(e){let t=new Map;for(let n of e){if("check"!==n.stage)continue;let e=n.commandKey??n.command,r=t.get(e);(r?.outcome!=="failed"||i2(n.outcome))&&t.set(e,n)}return[...t.values()]}function i5(e){return"compound"in e&&e.compound?.failed===!0}let i6={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function i3(e){return"stale"!==e&&(i2(e)||"running"===e)}function i7(e){if("ci"!==e.stage)return null;let t=is(e.command).commands.flatMap(({words:e})=>ai(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?al(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let i9={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},ae={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},at=/^[0-9a-f]{40}$/i;function an(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 ar(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 ai(e,t=0){let n=ih(e);if(null!==n)return t<3?is(n).commands.flatMap(e=>ai(e.words,t+1)):[];let r=ix(e);return r>=0&&"gh"===io(e[r])?[e.slice(r+1)]:[]}function aa(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 as={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function ao(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(as,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function al(e){let t=ao(e);return null!==t&&/^\d+$/.test(t)?t:null}let ac=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function ad(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==nS(t))return[];let n=is(e).commands.flatMap(({words:e})=>ai(e)).filter(e=>"run"===e[0]&&("list"===e[1]||"view"===e[1]));if(0===n.length)return[];let r=1===n.length?n[0]:null,i=r?.[1]==="list"?aa(r,["-c","--commit"])?.toLowerCase():void 0,a=i&&/^[0-9a-f]{7,40}$/.test(i)?i:null,s=an(t);return a||s.includes("headSha")?ar(s).flatMap(e=>{let t="string"==typeof e.headSha?e.headSha.toLowerCase():a;if(null===t)return[];let n="string"==typeof e.url?ac.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):r?.[1]==="view"?al(r):null,repo:(n??(r?aa(r,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:r?aa(r,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:r?aa(r,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let au=/\b\d{9,12}\b/g,ap=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function ah(e,t){if(e?.type!=="toolCall")return[];let n=iF(e);return null===n?[]:ad(n,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(ae,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let af="Public tree already matches; nothing to publish";function am(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function ag(e){let t="run"===e[0]&&"list"===e[1]?aa(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(i9,t)}function ax(e,t){let n=new Map,r=[];for(let{words:i}of is(e).commands){let e=i.map(e=>/^([A-Za-z_]\w*)=([\s\S]*)$/.exec(e));if(i.length>0&&e.every(e=>null!==e)){for(let t of e){if(!t)continue;let e=/^\$\(([\s\S]*)\)$/.exec(t[2])?.[1],r=void 0===e?[]:is(e).commands.flatMap(e=>ai(e.words));n.set(t[1],1===r.length&&ag(r[0]))}continue}for(let e of ai(i)){if(ag(e)){r.push({args:e,publish:!0});continue}let i="run"===e[0]&&("watch"===e[1]||"view"===e[1])?ao(e):null,a=am(i),s=null!==a?!0===n.get(a):null!==i&&/^\d+$/.test(i)&&t(i);r.push({args:e,publish:s})}}return r}function av(e,t){let n=ax(e,t);return n.length>0&&n.every(({publish:e})=>e)}function ay(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 ab(e,t,n){if(ay(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(ae,e.workflow)&&[...n.publishRuns.values()].some(n=>n.order>t.order&&null!==n.sha&&ay(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 aw={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},ak=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,aj=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) (ROLLED_BACK|ROLLBACK_FAILED|FAIL)\b/,aS=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) START old=\S* target=([0-9a-f]{7,40})\b/;function aC(e,t,n=!1,r=[],i,a=[]){let s,o,l=[],c=[],d=1,u=new Map,p=-1,h=-1,f=new Map,m={publishRuns:new Map,watched:[],heads:[],ciHeads:[],nothingToPublish:[],runs:[]},g=Array.isArray(e)?e:[],x=t instanceof Map?t:new Map,v=function(e,t,n=[]){let r=new Map,i=new Map,a=new Map;for(let e of n)null!==e.after&&a.set(e.after,[...a.get(e.after)??[],e]);let s=(e,t)=>{for(let n of e){let e=i.get(n.jobId);e&&(i.delete(n.jobId),r.set(e.toolCallId,{...e.result,isError:!1,content:[{type:"text",text:n.text}],details:{...null===n.exitCode?{}:{exitCode:n.exitCode},backgroundJob:{jobId:n.jobId,after:t}}}))}};for(let n of Array.isArray(e)?e:[]){if(!n||"toolCall"!==n.type)continue;let e=t.get(n.toolCallId);if(e){let t="bash"===n.toolName||"eval"===n.toolName?function(e){let t=e.details,n=t&&"object"==typeof t&&"async"in t?t.async:null;if(n&&"object"==typeof n&&"jobId"in n&&"string"==typeof n.jobId&&i0.test(n.jobId))return n.jobId;let r=an(e).trimStart();return r.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(r)?.[1]??null:null}(e):null;t?i.set(t,{toolCallId:n.toolCallId,result:e}):r.set(n.toolCallId,e),"wait"===n.toolName&&s(function(e){let t=e.details,n=t&&"object"==typeof t&&"jobs"in t?t.jobs:null,r=(Array.isArray(n)?n:[]).flatMap(e=>{if(!e||"object"!=typeof e||!("id"in e)||!("status"in e)||!("resultText"in e)||"string"!=typeof e.id||!i0.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[{...i1(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(r.length>0)return r;let i=an(e),a=[...i.matchAll(/^### (bg_\d+) \[\w+\] — (?:completed|failed)$/gm)];return a.map((e,t)=>{let n=(e.index??0)+e[0].length,r=i.slice(n,t+1<a.length?a[t+1].index:i.length),s=r.indexOf("\n```\n"),o=r.lastIndexOf("\n```");return i1(e[1],s>=0&&o>s?r.slice(s+5,o):"")})}(e),n.toolCallId);let a="read"===n.toolName?function(e,t){let n=e.input.path,r="string"==typeof n?/^proc:\/\/(bg_\d+)$/.exec(n)?.[1]:void 0;if(!r)return null;let[i,...a]=an(t).split("\n");return RegExp(`^1\\|${r} \\[\\w+\\] — (?:completed|failed)\\b`).test(i)?i1(r,a.map(e=>e.replace(/^\d+\|/,"")).join("\n")):null}(n,e):null;a&&s([a],n.toolCallId)}for(let e of a.get(n.toolCallId)??[])s(function(e){let t=e.replace(/^\s*<system-notice>\s*\n?/,"").replace(/\s*<\/system-notice>\s*$/,""),n=/^Background job (bg_\d+) has (?:completed|failed)\b[^\n]*(?:\n|$)/.exec(t);if(n)return[i1(n[1],t.slice(n[0].length))];let r=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return r.flatMap((e,n)=>{if(!i0.test(e[1]))return[];let i=(e.index??0)+e[0].length;return[i1(e[1],t.slice(i,n+1<r.length?r[n+1].index:t.length).replace(/^\n/,""))]})}(e.text),n.toolCallId)}return r}(g,x,Array.isArray(a)?a:[]),y=[];g.forEach((e,t)=>{let r;if(!e||"toolCall"!==e.type)return;let a=v.get(e.toolCallId);for(let s of(!function(e,t,n,r){let i=iF(t);if(null===i||!i.includes("gh"))return;let a=(t,n)=>{let i=e.publishRuns.get(t);i&&(null===n.sha||null!==i.sha)||e.publishRuns.set(t,{...n,order:i?.order??r})};for(let t of ad(i,n))e.runs.push({...t,order:r}),t.id&&t.sha&&t.workflow&&Object.hasOwn(i9,t.workflow)&&a(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==nS(t))return[];let n=is(e).commands.flatMap(({words:e})=>ai(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==n.length)return[];let r=aa(n[0],["-w","--workflow"])?.toLowerCase(),i=void 0!==r&&Object.hasOwn(i9,r),a=aa(n[0],["-R","--repo"])?.toLowerCase()??null;return an(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let n=t.toLowerCase();if(!i&&!Object.keys(i9).some(e=>n.includes(e)))return[];let r=t.match(au)??[];return 1===r.length?[{id:r[0],sha:ap.exec(n)?.[0]??null,repo:a}]:[]})}(i,n))a(e.id,e);for(let i of ah(t,n))e.ciHeads.push({...i,order:r});for(let t of function(e,t){let n=is(e),r=n.commands.flatMap(({words:e})=>ai(e)).filter(e=>"api"===e[0]),i=!n.uncertain&&1===n.commands.length&&1===r.length,a=t&&!t.isError&&0===nS(t)?an(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=aa(e,["-q","--jq"]),o=null;if(i&&".sha"===r)o=a.split("\n")[0]?.trim();else if(i&&null===r&&a.startsWith("{"))try{o=JSON.parse(a.slice(0,a.lastIndexOf("}")+1)).sha}catch{}let l="string"==typeof o&&at.test(o)?o.toLowerCase():null;s.push({repo:n[1].toLowerCase(),ref:n[2],sha:l})}return s}(i,n))e.heads.push({...t,order:r});let s=function(e,t){if(!t||t.isError||0!==nS(t)||2!==e.split(af).length)return null;let{lists:n}=is(e),r=0;for(;r<n.length&&["set","cd"].includes(iw(n[r])?.words[0]??"");)r+=1;let i=r<n.length-1?function(e){let t=iw(e)?.words,n=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!n)return null;let r=is(n[2]),i=1===r.lists.length?iw(r.lists[0]):null,a=i?.words[0]==="gh"?ai(i.words):[];if(1!==a.length||"run"!==a[0][0]||"list"!==a[0][1])return null;let s=aa(a[0],["-c","--commit"]),o=aa(a[0],["-w","--workflow"])?.toLowerCase();return s&&at.test(s)&&o&&Object.hasOwn(i9,o)?{name:n[1],sha:s.toLowerCase()}:null}(n[r]):null;return i&&function(e,t){if(e.background||1!==e.pipelines.length)return!1;let[n]=e.pipelines,[r,i,...a]=n.commands;if(n.negated||!i||a.length>1||"gh"!==r.words[0])return!1;let s=ai(r.words);if(1!==s.length||"run"!==s[0][0]||"view"!==s[0][1]||!s[0].includes("--log"))return!1;let o=ao(s[0]);if(am(o)!==t)return!1;for(let e=2;e<s[0].length;e+=1){let t=s[0][e];if("-R"===t||"--repo"===t)e+=1;else if(t!==o&&"--log"!==t&&!t.startsWith("--repo=")&&!/^2>/.test(t))return!1}let[l,...c]=i.words,d=c.filter(e=>e.startsWith("-")),u=c.filter(e=>!e.startsWith("-"));if("grep"!==l||!d.every(e=>/^-[oFas]+$/.test(e))||!d.some(e=>e.includes("o"))||1!==u.length||u[0]!==af)return!1;let[p]=a;return!p||("head"===p.words[0]||"tail"===p.words[0])&&p.words.slice(1).every(e=>/^(?:-n?\d*|\d+)$/.test(e))}(n[n.length-1],i.name)&&n.slice(r+1,-1).flatMap(e=>e.pipelines.flatMap(({commands:e})=>e)).every(({words:e})=>(function(e,t){let[n,...r]=e;if("["===n||"[["===n||"test"===n||"exit"===n||"true"===n||":"===n||"sleep"===n)return!0;if("echo"===n||"printf"===n)return r.every(e=>!/`|\$\(/.test(e)&&!/public|tree|already|matches|nothing|publish/i.test(e)&&[...e.matchAll(/\$\{?([A-Za-z_]\w*|[?])/g)].every(e=>e[1]===t||"?"===e[1]));if("gh"!==n)return!1;let i=ai(e);return 1===i.length&&"run"===i[0][0]&&"watch"===i[0][1]&&am(ao(i[0]))===t})(e,i.name))&&an(t).split("\n").some(e=>e.trim()===af)?i.sha:null}(i,n);s&&e.nothingToPublish.push({sha:s,order:r})}(m,e,a,t),Array.isArray(r=function(e,t,n,r){if(!e.input||"object"!=typeof e.input||Array.isArray(e.input)||"string"!=typeof e.toolName)return null;let i=iJ(t);if("notRun"===i)return null;let a={toolCallId:e.toolCallId,attempt:0},s=n&&!i?"running":"unobserved",o=iF(e);if(null!==o){var l;let e,n,r=(l=t,(n=(e=l?.details)&&"object"==typeof e&&"backgroundJob"in e?e.backgroundJob:null)&&"object"==typeof n&&"jobId"in n&&"after"in n&&"string"==typeof n.jobId&&"string"==typeof n.after?{jobId:n.jobId,after:n.after}:null);return iW(o,t).map(e=>{if("commit"===e.stage){var n;let r,i,l=t?"unobserved"===e.state&&function(e,t){if(t.isError)return!1;let{commands:n}=is(e),r=an(t),i=e=>n.some(({words:t})=>iL(t,0,e));return(!i("commit")||iK.test(r))&&(!i("push")||iG.test(r))}(o,t)?"done":iq[e.state]:s;return{...a,stage:"commit",..."done"===l?(r=(n=t)?an(n):"",(i=iK.exec(r))?{commit:i[1],title:i[2].trim()}:{commit:iG.exec(r)?.[1]??null}):{commit:null},docsOnly:!1,outcome:l}}let i=e.evidence??(r&&null!==e.exitCode?`Command exited with code ${e.exitCode}`:void 0),l=i&&r?`${r.jobId} \xb7 ${i}`:i,c="ci"===e.stage&&"failed"===e.state&&t?function(e,t){let n=is(e).commands.flatMap(({words:e})=>ai(e)),r=n.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),i=r?ao(r):null;if(null===i||!n.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&ao(e)===i))return null;let a=ar(an(t)).filter(e=>"completed"===e.status&&"string"==typeof e.conclusion),s=1===a.length?a[0].conclusion:null;return"string"!=typeof s||""===s||"success"===s||Object.hasOwn(aw,s)?null:s}(o,t):null;return{...a,stage:e.stage,command:o,exitCode:e.exitCode,labels:e.labels,outcome:c?"unverified":t?e.state:s,...e.compound?{compound:e.compound}:{},...l?{evidence:c?`${l} \xb7 ${c}`:l}:{},...c?{otherRun:{kind:"unjudged",conclusion:c}}:{}}})}let c=e.toolName.toLowerCase().split(/[.:/]/).pop()??"",d=i?void 0:t,u=d?.details&&"object"==typeof d.details?d.details:{};if("cross_review"===c){let t="resolve"===e.input.action?"resolve":"review";if(!d||d.isError)return{...a,stage:"review",action:t,findings:null,outcome:d?"failed":s};if("resolve"===t){if(!0===u.pass)return{...a,stage:"review",action:t,findings:0,outcome:"passed"};let e=Array.isArray(u.open)?u.open.length:null;return{...a,stage:"review",action:t,findings:e,outcome:!1===u.pass?"failed":"unobserved"}}let n=Array.isArray(u.findings)?u.findings.length:null;if(null!==n&&n>0)return{...a,stage:"review",action:t,findings:n,outcome:"failed"};let r=Array.isArray(u.reviewers)?u.reviewers:[];return!1===u.passable||r.some(e=>!e||"object"!=typeof e||!("status"in e)||"ok"!==e.status)?{...a,stage:"review",action:t,findings:n,outcome:"unverified",unusable:!0}:{...a,stage:"review",action:t,findings:n,outcome:null===n?"unobserved":"done"}}if("git_finalize"===c){let t="string"==typeof e.input.message?iV(e.input.message):void 0,n=t?{title:t}:{};if(!d)return{...a,stage:"commit",commit:null,docsOnly:!1,...n,outcome:s};let r=iY.exec(an(d)),i=("string"==typeof u.commitSha&&""!==u.commitSha.trim()?u.commitSha.trim():null)??r?.[1]??r?.[2]??null,o=d.isError||!1===u.ok,l=!o&&(!0===u.ok||null!==i),c=e.input.files,p=l&&Array.isArray(c)&&c.length>0&&c.every(e=>"string"==typeof e&&(iO.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>iH.test(e))));return{...a,stage:"commit",commit:l?i:null,docsOnly:p,...n,outcome:l?"done":o?"failed":"unobserved"}}if("eval"===c)return function(e,t,n){let r=function(e){if("string"==typeof e.code)return e.code;let t=e.cells;return Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"").join("\n"):""}(e.input);if(!iZ.test(r))return null;let i=iQ.exec(r)?.[2],a=void 0===i?void 0:iV(i.replace(/\\n/g,"\n").replace(/\\(["'`\\])/g,"$1")),s={toolCallId:e.toolCallId,attempt:0,stage:"commit",docsOnly:!1,...a?{title:a}:{}};if(!t)return{...s,commit:null,outcome:n};let o=an(t),l=iY.exec(o),c=l?(l[1]??l[2]).toLowerCase():null,d=iX.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(i_,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(iB,e.input.action);if(!ts(e.toolName)&&!to(e.toolName))return!1;let n=e.input.file_path??e.input.path;return"string"!=typeof n||/^[a-zA-Z]:[\\/]/.test(n)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(n)}(e,c))return!i&&t?.isError?null:(ts(e.toolName)||to(e.toolName))&&tp(e.input,d,r)?{...a,stage:"investigate",outcome:i?"unobserved":t||!n?"done":"running"}:{...a,stage:"edit",outcome:d?"done":s,..."task"===c?{dispatch:!0}:{},...!function(e,t,n){if(!t||!(ts(e.toolName)||to(e.toolName)))return!1;let r=tu(e.input,t);return r.length>0&&r.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let n=t?ta(t)??t:void 0,r=tT(ta(e,t)??e,n);if(/^[\\/]/.test(r)||/^[a-zA-Z]:[\\/]/.test(r))return!1;let i=r.split(/[\\/]/).filter(e=>""!==e&&"."!==e);return"HANDOFF.md"===i.at(-1)||"doc"===i[0]&&"history"===i[1]&&i.length>2})(e,n))}(e,d,r)?{}:{recordOnly:!0}};return Object.hasOwn(iU,c)?{...a,stage:"investigate",outcome:i?"unobserved":t||!n?"done":"running"}:null}(e,a,n,i))?r:r?[r]:[]))y.push({step:s,order:t})}),s=null,o=!1,y.forEach((e,t)=>{let{step:n,order:r}=e;if("commit"===n.stage&&"done"===n.outcome&&n.commit&&(s={step:{...n,commit:n.commit},order:r},o=!1),"edit"!==n.stage||"done"!==n.outcome||n.dispatch||n.recordOnly||(o=!0),"ci"!==n.stage||!s)return;let i=s,a=is(n.command).commands.flatMap(({words:e})=>ai(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(a){let e,s=al(a),l=e=>(m.publishRuns.get(e)?.order??1/0)<=r;if((e=ax(n.command,l).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){av(n.command,l)||"passed"!==n.outcome&&"failed"!==n.outcome||(s&&"passed"===n.outcome&&m.watched.push({id:s,order:r}),y[t]={order:r,step:{...n,outcome:"unverified",evidence:void 0,otherRun:{kind:"publish",outcome:n.outcome}}});return}let c=s?m.runs.filter(e=>e.id===s):[],d=c.find(e=>null!==e.sha)?.sha;if(!d||c.some(e=>ab(e,i,m))){d&&o&&"passed"===n.outcome&&(y[t]={order:r,step:{...n,stale:!0}});return}if("passed"===n.outcome||"failed"===n.outcome){let e=d.slice(0,7);y[t]={order:r,step:{...n,outcome:"unverified",evidence:`run ${s} \xb7 ${e}`,otherRun:{kind:"commit",sha:e,outcome:n.outcome}}}}return}if("unverified"!==n.outcome)return;let l=m.runs.find(e=>e.order===r&&null!==e.workflow&&Object.hasOwn(ae,e.workflow)&&ab(e,i,m));if(!l||"completed"!==l.status||"string"!=typeof l.conclusion)return;let c="success"===l.conclusion?"passed":Object.hasOwn(aw,l.conclusion)?"failed":null;c&&(y[t]={order:r,step:{...n,outcome:c,evidence:`run ${l.id??"?"} \xb7 ${l.status} ${l.conclusion}`,..."passed"===c&&o?{stale:!0}:{}}})}),y.forEach((e,t)=>{let{step:n,order:r}=e;if("deploy"!==n.stage||"unverified"!==n.outcome&&"unobserved"!==n.outcome)return;let i=function(e){let t=[],n=(e,r)=>{let i=ih(e);if(null!==i){if(r<3)for(let e of is(i).commands)n(e.words,r+1);return}if(!iy(e))return;let a=ix(e),s=iv.test(e[a])?a:e.findIndex((e,t)=>t>a&&!e.startsWith("-")),o=e[s+1];t.push(void 0!==o&&/^[0-9a-f]{7,40}$/i.test(o)?o.toLowerCase():null)};for(let{words:t}of is(e).commands)n(t,0);return 1===t.length?t[0]:null}(n.command),a=x.get(n.toolCallId);if("number"!=typeof a?.timestamp)return;let s=a.details,o=s&&"object"==typeof s&&"wallTimeMs"in s&&"number"==typeof s.wallTimeMs?s.wallTimeMs:0,l=1e3*Math.floor((a.timestamp-o)/1e3);for(let e=r;e<g.length;e+=1){let a=g[e],s=a?.type==="toolCall"?v.get(a.toolCallId):void 0;if(s)for(let e of an(s).split("\n")){let a=e.trim().replace(/^\d+[:-](?=\d{4}-\d\d-\d\dT)/,"");if(null===i){let e=aS.exec(a);e&&Date.parse(e[1])>=l&&(i=e[2]);continue}let s=ak.exec(a);if(s&&Date.parse(s[1])>=l&&ay(s[2],i)){y[t]={order:r,step:{...n,outcome:"passed",evidence:`${s[1]} READY ${s[2].slice(0,12)}`}};return}let o=aj.exec(a);if(o&&Date.parse(o[1])>=l){y[t]={order:r,step:{...n,outcome:"failed",evidence:a.length>120?`${a.slice(0,119)}…`:a}};return}}}});let b=(e,t)=>null!==e&&(m.publishRuns.get(e)?.order??1/0)<=t;for(let{step:e,order:t}of y){let n=e;if("ci"===n.stage){let e=is(n.command).commands.flatMap(({words:e})=>ai(e)).find(e=>"run"===e[0]&&"watch"===e[1]),r=e?al(e):null;r&&"passed"===n.outcome&&m.watched.push({id:r,order:t}),!n.compound&&av(n.command,e=>b(e,t))&&(n={toolCallId:n.toolCallId,attempt:n.attempt,stage:"investigate",outcome:"passed"===n.outcome||"unverified"===n.outcome?"done":n.outcome})}if("edit"!==n.stage||"done"!==n.outcome||n.dispatch){if("check"===n.stage||"review"===n.stage||"ci"===n.stage){let e="check"===n.stage?`check:${n.command}`:n.stage,t=u.get(e);(t?.outcome!=="failed"||i2(n.outcome))&&u.set(e,{stage:n.stage,outcome:n.outcome,order:l.length})}}else{let e=i8(u);e&&(c.push({from:e,attempt:d}),d+=1),u=new Map,p=l.length,n.recordOnly||(h=l.length)}n.attempt=d,f.set(n,t),l.push(n)}let w=!1;l.forEach((e,t)=>{t<("commit"===e.stage||w&&("ci"===e.stage||"deploy"===e.stage)?h:p)&&"investigate"!==e.stage&&"edit"!==e.stage&&("passed"===e.outcome||"done"===e.outcome)&&(e.stale=!0),"commit"===e.stage&&"done"===e.outcome&&(w=!0)});let k=l.filter(e=>"commit"===e.stage&&"done"===e.outcome&&e.attempt===d).at(-1),j=k?f.get(k)??-1:-1,S=k&&!k.stale&&k.commit&&at.test(k.commit)?{sha:k.commit.toLowerCase(),order:j}:null,C=S?function(e,t,n){let r=e.watched.find(({id:n,order:r})=>{let i=e.publishRuns.get(n);return r>t.order&&i?.sha===t.sha&&i.order>t.order&&i.order<=r});if(!r)return null;let i=new Map;for(let t of e.heads)t.order>r.order&&i.set(`${t.repo}#${t.ref}`,t);let a=[...n,...e.ciHeads.filter(e=>e.order<t.order)];for(let e of i.values())if(null!==e.sha&&e.sha!==t.sha&&a.some(t=>t.repo===e.repo&&t.sha===e.sha&&t.branch===e.ref))return{kind:"publicHeadUnchanged",repo:e.repo,ref:e.ref,sha:e.sha,runId:r.id};return null}(m,S,r)??(m.nothingToPublish.some(({sha:e,order:t})=>e===S.sha&&t>S.order)?{kind:"nothingToPublish",commit:S.sha}:null):null;if(C?.kind==="nothingToPublish"){let e=C.commit;l.forEach((t,n)=>{var r;let i,a=f.get(t)??-1;if("ci"!==t.stage||"unverified"!==t.outcome||a<=j||!m.nothingToPublish.some(t=>t.order===a&&t.sha===e)&&(r=t.command,!((i=is(r).commands.flatMap(({words:e})=>ai(e))).length>0&&i.every(t=>"run"===t[0]&&"list"===t[1]&&aa(t,["-c","--commit"])?.toLowerCase()===e))))return;let s={toolCallId:t.toolCallId,attempt:t.attempt,stage:"investigate",outcome:"done"};l[n]=s,f.set(s,a)})}let N=it.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||i2(r.outcome)){if(null!==n&&!("ci"!==r.stage||i3(t))&&!is(r.command).commands.some(({words:e})=>ai(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===n&&(i7(r)?.every(t=>e.has(t))??!1);if(i3(n)||t)continue}if(n=t,"stale"===t||"passed"===r.outcome||"failed"===r.outcome)for(let t of i7(r)??[])e.add(t)}}return n??"waiting"}let n="done";for(let e of i4(t)){let t=e.stale?"stale":e.outcome;i6[t]>i6[n]&&(n=t)}return n}(e,n),steps:n,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),T=N[it.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[it.indexOf("ci")],R=M.steps.some(e=>(f.get(e)??1/0)>j);C&&("waiting"===M.status||("unverified"===M.status||"stale"===M.status)&&!R)?M.status="notNeeded":C=null;let E=-1;N.forEach((e,t)=>{"waiting"!==e.status&&"failed"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status&&"stale"!==e.status&&e.steps.some(e=>!e.stale&&"failed"!==e.outcome&&!i5(e))&&(E=t)});let L=null;if(n&&l.length>0)if(i8(u))L={stage:"edit",returning:!0};else if(E<0)L={stage:N.find(e=>"waiting"!==e.status)?.stage??it[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 i=t.filter(e=>("commit"===e.stage||"ci"===e.stage||"deploy"===e.stage)&&e.steps.length>0&&"notNeeded"!==e.status&&"skipped"!==e.status),a=i.find(e=>"commit"!==e.stage&&Object.hasOwn(aN,e.status));return a?.stage??i.at(-1)?.stage??r.stage}(l,N,k),reached:E<0?null:it[E],next:L,publication:C}}let aN={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0};function aT(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 aI(e,t,n){let r=[],i=[],a=null;for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){i.push(n);continue}if(tw(n.toolName)){let e=tb(n,t.get(n.toolCallId));"authoritative"===e.kind&&(a=e.phases);continue}let e=iD(n,t.get(n.toolCallId));e&&r.push(e)}return{checks:r,dispatchCalls:i,files:tx(e,t,n),remaining:a?aT(a):null}}function aM(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}function aR(e,t,n){let r=[],i=null;for(let a=Math.max(0,t);a<Math.min(e.length,n);a++){let t=e[a];if("assistant"===t.role)for(let e of t.content??[])"toolCall"===e.type&&(i=e.toolCallId);else if("custom"===t.role&&"async-result"===t.customType){let e="string"==typeof t.content?t.content:t.content.map(e=>"text"===e.type?e.text:"").join("\n");r.push({text:e,after:i})}}return r}function aE(e,t){var n;let r=t;for(;r>=0&&(n=e[r],n?.role==="custom"?"compaction"===n.customType:n?.role==="user"&&("steer"===ie(n)||function(e){if("[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."===e||"[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다."===e||"[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."===e)return!0;let[t,n]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==n&&n.startsWith("requestId=")}(r9(n))));){let t=r-1;for(;t>=0&&"user"!==e[t].role;)t-=1;r=t}return r}function aL(e,t,n,r){let i=Math.min(e.length,r),a=new Map;for(let t=Math.max(0,n);t<i;t++){let n=e[t];"toolResult"===n.role&&a.set(n.toolCallId,t)}let s=[];for(let r=Math.max(0,n-1);r<i;r++){let i=e[r];if(r>=n&&"assistant"===i.role)for(let e of i.content??[]){if("toolCall"!==e.type||!tw(e.toolName))continue;let n=tb(e,t.get(e.toolCallId));"authoritative"===n.kind&&s.push({at:a.get(e.toolCallId)??r,phases:n.phases})}for(let e of i.trackerTodos??[]){let t=ty(e);t&&s.push({at:r+.5,phases:t})}}let o=null;for(let e of s)(!o||e.at>=o.at)&&(o=e);return o?o.phases:null}function a$(e,t,n,r=0,i=[]){for(let a=Math.max(0,r);a<Math.min(e.length,n);a++){let n=e[a];if("assistant"===n.role)for(let e of n.content??[])"toolCall"===e.type&&i.push(...ah(e,t.get(e.toolCallId)))}return i}function aP(e,t,n){let r=null,i=null;for(let a=Math.max(0,t-1);a<Math.min(e.length,n);a++){let t=e[a];for(let e of[t.timestamp,"assistant"===t.role?t.completedAt:void 0])"number"==typeof e&&Number.isFinite(e)&&((null===r||e<r)&&(r=e),(null===i||e>i)&&(i=e))}return{startedAt:r,endedAt:i}}function aA(e,t){if(0===e.length)return null;let n=[...e].sort((e,t)=>e-t),r=(n.length-1)*t,i=Math.floor(r),a=Math.ceil(r);return n[i]+(n[a]-n[i])*(r-i)}let aF=["investigate","implement","verify","report"],az={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},aW={bash:!0,eval:!0};function aD(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 aO(e,t,n,r){return!0===az[t]&&!tp(e.input,n.get(e.toolCallId),r)}function aH(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function aU(e){return"yield"===aH(e)&&!Array.isArray(e.input?.type)}function a_(e,t){if(0===e.length)return null;let{blocks:n,results:r}=aD(e),i=-1;n.forEach((e,t)=>{aU(e)&&(i=t)});let a=i>=0&&i===n.length-1,s=a?n.findLastIndex((e,t)=>t<i&&aU(e))+1:i+1,o={calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:a,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1},l=!1;for(let e of n.slice(s)){let n=aH(e);if(aO(e,n,r,t))"verify"===o.phase&&(o.reedits+=1),l=!0,o.phase="implement",o.verifiedAfterEdit=!1;else if(aW[n]){if(o.phase=l?"verify":"investigate",l){o.verifiedAfterEdit=!0;let t=iD(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 aB(e,t){if(!e)return{run:null,stations:aF.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?aF.indexOf(n.phase):aF.findLastIndex(e=>n.calls[e]>0),i=aF.map((e,i)=>{let a,s=n.calls[e];return a=t&&e===n.phase?"active":s>0?"verify"!==e||n.verifiedAfterEdit?"done":"stale":i<r?"skipped":t?"waiting":"none",{phase:e,state:a,calls:s}});return{run:n,stations:i}}function aq(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function aV(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 aK(e){return"pending"===e||"running"===e}let aG=new Map;function aJ(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function aZ(e){return e instanceof r$&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function aY(e,{sessionId:t,client:n,enabled:r}){let[a,s]=(0,i.useState)(aG),o=(0,i.useRef)(new Map),l=(0,i.useRef)(e);l.current=e;let c=(0,i.useCallback)(()=>{let e=o.current;s(t=>{let n=!1,r=new Map;for(let[i,a]of e){let e=t.get(i),s=e&&e.entries===a.collected&&e.state===a.state?e:{state:a.state,entries:a.collected};s!==e&&(n=!0),r.set(i,s)}return r.size!==t.size&&(n=!0),n?r:t})},[]),d=e.map(e=>`${e.key}|${aJ(e)}`).join("\n");return(0,i.useEffect)(()=>{if(!r)return;let e=!1,i=!1,a=null,s=o.current,d=new Set(l.current.map(e=>e.key));for(let e of[...s.keys()])d.has(e)||s.delete(e);for(let e of l.current){let t=aJ(e);s.get(e.key)?.signature!==t&&s.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(r,i,a,s)=>{if(!r.archiveName){i.state={kind:"empty",source:"live",note:s};return}try{let o=await n.getArchiveTranscript(t,r.archiveName,400,a);if(e)return;0===i.collected.length&&(i.collected=o.entries.flatMap((e,t)=>{let n=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:n,message:e.message}]:e.irc?[{id:n,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),i.state=0===o.entries.length?{kind:"empty",source:"archive",note:s}:{kind:"ready-archive",entries:o.entries,truncated:o.truncated,note:s}}catch(n){if(e||a.aborted)return;let t=aZ(n);i.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},p=async(r,i)=>{let a=s.get(r.key);if(a){if(!r.liveId)return void await u(r,a,i);try{var o,l;let s=await n.getLiveTranscript(t,r.liveId,a.nextByte,i);if(e)return;let c=(o=s.entries,l=s.fromByte,o.flatMap((e,t)=>{let n=e.id??`${l}:${t}`;if("message"===e.type&&e.message)return[{id:n,message:aV(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:n,irc:{from:"string"==typeof t.from?t.from:void 0,message:"string"==typeof t.message?t.message:void 0}}]}return[]}));s.reset||0===s.fromByte?a.collected=c:c.length>0&&(a.collected=[...a.collected,...c]),a.nextByte=s.nextByte,a.collected.length>0?("ready-live"!==a.state.kind||a.state.entries!==a.collected)&&(a.state={kind:"ready-live",entries:a.collected}):await u(r,a,i)}catch(t){if(e||i.aborted)return;if(r.archiveName){let e=aZ(t);await u(r,a,i,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=aZ(t);a.state="unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message}}}}},h=async()=>{if(e||i||"u">typeof document&&"visible"!==document.visibilityState)return;i=!0;let t=new AbortController;a=t;try{for(let e of l.current)await p(e,t.signal)}finally{i=!1}e||c()};h();let f=l.current.some(e=>aK(e.status))?setInterval(()=>void h(),3e3):void 0,m=()=>{"visible"===document.visibilityState&&h()};return document.addEventListener("visibilitychange",m),()=>{e=!0,a?.abort(),clearInterval(f),document.removeEventListener("visibilitychange",m)}},[n,r,c,t,d]),a}let aX=(0,i.createContext)({ledger:r_,subagents:[],toolResults:new Map}),aQ="omp-web:flow-motion",a0=new Set,a1=null;function a2(){if(null===a1)try{a1="paused"===window.localStorage.getItem(aQ)}catch{a1=!1}return a1}function a8(e){return a0.add(e),()=>{a0.delete(e)}}function a4(){return(0,i.useSyncExternalStore)(a8,a2,()=>!1)}function a5({paused:e}){let{st:t}=rg();return(0,r.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){a1=e;try{e?window.localStorage.setItem(aQ,"paused"):window.localStorage.removeItem(aQ)}catch{}for(let e of a0)e()})(!e),children:t("graph.motion.pause")})}function a6(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 a3(e){return e.stale?"stale":e.outcome}let a7=(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 a9({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 se({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 st({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":a3(e),children:[n,"commit"===e.stage&&e.commit&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsxs)("span",{className:"flow-sha-tail",children:["\xb7\xa0",(0,r.jsx)("code",{className:"flow-sha",children:e.commit.slice(0,7)})]})]})]})}function sn({step:e,label:t,st:n}){let i=i5(e),a=e.compound?.stages.map(e=>n(`flow.stage.${e}`)).join("\xb7")??"",s=e.otherRun,o=i?n("flow.why.compoundConfirmed",{stages:a}):s?.kind==="unjudged"?n("flow.why.watched.unjudged",{conclusion:s.conclusion}):s?n(`flow.why.watched.${s.outcome}`):n("flow.why.exitZero"),l=i?n("flow.why.compoundMissing"):"check"===e.stage?n("flow.why.check",{label:t}):s?.kind==="commit"?n("flow.why.ciOtherRun",{sha:s.sha}):s?.kind==="publish"?n("flow.why.ciPublishRun"):s?.kind==="unjudged"?n("flow.why.ciUnjudged",{conclusion:s.conclusion}):n(`flow.why.${e.stage}`),c=null!==e.exitCode?n("flow.exit",{code:e.exitCode}):n("failed"===e.outcome?"flow.exit.error":"running"===e.outcome?"flow.state.running":"flow.exit.none");return(0,r.jsxs)("div",{className:"flow-raw",children:["unverified"===e.outcome&&(0,r.jsxs)("p",{className:"flow-why",children:[(0,r.jsx)("b",{children:n("flow.why.confirmed")})," ",o,(0,r.jsx)("br",{}),(0,r.jsx)("b",{children:n("flow.why.missing")})," ",l]}),e.stale&&(0,r.jsx)("p",{className:"flow-why",children:n("flow.why.stale")}),void 0===e.commandKey?(0,r.jsx)("code",{className:"flow-raw-command",children:e.command}):(0,r.jsx)("p",{className:"flow-why",children:n("flow.commandOmitted")}),(0,r.jsx)("div",{className:"flow-exit",children:c}),e.evidence&&(0,r.jsxs)("div",{className:"flow-exit",children:[n("flow.evidence")," ",(0,r.jsx)("code",{className:"flow-evidence",children:e.evidence})]})]})}function sr({steps:e,st:t,attempts:n=!1}){return(0,r.jsx)("ul",{className:"flow-checks",children:e.map(e=>{let i="check"===e.stage?e.labels.map(e=>t(`flow.label.${e}`)).join("\xb7")||t("flow.label.check"):"review"===e.stage?t("resolve"===e.action?"flow.label.resolve":"flow.label.review"):"ci"===e.stage||"deploy"===e.stage||"commit"===e.stage?t(`flow.label.${e.stage}`):t(`flow.stage.${e.stage}`),a=a3(e),s=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(se,{outcome:a}),(0,r.jsx)(st,{step:e,st:t}),(0,r.jsxs)("span",{className:"flow-check-label",children:[n?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${i}`:i,i5(e)&&(0,r.jsx)("span",{className:"flow-compound",children:t("flow.compound.failed")})]})]});return"check"!==e.stage&&"ci"!==e.stage&&"deploy"!==e.stage?(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsx)("div",{className:"flow-check-head",children:s})},e.toolCallId):(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsxs)("details",{children:[(0,r.jsxs)("summary",{className:"flow-check-head",children:[s,(0,r.jsxs)("span",{className:"flow-disclose",children:[t("flow.details"),a7]})]}),(0,r.jsx)(sn,{step:e,label:i,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function si({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}),a7]}),(0,r.jsx)(sr,{steps:e,st:t,attempts:!0})]})}let sa=["failed","unverified","unobserved","stale","running","passed"];function ss({view:e,flow:t,live:n,st:i,compact:a=!1}){if(n&&t.current===e.stage)return i("flow.state.running");if("waiting"===e.status)return i("flow.state.waiting");if("skipped"===e.status||"notNeeded"===e.status)return i(`flow.state.${e.status}`);let s=e.steps[e.steps.length-1];if("investigate"===e.stage)return i("running"===e.status?"flow.state.running":"flow.state.done");if("edit"===e.stage&&"done"===e.status)return i(t.attempt>1?"flow.state.redone":"flow.state.done");if("check"===e.stage&&!a){let t=new Map;for(let n of i4(e.steps))t.set(a3(n),(t.get(a3(n))??0)+1);return sa.filter(e=>t.has(e)).map((e,n)=>(0,r.jsxs)("span",{children:[n>0&&" \xb7 ",(0,r.jsx)("span",{className:"flow-tone","data-tone":e,children:i(`flow.count.${e}`,{count:t.get(e)??0})})]},e))}return"check"===e.stage||"edit"===e.stage?(0,r.jsx)("span",{className:"flow-tone","data-tone":e.status,children:i(`flow.state.${e.status}`)}):(0,r.jsx)(st,{step:s,st:i})}function so({flow:e,live:t,st:n,id:i}){let a=e.loops[e.loops.length-1],s=a?e.steps.filter(e=>e.stage===a.from):[],o=n("flow.loop.badge",{attempt:e.attempt});return(0,r.jsxs)("div",{className:"flow-chain-panel",id:i,children:[(0,r.jsxs)("div",{className:"flow-chain-wrap","data-loop":a?"":void 0,style:a?{"--loop-from":it.indexOf(a.from)}:void 0,children:[(0,r.jsx)("ol",{className:"flow-chain","aria-label":n("flow.aria"),children:e.stages.map(i=>{let a=a6(i,e,t);return(0,r.jsxs)("li",{className:"flow-link","data-state":a,"aria-current":"active"===a?"step":void 0,children:[(0,r.jsx)(a9,{look:a}),(0,r.jsx)("span",{className:"flow-link-name",children:n(`flow.stage.${i.stage}`)}),(0,r.jsx)("span",{className:"flow-link-state",children:(0,r.jsx)(ss,{view:i,flow:e,live:t,st:n,compact:!0})})]},i.stage)})}),a&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flow-loop","aria-hidden":"true",children:[(0,r.jsx)("svg",{width:"22",height:"15",viewBox:"0 0 22 15",children:(0,r.jsx)("polyline",{points:"3 12 11 3 19 12",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,r.jsx)("span",{className:"flow-loop-count",children:o})]}),(0,r.jsxs)("p",{className:"flow-loop-caption",children:[(0,r.jsx)("span",{className:"flow-loop-caption-count",children:o}),n("review"===a.from?"flow.loop.findings":"flow.loop.failed",{stage:n(`flow.stage.${a.from}`),attempt:a.attempt})]})]})]}),s.length>0&&(0,r.jsx)("div",{className:"flow-chain-attempts",children:(0,r.jsx)(sr,{steps:s,st:n,attempts:!0})})]})}function sl({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:a=!0,cwd:s}){let o=(0,i.useMemo)(()=>t.filter(e=>aK(e.status)),[t]),l=r&&!!e&&o.length>0,c=aY((0,i.useMemo)(()=>o.map(e=>({key:e.id,liveId:e.id,status:e.status})),[o]),{sessionId:e??"",client:n,enabled:l&&a}),[d,u]=(0,i.useState)(null),p=o.map(e=>e.id).sort().join("\n");return(0,i.useEffect)(()=>{let t;if(!l||!e)return;let n=new AbortController,r=p.split("\n"),i=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,a=!0,s=0;async function o(){try{let t=await fetch(i,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!n.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),a=r.some(e=>!s.histories[e]))}catch{}finally{if(!n.signal.aborted){let e=a&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{n.abort(),window.clearTimeout(t)}},[p,l,e]),(0,i.useMemo)(()=>{let t=new Map;if(!l)return t;let n=d&&d.sessionId===e?d.histories:void 0;for(let e of o){let r=(a?c.get(e.id)?.entries??[]:[]).flatMap(e=>"message"in e?[e.message]:[]);t.set(e.id,{phase:function(e,t){if(0===e.length)return null;let{blocks:n,results:r}=aD(e),i="investigate",a=!1;for(let e of n){let n=aH(e);aO(e,n,r,t)?(a=!0,i="implement"):aW[n]?i=a?"verify":"investigate":"yield"===n&&(i="report",a=!1)}return i}(r,s),trace:a_(r,s),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=tk([...e],t);if(!n)return null;let r=tj(n);return 0===r.total||null===r.percent?null:{completed:r.completed,total:r.total,percent:r.percent,activeTask:r.activeTask?.content??null}}(r),history:n?.[e.id]??null})}return t},[o,s,d,l,c,e,a])}function sc(e,t){let n=aq(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 sd(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}):sc(e,t)}function su({phase:e}){let{st:t}=rg();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:aF.map((n,i)=>(0,r.jsxs)("span",{children:[i>0&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,r.jsx)("span",{"data-current":n===e?"":void 0,style:n===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${n}`)})]},n))})]})}let sp={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function sh(e,t){let n=t.passed+t.failed+t.unknown,i=t.failed>0?"failed":t.unknown>0?"unverified":"passed";return(0,r.jsx)("span",{className:"flow-tone","data-tone":i,children:e("subflow.checks",{passed:t.passed,total:n})})}function sf({flow:e,live:t,verdict:n,attempts:i}){let{st:a}=rg(),s=a4(),o=e.stations.findIndex(e=>"active"===e.state),l=aF.indexOf("implement"),c=i.filter(e=>"rework"===e.verdict).length,d=n?"accepted"===n.verdict?"done":"unverified":"waiting",u=n?`${a(`verdict.${n.verdict}`)}${null!==n.attempt&&n.attempt>1?` \xb7 ${a("verdict.attempt",{attempt:n.attempt})}`:""}`:a(t?"flow.state.waiting":"verdict.none");return(0,r.jsxs)("div",{className:"subagent-flow",children:[t&&o>=0&&(0,r.jsx)(a5,{paused:s}),(0,r.jsxs)("ol",{className:"flow-graph","aria-label":a("subflow.aria"),"data-live":t?"":void 0,"data-motion":s?"paused":void 0,children:[e.stations.map((t,n)=>{let i=sp[t.state];return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":t.phase,"data-state":i,"data-loop":c>0&&n>=l?"":void 0,"aria-current":"active"===t.state?"step":void 0,style:{"--col":n+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a(`phase.${t.phase}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(a9,{look:i}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:function(e,t,n){let i="verify"===t.phase&&null!==n&&n.checks.passed+n.checks.failed+n.checks.unknown>0;switch(t.state){case"active":return i&&n?(0,r.jsxs)(r.Fragment,{children:[e("flow.state.running")," \xb7 ",sh(e,n.checks)]}):e("flow.state.running");case"waiting":return e("flow.state.waiting");case"skipped":return e("flow.state.skipped");case"none":return e("detail.stageNone");case"unobserved":return e("subflow.unobserved");case"stale":return e(n&&n.checks.passed>0?"flow.state.stale":"flow.state.staleDone");case"done":if("report"===t.phase)return e("subflow.reported");if(i&&n)return sh(e,n.checks);if("implement"===t.phase&&n&&n.reedits>0)return`${e("subflow.calls",{count:t.calls})} \xb7 ${e("subflow.reedits",{count:n.reedits})}`;return e("subflow.calls",{count:t.calls})}}(a,t,e.run)})]})]})},t.phase)}),(0,r.jsx)("li",{className:"flow-graph-station","data-stage":"verdict","data-state":d,style:{"--col":aF.length+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a("graph.join")}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(a9,{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":aF.length+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsx)("span",{className:"flow-graph-return-text",children:a("subflow.rework",{count:c})})]})]})]})}function sm(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 sg({snapshot:e,view:t,id:n}){var i,a,s;let o,l,c,{st:d}=rg(),u=nd(5e3),p="number"!=typeof(o=e.progress?.durationMs)?null:o+(("pending"===e.status||"running"===e.status)&&e.lastUpdate>0?Math.max(0,u-e.lastUpdate):0);if(null===p)return null;let h=function(e,t){if(!e||e.rework||null===t||e.durationsSec.length<3)return null;let n=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(n.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:n.length};let r=aA(n,.5)??0;return{kind:"remaining",p25Ms:aA(n,.25)??0,medianMs:r,p75Ms:aA(n,.75)??0,samples:n.length,percent:Math.round(t/(t+r)*100)}}(t.history,p),f=(i=t.todo,!i||null===p||0===i.completed||i.completed>=i.total?null:p*(i.total-i.completed)/i.completed),m={color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},g=t.history,x=g?.rework&&null!==g.firstDispatchedAtMs?u-g.firstDispatchedAtMs:null;return(0,r.jsxs)("span",{id:n,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,r.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:d("eta.elapsed",{duration:sd(d,p)})}),g?.rework&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:m,title:d("eta.reworkHint"),children:null!==x&&x>=0?d("eta.rework",{attempt:g.attempt,duration:sd(d,x)}):d("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{title:d("eta.hint"),children:d("eta.remaining",{range:(a=h.p25Ms,s=h.p75Ms,l=aq(a),c=aq(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:sc(d,a),high:sc(d,s)})),samples:h.samples})})," \xb7 ",(0,r.jsx)("span",{style:m,children:d("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:{color:"var(--warning)"},title:d("eta.hint"),children:0===h.longerRuns?d("eta.overrun",{longest:sc(d,h.longestMs)}):d("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==f&&t.todo&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:m,title:d("eta.byTodoHint"),children:f<6e4?d("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):d("eta.byTodo",{duration:sc(d,f),completed:t.todo.completed,total:t.todo.total})})]})]})}let sx={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},sv={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function sy({maker:e,st:t}){let n=e.verdict?.verdict??"none",i=e.verdict?.attempt;return(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(sx[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(sv[n]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function sb(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 aI(n,r,t)}function sw(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function sk(e,t){let n=e?.state;return n?.kind!=="ready-live"?null:a_(n.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function sj({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 sS({calls:e}){let{ledger:t,subagents:n,toolResults:a,onOpenPanel:s,sessionId:o,cwd:l,onOpenMaker:c,selectedMaker:d}=(0,i.useContext)(aX),{st:u}=rg(),{t:p}=(0,F.s)(),[h,f]=(0,i.useState)(!1),m=(0,i.useId)(),g=(0,i.useMemo)(()=>rD(),[]),x=(0,i.useMemo)(()=>e.flatMap(e=>rJ(e,a.get(e.toolCallId))??[]).map(e=>rQ(e,n,t)),[e,a,n,t]),v=(0,i.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=rX(e.member,n,t);return r?[r]:[]}),[x,n,t]),y=sl({sessionId:o,snapshots:v,client:g,enabled:!0,transcripts:h,cwd:l}),b=(0,i.useMemo)(()=>new Map(x.flatMap(e=>{let t=r0(e.member,n);return t?[[e.member.key,t]]:[]})),[x,n]),w=(0,i.useMemo)(()=>h?[...b].filter(([,e])=>!aK(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:sw(t)})):[],[b,h]),k=aY(w,{sessionId:o??"",client:g,enabled:h&&!!o&&w.length>0}),j=d?.origin?x.find(e=>e.member.key===d.origin):void 0,S=j?.run,C=j?.verdict??null;if((0,i.useEffect)(()=>{if(!d||!c||!S)return;let e=d.status;e&&e.run===S&&e.verdict?.order===C?.order||c({...d,status:{run:S,verdict:C}},!1)},[c,d,S,C]),0===x.length)return null;let N=0,T=0,I=0;for(let e of x)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(N+=1),"completed"===e.run&&(T+=1),e.verdict?.verdict==="accepted"&&(I+=1);return(0,r.jsxs)("section",{className:"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":h,"aria-controls":m,title:u(h?"dispatch.collapse":"dispatch.expand"),onClick:()=>f(e=>!e),children:[(0,r.jsx)("span",{className:"answer-dispatch-heading",children:u("dispatch.title",{count:x.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:u("dispatch.tally",{running:N,done: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:m,"aria-label":h?p("dispatchLane.label"):void 0,children:x.map(e=>{var n;let i,a="pending"===e.run||"running"===e.run,s=a?v.find(t=>t.id===e.member.agentId):void 0,o=s?y.get(s.id):void 0,p=b.get(e.member.key),f=e.member.key===d?.origin,m=a&&"live"===e.runSource,g=h?aB(m?o?.trace??null:sk(k.get(e.member.key),l),m):null,x=h?r1(e.member,t):[];return(0,r.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":f?"":void 0,children:[h?(0,r.jsx)(sC,{maker:e,phase:m&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,n){if(!t)return{kind:"unobserved"};if(aK(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}=sb(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)(sj,{maker:e,st:u}),(0,r.jsx)(sy,{maker:e,st:u})]}),g&&(0,r.jsx)(sf,{flow:g,live:m,verdict:e.verdict,attempts:x}),h&&(0,r.jsx)(sT,{attempts:x}),s&&o&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[o.todo?`${sm(u,o.todo)} \xb7 `:null,(0,r.jsx)(sg,{snapshot:s,view:o})]}),h&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[a&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??u("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.model")}),(0,r.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${u("detail.fallback")}`:""}`:u("detail.modelNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${u("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("subflow.prior")}),(0,r.jsx)("dd",{children:(i=null!==(n=e.priorVerdict).attempt&&n.attempt>1?` \xb7 ${u("verdict.attempt",{attempt:n.attempt})}`:"",`${u(sv[n.verdict])}${i}${n.reason?` \xb7 ${n.reason}`:""}`)})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u(e.runTitle?"subflow.firstTitle":"subflow.runTitle")}),(0,r.jsx)("dd",{children:e.runTitle?e.title:u("detail.stageNone")})]}),e.verdict?.reason&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),h&&s&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:u("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:u("detail.openProcess")})]})]})}function sC({maker:e,phase:t,checks:n,onOpen:i}){let{st:a}=rg(),{t:s}=(0,F.s)(),o=e.verdict?.verdict??"none",l=a(sx[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)(sj,{maker:e,st:a}),(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?s("dispatchLane.runPhase",{run:l,phase:t}):l}),c&&(0,r.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===n.kind&&n.passed<n.total?"failed":n.kind,children:c}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsx)("span",{className:"answer-status-verdict","data-verdict":o,children:a(sv[o])})]}),i?(0,r.jsx)("button",{type:"button",className:"answer-link answer-dispatch-open","aria-label":s("dispatchLane.openLabel",{title:e.title}),onClick:i,children:s("dispatchLane.open")}):(0,r.jsx)("span",{className:"answer-dispatch-unavailable",title:s("makerDetail.unavailable"),children:s("dispatchLane.unavailable")})]})}function sN({maker:e}){let{ledger:t,subagents:n,sessionId:a,cwd:s}=(0,i.useContext)(aX),o=(0,i.useMemo)(()=>rD(),[]),l="pending"===e.run||"running"===e.run,c=l&&"live"===e.runSource,d=l?rX(e.member,n,t):void 0,u=sl({sessionId:a,snapshots:(0,i.useMemo)(()=>d?[d]:[],[d]),client:o,enabled:!0,transcripts:!0,cwd:s}),p=r0(e.member,n),h=(0,i.useMemo)(()=>p&&!aK(p.status)?[{key:e.member.key,liveId:p.id,status:p.status,archiveName:sw(p)}]:[],[p,e.member.key]),f=aY(h,{sessionId:a??"",client:o,enabled:!!a&&h.length>0}),m=d?u.get(d.id):void 0,g=aB(c?m?.trace??null:sk(f.get(e.member.key),s),c),x=r1(e.member,t);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sf,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,r.jsx)(sT,{attempts:x})]})}function sT({attempts:e}){let{t}=(0,F.s)();return e.length<2?null:(0,r.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":t("dispatchLane.label"),children:e.map((e,n)=>(0,r.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[n>0&&(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→ "}),null===e.attempt?t("dispatchLane.attemptUnknown"):t("dispatchLane.attempt",{attempt:e.attempt})," ",t(`dispatchLane.verdict.${e.verdict}`)]},`${e.attempt??"n"}-${n}`))})}let sI={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},sM={html:0,document:1,image:2},sR=/\.(?:md|mdx|markdown|txt)$/i;function sE(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function sL(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 s$({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:sE(e.bar.offset),width:sE(e.bar.width)}})}),(0,r.jsx)("span",{className:"flow-graph-time",children:sd(t,e.durationMs)})]}):(0,r.jsx)("span",{className:"flow-graph-time-missing",children:t(n?"summary.time.running":"summary.time.unobserved")})}function sP({entry:e,together:t,batch:n=!1,st:i}){let a=e.maker.member.workClass;return(0,r.jsxs)("span",{className:"flow-graph-maker-tags",children:[(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":a?void 0:"",children:i(`graph.kind.${a??"unknown"}`)}),n&&e.batchSize>1&&(0,r.jsx)("span",{className:"flow-graph-chip",children:i("graph.parallel.batch")}),t&&(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":"unknown"===e.concurrency?"":void 0,"data-concurrency":e.concurrency,children:i(`graph.concurrency.${e.concurrency}`)})]})}function sA({selectable:e,selected:t,detailId:n,onSelect:i,className:a,children:s,style:o}){return e?(0,r.jsx)("button",{type:"button",className:a,style:o,"aria-pressed":t,"aria-controls":n,onClick:i,children:s}):(0,r.jsx)("div",{className:a,style:o,children:s})}function sF({summary:e,makers:t,timings:n,live:a=!1,onOpenFile:s}){let o,l,c,{subagents:d,onOpenMaker:u}=(0,i.useContext)(aX),{st:p}=rg(),h=(0,i.useId)(),{flow:f}=e,m=(0,i.useMemo)(()=>(function(e,t,n,r){let i=function(e,t){let n=t.map(e=>null!==e.startedAt&&null!==e.durationMs?{start:e.startedAt,end:e.startedAt+e.durationMs}:null),r=e.startedAt,i=e.endedAt;for(let e of n)e&&((null===r||e.start<r)&&(r=e.start),(null===i||e.end>i)&&(i=e.end));let a=null!==r&&null!==i?i-r:0;return n.map(e=>e?a<=0||null===r?{offset:0,width:1}:{offset:(e.start-r)/a,width:(e.end-e.start)/a}:null)}(n,t),a=e.map(e=>"live"===e.runSource&&"running"===e.run),s=new Map;for(let t of e)s.set(t.member.toolCallId,(s.get(t.member.toolCallId)??0)+1);let o=e.map((n,r)=>{let o="unknown";for(let t=0;t<e.length;t+=1)if(t!==r&&(a[r]&&a[t]||n.observedParallelWith?.has(e[t].member.key))){o="overlapped";break}return{maker:n,bar:i[r],durationMs:t[r]?.durationMs??null,concurrency:o,batchSize:s.get(n.member.toolCallId)??1,liveRunning:a[r]}});return{makers:o,parallel:o.some(e=>"overlapped"===e.concurrency)?"observed":o.some(e=>e.batchSize>1)?"batch":"none",files:r.filter(e=>!sR.test(e.filePath)),docs:r.filter(e=>sR.test(e.filePath))}})(t,n,e.span,e.files),[t,n,e.span,e.files]),[g,x]=(0,i.useState)(void 0),v=a4(),y=e.files.length,b=a&&f.current?f.stages.find(e=>e.stage===f.current):void 0,w=void 0===g?b&&sL(b,f,y)?`stage:${b.stage}`:(o=f.stages.filter(e=>sL(e,f,y)),l=f.loops[f.loops.length-1],(c=(f.next?.returning&&l?o.find(e=>e.stage===l.from):void 0)??o.find(e=>"failed"===e.status)??o.find(e=>"unverified"===e.status||"stale"===e.status)??o.findLast(e=>"notNeeded"!==e.status&&"skipped"!==e.status)??o[o.length-1])?`stage:${c.stage}`:y>0?"files":null):g,k=f.loops[f.loops.length-1],j=k?it.indexOf(k.from):-1,S=it.indexOf("edit"),C=b?it.indexOf(b.stage):-1,N=m.makers.some(e=>e.liveRunning),T=m.files.length>0||m.docs.length>0,I=(0,i.useMemo)(()=>a?[]:function(e,t,n,r){let i=it.indexOf("edit"),a=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,s=[],o=n,l=e=>{let t=it.indexOf(e.stage);o&&t>i&&(s.push("branch"),o=!1),s.push(e.stage),o&&t===i&&(s.push("branch"),o=!1)},c=t[t.length-1];if(c){let t=it.indexOf(c.from);for(let n of e)it.indexOf(n.stage)<=t&&(a(n)||n.earlier.length>0||n.stage===c.from)&&l(n);for(let t of(o&&(s.push("branch"),o=!1),s.push("return"),e))it.indexOf(t.stage)>=i&&a(t)&&l(t)}else for(let t of e)a(t)&&l(t);return o&&s.push("branch"),r&&s.push("outputs"),s}(f.stages,f.loops,m.makers.length>0,T),[a,f.stages,f.loops,m.makers.length,T]),[M,R]=(0,i.useState)(null),E=null!==M&&M<I.length?M:null;(0,i.useEffect)(()=>{if(null===E)return;let e=window.setTimeout(()=>R(E+1<I.length?E+1:null),800);return()=>window.clearTimeout(e)},[E,I.length]);let 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 m.makers){let t=e.maker.verdict?.verdict??"none";$.set(t,($.get(t)??0)+1)}let P=1===$.size&&$.has("accepted"),A=f.stages[S+1],F=A?a6(A,f,a):"skipped",z=m.makers.length>0&&(0,r.jsxs)("li",{className:"flow-graph-branch","data-loop":k&&j>S?"":void 0,"data-merge":"skipped"===F||"waiting"===F||"approval"===F?"quiet":void 0,"data-beat":L("branch"),children:[(0,r.jsxs)("p",{className:"flow-graph-branch-head",children:[(0,r.jsx)("span",{children:p(1===m.makers.length?"graph.branch.one":"graph.branch",{count:m.makers.length})}),"none"!==m.parallel&&(0,r.jsx)("span",{className:"flow-graph-chip","data-parallel":m.parallel,children:p(`graph.parallel.${m.parallel}`)})]}),(0,r.jsx)("ul",{className:"flow-graph-lanes",children:m.makers.map(e=>{let t=`maker:${e.maker.member.key}`;return(0,r.jsx)("li",{className:"flow-graph-lane","data-run":e.maker.run,"data-live":e.liveRunning?"":void 0,children:(0,r.jsxs)(sA,{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)(sP,{entry:e,together:m.makers.length>1,st:p}),(0,r.jsx)("span",{className:"flow-graph-maker-time",children:(0,r.jsx)(s$,{entry:e,st:p})}),(0,r.jsx)(sy,{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)(a9,{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(sv[e])," ",$.get(e)]},e))})]})]},"branch"),W=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:f.attempt})})," ",p("review"===k.from?"flow.loop.findings":"flow.loop.failed",{stage:p(`flow.stage.${k.from}`),attempt:k.attempt})]})]},"return"),D=f.stages.map((e,t)=>{let n=a6(e,f,a),i=`stage:${e.stage}`,s=e.steps.some(i5);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)(sA,{selectable:sL(e,f,y),selected:w===i,detailId:h,onSelect:()=>x(i),className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:p(`flow.stage.${e.stage}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(a9,{look:n}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:(0,r.jsx)(ss,{view:e,flow:f,live:a,st:p})})]}),s&&(0,r.jsx)("span",{className:"flow-compound",children:p("flow.compound.failed")})]})},e.stage)}),O=[];D.forEach((e,t)=>{O.push(e),t===S&&z&&O.push(z),t===j&&W&&O.push(W)});let H=null;if(w?.startsWith("stage:")){let t=f.stages.find(e=>`stage:${e.stage}`===w);if(t){let n="ci"===t.stage&&null!==f.publication&&"notNeeded"===t.status,i="edit"===t.stage||n?[]:t.steps;H=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:p(`flow.stage.${t.stage}`)}),"ci"===t.stage&&f.publication&&(0,r.jsx)("p",{className:"flow-graph-note",children:"nothingToPublish"===f.publication.kind?p("flow.ci.nothingToPublish",{sha:f.publication.commit.slice(0,7)}):p("flow.ci.notNeeded",{run:f.publication.runId,repo:f.publication.repo,ref:f.publication.ref,sha:f.publication.sha.slice(0,7)})}),"edit"===t.stage&&(0,r.jsx)(rI,{files:e.files,onOpenFile:s}),i.length>0&&(0,r.jsx)(sr,{steps:i,st:p}),(0,r.jsx)(si,{steps:t.earlier,st:p})]})}}else if(w?.startsWith("maker:")){let e=m.makers.find(e=>`maker:${e.maker.member.key}`===w);if(e){let t=r0(e.maker.member,d);H=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,r.jsx)(sP,{entry:e,together:m.makers.length>1,batch:!0,st:p}),(0,r.jsx)("p",{className:"flow-graph-detail-line",children:(0,r.jsx)(sy,{maker:e.maker,st:p})}),(0,r.jsx)("div",{className:"flow-graph-maker-time",children:(0,r.jsx)(s$,{entry:e,st:p})}),(0,r.jsx)(sN,{maker:e.maker}),t&&u?(0,r.jsx)("button",{type:"button",className:"flow-graph-open",onClick:()=>u({key:`live:${t.id}`,toolCallId:e.maker.member.toolCallId,origin:e.maker.member.key,status:{run:e.maker.run,verdict:e.maker.verdict}}),children:p("graph.maker.open")}):(0,r.jsx)("p",{className:"flow-graph-note",children:p("graph.maker.unavailable")})]})}}else("files"===w||"docs"===w)&&(H=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:"files"===w?p(1===m.files.length?"graph.files.one":"graph.files",{count:m.files.length}):p(1===m.docs.length?"graph.docs.one":"graph.docs",{count:m.docs.length})}),(0,r.jsx)(rI,{files:"files"===w?m.files:m.docs,onOpenFile:s})]}));return(0,r.jsxs)("section",{className:"flow-section",children:[(0,r.jsxs)("div",{className:"flow-graph-head",children:[(0,r.jsx)("h4",{className:"flow-heading",children:p("flow.heading")}),(C>=0||N)&&(0,r.jsx)(a5,{paused:v}),I.length>1&&(0,r.jsx)("button",{type:"button",className:"flow-graph-replay",onClick:()=>R(null===E?0:null),children:p(null===E?"graph.replay":"graph.replay.stop")})]}),(0,r.jsx)("div",{className:"flow-graph-frame",children:(0,r.jsxs)("ol",{className:"flow-graph","aria-label":p("flow.aria"),"data-live":a?"":void 0,"data-motion":v?"paused":void 0,"data-replay":null===E?void 0:"",children:[O,T&&(0,r.jsxs)("li",{className:"flow-graph-outputs","data-beat":L("outputs"),children:[(0,r.jsx)("span",{className:"flow-graph-outputs-label",children:p("graph.outputs")}),m.files.length>0&&(0,r.jsx)(sA,{selectable:!0,selected:"files"===w,detailId:h,onSelect:()=>x("files"),className:"flow-graph-output",children:p(1===m.files.length?"graph.files.one":"graph.files",{count:m.files.length})}),m.docs.length>0&&(0,r.jsx)(sA,{selectable:!0,selected:"docs"===w,detailId:h,onSelect:()=>x("docs"),className:"flow-graph-output",children:p(1===m.docs.length?"graph.docs.one":"graph.docs",{count:m.docs.length})})]})]})}),H&&(0,r.jsx)("div",{className:"flow-graph-detail",id:h,role:"region","aria-label":p("graph.detail.aria"),children:H})]})}function sz(e,t,n){let r=new URLSearchParams({type:t});return n&&r.set("sessionId",n),`/api/files/${tC(e)}?${r}`}function sW(e,t){let[n,r]=(0,i.useState)({kind:"loading"});return(0,i.useEffect)(()=>{let n=new AbortController;return r({kind:"loading"}),fetch(e,{method:"head"===t?"HEAD":"GET",cache:"no-store",signal:n.signal}).then(async e=>{if(!e.ok)return null;if("head"===t)return"";if("text"===t)return e.text();let n=await e.json();return"string"==typeof n.content?n.content:null}).then(e=>{n.signal.aborted||r(null===e?{kind:"failed"}:{kind:"ready",content:e})}).catch(()=>{n.signal.aborted||r({kind:"failed"})}),()=>n.abort()},[e,t]),n}function sD({messageKey:e}){let{st:t}=rg();return(0,r.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function sO({deliverable:e,sessionId:t,title:n}){let{filePath:i,kind:a}=e;if("image"===a){let e=sz(i,"read",t);return(0,r.jsx)(sB,{src:e,title:n},e)}if("html"===a){let e=sz(i,"read",t);return(0,r.jsx)(sH,{url:e,title:n},e)}if(i.toLowerCase().endsWith(".pdf")){let e=sz(i,"read",t);return(0,r.jsx)(sU,{url:e,title:n},e)}let s=sz(i,"preview",t);return(0,r.jsx)(s_,{url:s,title:n},s)}function sH({url:e,title:t}){let n=sW(e,"json");return"ready"!==n.kind?(0,r.jsx)(sD,{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 sU({url:e,title:t}){let n=sW(e,"head");return"ready"!==n.kind?(0,r.jsx)(sD,{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 s_({url:e,title:t}){let n=sW(e,"text");return"ready"!==n.kind?(0,r.jsx)(sD,{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 sB({src:e,title:t}){let[n,a]=(0,i.useState)("loading");return"failed"===n?(0,r.jsx)(sD,{messageKey:"result.previewFailed"}):(0,r.jsxs)(r.Fragment,{children:["loading"===n?(0,r.jsx)(sD,{messageKey:"result.previewLoading"}):null,(0,r.jsx)("img",{className:"answer-result-media","data-fit":"contain",src:e,alt:t,draggable:!1,hidden:"loading"===n,onLoad:()=>a("ready"),onError:()=>a("failed")})]})}function sq({deliverables:e,onOpenFile:t}){let{sessionId:n}=(0,i.useContext)(aX),{st:a}=rg(),[o,l]=function(){let e=(0,i.useRef)(null),[t,n]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{let r=e.current;if(!r||t)return;if("u"<typeof IntersectionObserver)return void n(!0);let i=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n(!0)},{rootMargin:"200px 0px"});return i.observe(r),()=>i.disconnect()},[t]),[e,t]}(),[c,...d]=e;if(!c)return null;let u=tN(c.filePath),p=a("result.previewTitle",{name:u}),h=t?()=>t(c.filePath):void 0;return(0,r.jsxs)("section",{className:"answer-result","aria-label":a("result.label"),children:[(0,r.jsxs)("div",{ref:o,className:"answer-result-frame","data-kind":c.kind,children:[l&&(0,r.jsx)(sO,{deliverable:c,sessionId:n,title:p}),h&&(0,r.jsx)("button",{type:"button",className:"answer-result-cover",tabIndex:-1,"aria-hidden":"true",onClick:h})]}),(0,r.jsxs)("div",{className:"answer-result-bar",children:[(0,r.jsxs)("span",{className:"answer-result-title",children:[(0,r.jsx)("span",{className:"answer-result-kind",children:a("html"===c.kind?"result.kind.html":"image"===c.kind?"result.kind.image":c.filePath.toLowerCase().endsWith(".pdf")?"result.kind.pdf":"result.kind.document")}),(0,r.jsx)("span",{className:"answer-result-name",title:c.filePath,children:u})]}),h&&(0,r.jsx)(s.r,{className:"answer-result-open",variant:"neutralSolid",size:"medium",onClick:h,"aria-label":a("result.openNamed",{name:u}),children:a("result.open")})]}),d.length>0&&(0,r.jsxs)("div",{className:"answer-result-more",children:[(0,r.jsx)("span",{className:"answer-result-more-label",children:a("result.more",{count:d.length})}),(0,r.jsx)(rI,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}function sV({summary:e,live:t=!1,onOpenFile:n}){let{ledger:a,subagents:s,toolResults:o}=(0,i.useContext)(aX),{st:l}=rg(),c=(0,i.useMemo)(()=>t?[]:function(e){let t=[];for(let n of e){if(function(e){let t=e.toLowerCase().replace(/\\/g,"/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e];if(Object.hasOwn(sI,n)||n.startsWith(".next")||"doc"===n&&"history"===t[e+1])return!0}return!1}(n.filePath))continue;let e=function(e){let t=eW(e);return"html"===t||"htm"===t?"html":eO(e)?"document":eD(e)?"image":null}(n.filePath);e&&t.push({filePath:n.filePath,kind:e})}return t.map((e,t)=>({deliverable:e,index:t})).sort((e,t)=>sM[e.deliverable.kind]-sM[t.deliverable.kind]||e.index-t.index).map(({deliverable:e})=>e)}(e.files),[t,e.files]),[d,u]=(0,i.useState)(null),p=d??(e.latest&&0===c.length),h=(0,i.useId)(),f=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>rJ(e,o.get(e.toolCallId))??[]).map(e=>rQ(e,s,a)),[e.dispatchCalls,o,s,a]),m=(0,i.useMemo)(()=>f.map(e=>({startedAt:a.spawnedAt.get(e.member.key)??null,durationMs:a.durations.get(e.member.key)??null})),[f,a]),{flow:g,remaining:x}=e,v=e.checks.filter(e=>"failed"===e.state).length,y=e.checks.filter(e=>"failed"===e.state||"unobserved"===e.state).length,b=e.checks.filter(e=>e.compound?.failed).length,w=e.checks.filter(e=>"unverified"===e.state&&!e.compound?.failed).length,k=i4(g.steps).filter(e=>e.stale).length,j=y+f.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted").length;if(0===g.steps.length&&(t||0===e.files.length&&0===e.checks.length&&0===f.length&&!x?.length))return null;let S=[l(1===e.files.length?"summary.files.one":"summary.files",{count:e.files.length}),l(1===e.checks.length?"summary.checks.one":"summary.checks",{count:e.checks.length})];t&&S.unshift(l("summary.live")),v>0&&S.push(l("summary.checksFailed",{count:v})),b>0&&S.push(l("summary.compoundFailed",{count:b})),f.length>0&&S.push(l(1===f.length?"summary.makers.one":"summary.makers",{count:f.length})),x&&S.push(l("summary.remaining",{count:x.length})),!t&&j>0&&S.push(l("summary.unverified",{count:j})),w>0&&S.push(l(1===w?"summary.verdictUnverified.one":"summary.verdictUnverified",{count:w})),k>0&&S.push(l("summary.stale",{count:k}));let C=!t&&j>0||v>0||w>0||b>0||k>0;return(0,r.jsxs)("div",{className:"answer-summary","data-open":p?"":void 0,"data-live":t?"":void 0,"data-result":c.length>0?"":void 0,children:[c.length>0&&(0,r.jsx)(sq,{deliverables:c,onOpenFile:n}),(0,r.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":p,"aria-controls":h,title:l(p?"summary.collapse":"summary.expand"),onClick:()=>u(!p),children:[(0,r.jsx)("span",{className:"answer-summary-text","data-unverified":C?"":void 0,children:S.join(" \xb7 ")}),(0,r.jsx)("svg",{className:"answer-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),p&&(0,r.jsxs)("div",{className:"answer-summary-body",id:h,children:[g.steps.length>0&&(0,r.jsx)(sF,{summary:e,makers:f,timings:m,live:t,onOpenFile:n}),x&&(0,r.jsxs)("section",{className:"flow-remaining",children:[(0,r.jsx)("h4",{className:"flow-heading",children:l("summary.heading.remaining")}),0===x.length?(0,r.jsx)("p",{className:"answer-summary-empty",children:l("summary.todo.none")}):(0,r.jsx)("ul",{className:"flow-remaining-list",children:x.map((e,t)=>(0,r.jsxs)("li",{className:"answer-remaining","data-status":e.status,title:e.phase||void 0,children:[(0,r.jsx)("span",{className:"answer-remaining-status",children:l(`summary.todo.${e.status}`)}),(0,r.jsx)("span",{className:"answer-remaining-text",children:e.content}),e.blocker&&(0,r.jsx)("span",{className:"answer-remaining-blocker",children:l("summary.todo.blocker",{blocker:e.blocker})})]},`${e.phase}#${t}`))})]})]})]})}let sK=/^att_[0-9a-f]{32}$/,sG=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function sJ(e){return"string"==typeof e&&sK.test(e)}function sZ(e){return"string"==typeof e&&sG.test(e)}class sY extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let sX={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},sQ={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},s0={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function s1(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&&sQ[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&s0[r]?"text":null}let s2={".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 s8(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?s2[t.slice(n)]:void 0;if(r)return r;let i=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return i?.startsWith("audio/")?i:null}function s4(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function s5(e){if(!Array.isArray(e))return[];let t=[],n=0,r=0;for(let i of e){if(i&&"object"==typeof i&&"string"==typeof i.name&&i.name.length>0&&("text/markdown"===i.mimeType||"text/plain"===i.mimeType||"application/pdf"===i.mimeType)&&"number"==typeof i.size&&Number.isSafeInteger(i.size)&&i.size>=0&&i.size<=8388608&&"string"==typeof i.text&&i.text.length<=12e4){if(t.length>=3)break;!(n+i.size>0x1000000)&&(r+i.text.length>24e4||(t.push({name:i.name,mimeType:i.mimeType,size:i.size,text:i.text,...sJ(i.attachmentId)?{attachmentId:i.attachmentId}:{}}),n+=i.size,r+=i.text.length))}}return t}async function s6(e){let t,n=s1(e);if(!n)throw new sY("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new sY("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await os(e);else{try{t=await e.text()}catch(e){throw new sY("read_failed",e instanceof Error?e.message:String(e))}oo(t)}return{name:e.name,mimeType:sX[n],size:e.size,text:t}}function s3(e,t){let n=s5(t);if(0===n.length)return e;let r={userMessageLength:e.length,documents:n.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,textLength:r.length}))},i=`${ol}${JSON.stringify(r)}${oc}
|
|
@@ -16,7 +16,7 @@ Attached: ${n}`:`Attached: ${n}`}(g)).then(()=>{m(!0),setTimeout(()=>m(!1),1500)
|
|
|
16
16
|
${t}`)),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{if(void 0!==a)return;let n=!0;return(function(e,t){let n=`${e}
|
|
17
17
|
${t}`,r=eJ.get(n);if(void 0!==r)return Promise.resolve(r);let i=eZ.get(n);if(i)return i;let a=fetch(eV(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),r=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return eJ.set(n,r),r}).catch(()=>0).finally(()=>eZ.delete(n));return eZ.set(n,a),a})(e,t).then(e=>{n&&s(e)}),()=>{n=!1}},[a,e,t]),!a)return null;let u=Array.from({length:a},(e,t)=>t).filter(e=>!c.has(e));return 0===u.length?null:(0,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(i=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>l(i),children:(0,r.jsx)("img",{src:eV(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(i))})},i)),null!==o&&(0,r.jsx)(oR,{src:eV(e,t,o),fileName:`screen-${t.slice(-8)}-${o+1}`,onClose:()=>l(null)})]})}let oM={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function oR({src:e,fileName:t,onClose:n}){let{t:a}=(0,F.s)(),o=(0,i.useContext)(np),l=(0,i.useRef)(null),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)([]),[m,g]=(0,i.useState)(null),x=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=l.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{x.current?.abort(),document.body.style.overflow=t,e.open&&e.close()}},[]);let v=()=>{x.current?.abort(),n()},y=async()=>{let r,i;if(!o)return void p(a("toolImage.noComposer"));x.current?.abort();let s=new AbortController;x.current=s,d(!0),p(null);try{let n=await fetch(e,{signal:s.signal});if(!n.ok)throw Error(`HTTP ${n.status}`);let o=await n.blob(),l=oM[o.type];if(!l)throw Error(`unsupported ${o.type}`);if(0!==h.length&&m){let e=await nb(o,h);r=[new File([e.marked],`${t}-marked.png`,{type:"image/png"}),...e.crops.map((e,n)=>new File([e],`${t}-region-${n+1}.png`,{type:"image/png"}))];let n=1===h.length?"1":`1~${h.length}`;i=[a("toolImage.locatorIntro",{range:n}),...h.map((e,t)=>a("toolImage.locatorRegion",{n:t+1,x:e.x,y:e.y,w:e.w,h:e.h,width:m.width,height:m.height}))].join("\n")+"\n"}else r=[new File([o],`${t}.${l}`,{type:o.type})]}catch{if(s.signal.aborted)return;d(!1),p(a("toolImage.loadFailed"));return}if(!s.signal.aborted&&l.current?.open){if(!o(r,i)){d(!1),p(a("toolImage.noComposer"));return}n()}};return(0,_.createPortal)((0,r.jsxs)("dialog",{ref:l,className:"tool-image-dialog","aria-label":a("toolImage.dialogLabel"),onCancel:e=>{e.preventDefault(),v()},onClick:e=>{e.target===e.currentTarget&&v()},children:[(0,r.jsx)(nw,{src:e,regions:h,max:9,onAdd:e=>f(t=>t.length<9?[...t,e]:t),onNaturalSize:g,regionLabel:e=>a("toolImage.regionLabel",{n:e})}),u?(0,r.jsx)("p",{role:"alert",className:"tool-image-error",children:u}):(0,r.jsx)("p",{className:"tool-image-hint","data-hidden":h.length>0&&h.length<9?"true":void 0,children:h.length>=9?a("toolImage.markLimit",{count:9}):a("toolImage.markHint")}),(0,r.jsxs)("div",{className:"tool-image-actions",children:[(0,r.jsx)(s.r,{variant:"neutralSolid",size:"medium",loading:c,onClick:()=>void y(),title:a("toolImage.requestEditHint"),children:a("toolImage.requestEdit")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",disabled:0===h.length,onClick:()=>f([]),children:a("toolImage.clearMarks")}),(0,r.jsx)(s.r,{variant:"neutralWeak",size:"medium",onClick:v,children:a("i18n.close")})]})]}),document.body)}function oE({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(ox,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function oL({block:e,duration:t,sessionId:n,entryId:a,blockIndex:s}){let{t:o}=(0,F.s)(),[l,c]=(0,i.useState)(null),[d,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){c(null),u(!1),h(null);return}let t=!1;return n&&a?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=og.get(r);if(i)return og.delete(r),og.set(r,i),i;let a=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw og.delete(r),e});if(og.set(r,a),og.size>100){let e=og.keys().next().value;e&&og.delete(e)}return a})(n,a,s).then(e=>{t||c(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(o("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,s,a,n,o]);let f=e.deferred?l:e.thinking,m="string"==typeof f&&f.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":o("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:d?(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):m?(0,r.jsx)(nc,{className:"markdown-thinking-body",children:f}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:o("chat.thinking")})}),void 0!==t&&m&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function o$({block:e,result:t,duration:n,runStartedAt:a}){let s,{t:o}=(0,F.s)(),l=(0,i.useId)(),[c]=(0,i.useState)(()=>Date.now()),[d,u]=(0,i.useState)(null),p=e.toolName.toLowerCase(),h=JSON.stringify(e.input,null,2),f="todo"===p||p.endsWith(".todo")||p.endsWith("_todo"),m="bash"===p||p.startsWith("bash ")||p.endsWith(".bash")||p.endsWith("_bash"),g=t&&!t.isError?function(e){var t;let n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let i="string"==typeof n.diff?n.diff:null;return i?{text:i}:null}(t):null,x=f?"unknown"===(s=tb(e,t)).kind||0===s.phases.length?null:s.phases:null,v=g?g.text.split(/\r?\n/).reduce((e,t)=>(t.startsWith("+")&&!t.startsWith("+++")&&(e.added+=1),t.startsWith("-")&&!t.startsWith("---")&&(e.removed+=1),e),{added:0,removed:0}):null,y=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,b=null!==y&&("(no output)"===y.trim()||""===y.trim()),w=t?nS(t):null,k=t?t.isError||null!==w&&0!==w?"failed":"done":"running",j="failed"===k,S=d??j;if(f&&x)return(0,r.jsx)(oD,{phases:x});let C=m&&"string"==typeof e.input.command?e.input.command:"",N=!!(x||g),T=m?C.split(/\r?\n/,1)[0]??"":function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.length)return"";let i=e.toolName.toLowerCase();if(t=i,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(-120);if("file_path"in n)return String(n.file_path).slice(-120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let a=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==a)return String(a).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,x),I=!m&&/^\S+$/.test(T)&&/[\\/]/.test(T),M=v?o("toolRun.diffStats",{added:v.added,removed:v.removed}):"";return(0,r.jsxs)("div",{className:`tool-call-card ${j?"is-error":"running"===k?"is-running":"is-done"}${m?" is-shell":""}`,"aria-busy":"running"===k||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,r.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>u(!S),"aria-expanded":S,"aria-controls":S?l:void 0,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,r.jsx)(oz,{toolName:e.toolName}),(0,r.jsx)("span",{className:"tool-call-name",children:m?"bash":e.toolName}),m&&p.includes("(local)")&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"}),(0,r.jsx)("span",{className:`tool-call-target${I?" is-path":""}`,title:m?C:T,children:I?(0,r.jsx)("bdi",{dir:"ltr",children:T}):T}),v&&(0,r.jsxs)("span",{className:"tool-call-diffstats",title:M,"aria-label":M,children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",v.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",v.removed]})]}),(0,r.jsx)(oP,{state:k,duration:n,exitCode:w,startedAt:a??c}),(0,r.jsx)("svg",{className:"tool-call-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:S?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),S&&(0,r.jsx)("div",{id:l,className:"tool-call-body",children:m?(0,r.jsx)(oO,{command:C,output:y??"",pending:!t,isError:j}):(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(oH,{diff:g})}),t&&j&&(0,r.jsx)(oV,{text:y??"",isEmpty:b,isError:!0}),!N&&(0,r.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:h}),t&&!N&&!j&&(0,r.jsx)(oV,{text:y??"",isEmpty:b,isError:!1})]})})]})}function oP({state:e,duration:t,exitCode:n,startedAt:i}){let{t:a}=(0,F.s)();return"running"===e?(0,r.jsx)(oA,{startedAt:i}):(0,r.jsxs)(r.Fragment,{children:[void 0!==t&&(0,r.jsxs)("span",{className:"tool-run-duration",children:[t,"s"]}),"failed"===e&&(0,r.jsxs)("span",{className:"tool-run-failed",children:[(0,r.jsx)(nu.E,{tone:"critical",variant:"weak",size:"medium",children:a("toolRun.failed")}),null!==n&&(0,r.jsx)("span",{className:"tool-run-exit",children:a("toolRun.exitCode",{code:n})})]})]})}function oA({startedAt:e}){let{t}=(0,F.s)(),n=nd(500)-e;return n<400?null:(0,r.jsxs)("span",{className:"tool-run-running",children:[t("toolRun.running"),(0,r.jsxs)("span",{className:"tool-run-duration",children:[Math.floor(n/1e3),"s"]})]})}function oF(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function oz({toolName:e}){let t,n=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||oF(t,"edit")?"edit":oF(t,"read")||oF(t,"cat")?"read":oF(t,"write")||oF(t,"save")?"write":oF(t,"glob")||oF(t,"find")?"glob":oF(t,"grep")||oF(t,"search")?"grep":oF(t,"bash")||oF(t,"shell")||oF(t,"exec")?"bash":oF(t,"todo")?"todo":oF(t,"eval")?"eval":oF(t,"task")||oF(t,"agent")?"task":oF(t,"browser")||oF(t,"web_search")||oF(t,"fetch")?"browser":oF(t,"image")||oF(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)(oW,{kind:n})})})}function oW({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 oD({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)(rw,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function oO({command:e,output:t,pending:n,isError:i}){let{isDark:a}=nr(),{t:s}=(0,F.s)(),o=eL(t.split(/\r?\n/)),l=1===o.length&&""===o[0]?[]:o;return(0,r.jsxs)("div",{className:`shell-output-preview${i?" is-error":""}`,children:[(0,r.jsxs)("div",{className:"shell-command-line",children:[(0,r.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,r.jsx)(tI.A,{className:"shell-command-code",language:"bash",style:a?tM.xJ:tM.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsx)("div",{className:"shell-output-divider",children:(0,r.jsx)("span",{className:"shell-output-label",children:"Output"})}),(0,r.jsxs)("div",{className:"shell-output-body",children:[0===l.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:s("i18n.noOutput")}),l.map((e,t)=>{let n=eI(e).trimStart(),a=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${a}`.trim(),children:[e$(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 oH({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(oU,{text:e.text})})}function oU({text:e}){let{t}=(0,F.s)(),n=(0,i.useMemo)(()=>ry(e),[e]);if(!n)return(0,r.jsx)(oq,{text:e});let a=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[a&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(o_,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(o_,{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)(oB,{cell:e.left,side:"left"}),(0,r.jsx)(oB,{cell:e.right,side:"right"})]},t))})]},n))})}function o_({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 oB({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:a,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function oq({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 oV({text:e,isEmpty:t,isError:n}){let{t:i}=(0,F.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--danger-line)":"var(--success-line)"}`,background:n?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?i("i18n.noOutput"):e})})}function oK({message:e}){let{t}=(0,F.s)(),n=oY(e.content),a=(0,i.useMemo)(()=>{let e,t,r,i,a;return e=[],t=[],r=n.match(nN),i=r?.[1]??"",a=r?.index===void 0?n:n.slice(0,r.index),i.replace(nC,(n,r,i)=>{let a=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...a):t.push(...a),""}),{body:a.trim(),readFiles:e,modifiedFiles:t}},[n]),s=ow(e.timestamp),o=e.details&&"object"==typeof e.details&&"tokensBefore"in e.details&&"number"==typeof e.details.tokensBefore&&e.details.tokensBefore>0?e.details.tokensBefore:null;return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==o&&(0,r.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:nT(o)})}),s&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),a.body?(0,r.jsx)(nc,{className:"markdown-compaction-message",children:a.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(oG,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function oG({readFiles:e,modifiedFiles:t}){let{t:n}=(0,F.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(oJ,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(oJ,{title:n("i18n.readFiles"),files:e})]})}function oJ({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 oZ({message:e,cwd:t,onOpenFile:n}){var a;let s,{t:o}=(0,F.s)(),l=!1===e.display,[c,d]=(0,i.useState)(!l),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1),m=oY(e.content),g="string"==typeof(a=e.content)?[]:a.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",y=e.customType||"extension",b=ow(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:l?"var(--bg-subtle)":"var(--bg)",opacity:l&&!c?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:y}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:o("i18n.hiddenExtensionMessage")}),b&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:b})]}),c?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!m},children:g.map((e,t)=>{let n=oX(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),m?(0,r.jsx)(nc,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:m}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:o("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?(s=m.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":o("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[m||v?(0,r.jsx)("button",{onClick:()=>{ni(m||v).then(()=>{f(!0),setTimeout(()=>f(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(h?"i18n.copied":"i18n.copy")}):null,(x||l)&&(0,r.jsx)("button",{onClick:()=>{l?d(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:o(l?c?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(l&&c||!l&&u)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function oY(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function oX(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 oQ({message:e,sessionId:t}){let[n,a]=(0,i.useState)(null),[s,o]=(0,i.useState)(!1),[l,c]=(0,i.useState)(null),d=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===n,f=n??e.output;async function m(){if(p){o(!0),c(null);try{let e=await fetch(p),t=await e.json();t.success?a(t.data?.output??""):c(t.error??"failed")}catch(e){c(String(e))}finally{o(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=d?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:f?[{type:"text",text:f}]:[],isError:u,details:void 0!==e.exitCode?{exitCode:e.exitCode}:void 0,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(o$,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:m,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),l&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",l,")"]})]})]})}n(21340);let o0="cuelo-chat-search",o1="cuelo-chat-search-active";function o2(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 o8({open:e,onClose:t,containerRef:n,index:a,renderedStart:s,renderedEnd:o,contentKey:l,onReveal:c,onProgrammaticScroll:d,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[f,m]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,y]=(0,i.useState)({index:-1,total:0}),b=(0,i.useDeferredValue)(f),w=e?b.trim().toLowerCase():"",k=(0,i.useRef)(g);k.current=g;let j=(0,i.useRef)([]),S=(0,i.useRef)({key:null,needle:"",rendered:!1});(0,i.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,i.useEffect)(()=>()=>{o2(o0,[]),o2(o1,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){o2(o0,[]),o2(o1,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},y(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),i=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let a=(e.textContent??"").toLowerCase(),s=n.get(i);s||(s=[],n.set(i,s));for(let n=a.indexOf(t);-1!==n;n=a.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),s.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,i){let a=[];if(!t)return a;for(let s=0;s<e.length;s++){let o=s>=r&&s<i?n.get(s)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[s],t);for(let e=0;e<o;e++)a.push({item:s,k:e})}return a}(a,w,n,s,o);j.current=r;let i=te(r,k.current);y(e=>e.index===i&&e.total===r.length?e:{index:i,total:r.length});let l=[];for(let t of e.values())for(let e of t)l.push(e);if(o2(o0,l),i<0){o2(o1,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=s&&u.item<o,f=S.current,m=f.needle!==w||f.key?.item!==u.item||f.key?.k!==u.k||!f.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){o2(o1,[]),m&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(o2(o1,g?[g]:[]),m)if(d(),g){let e,n;e=g.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,a,s,o,l,g,n,c,d]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=te(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=f.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,r.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsx)("input",{ref:h,type:"search",value:f,onChange:e=>m(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,r.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,r.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}function o4({questions:e,containerRef:t,layoutKey:n,onJump:a,label:s}){let o=(0,i.useRef)(null),[l,c]=(0,i.useState)(-1),[d,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=d&&e.length>=2;(0,i.useEffect)(()=>{let n=t.current;if(!n||!p)return;let r=0,i=null,a=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,a=0,s=i.length-1,o=i.length-1;for(;a<=s;){let e=a+s>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(o=e,s=e-1):a=e+1}let l=o>=0?Number(i[o].dataset.chatItem):-1,d=-1;for(let t of e){if(t.item>l)break;d=t.item}c(d)},s=()=>{r||(r=requestAnimationFrame(a))};return r=requestAnimationFrame(a),n.addEventListener("scroll",s,{passive:!0}),()=>{n.removeEventListener("scroll",s),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,i.useEffect)(()=>{let e=o.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let n=t.offsetTop-e.scrollTop;(n<0||n+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[l]);let h=e.length,f=(0,i.useCallback)((e,t)=>{let n="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===n)return;e.preventDefault();let r=Math.max(0,Math.min(h-1,n));o.current?.querySelectorAll("button")[r]?.focus()},[h]);if(!p)return null;let m=e.some(e=>e.item===l)?l:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,r.jsx)("div",{ref:o,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(o5,{question:e,position:t,count:h,active:e.item===l,focusable:e.item===m,onJump:a,onMoveFocus:f},e.item))})})}let o5=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:a,onJump:s,onMoveFocus:o}){let l=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,r.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:a?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${l}`,title:l,onClick:()=>s(e.item),onKeyDown:e=>o(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function o6({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 o3={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function o7({compaction:e,t}){let[n,a]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;a(Date.now());let t=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((n-e.startedAt)/1e3)),o=e.reason&&!0===o3[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(o6,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),o?` \xb7 ${o}`:""]})}function o9({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 le=n(39092),lt=n.n(le);let ln=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","MITSU(미츠)","SHION(시온)","HIKARI(히카리)"],lr={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","MITSU(미츠)":"mitsu","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},li=["approval","choice","done","failed","blocked","working"],la={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},ls={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function lo(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function ll(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(la,e)?e:null}function lc(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:a,ko:s}=i;if("string"!=typeof e||""===e)continue;let o=ll(a);if(null===o)continue;let l=t+e.replace(/^\/+/,""),c=n.get(o);c?c.push(l):n.set(o,[l]),"string"==typeof s&&""!==s.trim()&&r.set(l,s.trim())}return{files:n,lines:r}}function ld(e,t,n){let r=t&&Object.hasOwn(lr,t)?lr[t]:null;return r?e.get(r)?.get(n)??null:null}async function lu(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return function(e){let t=new Map;if("object"!=typeof e||null===e)return t;let{characters:n}=e;if(!Array.isArray(n))return t;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:r,stickers:i,captions:a}=e;if("string"!=typeof n||""===n)continue;let s=lc(r,"/audio/completion/"),o=lc(i,"/stickers/"),l=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if("object"!=typeof n||null===n)continue;let{tag:e,ko:r}=n;if("string"!=typeof r||""===r.trim())continue;let i=ll(e);if(null===i)continue;let a=t.get(i);a?a.push(r.trim()):t.set(i,[r.trim()])}return t}(a),c=new Map;for(let e of li){let t=s.files.get(e)??[],n=new Map;for(let e of t){let t=s.lines.get(e);void 0!==t&&n.set(e,t)}c.set(e,{voices:t,stickers:o.files.get(e)??[],lines:n,captions:l.get(e)??[]})}t.set(n,c)}return t}(await t.json())}catch{return new Map}}function lp(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,a=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&a>=r?a+1:a]}function lh(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 lf(e,t,n,r){if(t&&("web6"!==t.provider||t.model!==lm))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!==lm))return{provider:n.provider,model:n.model,credentialId:n.credentialId}}return{provider:n,model:r,credentialId:void 0}}let lm="ChatGPT 6PRO",lg=["01","02","03"];function lx(e,t,n){if(!e||"streaming"===t||!ln.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),a=lp(lg.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>(function(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})(n));return a?{src:a,alt:la[r]}:null}let lv=new Map,ly=(0,i.createContext)(lv);function lb({utterances:e,children:t}){return(0,r.jsx)(ly.Provider,{value:e,children:t})}function lw({turnIndex:e,turnEntryId:t,sessionId:n,cwd:a,onOpenFile:s}){let o=(0,i.useContext)(ly).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)(lk,{utterance:e,sessionId:n,cwd:a,onOpenFile:s},e.key))}):null}function lk({utterance:e,sessionId:t,cwd:n,onOpenFile:a}){let s=rf(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId,e.model),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),u=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=u.current;e&&!o&&d(e.scrollHeight>e.clientHeight+1)},[e.text,o]);let p=e.text.trim().length>0,h=e.label?.trim(),f=s?.alias??h??nZ(e.provider),m=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==m?`작업 \xb7 ${h}`:null,x=lx(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)(rx,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:f}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...o?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(nc,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:a,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(c||o)&&(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>!e),"aria-expanded":o,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:o?"접기":"더보기"}),x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-e0a9ca790f024efb inline-utterance-sticker"}),(0,r.jsx)(lt(),{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 lj=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function lS(e,t,n,r){if("string"!=typeof n)return[];let i=lj.exec(n),a=i?.[1],s=i?.[2];return a&&s?[{toolCallId:e,...t?{name:t}:{},alias:a,model:s,batchSize:r}]:[]}function lC(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(...lS(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let i of e.tasks)!i||"object"!=typeof i||Array.isArray(i)||t.push(...lS(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function lN(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 lT=/^agent:\/\/([^/?#]+)\/?$/i;function lI(e,t){if(!e||"assistant"!==e.role)return[];let n=[];for(let r of e.content??[]){if("toolCall"!==r.type||"write"!==r.toolName)continue;let e=r.input,i="string"==typeof e.path?lT.exec(e.path):null,a=i?.[1],s=e.content;if(!a||"string"!=typeof s)continue;let o=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:a,message:s,...o?.from?{from:o.from}:{},...o?.receipts?{receipts:o.receipts}:{}})}return n}function lM(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 lR=["greeting","utterance","message","text"],lE=function(e){let t=(0,i.useMemo)(()=>rD(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let a of n.subagents){if(t.has(a.name))continue;let n=[...i].reverse().find(e=>e.name===a.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},a="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,s="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==a||void 0!==s)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==a?{resolvedModel:a,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),i}(a,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),a="string"==typeof t.task?lj.exec(t.task):null,s=a?.[1],o=a?.[2],l=i.find(e=>e.name===t.id)??(s&&o?r.requests.find(e=>e.alias===s&&e.model===o):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!l)return[];let c=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:r.turnIndex,summon:l,sends:c}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),a=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),s=aY(a,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&a.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:a}=e,s="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",o="failed"===s,l=a?.model.split("/",1)[0]?.trim()||void 0,c=o&&l?l:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=r.indexOf("/");if(i>0)return r.slice(0,i);let a=t?.model.trim()??"",s=a.indexOf("/");return s>0?a.slice(0,s):n?.trim()||void 0}(i,a,n),d=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,f=0;if((t?.entries??[]).forEach((t,n)=>{var r;let m;if("irc"in t){let{from:n,message:r,truncated:a}=t.irc;if(a||"string"!=typeof n||"string"!=typeof r)return;for(let t=f;t<e.sends.length;t+=1){let a=e.sends[t];if(a.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(a.send,i.id)&&a.send.from===n){h=a.turnIndex,f=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||c;if(!g||o&&l&&g!==l)return;let x=((m=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?m:function(e){let t="";for(let n of e.content??[]){if("toolCall"!==n.type||"yield"!==n.toolName)continue;let e=n.input.data,r="";if("string"==typeof e)r=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...lR]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let i=r.trim();i.length>0&&(t=i)}return t}(r))||(o?t.message.errorMessage?.trim()??"":"");if(0===x.length)return;let v=t.message.model||lM(i,a,g);p.push({key:`${i.id}:${n}`,turnIndex:h,speakerId:u,provider:g,...v?{model:v}:{},credentialId:t.message.credentialId,accountSessionId:null,label:o&&a?a.alias:d,text:x,status:s})}),0===p.length&&"settled"!==s&&c){let e=o?i.progress?.retryFailure?.errorMessage?.trim():void 0,t=lM(i,a,c);p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:c,...t?{model:t}:{},accountSessionId:null,label:o&&a?a.alias:d,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[r,s,e.sessionProvider])},lL="web6",l$=[],lP=[],lA=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let a=`${t}?sessionId=${encodeURIComponent(i)}`,s=await e(a,{signal:r});if(!s.ok)throw Error(`HTTP ${s.status}`);let o=await s.json(),l=o&&"object"==typeof o&&"consults"in o?o.consults:null;if(!Array.isArray(l))throw Error("consults 배열이 아니다");return l.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:a,text:s,error:o}=e;return{sessionId:t,startedAt:n,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof a&&""!==a?a:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof o&&""!==o?o:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(lP),a=(0,i.useRef)(""),s=e.sessionId??"",o=s.length>0;return(0,i.useEffect)(()=>{if(!o){a.current="",r(lP);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(s,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===a.current)return;a.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,o,s]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return l$;let r=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if("user"!==r.role)continue;let i=r.timestamp;"number"==typeof i&&Number.isFinite(i)&&t.push({index:n,openedAt:i})}return t}(t);if(0===r.length)return l$;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let a=t.error??"";0!==a.trim().length&&i.push({key:`${lL}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${lL}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return i.length>0?i:l$})(n,e.messages,s),[n,e.messages,s])},lF={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},lz={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function lW({rows:e,removeLabel:t,onRemove:n}){let a,{st:s}=rg(),[o,l]=(0,i.useState)(!1),{rows:c,hidden:d}=(a=Math.max(0,e.length-4),o||0===a?{rows:e,hidden:a}:{rows:e.slice(a),hidden:a}),u=e.length>4;return(0,i.useEffect)(()=>{u||l(!1)},[u]),(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":o,onClick:()=>l(e=>!e),children:o?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:d})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:c.map(e=>{let i=s7(e.text),a=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?s(1===e.images?"delivery.images.one":"delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,r.jsx)("span",{className:"answer-delivery-kind",children:s(lF[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:s(lz[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${a}`,onClick:()=>n(e.kind,e.text),children:(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}let lD=(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"})]}),lO=(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 lH({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?lD:lO})})})}let lU=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),l_=["normal","slow"],lB={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function lq(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(a),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},a=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}function lV(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let lK={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},lG=(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"})]}),lJ=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function lZ({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:a}=(0,F.s)(),s=function(e,t,n){let{locale:r}=(0,F.s)(),[a,s]=(0,i.useState)("idle"),[o,l]=(0,i.useState)(null),[c,d]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[m,g]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),y=(0,i.useRef)(null),b=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{f("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,i.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,b.current?.close(),b.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let n=y.current;y.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,i.useCallback)((e,t)=>{l(e),d(t??null),j("error")},[j]),C=(0,i.useCallback)(async()=>{let i,a=k.current+1;k.current=a,l(null),d(null),g(!0),s("connecting");let o=e;if(!o&&t){try{o=await t()}catch{o=void 0}if(k.current!==a)return}if(!o){k.current===a&&(g(!1),S("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===a&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==a){for(let e of i.getTracks())e.stop();return}v.current=i;try{let e,t,l=new RTCPeerConnection;for(let e of(x.current=l,i.getTracks()))l.addTrack(e,i);let c=document.createElement("audio");if(c.autoplay=!0,y.current=c,l.ontrack=e=>{let[t]=e.streams;t&&(c.srcObject=t)},await l.setLocalDescription(await l.createOffer()),await lq(l),k.current!==a)return;let d=l.localDescription?.sdp;if(!d)throw Error("The browser produced no offer SDP.");let u=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,sdp:d,locale:r})}),h=await u.json().catch(()=>({})),f="",m="";if(h&&"object"==typeof h&&("error"in h&&(e=h.error),"message"in h&&"string"==typeof h.message&&(t=h.message),"callId"in h&&"string"==typeof h.callId&&(f=h.callId),"sdp"in h&&"string"==typeof h.sdp&&(m=h.sdp)),!u.ok||!f||!m){k.current===a&&(g(!1),S(lV(u.status,e),t));return}if(k.current!==a)return void fetch(`/api/live/call/${encodeURIComponent(f)}`,{method:"DELETE"}).catch(()=>{});if(await l.setRemoteDescription({type:"answer",sdp:m}),k.current!==a){l.close(),fetch(`/api/live/call/${encodeURIComponent(f)}`,{method:"DELETE"}).catch(()=>{});return}w.current=f;let v=new EventSource(`/api/live/events?callId=${encodeURIComponent(f)}`);b.current=v,v.onmessage=e=>{let t;if(k.current===a){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;if("string"!=typeof t.state||(r=t.state,!0!==lB[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&&lU.test(e)&&j("idle")}return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},v.onerror=()=>{k.current===a&&w.current&&S("failed")},s("live")}catch(e){k.current===a&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===a&&g(!1)}},[e,t,n,r,S,j]),N=(0,i.useCallback)(()=>{if("idle"===a||"closed"===a||"error"===a){m||C();return}j("idle")},[m,a,C,j]);return(0,i.useEffect)(()=>()=>j("closed"),[j]),{state:a,failure:o,detail:c,transcript:u,supported:h,toggle:N}}(e,t,n),o="connecting"===s.state||"live"===s.state||"working"===s.state,l="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,c=a(o?"chat.liveStop":"chat.liveStart"),d=!1===s.supported?lK.unsupported:s.failure?lK[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,r.jsxs)("div",{role:"group","aria-label":a("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[d&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:a(d)}),l&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a(l)}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${o?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":o,title:p?a(p):c,"aria-label":p?a(p):c,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o?lJ:lG})})]})}let lY={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 lX({sessionId:e}){let{t}=(0,F.s)(),[n,a]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void a(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let s=Array.isArray(i.handles)?i.handles:[],o=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==o,a(o)}catch{}},s=async()=>{await i(),t||(n=window.setTimeout(()=>void s(),r?5e3:3e4))};return s(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:lY,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}let lQ=new Map,l0="ompweb-drafts-for-reload-v1",l1=!1,l2=new Map,l8=new Map,l4="\0stale",l5=new Map,l6=0,l3=new Map,l7=new Map,l9=new Map,ce=new Map,ct=new Map,cn=(e,t,n)=>oa(e,t,n.length?{sentAttachmentIds:n}:{}),cr=null,ci=!1;function ca(){if(l1||"u"<typeof sessionStorage)return;l1=!0;let e=sessionStorage.getItem(l0);if(e){sessionStorage.removeItem(l0);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)&&(lQ.set(e[0],co(t)),"string"==typeof t.draftId&&t.draftId&&(l2.set(e[0],t.draftId),l8.set(t.draftId,l4)),cg(e[0]))}}catch{}}}function cs(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(l0,JSON.stringify([...lQ.entries()].map(([e,t])=>{let n=l2.get(e);return[e,n?{...co(t),draftId:n}:co(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function co(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function cl(e){return!e.value&&0===e.images.length&&0===e.documents.length}function cc(e){ca();let t=lQ.get(e);return t?co(t):null}function cd(e,t){ca(),cl(t)?lQ.delete(e):lQ.set(e,co(t)),cg(e)}function cu(e){lQ.delete(e),cg(e)}function cp(e,t,n,r,i,a=[]){let s=[...t??[],...r].filter(nj).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=s5([...i??[],...a]);return{value:e.trim()?n.trim()?`${e}
|
|
18
18
|
|
|
19
|
-
${n}`:e:n,images:s,documents:o}}function ch(e,t,n){if(e===t)return n?co(n):cc(t);let r=cc(e),i=n&&!cl(n)?co(n):r??(n?co(n):null),a=cc(t),s=l2.get(e);if(l2.delete(e),s&&!l2.has(t)&&l2.set(t,s),cu(e),!i)return a;let o=a?cp(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return cd(t,o),co(o)}function cf(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function cm(e){ca();let t=l2.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)}`}(),l2.set(e,t)),t}function cg(e){let t=cf(lQ.get(e)?.documents),n=t.length?cm(e):l2.get(e);for(let[e,n]of l7){for(let e of t)n.delete(e);0===n.size&&l7.delete(e)}let r=`${n??""}|${t.join(",")}`;ce.get(e)!==r&&(0!==t.length||n?ce.set(e,r):ce.delete(e),cj())}async function cx(e){let t=cm(e);l3.set(t,(l3.get(t)??0)+1),await ct.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(l3.get(t)??1)-1;if(r>0?l3.set(t,r):l3.delete(t),e){let n=l7.get(t)??new Set;n.add(e),l7.set(t,n)}l8.set(t,l4),cj()}}}function cv(e,t){let n=l9.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&l9.delete(e),[...n].sort()}async function cy(){if(!cn)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 l2)t(n,cf(lQ.get(e)?.documents));for(let{draftId:e,ids:n}of l5.values())t(e,n);for(let[e,n]of l7)t(e,n);for(let e of l8.keys())t(e,[]);for(let e of l9.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(l3.has(e))return!1;let n=l8.get(e);return cv(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=l3.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=cv(r,i),a=cn(r,i,e).then(()=>{0===i.length?l8.delete(r):l8.set(r,i.join(","));let t=l9.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&l9.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});ct.set(r,a),await a,ct.get(r)===a&&ct.delete(r)}n?function(){if(ck)return;ck=!0;let e=setTimeout(()=>{ck=!1,cj()},cw);"object"==typeof e&&"unref"in e&&e.unref(),cw=Math.min(2*cw,6e4)}():cw=cb}let cb=5e3,cw=5e3,ck=!1;function cj(){if(cn){if(cr){ci=!0;return}cr=Promise.resolve().then(cy).finally(()=>{cr=null,ci&&(ci=!1,cj())})}}let cS=Math.floor(Number.MAX_SAFE_INTEGER/1048576),cC=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function cN(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=cS}async function cT(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!cN(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:cN((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:cC.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:cC.autoCleanupEnabled,orphanGraceDays:7}}async function cI(e={}){return cT(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function cM(e){return cT(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function cR(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 cE(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function cL(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 c$(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function cP(e,t,n){let r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`;return`${a}${s} `}let cA="omp-web:model-picks";function cF(){try{let e=JSON.parse(window.localStorage.getItem(cA)??"{}");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 cz(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*s)),c=Math.max(0,e-a-s),d=Math.max(0,n-t-a-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=r||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(r,h?u:p))}}function cW(e,t,n){return Math.min(e*t,n)}function cD(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,i.useState)({side:c??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),d=cz(i.top,i.bottom,n,cW(n,r,a),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,s,o,l,c,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var cO=n(14755);let cH="omp-web:model-roles-expanded";async function cU(e,t,n,r,i,a,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...c2,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(a&&(!c||"builtin"===c.source))return i(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return i(`/${o} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function c_(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let cB=["off","default","full"],cq={off:"none",default:"default",full:"full"},cV=cO.IN.join(" \xb7 "),cK=cO.C1.filter(e=>!cO.IN.includes(e)).join(" \xb7 ");function cG(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let cJ=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),cZ=0,cY={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function cX(e,t){return cJ.compare(e.name||e.modelId,t.name||t.modelId)||cJ.compare(e.provider,t.provider)||cJ.compare(e.modelId,t.modelId)}let cQ=["auto","off","minimal","low","medium","high","xhigh","max"],c0=["low","medium","high","xhigh"],c1={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},c2=[{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"}],c8=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],c4={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},c5={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function c6(e,t,n){let r=e.name.toLowerCase(),i=c3(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function c3(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function c7(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function c9(e){return{data:e.data,mimeType:e.mimeType}}function de(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function dt(e){return(e??[]).filter(nj).slice(0,10).map(de)}let dn=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,dr="\n\nTranscript of the audio ";function di(e){return s5(e).map(e=>{let t=on(e),n="audio"===t&&e.attachmentId&&!e.text.includes(dr)?dn.exec(e.text):null;return{...e,id:++cZ,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function da({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function ds(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 dl extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let dc="composer:unkeyed";async function dd(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new dl("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function du(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function dp({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function dh({error:e}){return e?(0,r.jsx)(dp,{tone:"error",title:"Model error",body:e}):null}function df({warnings:e}){return e&&0!==e.length?(0,r.jsx)(dp,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let dm=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:f,onMainPresetChange:m,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:y,onCompact:b,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:T,effectiveThinkingLevel:I,thinkingCeiling:M,onThinkingLevelChange:R,availableThinkingLevels:E,thinkingLevelMap:L,fastMode:$=null,fastModeBusy:P=!1,onFastModeToggle:A,retryInfo:z,deliveryRows:W=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,slashCommands:_,slashCommandsLoading:B,onLoadSlashCommands:q,onBuiltinCommand:V,soundEnabled:K,onSoundToggle:G,onAudioUnlock:J,onPromptWithStreamingBehavior:Z,draftKey:Y,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},en){let er,ei,ea,es,eo,el,ec,ed,eu,ep,{t:eh}=(0,F.s)(),{st:ef}=rg(),em=W.some(e=>e.removable),eg=U(),[ex,ev]=(0,i.useState)(()=>Y?cc(Y)?.value??"":""),[ey,eb]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{ey&&eN(cF())},[ey]);let[eT,eI]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(ey)try{eI("1"===window.localStorage.getItem(cH))}catch{}},[ey]);let eM=()=>{eI(e=>{let t=!e;try{window.localStorage.setItem(cH,t?"1":"0")}catch{}return t})},[eR,eE]=(0,i.useState)(!1),[eL,e$]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(!1),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(!1),[eU,e_]=(0,i.useState)(()=>Y?dt(cc(Y)?.images):[]),[eB,eq]=(0,i.useState)(()=>Y?di(cc(Y)?.documents):[]),[eV,eK]=(0,i.useState)(null),eG=(0,i.useMemo)(()=>eB.filter(e=>"ready"===e.status),[eB]),eJ=eB.some(e=>"ready"!==e.status||c_(e)),eZ=eB.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(dr))),eY=ex.trimStart(),eX=0===eU.length&&0===eB.length&&eY.startsWith("!"),eQ=eX&&eY.startsWith("!!"),[e0,e1]=(0,i.useState)(!1),[e2,e8]=(0,i.useState)(0),[e4,e5]=(0,i.useState)(null),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(0),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(0),[ti,ta]=(0,i.useState)(null),[ts,to]=(0,i.useState)(!1),[tl,tc]=(0,i.useState)(null),[td,tu]=(0,i.useState)(null),tp=X&&td?.cwd===X?td.values:{},th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tm=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(null),tj=(0,i.useRef)(null),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(0),tN=(0,i.useRef)(!1),tT=(0,i.useRef)([]),tI=(0,i.useRef)([]),tM=(0,i.useRef)([]),tR=(0,i.useRef)(null),tE=(0,i.useRef)(null),tL=(0,i.useRef)(Y),t$=(0,i.useRef)(ex),tP=(0,i.useRef)(eU),tA=(0,i.useRef)(0),tF=(0,i.useRef)(eB);t$.current=ex,tP.current=eU,tF.current=eB,(0,i.useImperativeHandle)(en,()=>({insertIfEmpty(e){let t=th.current;(t?t.value:ex).trim()||(t$.current=e,ev(e),e5(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=th.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ex,tP.current.length,tA.current,tF.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),s7(t)?.message??t),a=dt("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return nj(r)?[r]:[]})),s=di((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),s7(n)?.documents??[]));t$.current=i,tP.current=a,tF.current=s,ev(i),e5(null),tt(!1),e_(e=>(e.forEach(du),a)),eq(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tL.current!==e)return void ch(e,t);let n={value:t$.current,images:tP.current.map(c9),documents:tF.current.filter(e=>"ready"===e.status).map(da)},r=ch(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tL.current=t,i)return;let a=dt(r.images),s=ds(di(r.documents),tF.current),o=r.value;t$.current=o,tP.current=a,tF.current=s,ev(o),e_(e=>(e.forEach(du),a)),eq(s),e5(null),tt(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tL.current,a=r??i,s=a===i,o=!s&&a?cc(a):null,l=cp(e,t,s?t$.current:o?.value??"",s?tP.current.map(c9):o?.images??[],n,s?tF.current.filter(e=>"ready"===e.status).map(da):o?.documents??[]);if(a&&cd(a,l),!s)return;let c=t?.length?[...dt(t).slice(0,Math.max(0,10-tP.current.length)),...tP.current].slice(0,10):tP.current,d=ds(di(l.documents),tF.current);t$.current=l.value,tP.current=c,tF.current=d,ev(l.value),e5(null),tt(!1),t?.length&&e_(e=>{let n=Math.max(0,10-e.length),r=dt(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tP.current=i,i}),eq(d),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=th.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",o=i+s+e+a;t$.current=o,ev(o),e5(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tX(e)}}));let tz=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tP.current.length-tA.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eK(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:s9(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eK(eh("chat.attachImageLimit",{count:10})),i.length){tA.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));e_(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(du);let r=[...t,...n];return tP.current=r,r})}finally{tA.current-=i.length}}},[eh]),tW=(0,i.useCallback)(async e=>{for(let t of e){let e=s1(t);if(!e)continue;if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eK(eh("chat.attachTooLarge",{name:t.name,limit:s9(8388608)}));continue}if(tF.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eK(eh("chat.attachTotalTooLarge",{limit:s9(0x1000000)}));continue}let n={id:++cZ,name:t.name,mimeType:sX[e],size:t.size,text:"",status:"extracting"},r=[...tF.current,n];tF.current=r,eq(r);try{let e=await s6(t);if(tF.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new sY("text_too_large","Total extracted text exceeds 240000 characters");let r=tF.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tF.current=r,eq(r)}catch(i){let e=tF.current.some(e=>e.id===n.id),r=tF.current.filter(e=>e.id!==n.id);if(tF.current=r,eq(r),!e)continue;i instanceof sY?"text_too_large"===i.code?eK(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eK(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eK(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eK(eh("chat.attachPasswordProtected",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tD=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.id===e))return!1;let n=t?tF.current.map(n=>n.id===e?t:n):tF.current.filter(t=>t.id!==e);return tF.current=n,eq(n),!0},[]),tO=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.attachmentId===e))return!1;let n=tF.current.map(n=>n.attachmentId===e?t(n):n);return tF.current=n,eq(n),!0},[]),tH=(0,i.useCallback)((e,t,n)=>{if(!e||e===tL.current)return;let r=cc(e);r?.documents.some(e=>e.attachmentId===t)&&cd(e,{...r,documents:di(r.documents).map(e=>e.attachmentId===t?n(e):e).map(da)})},[]),tU=(0,i.useRef)(new Map),t_=(0,i.useRef)(new Map),tB=(0,i.useRef)(new Set),tq=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=or({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tV=(0,i.useCallback)(e=>e instanceof dl&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof dl&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tK=(0,i.useCallback)(async(e,t)=>{let n=tL.current,r=tF.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;t_.current.get(e)?.abort();let a=new AbortController;t_.current.set(e,a),tO(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await dd(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new dl("Invalid transcription result",null,null,null);let i=r.transcript;tO(e,e=>tq(e,i,tF.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tH(n,e,e=>tq(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tO(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof dl&&"confirmation_required"===n.code)return void tG.current?.(e);let t=tV(n);tO(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t_.current.get(e)===a&&t_.current.delete(e)}},[eh,tV,tO,tH,tq]),tG=(0,i.useRef)(null),tJ=(0,i.useCallback)(async e=>{let t;t_.current.get(e)?.abort();let n=new AbortController;t_.current.set(e,n),tO(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new dl("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await dd(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tO(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tV(t);tO(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t_.current.get(e)===n&&t_.current.delete(e)}t.requiresConfirmation?tO(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tK(e,!1)},[tK,tV,tO]);tG.current=tJ;let tZ=(0,i.useCallback)(e=>{let t=t_.current.get(e);t?t.abort():tO(e,e=>({...e,transcription:{state:"skipped"}}))},[tO]),tY=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++cZ,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tF.current,i];tF.current=a,eq(a);let s=(e,t)=>{let n=tF.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?s4("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?s4("utf-16be",t.subarray(2)):t.includes(0)?null:s4("utf-8",t)??s4("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tD(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await cI().catch(()=>cC)).uploadLimitMb),r.size>n){tD(i.id,null)&&eK(eh("chat.attachStoredTooLarge",{name:r.name,limit:s9(n)}));continue}let o={...i,stored:t,status:"uploading",size:0};if(!tD(i.id,o))continue;let l=tL.current??dc,c=await cx(l),d=null,u=new AbortController;tU.current.set(i.id,u);try{if(tB.current.has(i.id))continue;let e=await oi(r,{sessionId:Q,draftId:c.draftId,signal:u.signal}),n=tF.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=or({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tD(i.id,null)&&eK(eh("chat.attachTotalTooLarge",{limit:s9(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tD(i.id,h))d=e.id;else if(!tB.current.has(i.id)&&l!==tL.current){let t=cc(l)??{value:"",images:[],documents:[]};cd(l,{...t,documents:[...t.documents,da(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tD(i.id,null)&&eK(eh("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tU.current.delete(i.id),c.end(d)}d&&"audio"===t&&tF.current.some(e=>e.attachmentId===d)&&tJ(d)}},[tD,tJ,Q,eh]),tX=(0,i.useCallback)(async e=>{eK(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==s1(a)?n.push(a):s8(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tz(t),tW(n.filter(e=>e.size<=8388608)),tY(r,"audio"),tY([...i,...a],"file")])},[tW,tY,tz]),tQ=(0,i.useCallback)(e=>{e_(t=>{let n=[...t],[r]=n.splice(e,1);return r&&du(r),tP.current=n,n})},[]),t0=(0,i.useCallback)(e=>{let t=tF.current.find(t=>t.id===e);if(tB.current.add(e),tU.current.get(e)?.abort(),t?.attachmentId){t_.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of l7)t.delete(n)&&(0===t.size&&l7.delete(e),cj())}let r=tF.current.filter(t=>t.id!==e);tF.current=r,eq(r)},[]),t1=(0,i.useCallback)(()=>{tP.current=[],e_(e=>(e.forEach(du),[]))},[]),t2=(0,i.useCallback)(()=>{tF.current=[],eq([])},[]),t8=(0,i.useCallback)(()=>{t$.current="",ev(""),e5(null),tt(!1),Y&&cu(Y),tL.current&&tL.current!==Y&&cu(tL.current),t1(),t2(),eK(null),th.current&&(th.current.style.height="auto")},[t2,t1,Y]);(0,i.useEffect)(()=>{Y&&tL.current===Y&&cd(Y,{value:ex,images:eU.map(c9),documents:eG.map(da)})},[eU,Y,eG,ex]),(0,i.useEffect)(()=>{let e=tL.current;if(e===Y)return;e&&cd(e,{value:t$.current,images:tP.current.map(c9),documents:tF.current.filter(e=>"ready"===e.status).map(da)});let t=Y?cc(Y):null;tL.current=Y;let n=t?.value??"",r=dt(t?.images),i=di(t?.documents);t$.current=n,tP.current=r,tF.current=i,ev(n),e5(null),tt(!1),e_(e=>(e.forEach(du),r)),eq(i)},[Y]),(0,i.useEffect)(()=>{let e=th.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tP.current.forEach(du)},[]);let t4=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=cf(t);if(0===n.length)return()=>{};let r=++l6;return l5.set(r,{draftId:cm(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=l5.get(r);if(t){if(l5.delete(r),"accepted"===e){let e=l9.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);l9.set(t.draftId,e)}cj()}}}(tL.current??dc,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t5=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eY.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eU.length&&!eG.length||o||eJ)return;J?.();let i=eU.length?eU:void 0,a=eG.length?eG:void 0;if(r.startsWith("/")){await cU(r,_,V,t=>t4(a,()=>e(t,i,a)),eK,!!(i||a),q)&&t8();return}t8(),t4(a,()=>e(r,i,a))},[ex,eY,eU,eG,eJ,o,V,_,q,e,t8,J,t4]),t6=eY.startsWith("/")&&!/\s/.test(eY.slice(1))?eY.slice(1).toLowerCase():null,t3=(()=>{if(null===t6)return[];let e=[...o?[]:c2,..._??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=c3(e,eh).toLowerCase();return t.includes(t6)||n.includes(t6)}).sort((e,t)=>{let n=c6(e,t6,eh)-c6(t,t6,eh);return 0!==n?n:c5[e.source]-c5[t.source]||cJ.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t7,groups:t9}=(er=0,{commands:(ei=c8.map(e=>{let t=t3.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!c7(e,tp)),...t.filter(e=>c7(e,tp))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),ne=1===t3.length?eh(t6?"chat.match":"chat.command"):eh(t6?"chat.matches":"chat.commands",{count:t3.length}),nt=!!ex.trim(),nn=!eJ&&(nt||eU.length>0||eG.length>0),nr=(0,i.useCallback)((e,t)=>{if(!X)return void e5(null);let n=t??e.length;e5(cR(e.slice(0,n)))},[X]),ni=e4?.query??null,na=i.useMemo(()=>null!==ni&&ti&&ti.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:cL(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:cL(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||cE(e.entry.path)-cE(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(ti.entries,ni):[],[ni,ti,X]),ns=!!(ni&&ti?.truncated&&ti.cwd===X);(0,i.useEffect)(()=>{if(!ns||!X||!ni)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(ni)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tc({cwd:X,query:ni,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ns,ni,X]);let no=ns&&null!==tl&&tl.cwd===X&&tl.query===ni,nl=no?tl.matches:na,nc=null===e4?null:`${e4.start}:${+!!e4.quoted}:${e4.query}`;(0,i.useEffect)(()=>{if(null===nc){e3(!1),e9(0);return}e3(!0),e9(0)},[nc]);let nd=null!==e4,nu=cD(tk,te,{viewportFraction:.44,cap:360}),np=cD(tk,e0,{viewportFraction:.56,cap:460}),nh=cD(tk,e6,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!X)return;let e=tR.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tE.current===X||(tE.current=X,to(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{ta({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>cE(e.path)-cE(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tR.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tR.current=null}).finally(()=>{tE.current=null,to(!1)}))},[nd,X]);let nf=(0,i.useCallback)(e=>{if(!e4)return;let t=th.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e4.start),i=ex.slice(n);e4.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e4.quoted),s=r+a.text+i,o=r.length+a.cursorOffset;ev(s),e5(cR(s.slice(0,o))),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e4,ex]);(0,i.useEffect)(()=>{e7>=nl.length&&e9(Math.max(0,nl.length-1))},[nl.length,e7]),(0,i.useEffect)(()=>{tI.current.length=nl.length},[nl.length]),(0,i.useEffect)(()=>{e6&&tI.current[e7]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e7,e6]),(0,i.useEffect)(()=>{tn>=D.length&&tr(Math.max(0,D.length-1))},[D.length,tn]),(0,i.useEffect)(()=>{tM.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{te&&tM.current[tn]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tn,te]);let nm=(0,i.useCallback)(e=>{t$.current=e,ev(e),tt(!1),tr(0),e5(null),requestAnimationFrame(()=>{let t=th.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),ng=(0,i.useCallback)(e=>{let t=`/${e.name} `;t$.current=t,ev(t),e1(!1),e8(0),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eY.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eJ||!i&&0===eU.length&&0===eG.length?null:{message:i,images:eU.length?eU:void 0,documents:eG.length?eG:void 0};if(!s)return;J?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await cU(i,_,V,e=>{if(!Z)throw Error("Cannot queue this command while the session is busy.");t4(s.documents,()=>Z(e,o,s.images,s.documents))},eK,!!(s.images?.length||s.documents?.length),q)&&t8();return}t8(),"steer"===e&&n?t4(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t4(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eY,eU,eG,eJ,_,q,V,Z,n,a,t8,J,t4]),nv=(0,i.useCallback)(e=>{let t=t7.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e2-1);if("right"===e)return Math.min(t,e2+1);let n=tT.current[e2];if(!n)return"down"===e?Math.min(t,e2+1):Math.max(0,e2-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===e2)continue;let t=tT.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-a;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<o&&(s=n,o=c)}return s>=0?s:"down"===e?Math.min(t,e2+1):Math.max(0,e2-1)},[t7.length,e2]),ny=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tC.current<100,s=tS.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(te&&!s){if("ArrowDown"===e.key){e.preventDefault(),tr(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tr(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tt(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[tn]){e.preventDefault(),nm(D[tn]);return}}if(e0&&null!==t6){if("ArrowDown"===e.key){e.preventDefault(),e8(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e8(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e8(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e8(nv("left"));return}if("Escape"===e.key){e.preventDefault(),e1(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t7[e2]){e.preventDefault(),ng(t7[e2]);return}}if(e6&&null!==e4&&!s){if("ArrowDown"===e.key){e.preventDefault(),e9(e=>Math.min(Math.max(0,nl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e9(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e3(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nl[e7]){e.preventDefault(),nf(nl[e7]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===ex.trim().length){e.preventDefault(),e1(!1),e3(!1),tr(D.length-1),tt(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(n||a)?nx(n?"steer":"followup"):t5())},[o,n,a,t,e0,t6,t7,e2,ng,nx,t5,nv,e6,e4,nl,e7,nf,te,D,tn,nm,ex]),nb=(0,i.useCallback)(()=>{let e=th.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nw=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tX(t))},[tX]);(0,i.useEffect)(()=>{if(null===t6){e1(!1),e8(0),tN.current=!1;return}e1(!0),e8(0),!tN.current&&q&&(tN.current=!0,Promise.resolve(q()).catch(()=>{tN.current=!1}))},[t6,q]),(0,i.useEffect)(()=>{if(!e0||!X)return;let e=!1;return tu({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tu({cwd:X,values:n})}).catch(()=>{e||tu({cwd:X,values:{}})}),()=>{e=!0}},[e0,X]),(0,i.useEffect)(()=>{e2>=t7.length&&e8(Math.max(0,t7.length-1))},[t7.length,e2]),(0,i.useEffect)(()=>{tT.current.length=t7.length},[t7.length]),(0,i.useEffect)(()=>{e0&&tT.current[e2]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e2,e0]);let nk=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(cX):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(cX),nS=g??null,nC=nH.find(e=>e.alias===nS)?.provider??null,nN=nC?nk.filter(e=>e.provider===nC):nk,nI=(ea=ej.trim().toLocaleLowerCase())?nN.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):nN,nM=nN.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=nC?[]:(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$=ej.trim()?[]:nN.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nP=(e,t,n)=>{let i=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(eb(!1),eS(""),!i||c){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(cF(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(cA,JSON.stringify(r))}catch{}eN(r),f?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nA=l?nk.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,nF=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nz=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${nT(S.tokensBefore)} -> ${nT(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:nT(nF)})})`:null,nW=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},nD="auto"===(es=T??"auto")?M?`auto ≤ ${nW(M)??M}`:"auto":L?L[es]??es:es,nO=(T??"auto")==="auto"&&I&&"auto"!==I?L?.[I]??I:null,nU=R&&nO?eh("chat.currentReasoning",{level:nO}):null,n_=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...c0.filter(n_).map(e=>({level:"auto",ceiling:e})),...cQ.filter(e=>"auto"!==e&&n_(e)).map(e=>({level:e,ceiling:null}))],nq=Object.entries(cq).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tf.current&&!tf.current.contains(e.target)&&tm.current&&!tm.current.contains(e.target)&&(eb(!1),eS("")),tg.current&&!tg.current.contains(e.target)&&tx.current&&!tx.current.contains(e.target)&&eE(!1),tv.current&&!tv.current.contains(e.target)&&eA(!1),ty.current&&!ty.current.contains(e.target)&&ez(!1),tb.current&&!tb.current.contains(e.target)&&eH(!1),!tw.current||tw.current.contains(e.target)||th.current?.contains(e.target)||tt(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eH(!1)},[eg]);let nV=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eU.length||eB.length?" is-active":""}`,onClick:()=>tj.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eU.length||eB.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=eU.length||eB.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eU.length||eB.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),nK=m&&nH.length>0?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eR?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e$({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eR,onKeyDown:e=>{"Escape"===e.key&&eR&&(e.stopPropagation(),eE(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eg?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eR&&eL&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=cz(eL.top,eL.bottom,e,cW(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eL.top+6}:{top:eL.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eL.left,width:"max-content",minWidth:eL.width};return(0,r.jsx)("div",{ref:tx,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eE(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:nH.map(e=>{let t=e.alias===nS;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eE(!1),m({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:nG(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children: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=R?(0,r.jsxs)("div",{ref:ty,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eF?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eD({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(!1),ez(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eF,onKeyDown:e=>{"Escape"===e.key&&eF&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level:nD}),"aria-label":eh("chat.changeReasoning",{level:nD}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eF?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eF?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nD})]}),eF&&eW&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=cz(eW.top,eW.bottom,e,cW(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eW.top+6}:{top:eW.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eW.left,width:"max-content",minWidth:Math.max(180,eW.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),ty.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(T??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nW(i),s=t?`auto ≤ ${a??t}`:a??e,o=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(c1[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{ez(!1),R(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,nZ=A?(eo=P?eh("chat.fastModeBusy"):null===$?eh("chat.fastModeUnknown"):$.active?eh("chat.fastModeActive"):$.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),el=P||o||y,ec=$?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${$?.active?" is-active":""}`,onClick:A,disabled:el,"aria-pressed":null===$?void 0:$.enabled,"aria-busy":P||void 0,title:eo,"aria-label":eo,style:{flexShrink:0,opacity:o?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:$?.active?"var(--accent)":"none",stroke:ec?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===$?"3 2":void 0,style:{opacity:ec&&!$?.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:()=>nx("steer"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nn?"var(--warning)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nX=void 0!==G?(0,r.jsx)(lH,{soundEnabled:K??!0,onToggle:G}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tj,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tX(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(dh,{error:p}),(0,r.jsx)(df,{warnings:h}),W.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ef("delivery.title",{count:W.length})}),O&&em&&(0,r.jsxs)("button",{onClick:O,title:eh("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(lW,{rows:W,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("steer"===e?"steering":"followUp",t):void 0})]}),z&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:z.attempt,max:z.maxAttempts}),z.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",z.errorMessage]})]}),nz&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nz]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eV&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eV}),(0,r.jsx)("button",{type:"button",onClick:()=>eK(null),"aria-label":eh("i18n.close"),title:eh("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eU.length>0||eB.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eU.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tQ(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eB.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||c_(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"}}):rT(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):cY[e.mimeType]," \xb7 ",s9(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t0(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eZ.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eZ.map(e=>{let t,n,i,a,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?eh("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:l?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:l.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,r.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[l.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tK(o,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tJ(o),children:eh(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tk,style:{position:"relative",minWidth:0},children:[te&&D.length>0&&(0,r.jsxs)("div",{ref:tw,style:{position:"absolute",left:0,right:0,...cG(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nu.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===tn;return(0,r.jsxs)("button",{ref:e=>{tM.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>tr(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),e0&&null!==t6&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...cG(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:B?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:ne})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:10},children:B||0!==t3.length?t9.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(c4[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===e2,i=c7(e,tp);return(0,r.jsxs)("button",{ref:e=>{tT.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ng(e)},onMouseEnter:()=>e8(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),c3(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:c3(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e6&&null!==e4&&(ed=ts&&(!ti||ti.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=ti?.truncated&&!no?e4.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...cG(nh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nh.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ed?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nh.maxHeight-34),overflowY:"auto",padding:4},children:ed||0!==nl.length?nl.map((e,t)=>{let n=t===e7,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tI.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>e9(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(rS,{size:14}):rT(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ns&&!no?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eX?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eX?"var(--tool-bg)":o&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:th,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),tt(!1),nr(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nr(t.value,t.selectionStart)},onKeyDown:ny,onCompositionStart:()=>{tS.current=!0},onCompositionEnd:e=>{tS.current=!1,tC.current=Date.now();let t=e.currentTarget;nr(t.value,t.selectionStart)},onInput:nb,onPaste:nw,placeholder:o&&(n||a)?eh("chat.steerPlaceholder"):o?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),o?eg?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nY}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t5,disabled:!nn,"aria-busy":eJ||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eJ?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:nn?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eX&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eQ?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eQ?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!o)&&nV,!eg&&nK,!(eg&&o)&&(nk.length>0||nA||p)&&f&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.jsxs)("button",{className:`composer-chip${ey?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(e=>(e&&eS(""),!e))},disabled:o||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:ey?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ey?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":nk.length>0?"Change model":"No available models",children:[y?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nA??(nk.length>0?"Select model":"No models")})]}),ey&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=cz(ew.top,ew.bottom,e,cW(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tm,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),eb(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[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:eh("chat.frequentModels")}),n$.map(({option:e,count:t})=>nP(e,"frequent",t))]}),nE.length>0&&!ej.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":eT,"aria-controls":"model-role-rows",onClick:eM,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eT?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:eh("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nE.length}),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:!eT,children:nE.map(e=>{let t=nL?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{eb(!1),eS(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eh("chat.allModels")})]}),0===nR.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):nR.map((e,t)=>(0,r.jsxs)("div",{children:[nR.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nP(e,"all"))]},e.provider))]})]})})()]}),eg&&o&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nY}),!eg&&nJ,!eg&&nZ,!eg&&nU&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nU}),(0,r.jsx)(lX,{sessionId:Q})]}),(0,r.jsxs)("div",{ref:tb,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eO?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eO?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eO?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eg&&(0,r.jsxs)(r.Fragment,{children:[o&&nV,nK,nJ,nZ]}),!o&&N&&(0,r.jsxs)("div",{ref:tv,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eP?" is-active":""}`,onClick:()=>!o&&eA(e=>!e),disabled:o,title:eh("chat.changeToolPreset")+`: ${nq}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eP?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eP?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nq})]}),eP&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:cB.map(e=>{let t=cq[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:cV}):eh("chat.allBuiltInTools",{tools:`${cV} + ${cK}`});return(0,r.jsxs)("button",{onClick:()=>{eA(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!o&&b&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:b,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nX,eO&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eA(!1),ez(!1),eH(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(lZ,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nX]})]})]})]})});function dg({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=eI(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:e$(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function dx({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:s}=rg(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=(0,i.useId)(),f=e??[],{currentPhase:m,activeTask:g,remaining:x,completed:v,total:y,percent:b}=tj(f),w=t.steps.length>0,k=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,s);if(0===y&&null===k)return null;let j=y>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${j?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:j?"✓":"›"}),k&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:k}),y>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!k&&m&&(0,r.jsx)("span",{className:"todo-strip-phase",children:m.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:j?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:j?a("todo.progressDone",{percent:b??0,completed:v,total:y}):a("todo.progress",{percent:b??0,completed:v,total:y,remaining:x})})]}),w&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&w&&(0,r.jsx)(so,{flow:t,live:n,st:s,id:h}),o&&y>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[f.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[f.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(rw,{task:e},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function dv(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function dy(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function db(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 dw extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function dk(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 dw(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let dj="ompweb-update-client-id",dS="ompweb-update-resume-intent-v2",dC="ompweb-update-return-v1",dN="cuelo-restart-return-v1",dT="ompweb-update-failure-return-v1",dI="ompweb:update-wake";function dM(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function dR(){let e=sessionStorage.getItem(dj);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(dj,t),t}function dE(){sessionStorage.removeItem(dS)}function dL(){let e=sessionStorage.getItem(dC);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 d$(e){let t=dL();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(dC,JSON.stringify(n))}catch{}return n}async function dP(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:dR(),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 dA(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=dL();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(dC,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),dE();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(dI,{detail:{sessionId:e.sessionId}}))}async function dF(e){let t=function(e){let t=sessionStorage.getItem(dT);if(!t)return null;sessionStorage.removeItem(dT);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?(dE(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(dI,{detail:{sessionId:e.sessionId}})),"failed"):(await dA(e),"resumed")}function dz(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 dW(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 dD(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function dO(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function dH(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 dU(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function d_(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function dB(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!e4(r??void 0))return{message:e[n],entryId:r}}return null}let dq=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class dV 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 dK(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function dG(e){return new Promise(t=>setTimeout(t,e))}function dJ(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function dZ(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:dJ(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:dJ(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=dJ(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function dY(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 dX(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(dY).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function dQ(e){return"user"===e.role?`user:${dX(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 d0(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 d1(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function d2(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let d8=!1,d4={width:0,height:0},d5=new Set,d6=null;function d3(){let e=window.visualViewport,t=d2();d4.width!==window.innerWidth?d4={width:window.innerWidth,height:window.innerHeight}:t||(d4.height=Math.max(d4.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:d4.height});if(n!==d8)for(let e of(d8=n,d5))e()}function d7(e){if(d5.add(e),!d6){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,d3()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),d3(),d6=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{d5.delete(e),0===d5.size&&d6&&(d6(),d6=null)}}function d9(){return(0,i.useSyncExternalStore)(d7,()=>d8,()=>!1)}let ue={count:50,end:null};function ut(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function un(e,t,n){let{startIndex:r,endIndex:i}=ut(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function ur({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:la[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(lt(),{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 ui(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=(s7(t)?.message??t).trim();return n.length>0?n:null}function ua(e){return`omp-cues:${e}`}function us(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(ua(e),JSON.stringify(n.slice(-200)))}catch{}}let uo=[];function ul(e){return`omp-web:interrupted-dismissed:${e}`}let uc=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:f,sessionId:m,main:g,process:x,dispatchSlots:v,compactedDispatch:y,openRequest:b,startIndex:w,endIndex:k,sentinelRef:j,laterSentinelRef:S,flashItem:C,t:N,onProcessLogChange:T,cues:I,cueFollowRef:M}){(0,i.useEffect)(()=>{T({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:m})},[T,x,e,t,n,a,s,m]);let R=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[o.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(o.blocks?i.get(o.idx):void 0)??o.afterMainIndex??-1),l=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=e7(i.action);if(!0===e3[e]){let t={kind:"skill",action:e,name:e7(i.name)};n(JSON.stringify(t),t)}continue}let a=e7(i.memory),s=i.skill,o=s?{action:e7(s.action),name:e7(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:o}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...o?{skill:o}:{}})}}(o.blocks??e.content??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:e1,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,N]),E=(0,i.useMemo)(()=>{let r=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(r=t.idx);return function(e,t,n,r,i,a,s=[]){let o=function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&aE(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:aE(t,n),s=new Map;for(let[n,o]of(e.forEach((e,n)=>{"answer"===e.kind&&s.set(aE(t,e.anchorIdx),n)}),s)){if(n===a)continue;let e=i.find(e=>e>n);r.set(o,{from:n+1,to:e??t.length})}return r}(e,t,n),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,n]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(a$(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let i=n.to-1;for(;i>=n.from&&e4(s[i]);)i-=1;if(s[i]!==a.throughEntryId)continue;let o=aM(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=aL(t,r,n.from,n.to);c.set(e,{...a.summary,...p?{remaining:aT(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,i,a=[]){let s=aM(e,n,r),o=aL(e,t,n,r);return{...aI(s,t,i),remaining:o?aT(o):null,span:aP(e,n,r),flow:aC(s,t,!1,a,i,aR(e,n,r))}}(t,r,n.from,n.to,i,d),latest:e===l})}return c}(g,e,r,n,s,b,t)},[g,e,n,s,l,b,t]),L=w>0,$=k<g.length,P=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&e4(t[v]);)v-=1;let y="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,b=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(ok,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:o,entryId:t[i],onFork:l||c||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:y,onEditContent:f,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:m,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${b}-view-${i}`)},A=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[L&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((a,l)=>{let c=w+l,d=y?.position===c?(0,r.jsx)(sS,{calls:y.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,f=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<f}).map(e=>(0,r.jsx)(ur,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),b=h!==u,k=R.get(c),j=k?(0,r.jsx)(ok,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=b?(0,r.jsx)(lw,{turnIndex:u,turnEntryId:t[u],sessionId:m,cwd:s,onOpenFile:o}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx)),j,S,x]},`message-${a.idx}`);let C=tx(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=eH(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:E.get(c)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),y?.position===g.length&&k===g.length&&(0,r.jsx)(sS,{calls:y.calls}),$&&(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 ud({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsChange:m,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:y,onOpenWorkspaceView:b,onOpenSessionList:w,onOpenMaker:k,selectedMaker:j,onProcessLogChange:S,onOpenFile:C,transcriptReplacement:N,onComposerFocusChange:T,onSessionBusyChange:I,onWaitingChange:M,onAttentionChange:R,soundEnabled:E=!0,onSoundToggle:L,playCueSound:$=async()=>({sticker:null,text:null}),preloadCueSound:P,unlockAudio:A,jumpRequest:z=null,onJumpHandled:W}){var D,O;let H,B,q,{t:V}=(0,F.s)(),K=d9(),G=U(),J=(0,i.useRef)($);J.current=$;let Z=(0,i.useRef)(null),Y=(0,i.useRef)(P);Y.current=P;let[Q,ee]=(0,i.useState)([]),et=(0,i.useRef)(Q);et.current=Q;let en=(0,i.useRef)(0),er=(0,i.useRef)([]),ei=(0,i.useRef)([]),ea=(0,i.useRef)(null),es=(0,i.useRef)(0),eo=(0,i.useRef)(-1),el=(0,i.useRef)(-1),ec=(0,i.useCallback)(()=>{let e=ea.current?.current;return e?{sessionId:e,turn:es.current}:null},[]),ed=(0,i.useCallback)(e=>ea.current?.current===e.sessionId&&es.current===e.turn,[]),eu=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;en.current=Math.max(en.current+1,Date.now());let i={id:en.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};ee(e=>{let t=[...e,a];return null!==a.anchorEntryId&&us(n.sessionId,t),t})},[]),ep=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ed(n)&&("working"!==t||el.current!==n.turn);i()&&J.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&eu(e,t,n,r)}).catch(()=>{})},[ed,eu]),eh=(0,i.useCallback)(async(e,t,n,r)=>{let i=(await rh(e,t,n,r))?.alias??null;return i&&Y.current?.(i),i},[]),ef=(0,i.useCallback)((e,t,n,r,i)=>{let a=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=lh(e[n]),a=0;for(let t=r;t<=n;t++)lh(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(er.current,ei.current);eh(t.sessionId,n,r,i).then(n=>{ep(n,e,t,a)})},[ep,eh]),[em,eg]=(0,i.useState)(0),ex=(0,i.useRef)([]),ev=(0,i.useCallback)(e=>{if(es.current+=1,null!==lo(e.outcome)){let t=e.sessionId;ex.current.push({completion:e,trigger:t?{sessionId:t,turn:es.current}:null}),eg(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ex.current.splice(0)){let n=lo(e.outcome),r="neutral"===n?null:n;t?ef(r,t,e.provider,e.credentialId,e.model):J.current(null,r).catch(()=>{})}},[em,ef]);let ey=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ew,messages:ek,entryIds:ej,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eT,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:eL,modelThinkingLevels:e$,modelThinkingLevelMaps:eP,modelRoles:eA,toolPreset:eF,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,fastMode:eO,fastModeBusy:eU,handleFastModeToggle:eV,retryInfo:eK,contextUsage:eJ,forkingEntryId:eZ,isCompacting:e1,compaction:e3,compactError:e7,compactResult:te,displayModel:tt,modelSwitching:tn,sessionStats:tr,runStateKnown:ti,compactedWork:ta,slashCommands:ts,slashCommandsLoading:to,deliveryRows:tl,subagents:tc,todoPhases:td,notices:tu,extensionDialog:tp,extensionResponse:th,extensionCustomUi:tf,extensionStatuses:tm,extensionWidgets:tg,respondToExtensionUi:tx,sendExtensionCustomInput:tv,isAutoModelSelection:ty,agentPhase:tb,isNew:tw,autoFollowPaused:tj,resumeAutoFollow:tS,pauseAutoFollow:tC,goalStatus:tT,sessionIdRef:tI,messagesEndRef:tM,scrollContainerRef:tR,handleSend:tE,handleAbort:tL,handleFork:t$,handleNavigate:tP,handleModelChange:tA,handleRoleModelChange:tF,handleMainPresetChange:tz,newSessionAccount:tW,handleCompact:tD,handleSteer:tO,handleFollowUp:tH,handlePromptWithStreamingBehavior:tU,handleAbortCompaction:t_,handleRecallQueue:tB,handleRemoveQueuedMessage:tq,handleBuiltinSlashCommand:tV,handleToolPresetChange:tK,handleThinkingLevelChange:tG,loadSlashCommands:tJ,ensureNewSession:tZ,refreshLiveTranscript:tY}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,f=null===t&&null!==r,m=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(m),[v,y]=(0,i.useState)(!f&&!m),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(m?.leafId??null),[S,C]=(0,i.useState)(m?.context.messages??[]),[N,T]=(0,i.useState)(m?.context.entryIds??[]),[I,M]=(0,i.useState)(m?.context.compactedWork??null),[R,E]=(0,i.useReducer)(dW,{isStreaming:!1,streamingMessage:null}),[L,$]=(0,i.useState)(!1),[P,A]=(0,i.useState)(!1),[F,z]=(0,i.useState)(null),[W,D]=(0,i.useState)({}),[O,H]=(0,i.useState)([]),[U,_]=(0,i.useState)(null),[B,q]=(0,i.useState)([]),[V,K]=(0,i.useState)({}),[G,J]=(0,i.useState)({}),[Z,Y]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,eo]=(0,i.useState)(()=>{let e=m?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[el,ec]=(0,i.useState)(),[ed,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[ey,eb]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(m?.contextUsage??null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(null),[eL,e$]=(0,i.useState)(!1),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(null),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(null),eU=(0,i.useRef)(null),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)([]),[eJ,eZ]=(0,i.useState)(!1),[eY,eX]=(0,i.useReducer)(dZ,{visible:[],pending:[]}),[eQ,e1]=(0,i.useState)(null),[e2,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,to]=(0,i.useState)({steering:[],followUp:[]}),[tl,tc]=(0,i.useState)([]),[td,tu]=(0,i.useReducer)(r7,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{L||tu({type:"idle"})},[L]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${r6(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${r5(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(td,ts),[td,ts]),[tf,tm]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(m?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tT=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tI=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),tR=(0,i.useRef)(!1),tE=(0,i.useRef)(-1),tL=(0,i.useRef)("unknown"),t$=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(0),tF=(0,i.useRef)(!1),tz=(0,i.useRef)(0),tW=(0,i.useRef)(null),tD=(0,i.useRef)(null),tO=(0,i.useRef)(null),tH=(0,i.useRef)(!1),tU=(0,i.useRef)(!0),[t_,tB]=(0,i.useState)(!1),[tq,tV]=(0,i.useState)(null),tK=(0,i.useRef)(void 0),tG=(0,i.useRef)(0),tJ=(0,i.useRef)(0),tZ=(0,i.useRef)(()=>{}),tY=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t8=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,no=eT??g?.context.model??eR??null,nl=f?X??en:no,nc=(0,i.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,n+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nd=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nd.current+=1,tm(n=>n?.sid===e&&dU(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nd.current===n&&Array.isArray(t)&&tm(n=>n?.sid===e&&dU(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nf=(0,i.useCallback)(e=>{tN.current=e,T(e)},[]),nm=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&y(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=e5(a.context.messages,a.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);nh(s.messages),nf(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let o=!n&&t5.current===e;if(o||(eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&y(!1),!n){if(o)try{let t=t6.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t6.current===t&&(r.state?.thinkingLevel!==void 0?(eo(r.state.configuredThinkingLevel??r.state.thinkingLevel),ec(r.state.thinkingLevel)):r.running||(t5.current=null,eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nd.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eS(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t5.current=e,eo(i.configuredThinkingLevel??i.thinkingLevel),ec(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&to(dD(i.queuedMessages)),void 0!==i.subagents&&tc(e=>dz(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||to({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&y(!1)}},[np,nf,nh]),ng=(0,i.useCallback)(e=>{let t=na.current.then(async()=>{tj.current===e&&await nm(e)});return na.current=t.catch(()=>{}),t},[nm]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let o=e5(s.context.messages,s.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);nh(o.messages),nf(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nf,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await dk(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),ny=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;f&&r&&n&&!t1.current&&(t1.current=!0,l?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[f,r,l]),nb=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!f||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t4.current,i=t8.current;e&&eE(e);let a={cwd:r,type:"ensure_session",toolNames:(0,cO.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),o=t0.current,l=o?.body===s?o.createRequestId:dK();t0.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:l})});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();t0.current=null,t=d.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),d.model&&t2.current===e&&(eE(d.model),e||er(d.model)),d.thinkingLevel&&t4.current===n&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await dk(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[f,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await nb();if(!e)return eG([]),[];eZ(!0);try{let t=await dk(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[nb]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,tb.current&&(clearTimeout(tb.current),tb.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{ty.current?.close(),ty.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);ty.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tW.current?.(n):"agent_start"===n.type&&tD.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tW.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(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)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nT=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new dV(n.status)},[nN]),nI=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await dk(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e6(t=>t?.id===e.id?null:t)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await dk(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nR=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??dK(),message:t,type:e.type??"info"}})},[]),nE=(0,i.useCallback)(e=>{let t={role:"custom",customType:e0,content:eI(e).trim(),display:!0,timestamp:Date.now()},n=tT.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!e4(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${e8}${n.seq}`,baseEntryId:a,message:t});let s=e5(tC.current,tN.current,n.outputs);nh(s.messages),nf(s.entryIds)},[nh,nf]),nL=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e6(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(dy(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":nR({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ta(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[nR,o,e.chatInputRef]),n$=(0,i.useCallback)(()=>{let e=tI.current;return tI.current=!1,$(!1),eV(null),eb(null),E({type:"end"}),e},[]),nP=(0,i.useCallback)(()=>{tL.current="unknown",t$.current=null;let e=dB(tC.current,tN.current);tP.current=e?{entryId:e.entryId,key:dQ(e.message)}:null,tA.current+=1},[]),nA=(0,i.useCallback)(()=>{let e=tL.current,t=t$.current;if("unknown"===e){let n=dB(tC.current,tN.current),r=n?.message,i=tP.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:dQ(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=d_(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}:{}}:{}}},[]),nF=(0,i.useCallback)(e=>{let t=nA();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===n;s?.(e?nA():t)})},[s,nA]),nz=(0,i.useCallback)((e,t)=>tE.current!==e&&(tE.current=e,nF(t),!0),[nF]),nW=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nd.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(tc(e=>dz(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,tb.current=null,tM.current=!!s?.isStreaming,tR.current=!!s?.isPromptRunning,tI.current=!0,$(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eH(dH(s)),tb.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){tb.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,tb.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;tb.current=setTimeout(()=>void n(),600)}};tb.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),nD=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nm(e)}finally{if(nt.current!==t)return;let n=tR.current,r=tM.current;tR.current=!1,tM.current=!1,nr.current=null;let i=n$();n?nz(t):r&&i&&nF(),e&&nW(e)}},[nm,nF,nz,nW,n$]),nO=(0,i.useCallback)(async(e,t)=>{await dG(800);let n=Date.now();for(;tI.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nD(e,t)}}catch{}await dG(600)}},[nD]),nH=(0,i.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;tF.current&&tz.current===t&&tj.current===e;){await dG(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nm(e),tz.current!==t||tj.current!==e)return;tF.current=!1,A(!1),z(null);return}catch{}}},[nm]),nU=(0,i.useCallback)(async e=>{if(!tI.current)return;let t=nt.current;try{let n=nd.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let a=i.state;if(eA(a?.isCompacting??!1),eH(dH(a)),to(dD(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),tc(e=>dz(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tI.current)return;a&&(void 0!==a.systemPrompt&&eS(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await nD(e,t)}catch{}},[np,nD]),n_=(0,i.useCallback)(async e=>{let t=await nm(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tI.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,tR.current=!!n.isPromptRunning,tI.current=!0,$(!0),eV(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nO(e),!0)},[nN,nm,nO]),nB=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eP){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eP]),(0,i.useEffect)(()=>{if(!L&&!eP)return;let e=()=>{let e=tj.current;e&&nB(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[L,eP,nB]),(0,i.useEffect)(()=>{if(!L)return;let e=()=>{let e=tj.current;e&&nU(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[L,nU]),(0,i.useEffect)(()=>{if(L)return;let e=()=>{let e=tj.current;e&&!tI.current&&n_(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tI.current&&n_(t).then(e=>{e||tj.current!==t||tI.current||nm(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(dI,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(dI,n)}},[L,n_,nm]),tD.current=e=>{if(tj.current!==e||tI.current||tg.current||tO.current)return;let t=n_(e).then(async t=>{t||tj.current!==e||tI.current||await nm(e)}).catch(()=>{}).finally(()=>{tO.current===t&&(tO.current=null)});tO.current=t},(0,i.useEffect)(()=>{tI.current=L},[L]),tW.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=dQ(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=dQ(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=dQ(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let n=e5(t.messages,t.entryIds,tT.current.sessionId===tj.current?tT.current.outputs:[]);nh(n.messages),nf(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tI.current;nk(),e&&nP(),tM.current=!0,tI.current=!0,$(!0),eV({kind:"waiting_model"}),E({type:"start"});break}case"agent_end":if(!tI.current)break;if(eV(null),eb(null),E({type:"end"}),tj.current){nm(tj.current);let e=nd.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eS(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>dz(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tV(t.state.goal??null),to(dD(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tV(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||tR.current)break;let t=tj.current,n=n$();eA(!1);let r=t?nm(t):void 0;t&&nW(t),n&&nF(r);break}case"prompt_done":{let e=nt.current,t=tR.current;tR.current=!1,nr.current=null;let n=tE.current!==e;if(!t&&!n)break;let r=tj.current;nz(e,r?nm(r):void 0),!tM.current&&(n$(),r&&nW(r))}break;case"prompt_error":tL.current="failed",nR({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tL.current="failed",nR({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:aV(t)}),eV(null);break}case"message_end":{if(!tI.current)break;let t=e.message;if(t?.role==="assistant"&&(t$.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tL.current=d_(t)),t&&"user"===t.role){let e=aV(t),n=dX(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&dX(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tu({type:"user-message",kind:ie(e),text:r9(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nh(e=>[...e,aV(t)]);let n=tj.current;n&&nB(n),E({type:"reset"}),eV({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t5.current=t,t6.current+=1,eo(e.configured??n),ec(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eV(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eV(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";tc(n=>{let r=n.find(e=>e.id===t.id);return dz(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=>dz(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=>dz(e,[r]));break}case"queue_update":to({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eb({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eb(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}eA(!0),ez(null),eD(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)ez(e.errorMessage),eD(null);else if(!e.aborted){eD(d0(e.result,e.reason??"auto"));let t=tj.current;t&&(nm(t),nB(t))}break;case"extension_ui_request":nL(e)}},[nR,nu,np,nk,nL,nm,nF,nz,nB,nP,nW,n$,nf,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tI.current||tF.current||ni.current)return"unknown";let o=s3(n,a??[]),l=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tK.current?.(t,e),"accepted"):"unknown"}nP();let c=nt.current+1;nk(),tR.current=!0;let d=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...o.trim()?[{type:"text",text:o}]:[],...d]:o,timestamp:Date.now()};nh(e=>[...e,u]),nr.current=dX(u),nt.current=c,tI.current=!0,$(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),tZ.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,m=!1,g="unknown";try{if(f&&r){let e=tj.current??await tQ.current,t=await nb();t&&(h=t,X&&(eE(X),e&&await dk(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nT(t),m=!0,await dk(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),ny(1,n),g="accepted")}else t&&(h=t.id,await nT(t.id),m=!0,await dk(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&nO(h,c),g}catch(o){console.error("Failed to send message:",o);let r=o instanceof dw&&"update_draining"===o.code&&!1===o.accepted;if(!(!m||o instanceof dw&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return nO(h,c),"unknown";tR.current=!1,tI.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&dX(t)===s?e.slice(0,-1):e}),nR({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,d1(i),a,t?.id??h??void 0),nr.current=null,$(!1),eV(null),E({type:"end"}),"returned"}},[f,r,X,t,nb,nT,ny,nO,nR,nk,nj,e.chatInputRef,nP,nh]);tK.current=(0,i.useCallback)(async(n,r)=>{if(tI.current||tF.current)return;let i=`${r?"!!":"!"}${n}`;tF.current=!0,tZ.current(!0),z({command:n,excludeFromContext:r}),A(!0);try{let e=tj.current??t?.id??await nb();if(!e)throw Error("Unable to create a session for the shell command");await dk(e,{type:"bash",command:n,excludeFromContext:r}),await nm(e),ny(1,i)}catch(t){console.error("Failed to execute shell command:",t),nR({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tF.current=!1,z(null),A(!1)}},[nR,nb,nm,e.chatInputRef,ny,t]);let nV=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tF.current){try{await dk(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await dk(e,{type:"abort"}),tL.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nK=(0,i.useCallback)(async e=>{if(tF.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eN(e??null);try{let{cancelled:n,newSessionId:r}=await dk(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eN(null)}},[c]),nG=(0,i.useCallback)(async e=>{if(tF.current)return;let t=tj.current;t&&(dk(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nJ=(0,i.useCallback)(async e=>{if(tF.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&dk(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nZ=(0,i.useCallback)(async(e,t)=>{if(f){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t8.current=null,et(null)),Q(n),eE(n);let i=tj.current??await tQ.current;if(!i)return;try{await dk(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),e$(!0);try{await dk(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nm(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eT),nR({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nm(n)}finally{ni.current=!1,e$(!1)}}},[nR,eT,f,nm,Q]),nY=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(f){if(ni.current)return!1;ni.current=!0,e$(!0);let e=t2.current,a=t8.current,s=t4.current;try{t2.current=t,t8.current=n??null,t4.current="auto";let e=tj.current??await tQ.current;return e&&await dk(e,r),Q(t),et(n??null),eE(t),eo("auto"),ec(void 0),e&&await nm(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t8.current=a,t4.current=s,nR({type:"error",message:i(n)});let t=tj.current;return t&&await nm(t),!1}finally{ni.current=!1,e$(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),e$(!0);try{return await dk(a,r),await nm(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),nR({type:"error",message:i(e)}),await nm(a),!1}finally{ni.current=!1,e$(!1)}},[nR,eT,el,f,nm,Q,es]),nX=(0,i.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(f){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t4.current=t??null,eo(t??"auto"),ec(void 0),t2.current=e,t8.current=null,et(null),Q(e),eE(e)}let r=tj.current??(f?await tQ.current:null);if(r)try{await dk(r,{type:"set_role_model",role:e}),f||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Z,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eP){eU.current="manual",eA(!0),ez(null),eD(null);try{let t=await dk(e,{type:"compact"});eD(d0(t,"manual")),await nm(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eD(null)}finally{eA(!1)}}},[eP,nm]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();D(s.models),_(s.modelError??null),q(s.modelScopeWarnings??[]),K(s.thinkingLevels??{}),J(s.thinkingLevelMaps??{}),Y(s.roles??[]);let o=s.modelList??[];if(H(o),f&&!tj.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t4.current&&eo(t??"auto")}},[f,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await nb(),s=e=>(e.handled&&(e.error?nR({type:"error",message:e.error}):"openSessionStats"!==e.action&&nR({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eP)return s({handled:!0,error:"No active session to compact"});eU.current="manual",eA(!0),ez(null),eD(null);let e=await dk(a,{type:"compact",...i?{customInstructions:i}:{}});return eD(d0(e,"manual")),await nm(a,!0)&&ny(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await dk(a,{type:"reload"}),await Promise.all([nm(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await dk(a,{type:"set_session_name",name:i}),await nm(a)&&ny(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await dk(a,{type:"get_session_stats"});return e&&e1(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await dk(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nK();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await dk(a,{type:"goal",args:i});if(tV(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nE(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nR({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tI.current||tF.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tI.current=!0,$(!0),eV({kind:"running_command"});try{await nT(a);let e=await dk(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nm(a,!0)&&ny(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tI.current=!1,$(!1),eV(null),tj.current===a&&nW(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await dk(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nE(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[nR,nE,nT,nb,nK,eP,n0,nm,nw,nv,ny,h,nW]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r),"returned";let a=s3(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:a,images:s?.length??0});try{return await dk(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to steer:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r,i),"returned"}},[nR,e.chatInputRef]),n8=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(r),i),"returned";let s=s3(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:n,text:s,images:o?.length??0});try{return await dk(a,{type:"prompt",message:s,streamingBehavior:n,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(n){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",n),nR({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(r),i,a),"returned"}},[nR,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r),"returned";let a=s3(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:a,images:s?.length??0});try{return await dk(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to follow up:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r,i),"returned"}},[nR,e.chatInputRef]),n5=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await dk(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await dk(t,{type:"clear_queue"});tu({type:"withdraw"}),to({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nR({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nR]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await dk(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nR({type:"error",message:"Failed to remove queued message"})}},[nR]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ed;eo(e),eu(n),f&&(!tj.current||t7.current===tj.current)&&(t4.current=e,t3.current=n),ec(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await nb():r&&await dk(i,{type:"set_thinking_ceiling",ceiling:n}),await dk(i,{type:"set_thinking_level",level:e}),await nm(i)}catch(e){console.error("Failed to set thinking level:",e),nR({type:"error",message:"Failed to set thinking level"}),await nm(i)}},[f,nm,nR,ed,nb]);ev.current=nl?`${nl.provider}/${nl.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!L&&!eL&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?dO(t.state):void 0)??null})}).catch(()=>{})},[rt,L,eL]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await nb(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};em(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=dO(await dk(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await dk(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nR({type:"error",message:t instanceof Error?t.message:String(t)});try{i(dO(await dk(e,{type:"get_state"}))??null)}catch{i(null)}}finally{em(!1)}},[nb,ep,nR]),ri=(0,i.useCallback)(async e=>{let t=(0,cO.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await dk(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),ra=(0,i.useCallback)(e=>{tU.current=e,tB(t=>!e===t?t:!e)},[]);tZ.current=ra;let rs=(0,i.useCallback)((e="smooth")=>{tJ.current=Date.now()+700,tY.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tG.current=0,ra(!0),rs("smooth")},[rs,ra]),rl=(0,i.useCallback)(()=>{tG.current=0,ra(!1)},[ra]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!dq.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tG.current=Date.now()+1200)},[]),rd=(0,i.useCallback)(()=>{if(!tI.current&&!tF.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tG.current;!t&&Date.now()<tJ.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?ra(!0):t&&ra(!1))},[ra]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tT.current.sessionId!==tj.current&&(tT.current={sessionId:tj.current,outputs:[],seq:0}),t&&nm(t.id,!m,!0,m).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,tR.current=!!e.state.isPromptRunning,tI.current=!0,$(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nO(t.id)),e.state?.isBashRunning&&(tF.current=!0,A(!0),nH(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eA(n.isCompacting),eH(dH(n)),void 0!==n.contextUsage&&ek(n.contextUsage??null),void 0!==n.systemPrompt&&eS(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t5.current=t.id,eo(n.configuredThinkingLevel??n.thinkingLevel),ec(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&to(dD(n.queuedMessages)),void 0!==n.subagents&&tc(e=>dz(e,n.subagents??[])),void 0!==n.goal&&tV(n.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(ej)},[ej,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nJ)},[g?.tree,k,nJ,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rc),()=>{window.removeEventListener("keydown",rc)}),[rc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rc,{passive:!0}),e.addEventListener("wheel",rc,{passive:!0}),e.addEventListener("touchstart",rc,{passive:!0}),e.addEventListener("scroll",rd,{passive:!0}),()=>{e.removeEventListener("pointerdown",rc),e.removeEventListener("wheel",rc),e.removeEventListener("touchstart",rc),e.removeEventListener("scroll",rd)}},[S.length,v,rd,rc]),(0,i.useEffect)(()=>{if(t9.current||!L&&!P||!tU.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tJ.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[L,P,S.length,R.streamingMessage,eq,F,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,rs("instant");return}if(!t9.current&&tU.current){let e=Date.now()-ne.current<1500;rs(tI.current||tF.current||e?"instant":"smooth")}}},[S.length,L,P,rs,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,d]),(0,i.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[eW]),(0,i.useEffect)(()=>{if(0===eY.visible.length)return;let e=eY.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eY.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eY.visible]),(0,i.useEffect)(()=>{e1(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:b,activeLeafId:k,messages:S,entryIds:N,streamState:R,agentRunning:L,modelNames:W,modelList:O,modelError:U,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:el,thinkingCeiling:ed,retryInfo:ey,contextUsage:ew,systemPrompt:ej,forkingEntryId:eC,isCompacting:eP,compaction:eO,compactError:eF,compactResult:eW,currentModel:no,displayModel:nl,modelSwitching:eL,sessionStats:nc,runStateKnown:e_,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:ts,deliveryRows:th,subagents:tl,todoPhases:tf&&tf.sid===tj.current?tf.phases:null,compactedWork:I,notices:eY.visible,extensionDialog:e2,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nI,sendExtensionCustomInput:nM,isAutoModelSelection:f&&null===X,agentPhase:eq,isNew:f,autoFollowPaused:t_,resumeAutoFollow:ro,pauseAutoFollow:rl,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tY,scrollContainerRef:tX,handleSend:nq,handleAbort:nV,handleFork:nK,handleNavigate:nG,handleModelChange:nZ,handleRoleModelChange:nX,handleMainPresetChange:nY,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n4,handlePromptWithStreamingBehavior:n8,handleAbortCompaction:n5,handleRecallQueue:n6,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:ef,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:nb,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:E,setAgentRunning:$,setForkingEntryId:eN,bashRunning:P,pendingBash:F,handleAgentEventRef:tW}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ev,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsPanelOpen:g}),tX=(0,i.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=eQ(i);if(!a||"custom"!==i.role)continue;t??=[...e];let s=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&s.push(t);continue}let i=n.get(t);void 0===i&&(i=function(e){let t=eX(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,i)),i===a.sourceHash&&s.push(t)}s.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===a.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[r]={...i,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(eY)?{kind:"translated",text:n.slice(eY.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(i,eX(o.content??[]))}}return t??e})(ek),[ek]),tQ=rf(e?.id,tt?.provider,void 0,tt?.modelId),t0=tQ?.alias;(0,i.useEffect)(()=>{t0&&Y.current?.(t0)},[t0]);let t1=(0,i.useMemo)(()=>{if(!tt)return null;let e=tw?tW:nH.find(e=>e.alias===tQ?.alias)?.oauthPosition;return nH.find(t=>t.provider===tt.provider&&(void 0===t.oauthPosition?null===tQ||tQ.seed===t.seed:t.oauthPosition===e))?.alias??null},[tt,tw,tW,tQ]),t2=eC||eN,t8=e?.id;er.current=tX,ei.current=ej,ea.current=tI;let t4=(0,i.useRef)(!0);t4.current=!tj;let t5=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t5.current&&(es.current+=1),t5.current=eC},[eC]),(0,i.useEffect)(()=>()=>{es.current+=1},[]),(0,i.useEffect)(()=>{ee(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(ua(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t8),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t8)])},[t8]),(0,i.useEffect)(()=>{let e=tI.current;e&&et.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&ee(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(lh(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,tX,ej);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(us(e,r),r):t})},[tX,ej,tI]);let t6=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tI.current,t=t6.current;if(t6.current=e?{sessionId:e,entryIds:ej}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===lm&&r.push(t[a])}return r}(t.entryIds,ej,tX),r=ec();if(0===n.length||!r)return;let i=rp(e,"web6",void 0)?.alias??null;for(let e of n)et.current.some(t=>t.anchorEntryId===e)||ep(i,"done",r,{kind:"entry",entryId:e})},[ej,tX,tI,ec,ep]);let t3=eC&&tb?.kind==="running_tools"&&tb.tools.length>0&&tb.tools.every(e=>"wait"===e.name),t7=eb||s,{hideThinkingBlock:t9}=(D=t??e?.cwd??null,H=nF(),(0,i.useEffect)(()=>{nA(D).catch(()=>{})},[D]),H),ne=(0,i.useMemo)(()=>({hideThinking:t9}),[t9]);(0,i.useEffect)(()=>{var e;if(!tp||Z.current===tp.id)return;Z.current=tp.id;let t=ec();if(!t)return;el.current=t.turn;let n=eS.streamingMessage?.role==="assistant"?eS.streamingMessage:null,r=lf(er.current,n,tt?.provider,tt?.modelId);ef("select"===(e=tp.method)||"ask"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tp,eS.streamingMessage,tt?.provider,tt?.modelId,ec,ef]),(0,i.useEffect)(()=>(v=t2?tL:null,()=>void(v=null)),[t2,tL]),(0,i.useEffect)(()=>{I?.(t2)},[I,t2]),(0,i.useEffect)(()=>()=>I?.(!1),[I]),(0,i.useEffect)(()=>{M?.(t3)},[t3,M]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{R?.(null!==tp)},[R,tp]),(0,i.useEffect)(()=>()=>R?.(!1),[R]);let{main:nt,process:nn}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,o=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),o=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:o});a.messageCount+=t.length,a.toolCallCount+=n},l=eG(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:a,idx:e,runIndex:n,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){o(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,r.push(i);continue}if(e2(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===eQ(t)&&o(a,[{idx:i.idx}],0);continue}let s=eB(t,n),c=!1;for(let e of s){if("answer"===e.kind){d(i.idx,e.blocks),c=!0;continue}o(a,[{idx:i.idx,blocks:e.blocks}],eq(e.blocks)),l.collect(i.idx,e.blocks)}!c&&e_(t,n)&&d(i.idx,[])}return u(),{main:r,process:i}})(tX,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(e6(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!e6(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!e6(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,o=[],l=0,c=0,d=eG(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(n),precedingBlocks:o}),o=[]};for(let l=t+1;l<n;l++){let n=e[l];if("assistant"!==n.role){if(null!==eQ(n))continue;if(e2(n)){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:l});continue}let c=eB(n,r),h=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){p(l,e.blocks);continue}for(let t of(a.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eq(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&e_(n,r)&&p(l,[])}u();let h=d.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let f=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=f);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(tX,{sessionBusy:t2,isStreaming:eS.isStreaming,hideThinking:ne.hideThinking}),ne),[tX,t2,eS.isStreaming,ne]),nr=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=r2(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=r.get(l.position);e?e.calls.push(...n):r.set(l.position,{calls:[...n],placement:o?"after":"before"})}}"user"===e.role&&(a=t),e6(e)&&(s=t)});let{continuing:o}=r8(e,t,n);if(o){let e=r.get(o.position);e?e.calls.unshift(...o.calls):r.set(o.position,{calls:o.calls,placement:"before"})}return r})(nt,tX,ta?.messages),[nt,tX,ta]),ni=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=r8(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i);return{position:-1===a?e.length:a,calls:r}})(nt,tX,ta?.messages),[nt,tX,ta]),[na,ns]=(0,i.useState)(ue),{startIndex:no,endIndex:nl,hasLater:nc}=ut(nt.length,na),nd=null!==na.end&&nc,nu=(0,i.useRef)(nt.length);nu.current=nt.length;let np=(0,i.useRef)(null),nh=(0,i.useRef)(null),nf=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==na.end&&na.end>=nt.length&&ns(e=>({count:e.count,end:null}))},[na.end,nt.length]),(0,i.useEffect)(()=>{let e=np.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nf.current=t.scrollHeight-t.scrollTop,ns(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]),(0,i.useEffect)(()=>{if(null==nf.current)return;let e=tR.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nf.current),nf.current=null}},[na.count,tR]),(0,i.useEffect)(()=>{let e=nh.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ns(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=ut(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nu.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]);let[nm,ng]=(0,i.useState)(null),[nx,nv]=(0,i.useState)(0),ny=(0,i.useRef)(null),nb=(0,i.useCallback)(e=>{tC(),ny.current=e,ng(null),ns(t=>un(nu.current,e,t)),nv(e=>e+1)},[tC]);(0,i.useLayoutEffect)(()=>{let e=ny.current,t=tR.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;ny.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,ng(e)},[nx,na,nt,tR]),(0,i.useEffect)(()=>{if(null===nm)return;let e=setTimeout(()=>ng(null),1800);return()=>clearTimeout(e)},[nm]);let nw=(0,i.useCallback)(()=>{(0,_.flushSync)(()=>ns(ue));let e=tR.current;e&&(e.scrollTop=e.scrollHeight)},[tR]),nk=(0,i.useCallback)(()=>{nd&&nw(),tS()},[nd,nw,tS]),nj=(0,i.useRef)(null),[nS,nC]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!z||nj.current===z.id||z.sessionId!==e?.id||eb||0===tX.length)return;nj.current=z.id,W?.(z.id);let t=ej.indexOf(z.entryId);if(t<0)return void nC(!0);let n=0;for(let e=0;e<nt.length;e++){let r=nt[e].idx;if(r>t||(n=e,r===t))break}nb(n)},[z,e?.id,eb,tX.length,ej,nt,nb,W]),(0,i.useEffect)(()=>{if(!nS)return;let e=setTimeout(()=>nC(!1),6e3);return()=>clearTimeout(e)},[nS]);let[nN,nT]=(0,i.useState)(!1),[nI,nM]=(0,i.useState)(0),nR=(0,i.useMemo)(()=>nN?nt.map(e=>(function(e,t){if("answer"===e.kind)return e9(e.blocks);let n=t[e.idx];return n&&"content"in n?e9(n.content):""})(e,tX).toLowerCase()):uo,[nN,nt,tX]),nE=(0,i.useCallback)(e=>{tC(),ns(t=>un(nu.current,e,t))},[tC]),nL=(0,i.useCallback)(()=>nT(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tR.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nT(!0),nM(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tR]);let n$=(0,i.useMemo)(()=>{let e=[];return nt.forEach((t,n)=>{if("message"!==t.kind)return;let r=ui(tX[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nt,tX]),nP=`${no}:${nl}`,nz=ej.length>0?ej[ej.length-1]:null,[nW,nD]=(0,i.useState)(null),nO=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nO.current||!ti||eb||!e?.id||(nO.current=!0,t2||!nz||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(tX)||function(e){try{return window.localStorage.getItem(ul(e))}catch{return null}}(e.id)!==nz&&nD(nz))},[ti,eb,e?.id,t2,nz,tX]);let nU=(0,i.useCallback)(()=>{e?.id&&nW&&function(e,t){try{window.localStorage.setItem(ul(e),t)}catch{}}(e.id,nW),nD(null)},[e?.id,nW]),n_=null!==nW&&nW===nz&&!t2&&!nd,nB=tr?[tr.sessionId,tr.sessionFile??"",tr.sessionName??"",tr.userMessages,tr.assistantMessages,tr.toolCalls,tr.toolResults,tr.totalMessages,tr.tokens.input,tr.tokens.output,tr.tokens.cacheRead,tr.tokens.cacheWrite,tr.tokens.total,tr.cost??0,tr.totalActiveMs??0].join("|"):null,nq=(0,i.useRef)(tr);nq.current=tr,(0,i.useEffect)(()=>{m?.(nq.current)},[nB,m]),(0,i.useEffect)(()=>()=>{m?.(null)},[m]);let nV=eJ?`${eJ.percent??"null"}|${eJ.contextWindow}|${eJ.tokens??"null"}`:null,nK=(0,i.useRef)(eJ);nK.current=eJ,(0,i.useEffect)(()=>{x?.(nK.current)},[nV,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{y?.(tc)},[y,tc]),(0,i.useEffect)(()=>()=>{y?.([])},[y]);let{isDragOver:nG,handleDragEnter:nJ,handleDragOver:nZ,handleDragLeave:nY,handleDrop:nX}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t2||p?.current?.addAttachments(e)},[t2,p])),nQ=(0,i.useMemo)(()=>{var e;return e=ta?.messages,e&&e.length>0?[...e,...tX]:tX},[ta,tX]),n0=(0,i.useMemo)(()=>{let e=new Map;for(let t of nQ)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[nQ]),n1=(0,i.useMemo)(()=>{let e,t,n,r,i,a,s,o,l,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,i=new Map,a=new Map,s=new Map,o=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},l=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=rK(e.status);if(!r||l.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;l.add(r);let s=rV(e);null!==s&&i.set(r,s)},d=(e,t,r)=>{let i=t?n.get(t):void 0,a=rV(e);i&&"number"==typeof r&&null!==a&&"running"===rK(e.status)&&s.set(i,Math.max(s.get(i)??-1/0,r-a))},nQ.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=n0.get(e.toolCallId);if(t)for(let i of rJ(e,t)??[])n.set(i.agentId,i.key),"number"==typeof t.timestamp&&r.set(i.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(rG(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=rq(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:rq(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of rB(t.details?.jobs)){if("task"!==r.type)continue;let a=rq(r.id);if(a&&o(a,rK(r.status),i),c(r,a),d(r,a,t.timestamp),a&&"running"===rK(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of rG(t.content).matchAll(rZ)){let t=Object.fromEntries([...e[1].matchAll(rY)].map(e=>[e[1],e[2]]));t.id&&o(t.id,rK(t.status),i)}for(let e of rB(t.details?.jobs))"task"===e.type&&c(e,rq(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:i,parallelWith:a,runStartedAt:s}},[nQ,n0]),n2=(0,i.useMemo)(()=>({ledger:n1,subagents:tc,toolResults:n0,onOpenPanel:b,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:k,selectedMaker:j}),[n1,tc,n0,b,e?.id,e?.cwd,t,k,j]),n8=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=tX.length-1;n>=0;n-=1){let r=ui(tX[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[tX]),n4=(0,i.useMemo)(()=>tk(tX,n0,td,ta?.todoPhases??null),[tX,n0,td,ta]),n5=(0,i.useMemo)(()=>lN(eS.streamingMessage).join("|"),[eS.streamingMessage]),n6=(0,i.useMemo)(()=>JSON.stringify(lC(eS.streamingMessage)),[eS.streamingMessage]),n3=(0,i.useMemo)(()=>JSON.stringify(lI(eS.streamingMessage)),[eS.streamingMessage]),n7=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],o=new Map,l=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){l=n;continue}let i=lN(r),c=lI(r,a);if(0===i.length&&0===c.length||l<0)continue;let d=lC(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=o.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(a,e),s.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(tX,ej,n5.length>0?n5.split("|"):[],JSON.parse(n6),JSON.parse(n3)),[tX,ej,n5,n6,n3]),n9=e?.id??tI.current??void 0,re=(B=lE(O=(0,i.useMemo)(()=>({sessionId:n9,sessionProvider:tt?.provider,turns:n7,messages:tX,subagents:tc}),[n9,tt?.provider,n7,tX,tc])),q=lA(O),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...B,...q])),[B,q])),rt=tw&&0===tX.length&&!eS.isStreaming&&!t2,rn=e?.cwd??t??void 0,rr=tt?e$[`${tt.provider}:${tt.modelId}`]??null:null,ri=tt?eP[`${tt.provider}:${tt.modelId}`]??null:null,ra=(0,i.useRef)(null),rs=(0,i.useRef)(null),ro=(0,i.useCallback)(()=>{ra.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(T?.(ro),()=>T?.(null)),[ro,T]),(0,i.useLayoutEffect)(()=>{let e=rs.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tR.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tR.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[eb,tR]);let rl=(0,i.useCallback)((...e)=>(null!==na.end&&nw(),tE(...e)),[tE,na.end,nw]),rc=(0,r.jsx)("div",{ref:ra,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(dm,{ref:p,sessionId:e?.id??tI.current??void 0,onEnsureSession:tw&&t?tZ:void 0,onLiveTranscriptPersisted:tY,onSend:rl,onAbort:tL,onSteer:eC?tO:void 0,onFollowUp:eC?tH:void 0,onPromptWithStreamingBehavior:eC?tU:void 0,isStreaming:t2,model:tt,isAutoModelSelection:ty,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:eL,onModelChange:tA,onMainPresetChange:e||tw?tz:void 0,mainPresetActiveAlias:t1,modelRoles:eA,onRoleModelChange:tF,modelSwitching:tn,onCompact:e||tw?tD:void 0,onAbortCompaction:t_,isCompacting:e1,compactError:e7,compactResult:te,toolPreset:eF,onToolPresetChange:e||tw?tK:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,onThinkingLevelChange:e||tw?tG:void 0,fastMode:eO,fastModeBusy:eU,onFastModeToggle:e||tw?eV:void 0,availableThinkingLevels:rr,thinkingLevelMap:ri,retryInfo:eK,deliveryRows:tl,inputHistory:n8,onRecallQueue:tB,onRemoveQueuedMessage:tq,slashCommands:ts,slashCommandsLoading:to,onLoadSlashCommands:tJ,onBuiltinCommand:tV,soundEnabled:E,onSoundToggle:L,onAudioUnlock:A,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rd=eS.streamingMessage,ru=(0,i.useMemo)(()=>rd?eB(rd,{isStreaming:!0}):[],[rd]),rm=(0,i.useMemo)(()=>ru.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[ru]),rg=(0,i.useMemo)(()=>ru.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[ru]),rx=rd?.role==="assistant"?rd:null,rv=(0,i.useMemo)(()=>{let e=-1;for(let t=tX.length-1;t>=0;t-=1)if("user"===tX[t].role){e=t;break}let t=e<0?-1:aE(tX,e);return{start:t,blocks:aM(tX,t+1,tX.length),priorCiHeads:a$(tX,n0,t+1),jobNotices:aR(tX,t+1,tX.length)}},[tX,n0]),ry=(0,i.useMemo)(()=>aC(rx?[...rv.blocks,...rx.content??[]]:rv.blocks,n0,t2,rv.priorCiHeads,rn,rv.jobNotices),[rv,rx,n0,t2,rn]),rb=(0,i.useMemo)(()=>t2?{...aI(rv.blocks,n0,rn),span:aP(tX,rv.start+1,tX.length)}:null,[t2,rv,n0,rn,tX]),rw=(0,i.useMemo)(()=>rb?{...rb,flow:ry,latest:!0}:null,[rb,ry]),rk=eC&&(tb?.kind==="running_tools"||(rx?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rj=lf(tX,rx,tt?.provider,tt?.modelId),rS=rj.provider,rC=rj.model,rN=rj.credentialId;(0,i.useEffect)(()=>{if(!rk)return;let e=ec();e&&eo.current!==e.turn&&el.current!==e.turn&&(eo.current=e.turn,ef("working",e,rS,rN,rC))},[rk,rS,rC,rN,ec,ef]);let[rT,rI]=(0,i.useState)(null),rM=(0,i.useCallback)(e=>{rI(e)},[]),rR=(0,i.useMemo)(()=>eT?{role:"bashExecution",command:eT.command,output:"",excludeFromContext:eT.excludeFromContext}:null,[eT]),rE=(0,i.useMemo)(()=>{let e=[eC&&!rd&&tb?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tb,V):null,eN&&!eT?V("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eC,rd,tb,eN,eT,V]);(0,i.useEffect)(()=>{if(!rT)return void S?.(null);let e=[],t=[],n=0;if(rd&&rg.length>0){let r=rT.messages.length+e.length;for(let i of(e.push(rd),rg))t.push({idx:r,blocks:i}),n+=eq(i)}if(rR&&(t.push({idx:rT.messages.length+e.length}),e.push(rR)),0===t.length)return void S?.(rE?{...rT,status:rE}:rT);let r=-1;for(let e=rT.messages.length-1;e>=0;e--)if(e6(rT.messages[e])){r=e;break}let i=rT.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),S?.({...rT,groups:i,messages:[...rT.messages,...e],status:rE})},[rT,rg,rd,rR,rE,S]),(0,i.useEffect)(()=>()=>S?.(null),[S]);let rL=tg.filter(e=>"belowEditor"!==e.placement),r$=tg.filter(e=>"belowEditor"===e.placement);return ew?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ew}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":t7,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nJ,onDragOver:nZ,onDragLeave:nY,onDrop:nX,children:[t7?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:V("chat.loadingSession")})}):null,nG&&!t2&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:V("chat.attachFile")})}),tf&&(0,r.jsx)(ug,{request:tf,onInput:tv}),rt&&!N?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[860px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(X,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.78"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.12.6"]})]})]})]}),rn&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":V("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:V("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tN(rn)||rn}),(0,r.jsx)("code",{title:rn,children:rn}),(0,r.jsx)("p",{children:V("chat.emptyProjectHint")})]}),w&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:w,children:V("chat.openSessionList")})]}),(0,r.jsx)(uh,{notices:tu,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[N&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:N}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!N,style:{display:N?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(o8,{open:nN,onClose:nL,containerRef:tR,index:nR,renderedStart:no,renderedEnd:nl,contentKey:tX,onReveal:nE,onProgrammaticScroll:tC,focusRequest:nI,t:V}),nS&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:V("chat.jumpMissing")}),(0,r.jsx)(uh,{notices:tu,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tR,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(up,{widgets:rL}),(0,r.jsxs)(aX.Provider,{value:n2,children:[(0,r.jsx)(lb,{utterances:re,children:(0,r.jsx)(uc,{messages:tX,entryIds:ej,toolResultsMap:n0,modelNames:eM,messageCwd:rn,onOpenFile:C,sessionBusy:t2,isNew:tw,isStreaming:eS.isStreaming,handleFork:t$,forkingEntryId:eZ,handleNavigate:tP,handleEditContent:ey,sessionId:e?.id??tI.current??void 0,main:nt,dispatchSlots:nr,compactedDispatch:ni,openRequest:ta?.openRequest??null,process:nn,startIndex:no,endIndex:nl,sentinelRef:np,laterSentinelRef:nh,flashItem:nm,t:V,cues:Q,cueFollowRef:t4,onProcessLogChange:rM})}),!nd&&eS.isStreaming&&eS.streamingMessage&&rm.length>0&&(0,r.jsx)(ok,{message:eH(eS.streamingMessage,rm),sessionId:e?.id??tI.current??void 0,isStreaming:!0,modelNames:eM,cwd:rn,onOpenFile:C}),!nd&&rw&&(0,r.jsx)(sV,{summary:rw,live:!0,onOpenFile:C})]}),n_&&(0,r.jsx)(o9,{onDismiss:nU,t:V}),(0,r.jsx)("div",{ref:tM})]})})}),(0,r.jsx)(o4,{questions:n$,containerRef:tR,layoutKey:nP,onJump:nb,label:V("chat.questionRail")}),(t2&&tj||nd)&&(0,r.jsxs)("button",{type:"button",onClick:nk,"aria-label":V("chat.jumpToBottom"),title:V("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:G?44:void 0,borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),V("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rs,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tp&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,r.jsx)(um,{request:tp,onRespond:tx,onActivity:e=>void tv(e,"activity"),delivery:th})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(o7,{compaction:e3,t:V}),(0,r.jsx)(uu,{goal:tT,t:V}),(0,r.jsx)(up,{widgets:r$}),(n4||ry.steps.length>0)&&!(K&&G)&&(0,r.jsx)(dx,{phases:n4,flow:ry,busy:t2})]})}),rc,(0,r.jsx)(dg,{statuses:tm})]})]})}function uu({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nT(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nT(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function up({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function uh({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function uf({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,F.s)(),d=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!d.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=d.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:a},children:[o?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function um({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),f=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let m=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(uf,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{f(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{f();let n=e.target.value;d(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(uf,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(nc,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(uf,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&m()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function ug({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),o=eL(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eA[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":eP[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,e$(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function ux({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,o]=(0,i.useState)({kind:"idle"}),l=(0,i.useRef)(null),c=n.trim();(0,i.useEffect)(()=>{if(c.length<2)return void o({kind:"idle"});let e=new AbortController;o({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);o({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||o({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[c]);let d=e=>{let t=l.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),d(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var uv=n(50640),uy=n(73620);let ub=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function uw(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 uk=["tags","categories","keywords","tag","category"];function uj({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=uk.find(t=>Array.isArray(e[t])),s=a?e[a].map(uw).filter(Boolean):[],o=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=uw(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 uS=n(8745);let uC=(0,i.createContext)(null),uN=(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"})}),uT=(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"})}),uI=(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"})}),uM=(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"})}),uR=(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 uE({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:f}){let{t:m}=(0,F.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uI})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,l&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:l})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(uS.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)(uS.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(uS.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(uS.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":m("panel.more"),title:m("panel.more"),children:(0,r.jsx)(o.In,{size:"16px",svg:uR})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":m("panel.more"),children:(0,r.jsx)(c.k.ScrollArea,{children:(0,r.jsx)(c.k.Group,{children:h.map(e=>(0,r.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(uL,{}),f&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:f.onClick,"aria-label":f.label,title:f.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uM})})]})}function uL({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,i.useContext)(uC);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(o.In,{size:"16px",svg:n.expanded?uT:uN})})}let u$="cuelo-html-pick",uP="cuelo-html-pick-exit";function uA(e,t){return"string"==typeof e&&e.length<=t}function uF(e){return"number"==typeof e&&Number.isFinite(e)}function uz({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:o}){let{t:l}=(0,F.s)(),c=(0,i.useRef)(null),d=(0,i.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
|
|
19
|
+
${n}`:e:n,images:s,documents:o}}function ch(e,t,n){if(e===t)return n?co(n):cc(t);let r=cc(e),i=n&&!cl(n)?co(n):r??(n?co(n):null),a=cc(t),s=l2.get(e);if(l2.delete(e),s&&!l2.has(t)&&l2.set(t,s),cu(e),!i)return a;let o=a?cp(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return cd(t,o),co(o)}function cf(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function cm(e){ca();let t=l2.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)}`}(),l2.set(e,t)),t}function cg(e){let t=cf(lQ.get(e)?.documents),n=t.length?cm(e):l2.get(e);for(let[e,n]of l7){for(let e of t)n.delete(e);0===n.size&&l7.delete(e)}let r=`${n??""}|${t.join(",")}`;ce.get(e)!==r&&(0!==t.length||n?ce.set(e,r):ce.delete(e),cj())}async function cx(e){let t=cm(e);l3.set(t,(l3.get(t)??0)+1),await ct.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(l3.get(t)??1)-1;if(r>0?l3.set(t,r):l3.delete(t),e){let n=l7.get(t)??new Set;n.add(e),l7.set(t,n)}l8.set(t,l4),cj()}}}function cv(e,t){let n=l9.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&l9.delete(e),[...n].sort()}async function cy(){if(!cn)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 l2)t(n,cf(lQ.get(e)?.documents));for(let{draftId:e,ids:n}of l5.values())t(e,n);for(let[e,n]of l7)t(e,n);for(let e of l8.keys())t(e,[]);for(let e of l9.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(l3.has(e))return!1;let n=l8.get(e);return cv(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=l3.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=cv(r,i),a=cn(r,i,e).then(()=>{0===i.length?l8.delete(r):l8.set(r,i.join(","));let t=l9.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&l9.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});ct.set(r,a),await a,ct.get(r)===a&&ct.delete(r)}n?function(){if(ck)return;ck=!0;let e=setTimeout(()=>{ck=!1,cj()},cw);"object"==typeof e&&"unref"in e&&e.unref(),cw=Math.min(2*cw,6e4)}():cw=cb}let cb=5e3,cw=5e3,ck=!1;function cj(){if(cn){if(cr){ci=!0;return}cr=Promise.resolve().then(cy).finally(()=>{cr=null,ci&&(ci=!1,cj())})}}let cS=Math.floor(Number.MAX_SAFE_INTEGER/1048576),cC=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function cN(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=cS}async function cT(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!cN(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:cN((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:cC.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:cC.autoCleanupEnabled,orphanGraceDays:7}}async function cI(e={}){return cT(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function cM(e){return cT(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function cR(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 cE(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function cL(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 c$(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function cP(e,t,n){let r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,s=r===i?`:${r}`:`:${r}-${i}`;return`${a}${s} `}let cA="omp-web:model-picks";function cF(){try{let e=JSON.parse(window.localStorage.getItem(cA)??"{}");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 cz(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,o=i.prefer??"above",l=Math.min(i.minHeight??120,Math.max(0,n-2*s)),c=Math.max(0,e-a-s),d=Math.max(0,n-t-a-s),u="above"===o?c:d,p="above"===o?d:c,h=u>=r||u>=p;return{side:h?o:"above"===o?"below":"above",maxHeight:Math.max(l,Math.min(r,h?u:p))}}function cW(e,t,n){return Math.min(e*t,n)}function cD(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:o,minHeight:l,prefer:c}=n,[d,u]=(0,i.useState)({side:c??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),d=cz(i.top,i.bottom,n,cW(n,r,a),{gap:s,margin:o,minHeight:l,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,s,o,l,c,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),d}var cO=n(14755);let cH="omp-web:model-roles-expanded";async function cU(e,t,n,r,i,a,s){let o=e.slice(1).split(/\s/,1)[0];try{let l=t?.length?t:await s?.()??[],c=[...c2,...l].find(e=>e.name===o||"aliases"in e&&e.aliases?.includes(o));if(a&&(!c||"builtin"===c.source))return i(`/${o} cannot run with attachments. Remove them and retry.`),!1;let d=await n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return i(`/${o} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function c_(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let cB=["off","default","full"],cq={off:"none",default:"default",full:"full"},cV=cO.IN.join(" \xb7 "),cK=cO.C1.filter(e=>!cO.IN.includes(e)).join(" \xb7 ");function cG(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let cJ=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),cZ=0,cY={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function cX(e,t){return cJ.compare(e.name||e.modelId,t.name||t.modelId)||cJ.compare(e.provider,t.provider)||cJ.compare(e.modelId,t.modelId)}let cQ=["auto","off","minimal","low","medium","high","xhigh","max"],c0=["low","medium","high","xhigh"],c1={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},c2=[{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"}],c8=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],c4={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},c5={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function c6(e,t,n){let r=e.name.toLowerCase(),i=c3(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function c3(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function c7(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function c9(e){return{data:e.data,mimeType:e.mimeType}}function de(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function dt(e){return(e??[]).filter(nj).slice(0,10).map(de)}let dn=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,dr="\n\nTranscript of the audio ";function di(e){return s5(e).map(e=>{let t=on(e),n="audio"===t&&e.attachmentId&&!e.text.includes(dr)?dn.exec(e.text):null;return{...e,id:++cZ,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function da({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function ds(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 dl extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let dc="composer:unkeyed";async function dd(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new dl("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function du(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function dp({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function dh({error:e}){return e?(0,r.jsx)(dp,{tone:"error",title:"Model error",body:e}):null}function df({warnings:e}){return e&&0!==e.length?(0,r.jsx)(dp,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let dm=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:o,model:l,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:f,onMainPresetChange:m,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:y,onCompact:b,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:T,effectiveThinkingLevel:I,thinkingCeiling:M,onThinkingLevelChange:R,availableThinkingLevels:E,thinkingLevelMap:L,fastMode:$=null,fastModeBusy:P=!1,onFastModeToggle:A,retryInfo:z,deliveryRows:W=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,slashCommands:_,slashCommandsLoading:B,onLoadSlashCommands:q,onBuiltinCommand:V,soundEnabled:K,onSoundToggle:G,onAudioUnlock:J,onPromptWithStreamingBehavior:Z,draftKey:Y,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},en){let er,ei,ea,es,eo,el,ec,ed,eu,ep,{t:eh}=(0,F.s)(),{st:ef}=rg(),em=W.some(e=>e.removable),eg=U(),[ex,ev]=(0,i.useState)(()=>Y?cc(Y)?.value??"":""),[ey,eb]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{ey&&eN(cF())},[ey]);let[eT,eI]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(ey)try{eI("1"===window.localStorage.getItem(cH))}catch{}},[ey]);let eM=()=>{eI(e=>{let t=!e;try{window.localStorage.setItem(cH,t?"1":"0")}catch{}return t})},[eR,eE]=(0,i.useState)(!1),[eL,e$]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(!1),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(!1),[eU,e_]=(0,i.useState)(()=>Y?dt(cc(Y)?.images):[]),[eB,eq]=(0,i.useState)(()=>Y?di(cc(Y)?.documents):[]),[eV,eK]=(0,i.useState)(null),eG=(0,i.useMemo)(()=>eB.filter(e=>"ready"===e.status),[eB]),eJ=eB.some(e=>"ready"!==e.status||c_(e)),eZ=eB.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(dr))),eY=ex.trimStart(),eX=0===eU.length&&0===eB.length&&eY.startsWith("!"),eQ=eX&&eY.startsWith("!!"),[e0,e1]=(0,i.useState)(!1),[e2,e8]=(0,i.useState)(0),[e4,e5]=(0,i.useState)(null),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(0),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(0),[ti,ta]=(0,i.useState)(null),[ts,to]=(0,i.useState)(!1),[tl,tc]=(0,i.useState)(null),[td,tu]=(0,i.useState)(null),tp=X&&td?.cwd===X?td.values:{},th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tm=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(null),tj=(0,i.useRef)(null),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(0),tN=(0,i.useRef)(!1),tT=(0,i.useRef)([]),tI=(0,i.useRef)([]),tM=(0,i.useRef)([]),tR=(0,i.useRef)(null),tE=(0,i.useRef)(null),tL=(0,i.useRef)(Y),t$=(0,i.useRef)(ex),tP=(0,i.useRef)(eU),tA=(0,i.useRef)(0),tF=(0,i.useRef)(eB);t$.current=ex,tP.current=eU,tF.current=eB,(0,i.useImperativeHandle)(en,()=>({insertIfEmpty(e){let t=th.current;(t?t.value:ex).trim()||(t$.current=e,ev(e),e5(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=th.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ex,tP.current.length,tA.current,tF.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),s7(t)?.message??t),a=dt("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return nj(r)?[r]:[]})),s=di((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),s7(n)?.documents??[]));t$.current=i,tP.current=a,tF.current=s,ev(i),e5(null),tt(!1),e_(e=>(e.forEach(du),a)),eq(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tL.current!==e)return void ch(e,t);let n={value:t$.current,images:tP.current.map(c9),documents:tF.current.filter(e=>"ready"===e.status).map(da)},r=ch(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tL.current=t,i)return;let a=dt(r.images),s=ds(di(r.documents),tF.current),o=r.value;t$.current=o,tP.current=a,tF.current=s,ev(o),e_(e=>(e.forEach(du),a)),eq(s),e5(null),tt(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tL.current,a=r??i,s=a===i,o=!s&&a?cc(a):null,l=cp(e,t,s?t$.current:o?.value??"",s?tP.current.map(c9):o?.images??[],n,s?tF.current.filter(e=>"ready"===e.status).map(da):o?.documents??[]);if(a&&cd(a,l),!s)return;let c=t?.length?[...dt(t).slice(0,Math.max(0,10-tP.current.length)),...tP.current].slice(0,10):tP.current,d=ds(di(l.documents),tF.current);t$.current=l.value,tP.current=c,tF.current=d,ev(l.value),e5(null),tt(!1),t?.length&&e_(e=>{let n=Math.max(0,10-e.length),r=dt(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tP.current=i,i}),eq(d),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=th.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",o=i+s+e+a;t$.current=o,ev(o),e5(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tX(e)}}));let tz=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tP.current.length-tA.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eK(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:s9(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eK(eh("chat.attachImageLimit",{count:10})),i.length){tA.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));e_(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(du);let r=[...t,...n];return tP.current=r,r})}finally{tA.current-=i.length}}},[eh]),tW=(0,i.useCallback)(async e=>{for(let t of e){let e=s1(t);if(!e)continue;if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eK(eh("chat.attachTooLarge",{name:t.name,limit:s9(8388608)}));continue}if(tF.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eK(eh("chat.attachTotalTooLarge",{limit:s9(0x1000000)}));continue}let n={id:++cZ,name:t.name,mimeType:sX[e],size:t.size,text:"",status:"extracting"},r=[...tF.current,n];tF.current=r,eq(r);try{let e=await s6(t);if(tF.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new sY("text_too_large","Total extracted text exceeds 240000 characters");let r=tF.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tF.current=r,eq(r)}catch(i){let e=tF.current.some(e=>e.id===n.id),r=tF.current.filter(e=>e.id!==n.id);if(tF.current=r,eq(r),!e)continue;i instanceof sY?"text_too_large"===i.code?eK(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eK(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eK(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eK(eh("chat.attachPasswordProtected",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name})):eK(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tD=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.id===e))return!1;let n=t?tF.current.map(n=>n.id===e?t:n):tF.current.filter(t=>t.id!==e);return tF.current=n,eq(n),!0},[]),tO=(0,i.useCallback)((e,t)=>{if(!tF.current.some(t=>t.attachmentId===e))return!1;let n=tF.current.map(n=>n.attachmentId===e?t(n):n);return tF.current=n,eq(n),!0},[]),tH=(0,i.useCallback)((e,t,n)=>{if(!e||e===tL.current)return;let r=cc(e);r?.documents.some(e=>e.attachmentId===t)&&cd(e,{...r,documents:di(r.documents).map(e=>e.attachmentId===t?n(e):e).map(da)})},[]),tU=(0,i.useRef)(new Map),t_=(0,i.useRef)(new Map),tB=(0,i.useRef)(new Set),tq=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=or({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tV=(0,i.useCallback)(e=>e instanceof dl&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof dl&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tK=(0,i.useCallback)(async(e,t)=>{let n=tL.current,r=tF.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;t_.current.get(e)?.abort();let a=new AbortController;t_.current.set(e,a),tO(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await dd(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new dl("Invalid transcription result",null,null,null);let i=r.transcript;tO(e,e=>tq(e,i,tF.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tH(n,e,e=>tq(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tO(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof dl&&"confirmation_required"===n.code)return void tG.current?.(e);let t=tV(n);tO(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t_.current.get(e)===a&&t_.current.delete(e)}},[eh,tV,tO,tH,tq]),tG=(0,i.useRef)(null),tJ=(0,i.useCallback)(async e=>{let t;t_.current.get(e)?.abort();let n=new AbortController;t_.current.set(e,n),tO(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new dl("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await dd(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tO(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tV(t);tO(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t_.current.get(e)===n&&t_.current.delete(e)}t.requiresConfirmation?tO(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tK(e,!1)},[tK,tV,tO]);tG.current=tJ;let tZ=(0,i.useCallback)(e=>{let t=t_.current.get(e);t?t.abort():tO(e,e=>({...e,transcription:{state:"skipped"}}))},[tO]),tY=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tF.current.length>=3){eK(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++cZ,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tF.current,i];tF.current=a,eq(a);let s=(e,t)=>{let n=tF.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?s4("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?s4("utf-16be",t.subarray(2)):t.includes(0)?null:s4("utf-8",t)??s4("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tD(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await cI().catch(()=>cC)).uploadLimitMb),r.size>n){tD(i.id,null)&&eK(eh("chat.attachStoredTooLarge",{name:r.name,limit:s9(n)}));continue}let o={...i,stored:t,status:"uploading",size:0};if(!tD(i.id,o))continue;let l=tL.current??dc,c=await cx(l),d=null,u=new AbortController;tU.current.set(i.id,u);try{if(tB.current.has(i.id))continue;let e=await oi(r,{sessionId:Q,draftId:c.draftId,signal:u.signal}),n=tF.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=or({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tD(i.id,null)&&eK(eh("chat.attachTotalTooLarge",{limit:s9(0x1000000)}));continue}let h={...o,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tD(i.id,h))d=e.id;else if(!tB.current.has(i.id)&&l!==tL.current){let t=cc(l)??{value:"",images:[],documents:[]};cd(l,{...t,documents:[...t.documents,da(h)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tD(i.id,null)&&eK(eh("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tU.current.delete(i.id),c.end(d)}d&&"audio"===t&&tF.current.some(e=>e.attachmentId===d)&&tJ(d)}},[tD,tJ,Q,eh]),tX=(0,i.useCallback)(async e=>{eK(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==s1(a)?n.push(a):s8(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tz(t),tW(n.filter(e=>e.size<=8388608)),tY(r,"audio"),tY([...i,...a],"file")])},[tW,tY,tz]),tQ=(0,i.useCallback)(e=>{e_(t=>{let n=[...t],[r]=n.splice(e,1);return r&&du(r),tP.current=n,n})},[]),t0=(0,i.useCallback)(e=>{let t=tF.current.find(t=>t.id===e);if(tB.current.add(e),tU.current.get(e)?.abort(),t?.attachmentId){t_.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of l7)t.delete(n)&&(0===t.size&&l7.delete(e),cj())}let r=tF.current.filter(t=>t.id!==e);tF.current=r,eq(r)},[]),t1=(0,i.useCallback)(()=>{tP.current=[],e_(e=>(e.forEach(du),[]))},[]),t2=(0,i.useCallback)(()=>{tF.current=[],eq([])},[]),t8=(0,i.useCallback)(()=>{t$.current="",ev(""),e5(null),tt(!1),Y&&cu(Y),tL.current&&tL.current!==Y&&cu(tL.current),t1(),t2(),eK(null),th.current&&(th.current.style.height="auto")},[t2,t1,Y]);(0,i.useEffect)(()=>{Y&&tL.current===Y&&cd(Y,{value:ex,images:eU.map(c9),documents:eG.map(da)})},[eU,Y,eG,ex]),(0,i.useEffect)(()=>{let e=tL.current;if(e===Y)return;e&&cd(e,{value:t$.current,images:tP.current.map(c9),documents:tF.current.filter(e=>"ready"===e.status).map(da)});let t=Y?cc(Y):null;tL.current=Y;let n=t?.value??"",r=dt(t?.images),i=di(t?.documents);t$.current=n,tP.current=r,tF.current=i,ev(n),e5(null),tt(!1),e_(e=>(e.forEach(du),r)),eq(i)},[Y]),(0,i.useEffect)(()=>{let e=th.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tP.current.forEach(du)},[]);let t4=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=cf(t);if(0===n.length)return()=>{};let r=++l6;return l5.set(r,{draftId:cm(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=l5.get(r);if(t){if(l5.delete(r),"accepted"===e){let e=l9.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);l9.set(t.draftId,e)}cj()}}}(tL.current??dc,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t5=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eY.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eU.length&&!eG.length||o||eJ)return;J?.();let i=eU.length?eU:void 0,a=eG.length?eG:void 0;if(r.startsWith("/")){await cU(r,_,V,t=>t4(a,()=>e(t,i,a)),eK,!!(i||a),q)&&t8();return}t8(),t4(a,()=>e(r,i,a))},[ex,eY,eU,eG,eJ,o,V,_,q,e,t8,J,t4]),t6=eY.startsWith("/")&&!/\s/.test(eY.slice(1))?eY.slice(1).toLowerCase():null,t3=(()=>{if(null===t6)return[];let e=[...o?[]:c2,..._??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=c3(e,eh).toLowerCase();return t.includes(t6)||n.includes(t6)}).sort((e,t)=>{let n=c6(e,t6,eh)-c6(t,t6,eh);return 0!==n?n:c5[e.source]-c5[t.source]||cJ.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t7,groups:t9}=(er=0,{commands:(ei=c8.map(e=>{let t=t3.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!c7(e,tp)),...t.filter(e=>c7(e,tp))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),ne=1===t3.length?eh(t6?"chat.match":"chat.command"):eh(t6?"chat.matches":"chat.commands",{count:t3.length}),nt=!!ex.trim(),nn=!eJ&&(nt||eU.length>0||eG.length>0),nr=(0,i.useCallback)((e,t)=>{if(!X)return void e5(null);let n=t??e.length;e5(cR(e.slice(0,n)))},[X]),ni=e4?.query??null,na=i.useMemo(()=>null!==ni&&ti&&ti.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:cL(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:cL(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||cE(e.entry.path)-cE(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(ti.entries,ni):[],[ni,ti,X]),ns=!!(ni&&ti?.truncated&&ti.cwd===X);(0,i.useEffect)(()=>{if(!ns||!X||!ni)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(ni)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tc({cwd:X,query:ni,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ns,ni,X]);let no=ns&&null!==tl&&tl.cwd===X&&tl.query===ni,nl=no?tl.matches:na,nc=null===e4?null:`${e4.start}:${+!!e4.quoted}:${e4.query}`;(0,i.useEffect)(()=>{if(null===nc){e3(!1),e9(0);return}e3(!0),e9(0)},[nc]);let nd=null!==e4,nu=cD(tk,te,{viewportFraction:.44,cap:360}),np=cD(tk,e0,{viewportFraction:.56,cap:460}),nh=cD(tk,e6,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!X)return;let e=tR.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tE.current===X||(tE.current=X,to(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{ta({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>cE(e.path)-cE(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tR.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tR.current=null}).finally(()=>{tE.current=null,to(!1)}))},[nd,X]);let nf=(0,i.useCallback)(e=>{if(!e4)return;let t=th.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e4.start),i=ex.slice(n);e4.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e4.quoted),s=r+a.text+i,o=r.length+a.cursorOffset;ev(s),e5(cR(s.slice(0,o))),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(o,o),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e4,ex]);(0,i.useEffect)(()=>{e7>=nl.length&&e9(Math.max(0,nl.length-1))},[nl.length,e7]),(0,i.useEffect)(()=>{tI.current.length=nl.length},[nl.length]),(0,i.useEffect)(()=>{e6&&tI.current[e7]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e7,e6]),(0,i.useEffect)(()=>{tn>=D.length&&tr(Math.max(0,D.length-1))},[D.length,tn]),(0,i.useEffect)(()=>{tM.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{te&&tM.current[tn]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tn,te]);let nm=(0,i.useCallback)(e=>{t$.current=e,ev(e),tt(!1),tr(0),e5(null),requestAnimationFrame(()=>{let t=th.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),ng=(0,i.useCallback)(e=>{let t=`/${e.name} `;t$.current=t,ev(t),e1(!1),e8(0),requestAnimationFrame(()=>{let e=th.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eY.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eJ||!i&&0===eU.length&&0===eG.length?null:{message:i,images:eU.length?eU:void 0,documents:eG.length?eG:void 0};if(!s)return;J?.();let o="steer"===e?"steer":"followUp";if(i.startsWith("/")){await cU(i,_,V,e=>{if(!Z)throw Error("Cannot queue this command while the session is busy.");t4(s.documents,()=>Z(e,o,s.images,s.documents))},eK,!!(s.images?.length||s.documents?.length),q)&&t8();return}t8(),"steer"===e&&n?t4(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t4(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eY,eU,eG,eJ,_,q,V,Z,n,a,t8,J,t4]),nv=(0,i.useCallback)(e=>{let t=t7.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e2-1);if("right"===e)return Math.min(t,e2+1);let n=tT.current[e2];if(!n)return"down"===e?Math.min(t,e2+1):Math.max(0,e2-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,o=1/0;for(let n=0;n<=t;n+=1){if(n===e2)continue;let t=tT.current[n];if(!t)continue;let r=t.getBoundingClientRect(),l=r.top+r.height/2-a;if("down"===e?l<=4:l>=-4)continue;let c=1e3*Math.abs(l)+Math.abs(r.left+r.width/2-i);c<o&&(s=n,o=c)}return s>=0?s:"down"===e?Math.min(t,e2+1):Math.max(0,e2-1)},[t7.length,e2]),ny=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tC.current<100,s=tS.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(te&&!s){if("ArrowDown"===e.key){e.preventDefault(),tr(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tr(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tt(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[tn]){e.preventDefault(),nm(D[tn]);return}}if(e0&&null!==t6){if("ArrowDown"===e.key){e.preventDefault(),e8(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e8(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e8(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e8(nv("left"));return}if("Escape"===e.key){e.preventDefault(),e1(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t7[e2]){e.preventDefault(),ng(t7[e2]);return}}if(e6&&null!==e4&&!s){if("ArrowDown"===e.key){e.preventDefault(),e9(e=>Math.min(Math.max(0,nl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e9(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e3(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nl[e7]){e.preventDefault(),nf(nl[e7]);return}}if("ArrowUp"===e.key&&!s&&!o&&D.length>0&&0===ex.trim().length){e.preventDefault(),e1(!1),e3(!1),tr(D.length-1),tt(!0);return}if("Escape"===e.key&&!s&&o&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),o&&(n||a)?nx(n?"steer":"followup"):t5())},[o,n,a,t,e0,t6,t7,e2,ng,nx,t5,nv,e6,e4,nl,e7,nf,te,D,tn,nm,ex]),nb=(0,i.useCallback)(()=>{let e=th.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nw=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tX(t))},[tX]);(0,i.useEffect)(()=>{if(null===t6){e1(!1),e8(0),tN.current=!1;return}e1(!0),e8(0),!tN.current&&q&&(tN.current=!0,Promise.resolve(q()).catch(()=>{tN.current=!1}))},[t6,q]),(0,i.useEffect)(()=>{if(!e0||!X)return;let e=!1;return tu({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tu({cwd:X,values:n})}).catch(()=>{e||tu({cwd:X,values:{}})}),()=>{e=!0}},[e0,X]),(0,i.useEffect)(()=>{e2>=t7.length&&e8(Math.max(0,t7.length-1))},[t7.length,e2]),(0,i.useEffect)(()=>{tT.current.length=t7.length},[t7.length]),(0,i.useEffect)(()=>{e0&&tT.current[e2]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e2,e0]);let nk=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(cX):Object.entries(d??{}).map(([e,t])=>({provider:l?.provider??"unknown",modelId:e,name:t})).sort(cX),nS=g??null,nC=nH.find(e=>e.alias===nS)?.provider??null,nN=nC?nk.filter(e=>e.provider===nC):nk,nI=(ea=ej.trim().toLocaleLowerCase())?nN.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):nN,nM=nN.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=nC?[]:(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$=ej.trim()?[]:nN.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nP=(e,t,n)=>{let i=e.modelId===l?.modelId&&e.provider===l?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(eb(!1),eS(""),!i||c){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(cF(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(cA,JSON.stringify(r))}catch{}eN(r),f?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nA=l?nk.find(e=>e.modelId===l.modelId&&e.provider===l.provider)?.name??l.modelId:null,nF=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nz=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${nT(S.tokensBefore)} -> ${nT(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:nT(nF)})})`:null,nW=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},nD="auto"===(es=T??"auto")?M?`auto ≤ ${nW(M)??M}`:"auto":L?L[es]??es:es,nO=(T??"auto")==="auto"&&I&&"auto"!==I?L?.[I]??I:null,nU=R&&nO?eh("chat.currentReasoning",{level:nO}):null,n_=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...c0.filter(n_).map(e=>({level:"auto",ceiling:e})),...cQ.filter(e=>"auto"!==e&&n_(e)).map(e=>({level:e,ceiling:null}))],nq=Object.entries(cq).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tf.current&&!tf.current.contains(e.target)&&tm.current&&!tm.current.contains(e.target)&&(eb(!1),eS("")),tg.current&&!tg.current.contains(e.target)&&tx.current&&!tx.current.contains(e.target)&&eE(!1),tv.current&&!tv.current.contains(e.target)&&eA(!1),ty.current&&!ty.current.contains(e.target)&&ez(!1),tb.current&&!tb.current.contains(e.target)&&eH(!1),!tw.current||tw.current.contains(e.target)||th.current?.contains(e.target)||tt(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eH(!1)},[eg]);let nV=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eU.length||eB.length?" is-active":""}`,onClick:()=>tj.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:eU.length||eB.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=eU.length||eB.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eU.length||eB.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),nK=m&&nH.length>0?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eR?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e$({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eR,onKeyDown:e=>{"Escape"===e.key&&eR&&(e.stopPropagation(),eE(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eg?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eR&&eL&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=cz(eL.top,eL.bottom,e,cW(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eL.top+6}:{top:eL.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eL.left,width:"max-content",minWidth:eL.width};return(0,r.jsx)("div",{ref:tx,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eE(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:nH.map(e=>{let t=e.alias===nS;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eE(!1),m({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:nG(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children: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=R?(0,r.jsxs)("div",{ref:ty,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eF?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eD({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(!1),eS(""),eE(!1),ez(e=>!e)},disabled:o||y,"aria-haspopup":"menu","aria-expanded":eF,onKeyDown:e=>{"Escape"===e.key&&eF&&(e.stopPropagation(),ez(!1))},title:eh("chat.changeReasoning",{level:nD}),"aria-label":eh("chat.changeReasoning",{level:nD}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eF?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eF?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nD})]}),eF&&eW&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=cz(eW.top,eW.bottom,e,cW(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eW.top+6}:{top:eW.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eW.left,width:"max-content",minWidth:Math.max(180,eW.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(ez(!1),ty.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(T??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nW(i),s=t?`auto ≤ ${a??t}`:a??e,o=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(c1[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{ez(!1),R(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},t?`auto-${t}`:e)})})})()]}):null,nZ=A?(eo=P?eh("chat.fastModeBusy"):null===$?eh("chat.fastModeUnknown"):$.active?eh("chat.fastModeActive"):$.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),el=P||o||y,ec=$?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${$?.active?" is-active":""}`,onClick:A,disabled:el,"aria-pressed":null===$?void 0:$.enabled,"aria-busy":P||void 0,title:eo,"aria-label":eo,style:{flexShrink:0,opacity:o?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:$?.active?"var(--accent)":"none",stroke:ec?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===$?"3 2":void 0,style:{opacity:ec&&!$?.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:()=>nx("steer"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:nn?"var(--warning)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!nn,title:eJ?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nn?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nX=void 0!==G?(0,r.jsx)(lH,{soundEnabled:K??!0,onToggle:G}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tj,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tX(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(dh,{error:p}),(0,r.jsx)(df,{warnings:h}),W.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:ef("delivery.title",{count:W.length})}),O&&em&&(0,r.jsxs)("button",{onClick:O,title:eh("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(lW,{rows:W,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("steer"===e?"steering":"followUp",t):void 0})]}),z&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:z.attempt,max:z.maxAttempts}),z.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",z.errorMessage]})]}),nz&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nz]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eV&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eV}),(0,r.jsx)("button",{type:"button",onClick:()=>eK(null),"aria-label":eh("i18n.close"),title:eh("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(eU.length>0||eB.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eU.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tQ(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eB.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||c_(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"}}):rT(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):cY[e.mimeType]," \xb7 ",s9(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t0(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eZ.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eZ.map(e=>{let t,n,i,a,o=e.attachmentId,l=e.transcription,c=l?.state==="confirm"||l?.state==="running"?l.plan:null,d=c?eh("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:c.estimatedCalls}):null,u=l?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):l?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):l?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:l?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:l.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,r.jsxs)("div",{"data-transcription-state":l?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${l?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:l?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:l?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[l.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:l.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[l?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tK(o,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeSkip")})]}),(l?.state==="planning"||l?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tZ(o),children:eh("chat.transcribeCancel")}),(void 0===l||"skipped"===l.state||"failed"===l.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tJ(o),children:eh(l?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tk,style:{position:"relative",minWidth:0},children:[te&&D.length>0&&(0,r.jsxs)("div",{ref:tw,style:{position:"absolute",left:0,right:0,...cG(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nu.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===tn;return(0,r.jsxs)("button",{ref:e=>{tM.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>tr(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),e0&&null!==t6&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...cG(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:B?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:ne})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:10},children:B||0!==t3.length?t9.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(c4[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===e2,i=c7(e,tp);return(0,r.jsxs)("button",{ref:e=>{tT.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),ng(e)},onMouseEnter:()=>e8(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),c3(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:c3(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e6&&null!==e4&&(ed=ts&&(!ti||ti.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=ti?.truncated&&!no?e4.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...cG(nh.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nh.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ed?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nh.maxHeight-34),overflowY:"auto",padding:4},children:ed||0!==nl.length?nl.map((e,t)=>{let n=t===e7,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tI.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>e9(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(rS,{size:14}):rT(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:ns&&!no?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eX?" is-bash":""}${o?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eX?"var(--tool-bg)":o&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:th,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),tt(!1),nr(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nr(t.value,t.selectionStart)},onKeyDown:ny,onCompositionStart:()=>{tS.current=!0},onCompositionEnd:e=>{tS.current=!1,tC.current=Date.now();let t=e.currentTarget;nr(t.value,t.selectionStart)},onInput:nb,onPaste:nw,placeholder:o&&(n||a)?eh("chat.steerPlaceholder"):o?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),o?eg?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nY}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t5,disabled:!nn,"aria-busy":eJ||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eJ?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:nn?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nn?"var(--accent-hover)":"var(--text-dim)",cursor:nn?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eX&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eQ?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eQ?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!o)&&nV,!eg&&nK,!(eg&&o)&&(nk.length>0||nA||p)&&f&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.jsxs)("button",{className:`composer-chip${ey?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eb(e=>(e&&eS(""),!e))},disabled:o||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:ey?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o||y?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ey?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":nk.length>0?"Change model":"No available models",children:[y?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nA??(nk.length>0?"Select model":"No models")})]}),ey&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=cz(ew.top,ew.bottom,e,cW(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tm,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),eb(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[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:eh("chat.frequentModels")}),n$.map(({option:e,count:t})=>nP(e,"frequent",t))]}),nE.length>0&&!ej.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":eT,"aria-controls":"model-role-rows",onClick:eM,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eT?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:eh("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nE.length}),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:!eT,children:nE.map(e=>{let t=nL?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{eb(!1),eS(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)})}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eh("chat.allModels")})]}),0===nR.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):nR.map((e,t)=>(0,r.jsxs)("div",{children:[nR.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nP(e,"all"))]},e.provider))]})]})})()]}),eg&&o&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nY}),!eg&&nJ,!eg&&nZ,!eg&&nU&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nU}),(0,r.jsx)(lX,{sessionId:Q})]}),(0,r.jsxs)("div",{ref:tb,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eO?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eO?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eO,onClick:()=>{eb(!1),eS(""),eH(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eO?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eg&&(0,r.jsxs)(r.Fragment,{children:[o&&nV,nK,nJ,nZ]}),!o&&N&&(0,r.jsxs)("div",{ref:tv,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eP?" is-active":""}`,onClick:()=>!o&&eA(e=>!e),disabled:o,title:eh("chat.changeToolPreset")+`: ${nq}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eP?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:o?"not-allowed":"pointer",fontSize:12,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eP?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nq})]}),eP&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:cB.map(e=>{let t=cq[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:cV}):eh("chat.allBuiltInTools",{tools:`${cV} + ${cK}`});return(0,r.jsxs)("button",{onClick:()=>{eA(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!o&&b&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:b,disabled:o&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:o&&!k?"not-allowed":"pointer",fontSize:12,opacity:o&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!o||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nX,eO&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eA(!1),ez(!1),eH(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(lZ,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nX]})]})]})]})});function dg({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=eI(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:e$(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function dx({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:s}=rg(),[o,l]=(0,i.useState)(!1),[c,d]=(0,i.useState)(!1),[u,p]=(0,i.useState)(!1),h=(0,i.useId)(),f=e??[],{currentPhase:m,activeTask:g,remaining:x,completed:v,total:y,percent:b}=tj(f),w=t.steps.length>0,k=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,s);if(0===y&&null===k)return null;let j=y>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${j?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:j?"✓":"›"}),k&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:k}),y>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":o,onClick:()=>l(e=>!e),children:[!k&&m&&(0,r.jsx)("span",{className:"todo-strip-phase",children:m.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:j?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:j?a("todo.progressDone",{percent:b??0,completed:v,total:y}):a("todo.progress",{percent:b??0,completed:v,total:y,remaining:x})})]}),w&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":h,onClick:()=>d(e=>!e),children:[s("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&w&&(0,r.jsx)(so,{flow:t,live:n,st:s,id:h}),o&&y>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[f.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[f.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(rw,{task:e},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>p(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function dv(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function dy(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function db(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 dw extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function dk(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 dw(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let dj="ompweb-update-client-id",dS="ompweb-update-resume-intent-v2",dC="ompweb-update-return-v1",dN="cuelo-restart-return-v1",dT="ompweb-update-failure-return-v1",dI="ompweb:update-wake";function dM(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function dR(){let e=sessionStorage.getItem(dj);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(dj,t),t}function dE(){sessionStorage.removeItem(dS)}function dL(){let e=sessionStorage.getItem(dC);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 d$(e){let t=dL();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(dC,JSON.stringify(n))}catch{}return n}async function dP(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:dR(),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 dA(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=dL();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(dC,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),dE();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(dI,{detail:{sessionId:e.sessionId}}))}async function dF(e){let t=function(e){let t=sessionStorage.getItem(dT);if(!t)return null;sessionStorage.removeItem(dT);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?(dE(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(dI,{detail:{sessionId:e.sessionId}})),"failed"):(await dA(e),"resumed")}function dz(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 dW(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 dD(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function dO(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function dH(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 dU(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function d_(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function dB(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!e4(r??void 0))return{message:e[n],entryId:r}}return null}let dq=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class dV 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 dK(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function dG(e){return new Promise(t=>setTimeout(t,e))}function dJ(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function dZ(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:dJ(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:dJ(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=dJ(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function dY(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 dX(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(dY).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function dQ(e){return"user"===e.role?`user:${dX(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 d0(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 d1(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function d2(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let d8=!1,d4={width:0,height:0},d5=new Set,d6=null;function d3(){let e=window.visualViewport,t=d2();d4.width!==window.innerWidth?d4={width:window.innerWidth,height:window.innerHeight}:t||(d4.height=Math.max(d4.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:d4.height});if(n!==d8)for(let e of(d8=n,d5))e()}function d7(e){if(d5.add(e),!d6){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,d3()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),d3(),d6=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{d5.delete(e),0===d5.size&&d6&&(d6(),d6=null)}}function d9(){return(0,i.useSyncExternalStore)(d7,()=>d8,()=>!1)}let ue={count:50,end:null};function ut(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function un(e,t,n){let{startIndex:r,endIndex:i}=ut(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function ur({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:la[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(lt(),{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 ui(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=(s7(t)?.message??t).trim();return n.length>0?n:null}function ua(e){return`omp-cues:${e}`}function us(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(ua(e),JSON.stringify(n.slice(-200)))}catch{}}let uo=[];function ul(e){return`omp-web:interrupted-dismissed:${e}`}let uc=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:o,sessionBusy:l,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:f,sessionId:m,main:g,process:x,dispatchSlots:v,compactedDispatch:y,openRequest:b,startIndex:w,endIndex:k,sentinelRef:j,laterSentinelRef:S,flashItem:C,t:N,onProcessLogChange:T,cues:I,cueFollowRef:M}){(0,i.useEffect)(()=>{T({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:m})},[T,x,e,t,n,a,s,m]);let R=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let o of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[o.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(o.blocks?i.get(o.idx):void 0)??o.afterMainIndex??-1),l=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=e7(i.action);if(!0===e3[e]){let t={kind:"skill",action:e,name:e7(i.name)};n(JSON.stringify(t),t)}continue}let a=e7(i.memory),s=i.skill,o=s?{action:e7(s.action),name:e7(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:o}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...o?{skill:o}:{}})}}(o.blocks??e.content??[],r,(e,t)=>{if(l.has(e))return;l.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return N("chat.savedSkill",{action:e.action,name:e.name});let t=N("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${N("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:e1,content:[N("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,N]),E=(0,i.useMemo)(()=>{let r=null;if(l)for(let t of g)"message"===t.kind&&e[t.idx]?.role==="user"&&(r=t.idx);return function(e,t,n,r,i,a,s=[]){let o=function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&aE(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:aE(t,n),s=new Map;for(let[n,o]of(e.forEach((e,n)=>{"answer"===e.kind&&s.set(aE(t,e.anchorIdx),n)}),s)){if(n===a)continue;let e=i.find(e=>e>n);r.set(o,{from:n+1,to:e??t.length})}return r}(e,t,n),l=-1;for(let e of o.keys())e>l&&(l=e);let c=new Map,d=[],u=0;for(let[e,n]of[...o].sort((e,t)=>e[1].from-t[1].from)){if(a$(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let i=n.to-1;for(;i>=n.from&&e4(s[i]);)i-=1;if(s[i]!==a.throughEntryId)continue;let o=aM(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),p=aL(t,r,n.from,n.to);c.set(e,{...a.summary,...p?{remaining:aT(p)}:{},dispatchCalls:o,latest:e===l}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,i,a=[]){let s=aM(e,n,r),o=aL(e,t,n,r);return{...aI(s,t,i),remaining:o?aT(o):null,span:aP(e,n,r),flow:aC(s,t,!1,a,i,aR(e,n,r))}}(t,r,n.from,n.to,i,d),latest:e===l})}return c}(g,e,r,n,s,b,t)},[g,e,n,s,l,b,t]),L=w>0,$=k<g.length,P=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&e4(t[v]);)v-=1;let y="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,b=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(ok,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:o,entryId:t[i],onFork:l||c||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:l?void 0:h,prevAssistantEntryId:l?void 0:y,onEditContent:f,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:m,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${b}-view-${i}`)},A=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:C===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[L&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:N("chat.loadEarlier",{count:w})}),g.slice(w,k).map((a,l)=>{let c=w+l,d=y?.position===c?(0,r.jsx)(sS,{calls:y.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[c+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,f=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<f}).map(e=>(0,r.jsx)(ur,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:M},`cue-${e.id}`)),b=h!==u,k=R.get(c),j=k?(0,r.jsx)(ok,{message:k,cwd:s,onOpenFile:o},`saved-lessons-${c}`):null,S=b?(0,r.jsx)(lw,{turnIndex:u,turnEntryId:t[u],sessionId:m,cwd:s,onOpenFile:o}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx)),j,S,x]},`message-${a.idx}`);let C=tx(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[d,A(c,P(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=eH(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(c),turnSummary:E.get(c)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),y?.position===g.length&&k===g.length&&(0,r.jsx)(sS,{calls:y.calls}),$&&(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 ud({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:o,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsChange:m,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:y,onOpenWorkspaceView:b,onOpenSessionList:w,onOpenMaker:k,selectedMaker:j,onProcessLogChange:S,onOpenFile:C,transcriptReplacement:N,onComposerFocusChange:T,onSessionBusyChange:I,onWaitingChange:M,onAttentionChange:R,soundEnabled:E=!0,onSoundToggle:L,playCueSound:$=async()=>({sticker:null,text:null}),preloadCueSound:P,unlockAudio:A,jumpRequest:z=null,onJumpHandled:W}){var D,O;let H,B,q,{t:V}=(0,F.s)(),K=d9(),G=U(),J=(0,i.useRef)($);J.current=$;let Z=(0,i.useRef)(null),Y=(0,i.useRef)(P);Y.current=P;let[Q,ee]=(0,i.useState)([]),et=(0,i.useRef)(Q);et.current=Q;let en=(0,i.useRef)(0),er=(0,i.useRef)([]),ei=(0,i.useRef)([]),ea=(0,i.useRef)(null),es=(0,i.useRef)(0),eo=(0,i.useRef)(-1),el=(0,i.useRef)(-1),ec=(0,i.useCallback)(()=>{let e=ea.current?.current;return e?{sessionId:e,turn:es.current}:null},[]),ed=(0,i.useCallback)(e=>ea.current?.current===e.sessionId&&es.current===e.turn,[]),eu=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;en.current=Math.max(en.current+1,Date.now());let i={id:en.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};ee(e=>{let t=[...e,a];return null!==a.anchorEntryId&&us(n.sessionId,t),t})},[]),ep=(0,i.useCallback)((e,t,n,r)=>{let i=()=>ed(n)&&("working"!==t||el.current!==n.turn);i()&&J.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&eu(e,t,n,r)}).catch(()=>{})},[ed,eu]),eh=(0,i.useCallback)(async(e,t,n,r)=>{let i=(await rh(e,t,n,r))?.alias??null;return i&&Y.current?.(i),i},[]),ef=(0,i.useCallback)((e,t,n,r,i)=>{let a=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=lh(e[n]),a=0;for(let t=r;t<=n;t++)lh(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(er.current,ei.current);eh(t.sessionId,n,r,i).then(n=>{ep(n,e,t,a)})},[ep,eh]),[em,eg]=(0,i.useState)(0),ex=(0,i.useRef)([]),ev=(0,i.useCallback)(e=>{if(es.current+=1,null!==lo(e.outcome)){let t=e.sessionId;ex.current.push({completion:e,trigger:t?{sessionId:t,turn:es.current}:null}),eg(e=>e+1)}o?.(e)},[o]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ex.current.splice(0)){let n=lo(e.outcome),r="neutral"===n?null:n;t?ef(r,t,e.provider,e.credentialId,e.model):J.current(null,r).catch(()=>{})}},[em,ef]);let ey=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:eb,error:ew,messages:ek,entryIds:ej,streamState:eS,agentRunning:eC,bashRunning:eN,pendingBash:eT,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:eL,modelThinkingLevels:e$,modelThinkingLevelMaps:eP,modelRoles:eA,toolPreset:eF,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,fastMode:eO,fastModeBusy:eU,handleFastModeToggle:eV,retryInfo:eK,contextUsage:eJ,forkingEntryId:eZ,isCompacting:e1,compaction:e3,compactError:e7,compactResult:te,displayModel:tt,modelSwitching:tn,sessionStats:tr,runStateKnown:ti,compactedWork:ta,slashCommands:ts,slashCommandsLoading:to,deliveryRows:tl,subagents:tc,todoPhases:td,notices:tu,extensionDialog:tp,extensionResponse:th,extensionCustomUi:tf,extensionStatuses:tm,extensionWidgets:tg,respondToExtensionUi:tx,sendExtensionCustomInput:tv,isAutoModelSelection:ty,agentPhase:tb,isNew:tw,autoFollowPaused:tj,resumeAutoFollow:tS,pauseAutoFollow:tC,goalStatus:tT,sessionIdRef:tI,messagesEndRef:tM,scrollContainerRef:tR,handleSend:tE,handleAbort:tL,handleFork:t$,handleNavigate:tP,handleModelChange:tA,handleRoleModelChange:tF,handleMainPresetChange:tz,newSessionAccount:tW,handleCompact:tD,handleSteer:tO,handleFollowUp:tH,handlePromptWithStreamingBehavior:tU,handleAbortCompaction:t_,handleRecallQueue:tB,handleRemoveQueuedMessage:tq,handleBuiltinSlashCommand:tV,handleToolPresetChange:tK,handleThinkingLevelChange:tG,loadSlashCommands:tJ,ensureNewSession:tZ,refreshLiveTranscript:tY}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:o,onSessionCreated:l,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,f=null===t&&null!==r,m=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(m),[v,y]=(0,i.useState)(!f&&!m),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(m?.leafId??null),[S,C]=(0,i.useState)(m?.context.messages??[]),[N,T]=(0,i.useState)(m?.context.entryIds??[]),[I,M]=(0,i.useState)(m?.context.compactedWork??null),[R,E]=(0,i.useReducer)(dW,{isStreaming:!1,streamingMessage:null}),[L,$]=(0,i.useState)(!1),[P,A]=(0,i.useState)(!1),[F,z]=(0,i.useState)(null),[W,D]=(0,i.useState)({}),[O,H]=(0,i.useState)([]),[U,_]=(0,i.useState)(null),[B,q]=(0,i.useState)([]),[V,K]=(0,i.useState)({}),[G,J]=(0,i.useState)({}),[Z,Y]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,eo]=(0,i.useState)(()=>{let e=m?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[el,ec]=(0,i.useState)(),[ed,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,em]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[ey,eb]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(m?.contextUsage??null),[ej,eS]=(0,i.useState)(null),[eC,eN]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(null),[eL,e$]=(0,i.useState)(!1),[eP,eA]=(0,i.useState)(!1),[eF,ez]=(0,i.useState)(null),[eW,eD]=(0,i.useState)(null),[eO,eH]=(0,i.useState)(null),eU=(0,i.useRef)(null),[e_,eB]=(0,i.useState)(!1),[eq,eV]=(0,i.useState)(null),[eK,eG]=(0,i.useState)([]),[eJ,eZ]=(0,i.useState)(!1),[eY,eX]=(0,i.useReducer)(dZ,{visible:[],pending:[]}),[eQ,e1]=(0,i.useState)(null),[e2,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,to]=(0,i.useState)({steering:[],followUp:[]}),[tl,tc]=(0,i.useState)([]),[td,tu]=(0,i.useReducer)(r7,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{L||tu({type:"idle"})},[L]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${r6(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${r5(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(td,ts),[td,ts]),[tf,tm]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(m?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tT=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tI=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),tR=(0,i.useRef)(!1),tE=(0,i.useRef)(-1),tL=(0,i.useRef)("unknown"),t$=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(0),tF=(0,i.useRef)(!1),tz=(0,i.useRef)(0),tW=(0,i.useRef)(null),tD=(0,i.useRef)(null),tO=(0,i.useRef)(null),tH=(0,i.useRef)(!1),tU=(0,i.useRef)(!0),[t_,tB]=(0,i.useState)(!1),[tq,tV]=(0,i.useState)(null),tK=(0,i.useRef)(void 0),tG=(0,i.useRef)(0),tJ=(0,i.useRef)(0),tZ=(0,i.useRef)(()=>{}),tY=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t8=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,no=eT??g?.context.model??eR??null,nl=f?X??en:no,nc=(0,i.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let o=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,o&&(e.input+=o.input??0,e.output+=o.output??0,e.cacheRead+=o.cacheRead??0,e.cacheWrite+=o.cacheWrite??0,n+=o.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,eQ,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nd=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nd.current+=1,tm(n=>n?.sid===e&&dU(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nd.current===n&&Array.isArray(t)&&tm(n=>n?.sid===e&&dU(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nf=(0,i.useCallback)(e=>{tN.current=e,T(e)},[]),nm=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&y(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=e5(a.context.messages,a.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);nh(s.messages),nf(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let o=!n&&t5.current===e;if(o||(eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&y(!1),!n){if(o)try{let t=t6.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t6.current===t&&(r.state?.thinkingLevel!==void 0?(eo(r.state.configuredThinkingLevel??r.state.thinkingLevel),ec(r.state.thinkingLevel)):r.running||(t5.current=null,eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ec(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nd.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eS(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t5.current=e,eo(i.configuredThinkingLevel??i.thinkingLevel),ec(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&to(dD(i.queuedMessages)),void 0!==i.subagents&&tc(e=>dz(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||to({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&y(!1)}},[np,nf,nh]),ng=(0,i.useCallback)(e=>{let t=na.current.then(async()=>{tj.current===e&&await nm(e)});return na.current=t.catch(()=>{}),t},[nm]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let o=e5(s.context.messages,s.context.entryIds??[],tT.current.sessionId===e?tT.current.outputs:[]);nh(o.messages),nf(o.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nf,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await dk(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),ny=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;f&&r&&n&&!t1.current&&(t1.current=!0,l?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[f,r,l]),nb=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!f||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t4.current,i=t8.current;e&&eE(e);let a={cwd:r,type:"ensure_session",toolNames:(0,cO.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),o=t0.current,l=o?.body===s?o.createRequestId:dK();t0.current={body:s,createRequestId:l};let c=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:l})});if(!c.ok)throw Error(`HTTP ${c.status}`);let d=await c.json();t0.current=null,t=d.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),d.model&&t2.current===e&&(eE(d.model),e||er(d.model)),d.thinkingLevel&&t4.current===n&&(eo(d.configuredThinkingLevel??d.thinkingLevel),ec(d.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await dk(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[f,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await nb();if(!e)return eG([]),[];eZ(!0);try{let t=await dk(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eZ(!1)}},[nb]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,tb.current&&(clearTimeout(tb.current),tb.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{ty.current?.close(),ty.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);ty.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tW.current?.(n):"agent_start"===n.type&&tD.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tW.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(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)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nT=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new dV(n.status)},[nN]),nI=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await dk(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e6(t=>t?.id===e.id?null:t)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await dk(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nR=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??dK(),message:t,type:e.type??"info"}})},[]),nE=(0,i.useCallback)(e=>{let t={role:"custom",customType:e0,content:eI(e).trim(),display:!0,timestamp:Date.now()},n=tT.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!e4(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${e8}${n.seq}`,baseEntryId:a,message:t});let s=e5(tC.current,tN.current,n.outputs);nh(s.messages),nf(s.entryIds)},[nh,nf]),nL=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e6(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(dy(t)&&o?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e6(t);break;case"notify":nR({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ta(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[nR,o,e.chatInputRef]),n$=(0,i.useCallback)(()=>{let e=tI.current;return tI.current=!1,$(!1),eV(null),eb(null),E({type:"end"}),e},[]),nP=(0,i.useCallback)(()=>{tL.current="unknown",t$.current=null;let e=dB(tC.current,tN.current);tP.current=e?{entryId:e.entryId,key:dQ(e.message)}:null,tA.current+=1},[]),nA=(0,i.useCallback)(()=>{let e=tL.current,t=t$.current;if("unknown"===e){let n=dB(tC.current,tN.current),r=n?.message,i=tP.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:dQ(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=d_(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}:{}}:{}}},[]),nF=(0,i.useCallback)(e=>{let t=nA();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tA.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tA.current===n;s?.(e?nA():t)})},[s,nA]),nz=(0,i.useCallback)((e,t)=>tE.current!==e&&(tE.current=e,nF(t),!0),[nF]),nW=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nd.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(tc(e=>dz(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,tb.current=null,tM.current=!!s?.isStreaming,tR.current=!!s?.isPromptRunning,tI.current=!0,$(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){eA(!0),eH(dH(s)),tb.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){tb.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,tb.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;tb.current=setTimeout(()=>void n(),600)}};tb.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),nD=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nm(e)}finally{if(nt.current!==t)return;let n=tR.current,r=tM.current;tR.current=!1,tM.current=!1,nr.current=null;let i=n$();n?nz(t):r&&i&&nF(),e&&nW(e)}},[nm,nF,nz,nW,n$]),nO=(0,i.useCallback)(async(e,t)=>{await dG(800);let n=Date.now();for(;tI.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nD(e,t)}}catch{}await dG(600)}},[nD]),nH=(0,i.useCallback)(async e=>{let t=tz.current+1;for(tz.current=t;tF.current&&tz.current===t&&tj.current===e;){await dG(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nm(e),tz.current!==t||tj.current!==e)return;tF.current=!1,A(!1),z(null);return}catch{}}},[nm]),nU=(0,i.useCallback)(async e=>{if(!tI.current)return;let t=nt.current;try{let n=nd.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let a=i.state;if(eA(a?.isCompacting??!1),eH(dH(a)),to(dD(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),tc(e=>dz(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tI.current)return;a&&(void 0!==a.systemPrompt&&eS(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await nD(e,t)}catch{}},[np,nD]),n_=(0,i.useCallback)(async e=>{let t=await nm(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tI.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,tR.current=!!n.isPromptRunning,tI.current=!0,$(!0),eV(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nO(e),!0)},[nN,nm,nO]),nB=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eP){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eP]),(0,i.useEffect)(()=>{if(!L&&!eP)return;let e=()=>{let e=tj.current;e&&nB(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[L,eP,nB]),(0,i.useEffect)(()=>{if(!L)return;let e=()=>{let e=tj.current;e&&nU(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[L,nU]),(0,i.useEffect)(()=>{if(L)return;let e=()=>{let e=tj.current;e&&!tI.current&&n_(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tI.current&&n_(t).then(e=>{e||tj.current!==t||tI.current||nm(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(dI,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(dI,n)}},[L,n_,nm]),tD.current=e=>{if(tj.current!==e||tI.current||tg.current||tO.current)return;let t=n_(e).then(async t=>{t||tj.current!==e||tI.current||await nm(e)}).catch(()=>{}).finally(()=>{tO.current===t&&(tO.current=null)});tO.current=t},(0,i.useEffect)(()=>{tI.current=L},[L]),tW.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=dQ(e);s.set(t,(s.get(t)??0)+1)}let o=Math.min(r.length,i.length);for(let e of r.slice(0,o)){let t=dQ(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let l=r.slice(o).filter(e=>{let t=dQ(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...l],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let n=e5(t.messages,t.entryIds,tT.current.sessionId===tj.current?tT.current.outputs:[]);nh(n.messages),nf(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tI.current;nk(),e&&nP(),tM.current=!0,tI.current=!0,$(!0),eV({kind:"waiting_model"}),E({type:"start"});break}case"agent_end":if(!tI.current)break;if(eV(null),eb(null),E({type:"end"}),tj.current){nm(tj.current);let e=nd.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eS(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&tc(e=>dz(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tV(t.state.goal??null),to(dD(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tV(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||tR.current)break;let t=tj.current,n=n$();eA(!1);let r=t?nm(t):void 0;t&&nW(t),n&&nF(r);break}case"prompt_done":{let e=nt.current,t=tR.current;tR.current=!1,nr.current=null;let n=tE.current!==e;if(!t&&!n)break;let r=tj.current;nz(e,r?nm(r):void 0),!tM.current&&(n$(),r&&nW(r))}break;case"prompt_error":tL.current="failed",nR({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tL.current="failed",nR({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:aV(t)}),eV(null);break}case"message_end":{if(!tI.current)break;let t=e.message;if(t?.role==="assistant"&&(t$.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tL.current=d_(t)),t&&"user"===t.role){let e=aV(t),n=dX(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&dX(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tu({type:"user-message",kind:ie(e),text:r9(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nh(e=>[...e,aV(t)]);let n=tj.current;n&&nB(n),E({type:"reset"}),eV({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t5.current=t,t6.current+=1,eo(e.configured??n),ec(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eV(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eV(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";tc(n=>{let r=n.find(e=>e.id===t.id);return dz(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=>dz(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=>dz(e,[r]));break}case"queue_update":to({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eb({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eb(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}eA(!0),ez(null),eD(null);break;case"auto_compaction_end":case"compaction_end":if(eA(!1),e.errorMessage)ez(e.errorMessage),eD(null);else if(!e.aborted){eD(d0(e.result,e.reason??"auto"));let t=tj.current;t&&(nm(t),nB(t))}break;case"extension_ui_request":nL(e)}},[nR,nu,np,nk,nL,nm,nF,nz,nB,nP,nW,n$,nf,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tI.current||tF.current||ni.current)return"unknown";let o=s3(n,a??[]),l=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tK.current?.(t,e),"accepted"):"unknown"}nP();let c=nt.current+1;nk(),tR.current=!0;let d=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...o.trim()?[{type:"text",text:o}]:[],...d]:o,timestamp:Date.now()};nh(e=>[...e,u]),nr.current=dX(u),nt.current=c,tI.current=!0,$(!0),eV(l?{kind:"running_command"}:{kind:"waiting_model"}),E({type:"start"}),tZ.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,m=!1,g="unknown";try{if(f&&r){let e=tj.current??await tQ.current,t=await nb();t&&(h=t,X&&(eE(X),e&&await dk(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nT(t),m=!0,await dk(t,{type:"prompt",message:o,...p?.length?{images:p}:{}}),ny(1,n),g="accepted")}else t&&(h=t.id,await nT(t.id),m=!0,await dk(t.id,{type:"prompt",message:o,...p?.length?{images:p}:{}}),g="accepted");return l&&h&&nO(h,c),g}catch(o){console.error("Failed to send message:",o);let r=o instanceof dw&&"update_draining"===o.code&&!1===o.accepted;if(!(!m||o instanceof dw&&"prompt_rejected"===o.code&&!1===o.accepted||r)&&h)return nO(h,c),"unknown";tR.current=!1,tI.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&dX(t)===s?e.slice(0,-1):e}),nR({type:"error",message:o instanceof Error?o.message:String(o)}),e.chatInputRef?.current?.restoreSubmission?.(n,d1(i),a,t?.id??h??void 0),nr.current=null,$(!1),eV(null),E({type:"end"}),"returned"}},[f,r,X,t,nb,nT,ny,nO,nR,nk,nj,e.chatInputRef,nP,nh]);tK.current=(0,i.useCallback)(async(n,r)=>{if(tI.current||tF.current)return;let i=`${r?"!!":"!"}${n}`;tF.current=!0,tZ.current(!0),z({command:n,excludeFromContext:r}),A(!0);try{let e=tj.current??t?.id??await nb();if(!e)throw Error("Unable to create a session for the shell command");await dk(e,{type:"bash",command:n,excludeFromContext:r}),await nm(e),ny(1,i)}catch(t){console.error("Failed to execute shell command:",t),nR({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tF.current=!1,z(null),A(!1)}},[nR,nb,nm,e.chatInputRef,ny,t]);let nV=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tF.current){try{await dk(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await dk(e,{type:"abort"}),tL.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nK=(0,i.useCallback)(async e=>{if(tF.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eN(e??null);try{let{cancelled:n,newSessionId:r}=await dk(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eN(null)}},[c]),nG=(0,i.useCallback)(async e=>{if(tF.current)return;let t=tj.current;t&&(dk(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nJ=(0,i.useCallback)(async e=>{if(tF.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&dk(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nZ=(0,i.useCallback)(async(e,t)=>{if(f){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t8.current=null,et(null)),Q(n),eE(n);let i=tj.current??await tQ.current;if(!i)return;try{await dk(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),e$(!0);try{await dk(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nm(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eT),nR({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nm(n)}finally{ni.current=!1,e$(!1)}}},[nR,eT,f,nm,Q]),nY=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(f){if(ni.current)return!1;ni.current=!0,e$(!0);let e=t2.current,a=t8.current,s=t4.current;try{t2.current=t,t8.current=n??null,t4.current="auto";let e=tj.current??await tQ.current;return e&&await dk(e,r),Q(t),et(n??null),eE(t),eo("auto"),ec(void 0),e&&await nm(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t8.current=a,t4.current=s,nR({type:"error",message:i(n)});let t=tj.current;return t&&await nm(t),!1}finally{ni.current=!1,e$(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),e$(!0);try{return await dk(a,r),await nm(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),nR({type:"error",message:i(e)}),await nm(a),!1}finally{ni.current=!1,e$(!1)}},[nR,eT,el,f,nm,Q,es]),nX=(0,i.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(f){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t4.current=t??null,eo(t??"auto"),ec(void 0),t2.current=e,t8.current=null,et(null),Q(e),eE(e)}let r=tj.current??(f?await tQ.current:null);if(r)try{await dk(r,{type:"set_role_model",role:e}),f||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Z,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eP){eU.current="manual",eA(!0),ez(null),eD(null);try{let t=await dk(e,{type:"compact"});eD(d0(t,"manual")),await nm(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eD(null)}finally{eA(!1)}}},[eP,nm]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();D(s.models),_(s.modelError??null),q(s.modelScopeWarnings??[]),K(s.thinkingLevels??{}),J(s.thinkingLevelMaps??{}),Y(s.roles??[]);let o=s.modelList??[];if(H(o),f&&!tj.current){let e=(s.defaultModel?o.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??o[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t4.current&&eo(t??"auto")}},[f,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await nb(),s=e=>(e.handled&&(e.error?nR({type:"error",message:e.error}):"openSessionStats"!==e.action&&nR({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eP)return s({handled:!0,error:"No active session to compact"});eU.current="manual",eA(!0),ez(null),eD(null);let e=await dk(a,{type:"compact",...i?{customInstructions:i}:{}});return eD(d0(e,"manual")),await nm(a,!0)&&ny(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await dk(a,{type:"reload"}),await Promise.all([nm(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await dk(a,{type:"set_session_name",name:i}),await nm(a)&&ny(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await dk(a,{type:"get_session_stats"});return e&&e1(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await dk(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nK();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await dk(a,{type:"goal",args:i});if(tV(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nE(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nR({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tI.current||tF.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tI.current=!0,$(!0),eV({kind:"running_command"});try{await nT(a);let e=await dk(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nm(a,!0)&&ny(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tI.current=!1,$(!1),eV(null),tj.current===a&&nW(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await dk(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nE(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eA(!1)}},[nR,nE,nT,nb,nK,eP,n0,nm,nw,nv,ny,h,nW]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r),"returned";let a=s3(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"steer",text:a,images:s?.length??0});try{return await dk(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to steer:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r,i),"returned"}},[nR,e.chatInputRef]),n8=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(r),i),"returned";let s=s3(t,i??[]),o=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:n,text:s,images:o?.length??0});try{return await dk(a,{type:"prompt",message:s,streamingBehavior:n,...o?.length?{images:o}:{}}),tu({type:"ack",id:l}),"accepted"}catch(n){return tu({type:"fail",id:l}),console.error("Failed to queue prompt:",n),nR({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(r),i,a),"returned"}},[nR,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return nR({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r),"returned";let a=s3(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:"followUp",text:a,images:s?.length??0});try{return await dk(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:o}),"accepted"}catch(a){return tu({type:"fail",id:o}),console.error("Failed to follow up:",a),nR({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,d1(n),r,i),"returned"}},[nR,e.chatInputRef]),n5=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await dk(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n6=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await dk(t,{type:"clear_queue"});tu({type:"withdraw"}),to({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nR({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nR]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await dk(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),to(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),nR({type:"error",message:"Failed to remove queued message"})}},[nR]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ed;eo(e),eu(n),f&&(!tj.current||t7.current===tj.current)&&(t4.current=e,t3.current=n),ec(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await nb():r&&await dk(i,{type:"set_thinking_ceiling",ceiling:n}),await dk(i,{type:"set_thinking_level",level:e}),await nm(i)}catch(e){console.error("Failed to set thinking level:",e),nR({type:"error",message:"Failed to set thinking level"}),await nm(i)}},[f,nm,nR,ed,nb]);ev.current=nl?`${nl.provider}/${nl.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!L&&!eL&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?dO(t.state):void 0)??null})}).catch(()=>{})},[rt,L,eL]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await nb(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};em(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=dO(await dk(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await dk(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nR({type:"error",message:t instanceof Error?t.message:String(t)});try{i(dO(await dk(e,{type:"get_state"}))??null)}catch{i(null)}}finally{em(!1)}},[nb,ep,nR]),ri=(0,i.useCallback)(async e=>{let t=(0,cO.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await dk(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),ra=(0,i.useCallback)(e=>{tU.current=e,tB(t=>!e===t?t:!e)},[]);tZ.current=ra;let rs=(0,i.useCallback)((e="smooth")=>{tJ.current=Date.now()+700,tY.current?.scrollIntoView({behavior:e})},[]),ro=(0,i.useCallback)(()=>{tG.current=0,ra(!0),rs("smooth")},[rs,ra]),rl=(0,i.useCallback)(()=>{tG.current=0,ra(!1)},[ra]),rc=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!dq.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tG.current=Date.now()+1200)},[]),rd=(0,i.useCallback)(()=>{if(!tI.current&&!tF.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tG.current;!t&&Date.now()<tJ.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?ra(!0):t&&ra(!1))},[ra]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tT.current.sessionId!==tj.current&&(tT.current={sessionId:tj.current,outputs:[],seq:0}),t&&nm(t.id,!m,!0,m).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,tR.current=!!e.state.isPromptRunning,tI.current=!0,$(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),E({type:"start"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nO(t.id)),e.state?.isBashRunning&&(tF.current=!0,A(!0),nH(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&eA(n.isCompacting),eH(dH(n)),void 0!==n.contextUsage&&ek(n.contextUsage??null),void 0!==n.systemPrompt&&eS(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t5.current=t.id,eo(n.configuredThinkingLevel??n.thinkingLevel),ec(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&to(dD(n.queuedMessages)),void 0!==n.subagents&&tc(e=>dz(e,n.subagents??[])),void 0!==n.goal&&tV(n.goal??null)),e&&eB(!0)}),()=>{tz.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(ej)},[ej,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nJ)},[g?.tree,k,nJ,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rc),()=>{window.removeEventListener("keydown",rc)}),[rc]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rc,{passive:!0}),e.addEventListener("wheel",rc,{passive:!0}),e.addEventListener("touchstart",rc,{passive:!0}),e.addEventListener("scroll",rd,{passive:!0}),()=>{e.removeEventListener("pointerdown",rc),e.removeEventListener("wheel",rc),e.removeEventListener("touchstart",rc),e.removeEventListener("scroll",rd)}},[S.length,v,rd,rc]),(0,i.useEffect)(()=>{if(t9.current||!L&&!P||!tU.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tJ.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[L,P,S.length,R.streamingMessage,eq,F,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tH.current){tH.current=!0,rs("instant");return}if(!t9.current&&tU.current){let e=Date.now()-ne.current<1500;rs(tI.current||tF.current||e?"instant":"smooth")}}},[S.length,L,P,rs,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,d]),(0,i.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[eW]),(0,i.useEffect)(()=>{if(0===eY.visible.length)return;let e=eY.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eY.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eY.visible]),(0,i.useEffect)(()=>{e1(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:b,activeLeafId:k,messages:S,entryIds:N,streamState:R,agentRunning:L,modelNames:W,modelList:O,modelError:U,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:el,thinkingCeiling:ed,retryInfo:ey,contextUsage:ew,systemPrompt:ej,forkingEntryId:eC,isCompacting:eP,compaction:eO,compactError:eF,compactResult:eW,currentModel:no,displayModel:nl,modelSwitching:eL,sessionStats:nc,runStateKnown:e_,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:ts,deliveryRows:th,subagents:tl,todoPhases:tf&&tf.sid===tj.current?tf.phases:null,compactedWork:I,notices:eY.visible,extensionDialog:e2,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nI,sendExtensionCustomInput:nM,isAutoModelSelection:f&&null===X,agentPhase:eq,isNew:f,autoFollowPaused:t_,resumeAutoFollow:ro,pauseAutoFollow:rl,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tY,scrollContainerRef:tX,handleSend:nq,handleAbort:nV,handleFork:nK,handleNavigate:nG,handleModelChange:nZ,handleRoleModelChange:nX,handleMainPresetChange:nY,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n4,handlePromptWithStreamingBehavior:n8,handleAbortCompaction:n5,handleRecallQueue:n6,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:ef,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:nb,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:E,setAgentRunning:$,setForkingEntryId:eN,bashRunning:P,pendingBash:F,handleAgentEventRef:tW}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:ev,onAttentionNeeded:l,onSessionCreated:c,onSessionForked:d,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:f,onSessionStatsPanelOpen:g}),tX=(0,i.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=eQ(i);if(!a||"custom"!==i.role)continue;t??=[...e];let s=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&s.push(t);continue}let i=n.get(t);void 0===i&&(i=function(e){let t=eX(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,i)),i===a.sourceHash&&s.push(t)}s.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(s=s.filter(t=>e[t].timestamp===a.sourceTimestamp));let o=1===s.length?t[s[0]]:null;if(o?.role!=="assistant"){t[r]={...i,details:void 0};continue}t[s[0]]={...o,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(eY)?{kind:"translated",text:n.slice(eY.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(i,eX(o.content??[]))}}return t??e})(ek),[ek]),tQ=rf(e?.id,tt?.provider,void 0,tt?.modelId),t0=tQ?.alias;(0,i.useEffect)(()=>{t0&&Y.current?.(t0)},[t0]);let t1=(0,i.useMemo)(()=>{if(!tt)return null;let e=tw?tW:nH.find(e=>e.alias===tQ?.alias)?.oauthPosition;return nH.find(t=>t.provider===tt.provider&&(void 0===t.oauthPosition?null===tQ||tQ.seed===t.seed:t.oauthPosition===e))?.alias??null},[tt,tw,tW,tQ]),t2=eC||eN,t8=e?.id;er.current=tX,ei.current=ej,ea.current=tI;let t4=(0,i.useRef)(!0);t4.current=!tj;let t5=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eC&&!t5.current&&(es.current+=1),t5.current=eC},[eC]),(0,i.useEffect)(()=>()=>{es.current+=1},[]),(0,i.useEffect)(()=>{ee(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(ua(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t8),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t8)])},[t8]),(0,i.useEffect)(()=>{let e=tI.current;e&&et.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&ee(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(lh(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,tX,ej);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(us(e,r),r):t})},[tX,ej,tI]);let t6=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tI.current,t=t6.current;if(t6.current=e?{sessionId:e,entryIds:ej}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===lm&&r.push(t[a])}return r}(t.entryIds,ej,tX),r=ec();if(0===n.length||!r)return;let i=rp(e,"web6",void 0)?.alias??null;for(let e of n)et.current.some(t=>t.anchorEntryId===e)||ep(i,"done",r,{kind:"entry",entryId:e})},[ej,tX,tI,ec,ep]);let t3=eC&&tb?.kind==="running_tools"&&tb.tools.length>0&&tb.tools.every(e=>"wait"===e.name),t7=eb||s,{hideThinkingBlock:t9}=(D=t??e?.cwd??null,H=nF(),(0,i.useEffect)(()=>{nA(D).catch(()=>{})},[D]),H),ne=(0,i.useMemo)(()=>({hideThinking:t9}),[t9]);(0,i.useEffect)(()=>{var e;if(!tp||Z.current===tp.id)return;Z.current=tp.id;let t=ec();if(!t)return;el.current=t.turn;let n=eS.streamingMessage?.role==="assistant"?eS.streamingMessage:null,r=lf(er.current,n,tt?.provider,tt?.modelId);ef("select"===(e=tp.method)||"ask"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tp,eS.streamingMessage,tt?.provider,tt?.modelId,ec,ef]),(0,i.useEffect)(()=>(v=t2?tL:null,()=>void(v=null)),[t2,tL]),(0,i.useEffect)(()=>{I?.(t2)},[I,t2]),(0,i.useEffect)(()=>()=>I?.(!1),[I]),(0,i.useEffect)(()=>{M?.(t3)},[t3,M]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{R?.(null!==tp)},[R,tp]),(0,i.useEffect)(()=>()=>R?.(!1),[R]);let{main:nt,process:nn}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,o=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),o=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:o});a.messageCount+=t.length,a.toolCallCount+=n},l=eG(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.set(e,n+1),r.push({kind:"answer",anchorIdx:a,idx:e,runIndex:n,blocks:l.attach(t),precedingBlocks:[]})},u=()=>{let e=l.takeRemaining();e&&d(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){o(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,r.push(i);continue}if(e2(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===eQ(t)&&o(a,[{idx:i.idx}],0);continue}let s=eB(t,n),c=!1;for(let e of s){if("answer"===e.kind){d(i.idx,e.blocks),c=!0;continue}o(a,[{idx:i.idx,blocks:e.blocks}],eq(e.blocks)),l.collect(i.idx,e.blocks)}!c&&e_(t,n)&&d(i.idx,[])}return u(),{main:r,process:i}})(tX,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(e6(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!e6(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!e6(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,o=[],l=0,c=0,d=eG(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:l++,blocks:d.attach(n),precedingBlocks:o}),o=[]};for(let l=t+1;l<n;l++){let n=e[l];if("assistant"!==n.role){if(null!==eQ(n))continue;if(e2(n)){u(),i.push({kind:"message",idx:l,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:l});continue}let c=eB(n,r),h=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){p(l,e.blocks);continue}for(let t of(a.push(h>0?{idx:l,blocks:e.blocks}:{idx:l}),s+=eq(e.blocks),d.collect(l,e.blocks),e.blocks))o.push(t)}0===h&&e_(n,r)&&p(l,[])}u();let h=d.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:l++,blocks:h.blocks,precedingBlocks:[]});let f=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=f);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(tX,{sessionBusy:t2,isStreaming:eS.isStreaming,hideThinking:ne.hideThinking}),ne),[tX,t2,eS.isStreaming,ne]),nr=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=r2(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),o=e.filter(e=>e.item.idx<=t).pop(),l=o??e.find(e=>e.item.idx>t);if(l){let e=r.get(l.position);e?e.calls.push(...n):r.set(l.position,{calls:[...n],placement:o?"after":"before"})}}"user"===e.role&&(a=t),e6(e)&&(s=t)});let{continuing:o}=r8(e,t,n);if(o){let e=r.get(o.position);e?e.calls.unshift(...o.calls):r.set(o.position,{calls:o.calls,placement:"before"})}return r})(nt,tX,ta?.messages),[nt,tX,ta]),ni=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=r8(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i);return{position:-1===a?e.length:a,calls:r}})(nt,tX,ta?.messages),[nt,tX,ta]),[na,ns]=(0,i.useState)(ue),{startIndex:no,endIndex:nl,hasLater:nc}=ut(nt.length,na),nd=null!==na.end&&nc,nu=(0,i.useRef)(nt.length);nu.current=nt.length;let np=(0,i.useRef)(null),nh=(0,i.useRef)(null),nf=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==na.end&&na.end>=nt.length&&ns(e=>({count:e.count,end:null}))},[na.end,nt.length]),(0,i.useEffect)(()=>{let e=np.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nf.current=t.scrollHeight-t.scrollTop,ns(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]),(0,i.useEffect)(()=>{if(null==nf.current)return;let e=tR.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nf.current),nf.current=null}},[na.count,tR]),(0,i.useEffect)(()=>{let e=nh.current,t=tR.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ns(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=ut(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nu.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[na,nt.length,tR]);let[nm,ng]=(0,i.useState)(null),[nx,nv]=(0,i.useState)(0),ny=(0,i.useRef)(null),nb=(0,i.useCallback)(e=>{tC(),ny.current=e,ng(null),ns(t=>un(nu.current,e,t)),nv(e=>e+1)},[tC]);(0,i.useLayoutEffect)(()=>{let e=ny.current,t=tR.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;ny.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,ng(e)},[nx,na,nt,tR]),(0,i.useEffect)(()=>{if(null===nm)return;let e=setTimeout(()=>ng(null),1800);return()=>clearTimeout(e)},[nm]);let nw=(0,i.useCallback)(()=>{(0,_.flushSync)(()=>ns(ue));let e=tR.current;e&&(e.scrollTop=e.scrollHeight)},[tR]),nk=(0,i.useCallback)(()=>{nd&&nw(),tS()},[nd,nw,tS]),nj=(0,i.useRef)(null),[nS,nC]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!z||nj.current===z.id||z.sessionId!==e?.id||eb||0===tX.length)return;nj.current=z.id,W?.(z.id);let t=ej.indexOf(z.entryId);if(t<0)return void nC(!0);let n=0;for(let e=0;e<nt.length;e++){let r=nt[e].idx;if(r>t||(n=e,r===t))break}nb(n)},[z,e?.id,eb,tX.length,ej,nt,nb,W]),(0,i.useEffect)(()=>{if(!nS)return;let e=setTimeout(()=>nC(!1),6e3);return()=>clearTimeout(e)},[nS]);let[nN,nT]=(0,i.useState)(!1),[nI,nM]=(0,i.useState)(0),nR=(0,i.useMemo)(()=>nN?nt.map(e=>(function(e,t){if("answer"===e.kind)return e9(e.blocks);let n=t[e.idx];return n&&"content"in n?e9(n.content):""})(e,tX).toLowerCase()):uo,[nN,nt,tX]),nE=(0,i.useCallback)(e=>{tC(),ns(t=>un(nu.current,e,t))},[tC]),nL=(0,i.useCallback)(()=>nT(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tR.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nT(!0),nM(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tR]);let n$=(0,i.useMemo)(()=>{let e=[];return nt.forEach((t,n)=>{if("message"!==t.kind)return;let r=ui(tX[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nt,tX]),nP=`${no}:${nl}`,nz=ej.length>0?ej[ej.length-1]:null,[nW,nD]=(0,i.useState)(null),nO=(0,i.useRef)(!1);(0,i.useEffect)(()=>{nO.current||!ti||eb||!e?.id||(nO.current=!0,t2||!nz||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(tX)||function(e){try{return window.localStorage.getItem(ul(e))}catch{return null}}(e.id)!==nz&&nD(nz))},[ti,eb,e?.id,t2,nz,tX]);let nU=(0,i.useCallback)(()=>{e?.id&&nW&&function(e,t){try{window.localStorage.setItem(ul(e),t)}catch{}}(e.id,nW),nD(null)},[e?.id,nW]),n_=null!==nW&&nW===nz&&!t2&&!nd,nB=tr?[tr.sessionId,tr.sessionFile??"",tr.sessionName??"",tr.userMessages,tr.assistantMessages,tr.toolCalls,tr.toolResults,tr.totalMessages,tr.tokens.input,tr.tokens.output,tr.tokens.cacheRead,tr.tokens.cacheWrite,tr.tokens.total,tr.cost??0,tr.totalActiveMs??0].join("|"):null,nq=(0,i.useRef)(tr);nq.current=tr,(0,i.useEffect)(()=>{m?.(nq.current)},[nB,m]),(0,i.useEffect)(()=>()=>{m?.(null)},[m]);let nV=eJ?`${eJ.percent??"null"}|${eJ.contextWindow}|${eJ.tokens??"null"}`:null,nK=(0,i.useRef)(eJ);nK.current=eJ,(0,i.useEffect)(()=>{x?.(nK.current)},[nV,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{y?.(tc)},[y,tc]),(0,i.useEffect)(()=>()=>{y?.([])},[y]);let{isDragOver:nG,handleDragEnter:nJ,handleDragOver:nZ,handleDragLeave:nY,handleDrop:nX}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t2||p?.current?.addAttachments(e)},[t2,p])),nQ=(0,i.useMemo)(()=>{var e;return e=ta?.messages,e&&e.length>0?[...e,...tX]:tX},[ta,tX]),n0=(0,i.useMemo)(()=>{let e=new Map;for(let t of nQ)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[nQ]),n1=(0,i.useMemo)(()=>{let e,t,n,r,i,a,s,o,l,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,i=new Map,a=new Map,s=new Map,o=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},l=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=rK(e.status);if(!r||l.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;l.add(r);let s=rV(e);null!==s&&i.set(r,s)},d=(e,t,r)=>{let i=t?n.get(t):void 0,a=rV(e);i&&"number"==typeof r&&null!==a&&"running"===rK(e.status)&&s.set(i,Math.max(s.get(i)??-1/0,r-a))},nQ.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=n0.get(e.toolCallId);if(t)for(let i of rJ(e,t)??[])n.set(i.agentId,i.key),"number"==typeof t.timestamp&&r.set(i.key,t.timestamp)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(rG(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=rq(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:rq(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of rB(t.details?.jobs)){if("task"!==r.type)continue;let a=rq(r.id);if(a&&o(a,rK(r.status),i),c(r,a),d(r,a,t.timestamp),a&&"running"===rK(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of rG(t.content).matchAll(rZ)){let t=Object.fromEntries([...e[1].matchAll(rY)].map(e=>[e[1],e[2]]));t.id&&o(t.id,rK(t.status),i)}for(let e of rB(t.details?.jobs))"task"===e.type&&c(e,rq(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:i,parallelWith:a,runStartedAt:s}},[nQ,n0]),n2=(0,i.useMemo)(()=>({ledger:n1,subagents:tc,toolResults:n0,onOpenPanel:b,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:k,selectedMaker:j}),[n1,tc,n0,b,e?.id,e?.cwd,t,k,j]),n8=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=tX.length-1;n>=0;n-=1){let r=ui(tX[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[tX]),n4=(0,i.useMemo)(()=>tk(tX,n0,td,ta?.todoPhases??null),[tX,n0,td,ta]),n5=(0,i.useMemo)(()=>lN(eS.streamingMessage).join("|"),[eS.streamingMessage]),n6=(0,i.useMemo)(()=>JSON.stringify(lC(eS.streamingMessage)),[eS.streamingMessage]),n3=(0,i.useMemo)(()=>JSON.stringify(lI(eS.streamingMessage)),[eS.streamingMessage]),n7=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],o=new Map,l=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){l=n;continue}let i=lN(r),c=lI(r,a);if(0===i.length&&0===c.length||l<0)continue;let d=lC(r),u=o.get(l);u||(u={index:l,entryId:t[l],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(l,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=o.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},o.set(a,e),s.push(e));let l=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!l.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!d.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(tX,ej,n5.length>0?n5.split("|"):[],JSON.parse(n6),JSON.parse(n3)),[tX,ej,n5,n6,n3]),n9=e?.id??tI.current??void 0,re=(B=lE(O=(0,i.useMemo)(()=>({sessionId:n9,sessionProvider:tt?.provider,turns:n7,messages:tX,subagents:tc}),[n9,tt?.provider,n7,tX,tc])),q=lA(O),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...B,...q])),[B,q])),rt=tw&&0===tX.length&&!eS.isStreaming&&!t2,rn=e?.cwd??t??void 0,rr=tt?e$[`${tt.provider}:${tt.modelId}`]??null:null,ri=tt?eP[`${tt.provider}:${tt.modelId}`]??null:null,ra=(0,i.useRef)(null),rs=(0,i.useRef)(null),ro=(0,i.useCallback)(()=>{ra.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(T?.(ro),()=>T?.(null)),[ro,T]),(0,i.useLayoutEffect)(()=>{let e=rs.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tR.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tR.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[eb,tR]);let rl=(0,i.useCallback)((...e)=>(null!==na.end&&nw(),tE(...e)),[tE,na.end,nw]),rc=(0,r.jsx)("div",{ref:ra,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(dm,{ref:p,sessionId:e?.id??tI.current??void 0,onEnsureSession:tw&&t?tZ:void 0,onLiveTranscriptPersisted:tY,onSend:rl,onAbort:tL,onSteer:eC?tO:void 0,onFollowUp:eC?tH:void 0,onPromptWithStreamingBehavior:eC?tU:void 0,isStreaming:t2,model:tt,isAutoModelSelection:ty,modelNames:eM,modelList:eR,modelError:eE,modelScopeWarnings:eL,onModelChange:tA,onMainPresetChange:e||tw?tz:void 0,mainPresetActiveAlias:t1,modelRoles:eA,onRoleModelChange:tF,modelSwitching:tn,onCompact:e||tw?tD:void 0,onAbortCompaction:t_,isCompacting:e1,compactError:e7,compactResult:te,toolPreset:eF,onToolPresetChange:e||tw?tK:void 0,thinkingLevel:ez,effectiveThinkingLevel:eW,thinkingCeiling:eD,onThinkingLevelChange:e||tw?tG:void 0,fastMode:eO,fastModeBusy:eU,onFastModeToggle:e||tw?eV:void 0,availableThinkingLevels:rr,thinkingLevelMap:ri,retryInfo:eK,deliveryRows:tl,inputHistory:n8,onRecallQueue:tB,onRemoveQueuedMessage:tq,slashCommands:ts,slashCommandsLoading:to,onLoadSlashCommands:tJ,onBuiltinCommand:tV,soundEnabled:E,onSoundToggle:L,onAudioUnlock:A,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rd=eS.streamingMessage,ru=(0,i.useMemo)(()=>rd?eB(rd,{isStreaming:!0}):[],[rd]),rm=(0,i.useMemo)(()=>ru.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[ru]),rg=(0,i.useMemo)(()=>ru.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[ru]),rx=rd?.role==="assistant"?rd:null,rv=(0,i.useMemo)(()=>{let e=-1;for(let t=tX.length-1;t>=0;t-=1)if("user"===tX[t].role){e=t;break}let t=e<0?-1:aE(tX,e);return{start:t,blocks:aM(tX,t+1,tX.length),priorCiHeads:a$(tX,n0,t+1),jobNotices:aR(tX,t+1,tX.length)}},[tX,n0]),ry=(0,i.useMemo)(()=>aC(rx?[...rv.blocks,...rx.content??[]]:rv.blocks,n0,t2,rv.priorCiHeads,rn,rv.jobNotices),[rv,rx,n0,t2,rn]),rb=(0,i.useMemo)(()=>t2?{...aI(rv.blocks,n0,rn),span:aP(tX,rv.start+1,tX.length)}:null,[t2,rv,n0,rn,tX]),rw=(0,i.useMemo)(()=>rb?{...rb,flow:ry,latest:!0}:null,[rb,ry]),rk=eC&&(tb?.kind==="running_tools"||(rx?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rj=lf(tX,rx,tt?.provider,tt?.modelId),rS=rj.provider,rC=rj.model,rN=rj.credentialId;(0,i.useEffect)(()=>{if(!rk)return;let e=ec();e&&eo.current!==e.turn&&el.current!==e.turn&&(eo.current=e.turn,ef("working",e,rS,rN,rC))},[rk,rS,rC,rN,ec,ef]);let[rT,rI]=(0,i.useState)(null),rM=(0,i.useCallback)(e=>{rI(e)},[]),rR=(0,i.useMemo)(()=>eT?{role:"bashExecution",command:eT.command,output:"",excludeFromContext:eT.excludeFromContext}:null,[eT]),rE=(0,i.useMemo)(()=>{let e=[eC&&!rd&&tb?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tb,V):null,eN&&!eT?V("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eC,rd,tb,eN,eT,V]);(0,i.useEffect)(()=>{if(!rT)return void S?.(null);let e=[],t=[],n=0;if(rd&&rg.length>0){let r=rT.messages.length+e.length;for(let i of(e.push(rd),rg))t.push({idx:r,blocks:i}),n+=eq(i)}if(rR&&(t.push({idx:rT.messages.length+e.length}),e.push(rR)),0===t.length)return void S?.(rE?{...rT,status:rE}:rT);let r=-1;for(let e=rT.messages.length-1;e>=0;e--)if(e6(rT.messages[e])){r=e;break}let i=rT.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),S?.({...rT,groups:i,messages:[...rT.messages,...e],status:rE})},[rT,rg,rd,rR,rE,S]),(0,i.useEffect)(()=>()=>S?.(null),[S]);let rL=tg.filter(e=>"belowEditor"!==e.placement),r$=tg.filter(e=>"belowEditor"===e.placement);return ew?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ew}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":t7,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:nJ,onDragOver:nZ,onDragLeave:nY,onDrop:nX,children:[t7?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:V("chat.loadingSession")})}):null,nG&&!t2&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:V("chat.attachFile")})}),tf&&(0,r.jsx)(ug,{request:tf,onInput:tv}),rt&&!N?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[860px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(X,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.79"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.12.6"]})]})]})]}),rn&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":V("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:V("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tN(rn)||rn}),(0,r.jsx)("code",{title:rn,children:rn}),(0,r.jsx)("p",{children:V("chat.emptyProjectHint")})]}),w&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:w,children:V("chat.openSessionList")})]}),(0,r.jsx)(uh,{notices:tu,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[N&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:N}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!N,style:{display:N?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(o8,{open:nN,onClose:nL,containerRef:tR,index:nR,renderedStart:no,renderedEnd:nl,contentKey:tX,onReveal:nE,onProgrammaticScroll:tC,focusRequest:nI,t:V}),nS&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:V("chat.jumpMissing")}),(0,r.jsx)(uh,{notices:tu,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tR,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(up,{widgets:rL}),(0,r.jsxs)(aX.Provider,{value:n2,children:[(0,r.jsx)(lb,{utterances:re,children:(0,r.jsx)(uc,{messages:tX,entryIds:ej,toolResultsMap:n0,modelNames:eM,messageCwd:rn,onOpenFile:C,sessionBusy:t2,isNew:tw,isStreaming:eS.isStreaming,handleFork:t$,forkingEntryId:eZ,handleNavigate:tP,handleEditContent:ey,sessionId:e?.id??tI.current??void 0,main:nt,dispatchSlots:nr,compactedDispatch:ni,openRequest:ta?.openRequest??null,process:nn,startIndex:no,endIndex:nl,sentinelRef:np,laterSentinelRef:nh,flashItem:nm,t:V,cues:Q,cueFollowRef:t4,onProcessLogChange:rM})}),!nd&&eS.isStreaming&&eS.streamingMessage&&rm.length>0&&(0,r.jsx)(ok,{message:eH(eS.streamingMessage,rm),sessionId:e?.id??tI.current??void 0,isStreaming:!0,modelNames:eM,cwd:rn,onOpenFile:C}),!nd&&rw&&(0,r.jsx)(sV,{summary:rw,live:!0,onOpenFile:C})]}),n_&&(0,r.jsx)(o9,{onDismiss:nU,t:V}),(0,r.jsx)("div",{ref:tM})]})})}),(0,r.jsx)(o4,{questions:n$,containerRef:tR,layoutKey:nP,onJump:nb,label:V("chat.questionRail")}),(t2&&tj||nd)&&(0,r.jsxs)("button",{type:"button",onClick:nk,"aria-label":V("chat.jumpToBottom"),title:V("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:G?44:void 0,borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),V("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rs,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tp&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:(0,r.jsx)(um,{request:tp,onRespond:tx,onActivity:e=>void tv(e,"activity"),delivery:th})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:860,margin:"0 auto"},children:[(0,r.jsx)(o7,{compaction:e3,t:V}),(0,r.jsx)(uu,{goal:tT,t:V}),(0,r.jsx)(up,{widgets:r$}),(n4||ry.steps.length>0)&&!(K&&G)&&(0,r.jsx)(dx,{phases:n4,flow:ry,busy:t2})]})}),rc,(0,r.jsx)(dg,{statuses:tm})]})]})}function uu({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nT(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nT(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function up({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function uh({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function uf({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:o,children:l}){let{t:c}=(0,F.s)(),d=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!d.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=d.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":o?.status==="sending"||void 0,style:{maxBlockSize:a},children:[o?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===o.status?"alert":"status","data-state":o.status,children:"sending"===o.status?c("chat.responseSending"):`${c("chat.responseFailed")}${o.error?` (${o.error})`:""}`}):null,l]})}function um({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,F.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),f=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{l("editor"===e.method?e.prefill??"":""),p(""),d("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let m=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(uf,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),o=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{f(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),o&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{f();let n=e.target.value;d(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(uf,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(nc,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(uf,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&m()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&m()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:m,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function ug({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),o=eL(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eA[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":eP[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(o.length?o:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,e$(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function ux({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,o]=(0,i.useState)({kind:"idle"}),l=(0,i.useRef)(null),c=n.trim();(0,i.useEffect)(()=>{if(c.length<2)return void o({kind:"idle"});let e=new AbortController;o({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);o({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||o({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[c]);let d=e=>{let t=l.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),d(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:l,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),d(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var uv=n(50640),uy=n(73620);let ub=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function uw(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 uk=["tags","categories","keywords","tag","category"];function uj({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=uk.find(t=>Array.isArray(e[t])),s=a?e[a].map(uw).filter(Boolean):[],o=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=uw(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 uS=n(8745);let uC=(0,i.createContext)(null),uN=(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"})}),uT=(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"})}),uI=(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"})}),uM=(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"})}),uR=(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 uE({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:l,subtitleKind:d="text",state:u,viewSwitch:p,actions:h=[],close:f}){let{t:m}=(0,F.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uI})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,l&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:l,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:l})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:l,children:l}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(uS.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)(uS.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(uS.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(uS.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(o.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(c.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(c.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":m("panel.more"),title:m("panel.more"),children:(0,r.jsx)(o.In,{size:"16px",svg:uR})})}),(0,r.jsx)(c.k.Positioner,{children:(0,r.jsx)(c.k.Content,{"aria-label":m("panel.more"),children:(0,r.jsx)(c.k.ScrollArea,{children:(0,r.jsx)(c.k.Group,{children:h.map(e=>(0,r.jsx)(c.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(c.k.ItemBody,{children:(0,r.jsx)(c.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(uL,{}),f&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:f.onClick,"aria-label":f.label,title:f.label,children:(0,r.jsx)(o.In,{size:"16px",svg:uM})})]})}function uL({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,i.useContext)(uC);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(o.In,{size:"16px",svg:n.expanded?uT:uN})})}let u$="cuelo-html-pick",uP="cuelo-html-pick-exit";function uA(e,t){return"string"==typeof e&&e.length<=t}function uF(e){return"number"==typeof e&&Number.isFinite(e)}function uz({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:o}){let{t:l}=(0,F.s)(),c=(0,i.useRef)(null),d=(0,i.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
|
|
20
20
|
var NONCE=${JSON.stringify(n)},TYPE=${JSON.stringify(u$)},EXIT=${JSON.stringify(uP)};
|
|
21
21
|
var host=window.parent;
|
|
22
22
|
if(document.currentScript)document.currentScript.remove();
|